Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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")
Ejemplo n.º 3
0
    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'
Ejemplo n.º 4
0
#!/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
Ejemplo n.º 5
0
#       Takes in user input for courses and creates a calendar for them

from uwaterlooapi import UWaterlooAPI
from ics import Calendar, Event
from datetime import date, timedelta, time, datetime
import arrow
from pytz import timezone

#       I should not reveal this
uw = UWaterlooAPI(api_key="8ab9363c27cf84a3fdf526a89269e81a")

cal = Calendar()

#       Term start/end dates (not in api)
term_dates = {"1171":{"start":date(2017, 1, 3), "end":date(2017, 4, 3)},
              "1169":{"start":date(2016, 8, 8), "end":date(2016, 12, 5)}}


#       get_section(str, str) returns first section(dic) with same
#               last 3 characters as sec_id.
#        returns -1 if not found
def get_section(course_info, sec_id):
        for section in course_info:
                if section["section"][-3:] == sec_id:
                        return section
        return -1


#       get_section(str, str) returns first section(dic) equal
#               to section_name.
#       returns -1 if not found
Ejemplo n.º 6
0
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:])
Ejemplo n.º 7
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)
#!/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
class Subject(object):
    def __init__(self,name,catalog,section,starts,ends,days,prof):
        self.name=name
        self.catalog=catalog
        self.section=section
        self.starts=starts
        self.ends=ends
        self.days=dyas
        self.prof=prof
    def display(self):
        print '%s:%s:%s:%s:%s:%s:%s' %(self.name,self.catalog,self.section,self.starts,self.ends,self.days,self.prof)
    def numeric_time(self):
        return (int(self.starts),int(self.ends))
uw=UWaterlooAPI(api_key=raw_input("Please Enter Your APIkey"))
courses=raw_input("Please enter your desired courses, e.g. 'CS 136, MATH 230'")

# acquiring course information

courses=courses.split(',')
course=[]
for i in range(0,len(courses)):
    a=courses[i].split()
    course.append((a[0],a[1]))
datalist=[]

#downloading data via the api

for k,v in course:
    datalist.append(uw.course_schedule(k,v))
time=raw_input('please enter the time period you would like to take course, e.g. "9:30,14:20" means courses starts from 9:30 ends before 14:20 everyday')
Ejemplo n.º 10
0
def test_validCourse():
    uw_api = UWaterlooAPI(uw_api_key)
    courses = app.getCourses.generateCourses(uw_api)
    assert len(courses) > 0
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
# 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()
Ejemplo n.º 13
0
def test_invalidCourse():
    uw_api = UWaterlooAPI(uw_api_key)
    assert app.checkValidCourse.course_exists('DOESNT', '135', uw_api) == False
Ejemplo n.º 14
0
def test_validCourse():
    uw_api = UWaterlooAPI(uw_api_key)
    assert app.checkValidCourse.course_exists('CS', '135', uw_api) == True
Ejemplo n.º 15
0
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
from uwaterlooapi import UWaterlooAPI

if __name__ == '__main__':
    uw = UWaterlooAPI(api_key="7d0e829ff82a1aa902f44d6609a1cbb2")
    places = uw.menu()

    lunches = places['outlets'][0]['menu'][0]['meals']['lunch'][0]['product_name']
    print(lunches)

    lunch = places['outlets'][1]['menu'][0]['meals']['dinner'][0]['product_name']
    print(lunch)

    locations = places['outlets'][0]
    print("\n" + locations['outlet_name'] + ": ")
    dates = locations['menu']
    for date in dates:
        print(" - " + date['date'])
        if date['meals']['lunch']:
            lunches = date['meals']['lunch']
            for lunch in lunches:
                print('    + ' + lunch['product_name'])

    locations = places['outlets'][1]
    print("\n" + locations['outlet_name'] + ": ")
    dates = locations['menu']
    for date in dates:
        print(" - " + date['date'])
        dinners = date['meals']['dinner']
        for dinner in dinners:
            print('    + ' + dinner['product_name'])
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)
Ejemplo n.º 18
0
        try:
            return uw.courses(subjects)
        except:
            print("Requesting subject {} info failed. Reconnecting...".format(subject, catalog_number))
            time.sleep(0.5)

def get_course_info(subject, catalog_number):
    while True:
        try:
            return uw.course(subject, catalog_number)
        except:
            print("Requesting {} {} info failed. Reconnecting...".format(subject, catalog_number))
            time.sleep(0.5)

if __name__ == "__main__":
    uw = UWaterlooAPI(api_key=key)
    subjects = uw.subject_codes()
    print("Number of subjects: {}".format(len(subjects)))
    i   = 0
    data = []
    for subject_reponse in subjects:
        subject = subject_reponse["subject"]
        catalog_list = get_subject(subject)
        print("Number of course catalog ids for subject {} is: {}".format(subject, len(catalog_list)))
        for item in catalog_list:
            catalog_number = item["catalog_number"]
            course_info = get_course_info(subject, catalog_number)
            name = subject + " " + catalog_number
            course_info["name"] = name

            print("Course name: {}".format(name))
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()
Ejemplo n.º 20
0
from uwaterlooapi import UWaterlooAPI

uw = UWaterlooAPI(api_key="ec16c4c498c87b043a33e9903a61c51d")

print uw.schedule_by_class_number("007407")
Ejemplo n.º 21
0
class goose_bot:
    """Goose bot class, performs actions for a reddit helper bot."""
    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'

##############################################################################
#                        UW COURSE COMMENTING METHODS                        #
##############################################################################

    def _parse_uw_course_text(self, text):
        """Private method that parses specified text for a course code \n
           i.e: CS 136"""
        match = re.compile('[A-Za-z]{2,}\s?[0-9]{3}')
        course_tuple = re.findall(match, text)
        courses = []

        # Transfer tuple elements into array, removing any possible middle spacing
        for course in course_tuple:
            course = course.replace(" ", "")
            courses.append(course)
        # Converting to dictionaries removes duplicate courses
        courses = list(dict.fromkeys(courses))
        return courses

    def _gen_uw_course_comment(self, text):
        """Generates a bot reply containing links to courses mentioned
           in a submission and its full title for context."""
        courses = self._parse_uw_course_text(text)
        reply_string = 'Honk! It looks like you mentioned a few university courses in your post!\n\n'
        matching = re.compile('[A-Za-z]{2,}|[0-9]{3}')

        # print url and a short course name descrip.
        for course in courses:
            program_course_array = re.findall(matching, course)
            program_name = program_course_array[0].upper()
            course_code = program_course_array[1]
            if self.uw_api.course(program_name, course_code):
                course = self.uw_api.course(program_name, course_code)
                reply_string += f'\n\n[{program_name} {course_code}]({course["url"]}): {course["title"]} \n\n'
            elif len(courses) == 1:
                # If one element exists but does not match any course code,
                # no reply should be generated.
                return ""
        reply_string += "\n\n---\n\n"
        reply_string += f"\n\nI am an automated goose &#x1f9a2; - you can contact my creators [here](https://www.reddit.com/message/compose/?to=/u/{self.bot.user.me().name})"
        return reply_string

##############################################################################
#                          SUBMISSION REPLY METHODS                          #
##############################################################################

    def check_match(self, submission):
        """Checks if reddit submission title or text contains given content type,
           and if bot has already responded to post.\n
           Returns true if post matches content_type regex,
           and if no bot comment exists on post."""
        if re.search(r'[A-Za-z]{2,4}\s?[0-9]{3}', submission.title) or \
            re.search(r'[A-Za-z]{2,4}\s?[0-9]{3}', submission.selftext):
            if self._post_id_check(
                    submission.id):  # bot comment exists, and content match
                return False
            else:
                return True  # no bot comment exists, and matches specific content
        # Insert any other string matches here...
        else:
            return False  # no content match

    def submission_reply(self, submission, content_type="courses"):
        """Replies to the submission, and adds the submission id to a txt document."""
        comment = ""
        # To check for both submission text and body for content,
        # just concatenate them into the same string, separated by a space.
        if content_type == "courses":  # for course replies
            comment = self._gen_uw_course_comment(submission.title + " " +
                                                  submission.selftext)
        # Insert other content_type flagging here...

        if comment:  # If generated comment is non-empty
            print(
                f'Replying to post \"{submission.title}\" with id {submission.id}'
            )
            submission.reply(comment)
            self._save_submission_id(submission.id)

    def _post_id_check(self, submission_id):
        """Private method to check if submission id exists in txt file"""
        try:
            read_comment_id = open(self.sub_reply_txt)
        except IOError:
            read_comment_id = open(self.sub_reply_txt, 'w+')
            read_comment_id.close()
            read_comment_id = open(self.sub_reply_txt, "r")
        readline_comment_id = read_comment_id.readlines()
        for line in readline_comment_id:
            if submission_id + "\n" == str(line):
                read_comment_id.close()
                return True
        read_comment_id.close()
        return False  # empty txt file or bot did not comment.

    def _save_submission_id(self, submission_id):
        """Private method that adds submission id of which a reply 
           was made to into a txt document."""
        with open(self.sub_reply_txt, "a+") as write_comment_id:
            print(f'Saving {submission_id} to {self.sub_reply_txt}')
            write_comment_id.write(f'{submission_id}\n')

##############################################################################
#                              MENTION REPLIES                               #
##############################################################################

    def inbox_reply(self, comment):
        """Replies to inbox mentions or comments replies on posts, when they match specific 
           words or phrases below."""
        if "good bot" in comment.body.lower():
            comment.reply(self._good_bot())
            comment.mark_read()
        elif "bad bot" in comment.body.lower():
            comment.reply(self._bad_bot())
            # add the user to a filter list
            comment.mark_read()
        elif "thank mr. goose" in comment.body.lower():
            comment.reply(self._thank_mr_goose())
            comment.mark_read()
        elif "bruh moment" == comment.body.lower() \
            or "bruh"== comment.body.lower():
            comment.reply(self._bruh_moment())
            comment.mark_read()
        else:
            return
        print(
            f'Replying to comment {comment.id}, found on the post ' +
            f'\"{comment.submission.title}\", with id {comment.submission.id}')

    def _good_bot(self):
        return 'honk honk! &#x1f9a2;'

    def _bad_bot(self):
        # put user on removal list
        return 'sad honk :('

    def _thank_mr_goose(self):
        return 'thank mr. goose <3'

    def _bruh_moment(self):
        return 'bruh moment'

##############################################################################
#                           String overload functions                        #
##############################################################################

    def __repr__(self):
        return str({
            "Bot name": self.bot.user.me().name,
            "Bot ID": self.bot.user.me().id,
            "UW key": self.uw_key,
            "Bot karma": self.bot.user.me().comment_karma,
            "Bot creation": self.bot.user.me().created_utc
        })

    def __str__(self):
        return  f'Bot name:     {self.bot.user.me().name} \n' + \
                f'Bot ID:       {self.bot.user.me().id} \n' + \
                f'UW key:       {self.uw_key} \n' + \
                f'Bot karma:    {self.bot.user.me().comment_karma} \n' + \
                f'Bot creation: {self.bot.user.me().created_utc}'
Ejemplo n.º 22
0
Yuxuan Chen

23 January 2016
'''

import time
import os
rows, columns = os.popen('stty size', 'r').read().split()
from termcolor import colored, cprint

# keep the api key private
f = open(os.path.dirname(__file__) + '/data/uw-api.txt', 'r')
api_key = f.readline().strip()

from uwaterlooapi import UWaterlooAPI
uw = UWaterlooAPI(api_key=api_key)

infosessions = uw.infosessions()
previousDate = ""

today = time.strftime("%B %-d, %Y")

start = -1
counter = 0
for infosession in infosessions:
	if (today == infosession["date"]):
		start = counter
	counter += 1
if (start == -1):
	today = time.strftime("%B") + " " + str((int(time.strftime("%-d"))-2) % 30) + ", " + time.strftime("%Y")
counter = 0
Ejemplo n.º 23
0
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]
        
Ejemplo n.º 24
0
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
Ejemplo n.º 25
0
KEY = local_settings.PARAM_KEY
USER_AGENT = local_settings.PARAM_USER_AGENT
DATABASE = local_settings.PARAM_DATABASE

# Initialize DB
conn = sqlite3.connect(DATABASE)
conn.isolation_level = None
cursor = conn.cursor()

# Initialize Logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
logging.debug("Connecting to %", DATABASE)

if __name__ == "__main__":
    # Set UW API
    uw = UWaterlooAPI(api_key=KEY)
    uw_subjects = []
    avail_codes = [TERM, HOLIDAYS, SCHEDULE, HELP]
    term_dates = {}
    term_dates[1159] = {"start_date": "2015-09-14", "end_date": "2015-12-22"}
    term_dates[1161] = {"start_date": "2016-01-04", "end_date": "2016-04-23"}
    term_dates[1165] = {"start_date": "2016-05-02", "end_date": "2016-08-13"}


    for course in uw.subject_codes():
        uw_subjects.append(course.get("subject"))

    reddit = praw.Reddit(user_agent=USER_AGENT)
    reddit.login(LOGIN, PASSWORD)

    # Main loop
Ejemplo n.º 26
0
from uwaterlooapi import UWaterlooAPI

uw = UWaterlooAPI(api_key="ec16c4c498c87b043a33e9903a61c51d")





print uw.schedule_by_class_number("007407")




Ejemplo n.º 27
0
    '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:
Ejemplo n.º 28
0
from uwaterlooapi import UWaterlooAPI
uw = UWaterlooAPI(api_key="YOUR API KEY")
from Tkinter import *
import time


# Initialize Graphics
root = Tk()
root.geometry("1920x1000-5-30")

# Create button bar
selectionBar = Frame(root, relief = RAISED)
selectionBar.pack(fill=X)
selectionBar.config(background = '#ffffff')

# Create info box
infoBox = Frame(root)
infoBox.pack(fill=BOTH, expand = 1)

def initInfo():
    # Clear the infoBox frame
    for widget in infoBox.winfo_children():
        widget.destroy()
    # Gets date data and declares variables
    infoSes = []
    info = uw.infosessions()
    today = time.strptime(time.strftime("%x"), "%x")
    start = 0
    # Finds first info session that hasnt happened
    while today > time.strptime(info[start][u'date'].encode('utf-8'), "%B %d, %Y"):
        start += 1
Ejemplo n.º 29
0
		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(
Ejemplo n.º 30
0
"""
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
        if e.message in ("Bad Gateway", "Timed out"):
            sleep(1)
        elif e.message == "Unauthorized":
            # The user has removed or blocked the bot.
            update_id += 1
        else:
            raise e


def echo(bot, update_id, message):
    bot.sendMessage(chat_id="130724919", text=message)
    return update_id


API_KEY = apikeys.getUWApiKey()
uw = UWaterlooAPI(api_key=API_KEY)


todays_sessions = []


day = int(time.strftime("%d"))

todaysDate = time.strftime("%B ") + str(day) + time.strftime(", %Y")


for event in uw.infosessions():
    if "CANCELLED" in event["employer"].upper():
        continue
    if event["date"] == todaysDate:
        event["start_time"] = time.strftime("%H:%M", time.strptime(event["start_time"], "%I:%M %p"))