def test_get_by_id(self): """Get Module by ID.""" module = Module(title='foo', order=5, template_id='i_1') module.save() retrieved = Module.query.get_or_404(module.id) assert retrieved == module
def process_mod(self, path, module): # path info basename = os.path.basename(path) dirname = os.path.dirname(path) unpacked_dir = os.path.join(dirname, module.slug) # unpack archive logger.info("unpacking archive: %s", basename) shutil.unpack_archive(path, unpacked_dir, "zip") # convert db.xml to module.xml xml_file = os.path.join(unpacked_dir, "db.xml") if os.path.exists(xml_file): # parse data self.parse_xml(xml_file, module) # create dst dst = os.path.join(unpacked_dir, "module.xml") # export xml module.export_xml(dst) else: raise ValueError("db.xml not found") # create archive Module.create_archive(unpacked_dir, module.slug) return module
def add_module_to_subject(request,subject_id): context = {} context['user'] = request.user this_subject = Subject.objects.get(id=subject_id) context['subject'] = this_subject if request.method=="POST": subject_id = request.POST.get('subject_id','') module_name = request.POST.get('module_name','') module_description = request.POST.get('module_description','') module_creator_id = request.POST.get('module_creator_id','') if module_name=='' or module_description=='' or module_creator_id=='' or subject_id=='': to_json = { 'result': 'failed' } return HttpResponse(simplejson.dumps(to_json), content_type="application/json") else: module_creator = User.objects.get(id=module_creator_id) module = Module(name=module_name,description=module_description,creator=module_creator) module.save() module.instructors.add(module_creator) this_subject = Subject.objects.get(id=subject_id) module.subjects.add(this_subject) to_json = { 'result': 'succeeded', } return HttpResponse(simplejson.dumps(to_json), content_type="application/json") else: context['modules'] = Module.objects.all() context['subject_modules'] = Module.objects.filter(subjects__id=subject_id) return render_to_response('add_module_to_subject.html', context, RequestContext(request,context))
def __init__(self): """ Tanh constructor """ Module.__init__(self) self.s = None
def get(self): user = users.get_current_user() if(user): userQuery = User.query(User.userid == user.user_id()) userEntity = None for thisUser in userQuery: userEntity = thisUser formCheck(self, user) missedLectureCheck(user) if userEntity.email is None: userEntity.email = user.email() userEntity.put() if userEntity is None: userEntity = User( userid=user.user_id(), score=0, streak=0, count=0, history=[], email = user.email()) module1Query = Module.query(Module.code == 'GENG0013') for module in module1Query: for lecture in module.lectures: userEntity.lectures.append(lecture) module2Query = Module.query(Module.code == 'GENG0002') for module in module2Query: for lecture in module.lectures: userEntity.lectures.append(lecture) challengeQuery = Challenge.query().order(Challenge.challengeid) for challenge in challengeQuery: userEntity.challenges.append(challenge) userEntity.put() self.redirect('/info') completedChalls = [] for challenge in userEntity.challenges: if challenge.complete: completedChalls.append(challenge) template_values = { 'username' : userEntity.username, 'logout' : users.create_logout_url(self.request.uri), 'score' : userEntity.score, 'count' : userEntity.count, 'streak' : userEntity.streak, 'completedChalls' : completedChalls } template = JINJA_ENVIRONMENT.get_template('/assets/home.html') self.response.write(template.render(template_values)) else: self.redirect(users.create_login_url(self.request.uri))
def test_add_article_with_module(self): """Add a module to an article.""" module = Module(title='module_article') module.save() article = ArticleFactory() article.module = module article.save() assert isinstance(article.module_id, int)
def __init__(self): """ LossCrossEntropy constructor """ Module.__init__(self) self.y = None self.target = None self.target_onehot = None
def __init__(self): """ LossMSE constructor """ Module.__init__(self) self.y = None self.target = None self.e = None self.n = None
def new_module(): type = Module_Type.select().where( Module_Type.id == request.form['module_type']) if not type.exists(): flash('Module type bestaat niet.', AlertType.WARNING.value) return redirect(url_for('admin.modules')) module = Module(type=type) module.save() return redirect(url_for('admin.modules'))
def __init__(self, alpha=0.01): """ LeakyReLU constructor :param alpha: non-negative float :raises ValueError, if `alpha` is not a non-negative float """ if not isinstance(alpha, float) or alpha < 0: raise ValueError("LeakyReLU alpha must be a non-negative float") Module.__init__(self) self.alpha = alpha self.s = None
def get(self, moduleID, title, institution, teachDate, instructors, description): account = get_account() if account: newCourse = dict() newCourse["CourseURL"] = urlparse.unquote( self.request.get('courseURL')) newCourse["Title"] = title newCourse["Institution"] = institution newCourse["TeachingDate"] = teachDate newCourse["Instructors"] = instructors newCourse["Description"] = description newCourse["DownloadPageLink"] = urlparse.unquote( self.request.get('materials')) newCourse["scoreRanking"] = 1 moduleID = int(moduleID) match = Module.query(Module.category == moduleID).fetch() match = match[0] moduleCourses = match.courses newCourse['ID'] = len(moduleCourses) moduleCourses.append(newCourse) match.courses = moduleCourses match.courses = sorted( match.courses, key=lambda k: k['scoreRanking'], reverse=True) match.put() response = {'success': 'Course submitted successfully.'} else: response = {'error': 'You are not logged in. '} self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(response))
def test_model_Module_basic(self): """Test Module model with minimum parameters""" name = 'test module' title = 'Test title' url = '/test_url/' obj = Module(name=name, title=title, url=url) obj.save() self.assertIsNotNone(obj.id) obj = Module.objects.get(id=obj.id) self.assertEquals(obj.name, name) self.assertEquals(obj.title, title) self.assertEquals(obj.url, url) self.assertEquals(obj.details, '') self.assertTrue(obj.display) self.assertTrue(obj.system) self.assertEqual(obj.get_absolute_url(), '/admin/module/view/{}'.format(obj.id))
def modules(): modules = Module.select().order_by(Module.build_on.desc()) module_types = Module_Type.select() return render_template('modules/index.html', modules=modules, module_types=module_types)
def edit_module_submission(module_id): try: module_data = Module.query.get(module_id) setattr(module_data, 'name', request.form['name']) setattr(module_data, 'grade_id', request.form['grade_id']) setattr(module_data, 'semester_id', request.form['semester_id']) Module.update(module_data) flash('Module ' + request.form['name'] + ' was successfully edited!') except: db.session.rollback() print(sys.exc_info()) flash('An error occurred. Module ' + request.form['name'] + ' could not be edit.') finally: db.session.close() query = Module.query.filter(Module.grade_id==request.form['grade_id'], Module.semester_id==request.form['semester_id']) return render_template('pages/modules.html', data=query, userinfo=session['profile'])
def get(self): modules = [m.to_dict() for m in Module.query().fetch()] modules = sorted( modules, key=lambda module: module['name'].lower() ) self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(modules))
def add_module_submission(): try: grade_id=request.form['grade_id'] semester_id = request.form['semester_id'] new_module = Module( name=request.form['name'], grade_id=grade_id, semester_id=semester_id ) Module.insert(new_module) flash('Module ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() print(sys.exc_info()) flash('An error occurred. Module ' + request.form['name'] + ' could not be listed.') finally: db.session.close() query = Module.query.filter(Module.grade_id==grade_id, Module.semester_id==semester_id) return render_template('pages/modules.html', data=query, userinfo=session['profile'])
def edit_module_form(module_id): form = ModuleForm() module_query = Module.query.get(module_id) module_details = Module.format(module_query) form.name.data = module_details['name'] form.grade_id.data = module_details['grade_id'] form.semester_id.data = module_details['semester_id'] grades = Grade.query.order_by(Grade.id).all() return render_template('forms/edit_adds.html', form=form, grades=grades, module_id=module_id, userinfo=session['profile'])
def get_recent_ann(module_code, count, duration=0): try: course_id = Module.select(Module.module_id). \ where(Module.module_code.contains(module_code)). \ order_by(Module.acad_year.desc(), Module.semester.desc()). \ get().module_id results = strf_announcements(IVLE.announcements(courseId=course_id, duration=duration).Results[:count]) return (results, True) if results else ('There are no announcements for {}'.format(module_code), True) except Exception as e: print(e) return (userstr.recent_ann_false, False)
def loadModules(): # GENG0014 = Module( # code='GENG0014', # lectures=[ # Lecture(module='GENG0014', location=35, day=3, time=15), # Lecture(module='GENG0014', location=35, day=4, time=11)]) # GENG0014.put() GENG0013 = Module( code='GENG0013', lectures=[ Lecture(module='GENG0013', title='TT Math Support', location='2', day=0, time=11, duration=1), Lecture(module='GENG0013', title='TT Math Support', location='35', day=0, time=15, duration=1), Lecture(module='GENG0013', title='TT Math Support', location='16', day=3, time=9, duration=2), Lecture(module='GENG0013', title='TT Math Support', location='59', day=3, time=12, duration=2)]) GENG0013.put() GENG0002 = Module( code='GENG0002', lectures=[ Lecture(module='GENG0002', title='Mathematics B', location='59;67;34;32;16;13', day=0, time=17, duration=1), Lecture(module='GENG0002', title='Mathematics B', location='2a', day=1, time=11, duration=1), Lecture(module='GENG0002', title='Mathematics B', location='58', day=2, time=11, duration=1), Lecture(module='GENG0002', title='Mathematics B', location='2a', day=3, time=11, duration=1), Lecture(module='GENG0002', title='Mathematics B', location='7;5;27;16', day=3, time=16, duration=2)]) GENG0002.put()
def setup_modules(): try: response = IVLE.modules(includeAllInfo=False) module_list = [] for module in response.Results: mod, _ = Module.get_or_create(module_code=module.CourseCode, acad_year=module.CourseAcadYear, semester=int(module.CourseSemester[-1]), defaults={'module_id': module.ID}) if mod.module_id is None or mod.module_id == '': mod.module_id = MODULE_ID_NULL_STRING mod.save() return (userstr.setup_modules_true, True) except Exception as e: print(e) return (userstr.setup_modules_false, False)
def add_module(request): context = {} context['user'] = request.user if request.method=="POST": module_name = request.POST.get('module_name','') module_description = request.POST.get('module_description','') module_creator_id = request.POST.get('module_creator_id','') if module_name=='' or module_description=='' or module_creator_id=='': to_json = { 'result': 'failed' } return HttpResponse(simplejson.dumps(to_json), content_type="application/json") else: module_creator = User.objects.get(id=module_creator_id) module = Module(name=module_name,description=module_description,creator=module_creator) module.save() module.instructors.add(module_creator) to_json = { 'result': 'succeeded', 'new_module_id': module.id } return HttpResponse(simplejson.dumps(to_json), content_type="application/json") return render_to_response('add_module.html', context, RequestContext(request,context))
def newmodule(): if current_user.email not in TA_EMAILS: abort(404) if request.method == 'GET': return render_template('newmodule.jinja2') if request.method == 'POST': name = request.form.get('name') number = request.form.get('number') description = request.form.get('description') exercise = request.form.get('exercise') module = Module(name = name, number = number, description = description, exercise = exercise) db.session.add(module) db.session.commit() return render_template('newmodulesubmitted.jinja2')
def get(self): jac = job_api_calls.JobApiCalls() categories = jac.get_categories() y = youtube.Youtube() ocws = ocwsearch.OCWSearch() for c in categories: # retrieve items from API's c_id = int(c['id']) name = HTMLParser.HTMLParser().unescape(c['name']) search_name = name + " tutorial" y_list, y_type = y.search(search_name) course_list = ocws.search(name) # store/update as needed match = Module.query(Module.category == c_id).fetch() module = Module( name=name, youtube=y_list, yt_type=y_type, courses=course_list, category=c_id ) if len(match) == 0: module.put() else: match = match[0] if (str(match.name) != name or str(match.yt_type) != y_type or match.youtube != y_list or match.courses != course_list): match.name = name match.youtube = y_list match.yt_type = y_type match.courses = course_list match.put() self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(categories))
def index(): users_count = User.select().count() last_registered_user = User.select().order_by( User.registered_on.desc()).get() modules = Module.select() last_created_group = Group.select().order_by(Group.created_on.desc()) if last_created_group.exists(): last_created_group = last_created_group.get() group_count = Group.select().count() return render_template('home.html', users_count=users_count, last_registered_user=last_registered_user, group_count=group_count, last_created_group=last_created_group, modules=modules)
def api_module_locations(module_uuid): module = Module.select().where(Module.uuid == module_uuid) if not module.exists(): resp = make_response(jsonify({'error': 'module not found.'}), 404) return resp module = module.get() module_locations = Module_Location.select().where( Module_Location.module == module) dict = json.models_to_dict(module_locations) for m in dict: m['start'] = m['start_date'] m['end'] = m['end_date'] m['title'] = m['location']['address'] + ', ' + m['location']['city'] return jsonify(dict)
def module(module_uuid): module = Module.select().where(Module.uuid == module_uuid) if not module.exists(): flash('Module bestaat niet.', AlertType.WARNING.value) return redirect(url_for('admin.modules')) module = module.get() module_locatons = Module_Location.select().where( Module_Location.module == module).order_by( Module_Location.start_date.desc()).limit(5) locations = Location.select().where( Location.unavailable_from > datetime.now().date()) return render_template('modules/module.html', module=module, locations=module_locatons, available_locations=locations, datetime=datetime)
def get(self, moduleID, courseID): courseID = int(courseID) account = get_account() if account: courseVoteList = dict(account.courses_voted) idPair = moduleID + "+" + str(courseID) if idPair not in courseVoteList.keys() or courseVoteList[idPair] == 'Y': case = "votedYes" if idPair not in courseVoteList.keys(): case = "notVoted" courseVoteList[idPair] = 'N' account.courses_voted = courseVoteList.items() account.put() moduleID = int(moduleID) match = Module.query(Module.category == moduleID).fetch() match = match[0] moduleCourses = match.courses newScore = 0 for course in moduleCourses: if course: if course['ID'] == courseID: if case == "notVoted": course["scoreRanking"] = course[ "scoreRanking"] - 1 else: course["scoreRanking"] = course[ "scoreRanking"] - 2 newScore = course["scoreRanking"] match.courses = moduleCourses match.courses = sorted( match.courses, key=lambda k: k['scoreRanking'], reverse=True) match.put() response = { 'success': 'Vote submitted successfully.', 'newScore': newScore} else: response = {'error': 'No.'} else: response = {'error': 'You are not logged in. '} self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(response))
def module(): """获取模块 --- tags: - 资讯 security: - api_key: [] responses: 200: description: 首页模块列表 schema: $ref: '#/definitions/ApiResponse' examples: code: 0 data: [{}, {}] message: 'success' """ modules = Module.get(num='all', child_num=0) res = { 'data': modules } return success(res)
def create_paste(): form= PasteForm(request.form) if request.method == 'POST' : paste= None if form.id.data != None: paste= Paste.query.get(form.id.data) if paste != None: paste.author= form.author.data paste.content= form.content.data paste.name= form.name.data #remove modules for module in paste.modules: db.session.delete(module) if paste == None: paste= Paste(author= form.author.data, content= form.content.data, name= form.name.data) db.session.add(paste) db.session.commit() for module in form.modules: if module.expanded.data == 0: #skip content of non-expanded modules module.content.data= "" m= Module(name= module.mod_name.data, score= module.score.data, content= module.content.data, module_id= module.module_id.data, paste_id= paste.id) db.session.add(m) db.session.commit() return redirect(url_for('show_paste', paste_id=paste.id)) return "0"
def get(self, modulename): match = Module.query(Module.name == modulename).fetch() if len(match) > 0: response = {'response': 'module exists'} else: y = youtube.Youtube() ocws = ocwsearch.OCWSearch() search_name = modulename + " tutorial" y_list, y_type = y.search(search_name) course_list = ocws.search(modulename) module = Module( name=modulename, youtube=y_list, yt_type=y_type, courses=course_list ) module.put() response = {'response': 'successfully stored'} module.category = module.key.id() module.put() self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(response))
def get_info(self, module_id): module_id = int(module_id) module = Module.get_by_id(module_id) votedCourses = {} account = get_account() if account: votedCourses = account.courses_voted votedCourses = dict(votedCourses) newJobsJSON = [] jobs = Project.query(Project.job_type == module.name).fetch() for job in jobs: newProject = self.convert_to_project_JSON(job) newJobsJSON.append(newProject) info = { 'name': module.name, 'youtube': module.youtube, 'yt_type': module.yt_type, 'courses': module.courses, 'category': module.category, 'jobs': newJobsJSON, 'votedCourses': votedCourses } return info
def home() -> ApiResult: """获取首页 --- tags: - 前台API responses: 200: description: 首页模块列表 schema: $ref: '#/definitions/Module' examples: code: 0 data: [{}, {}] message: 'success' """ res = cache.get('home_json') if not res: modules = Module.get_item(10) result = [] for m in modules: if m.template_id == 'i_5': item = m.to_json() else: item = m.to_json(2) for c in item['child']: if c['thumb_pic']: c['thumb_pic'] = 'http://' + c['thumb_pic'] result.append(item) res = {'data': result} cache.set('home_json', json.dumps(res)) cache.expire('home_json', current_app.config['EXPIRE_TIME']) else: res = json.loads(res) return success(res)
def register(action, dom, attrs): """ Register XML-response in DB. Get items form DOM and clear XML. Valid actions: 203|204|205|207. Arguments: dom - DOM object attrs - Dictionary (requested items: action, data (XML), selected_item, custom_code and another...) Returns: data - Dictionary (next_custom_code) """ print_db_state() IsError = False print_action(action, 'DBase.Register') # ---- # User # ---- userID = get_item(dom, attrs, 'userID') user = userID and User.query.filter_by(userID=userID).first() if not user: user = User(userID, title=get_item(dom, attrs, 'userName'), email=getDOMItemValue(dom, 'orderEmail')) _add(user) # ------ # Module # ------ wizardID = get_item(dom, attrs, 'wizardID') module = wizardID and Module.query.filter_by(wizardID=wizardID).first() if not module: module = Module(wizardID, title=re.sub(r'\s+', ' ', re.sub(r'<.*?>', '', get_item(dom, attrs, 'wizardName')))) m = re.search(r'.*(DUS-[\d-]*)', module.wizardName) if m: module.DUS = m.group(1) _add(module) # ------------------ # Parameters & Items # ------------------ for n, x in enumerate(getDOMParameters(dom, False)): parameter = Parameter.query.filter_by(CIS=x['id']).first() if not parameter: parameter = Parameter(x['id'], valid_parameter_names.get(x['type'].upper()), unit=x['unit']) _add(parameter) item = Item.query.filter_by(parameter=parameter, module=module).first() if not item: item = Item(parameter, module) _add(item) # --------------------- # Order & Prices & Data # --------------------- if action not in valid_action_types: IsError = True otype = -1 id = get_item(dom, attrs, 'selected_item') code = get_item(dom, attrs, 'custom_code') IsAddOrder = False IsUpdateOrder = False custom_code = '' order = None if IsError: pass # ---------------------------------------------- # Get Order item from DB and update or add a new # ---------------------------------------------- elif action == '203': if not id: otype = ORDER_STANDARD order = Order.query.filter_by(user=user, module=module, otype=otype).first() else: order = get_order(id, None) custom_code = order and order.code otype = -1 elif action == '204': otype = ORDER_CUSTOM order = get_order(id, code, user=user, module=module) elif action == '205': otype = ORDER_CUSTOM #order = get_order(None, code, user=user, module=module) elif action == '207': otype = ORDER_DONE else: otype = -1 if IsDebug: print '>>> Order: %s %s %s' % (order, str(code), str(id)) if otype in valid_order_types: price_columns = get_columns(dom, attrs, model_price_columns) if not attrs.get('title'): attrs['title'] = gettext(valid_order_names[otype]) if not order: order = Order(user, module, otype, get_columns(dom, attrs, model_order_columns)) #if otype == ORDER_DONE: # order.code = Order.generate_custom_code(user, module, otype=ORDER_DONE) #elif otype == ORDER_CUSTOM: # order.code = get_item(dom, attrs, 'custom_code') or \ # Order.generate_custom_code(user, module, otype=otype) IsAddOrder = True else: if action in ('203','207'): pass elif action == '204': if order.option_update: order.data = order._data(get_item(dom, attrs, 'data')) IsUpdateOrder = True elif action == '205': order.set_attrs(get_columns(dom, attrs, model_order_columns)) IsUpdateOrder = True current_price = Order.generate_current_price(int(float(price_columns['total']) * 100), \ price_columns['currency']) if IsAddOrder: last_price = '' order.current_price = current_price else: last_price = order.current_price if order.otype in (ORDER_STANDARD, ORDER_CUSTOM,): order.current_price = current_price order.rating = order.current_price < last_price and RATING_DOWN or \ order.current_price > last_price and RATING_UP or \ RATING_EQUAL else: order.rating = current_price > last_price and RATING_DOWN or \ current_price < last_price and RATING_UP or \ RATING_EQUAL if IsDebug: print '>>> Current price: %s %s %s' % (last_price, order.current_price, order.rating) if order and IsAddOrder: _add(order) if order and (IsAddOrder or (order.option_cost and last_price != current_price)): _add(Price(order, price_columns)) # ---------- # Save to DB # ---------- _commit(IsUpdateOrder and True or False) # --------------------- # Get data for response # --------------------- data = {} next_custom_code = Order.generate_custom_code(user, module) if action in ('203','204','205',): if order: data['title'] = order.title data['custom_code'] = order.code or custom_code data['next_custom_code'] = order.option_update and order.code or next_custom_code data['option_update'] = order.option_update data['option_cost'] = order.option_cost else: data['next_custom_code'] = next_custom_code data['custom_code'] = custom_code return data
# setup logging if args.debug: logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) else: logging.basicConfig(stream=sys.stdout, level=logging.INFO) logger = logging.getLogger(__name__) from slugify import slugify from models import Module from parsers import FantasyGrounds if __name__ == "__main__": # create module module = Module() module.id = args.id or str(uuid.uuid4()) module.name = args.name or "Unknown" module.slug = slugify(module.name) module.author = args.author or "Unknown" module.code = args.code module.image = args.cover or "Cover.jpg" # create data parser dp = None if args.parser == "fg": # FantasyGrounds dp = FantasyGrounds() module.description = "Converted from FG"
def new_module_location(module_uuid): _location = request.form['location'] _placed_on = request.form['placed_on'] _placed_til = None if not request.form['placed_til'] else request.form[ 'placed_til'] # # check if module exists # module = Module.select().where(Module.uuid == module_uuid) if not module.exists(): flash('Module bestaat niet.', AlertType.WARNING.value) return redirect(url_for('admin.modules')) module = module.get() # # check if data is valid # if not _location or not _placed_on or not _placed_til: flash('Verplichte velden niet ingevuld.', AlertType.WARNING.value) return redirect(url_for('admin.module', module_uuid=module.uuid)) if _placed_on > _placed_til: flash('Module kan niet eerder weggehaald worden dan geplaatst.', AlertType.WARNING.value) return redirect(url_for('admin.module', module_uuid=module.uuid)) # # check if location exists # location = Location.select().where(Location.id == _location) if not location.exists(): flash('Locatie bestaat niet.', AlertType.WARNING.value) return redirect(url_for('admin.module', module_uuid=module.uuid)) location = location.get() # # check if location is still available # if datetime.strptime(_placed_on, '%Y-%m-%d').date( ) > location.unavailable_from or datetime.strptime( _placed_til, '%Y-%m-%d').date() > location.unavailable_from: flash('Locatie niet meer beschikbaar dan.', AlertType.WARNING.value) return redirect(url_for('admin.module', module_uuid=module.uuid)) # # check if module is still placed # q = Module_Location.select().where(Module_Location.module == module).where( (Module_Location.start_date.between(_placed_on, _placed_til)) | (Module_Location.end_date.between(_placed_on, _placed_til))) if q.exists(): flash('Module dan nog geplaatst.', AlertType.WARNING.value) return redirect(url_for('admin.module', module_uuid=module.uuid)) # TODO: does not work when period is before and after placed period: 2017-01-01 and 2019-01-01 when periods are in that period # # add new module location # Module_Location.create(module=module, location=location, start_date=_placed_on, end_date=_placed_til) return redirect(url_for('admin.module', module_uuid=module.uuid))
def __get_module_data(self, module_link: (str, str)) -> Optional[Module]: name, url = module_link response: Response = self.cached_requester.cached_request(url) if response.status_code == 404: module = Module(url=url, name=name) self.issues.append(f"Module {name} does not exist") self.cache_module(module) return module html: BeautifulSoup = BeautifulSoup(response.content, "html.parser") title = html.find("h1").text.rsplit("-", maxsplit=1) name = title[0].strip() code = title[1].strip() info_table = html.find("table").find("tbody") rows = info_table.find_all("tr") basic_info = rows.pop(0).find_all("td") levels: [str] = [] duration: str = "Unspecified" nqf_lvl: int = 0 creds: int = 0 try: levels_str = basic_info[0].text duration_str = basic_info[1].text.strip() nqf_str = basic_info[2].text[-1:].strip() creds_str = basic_info[3].text.split(": ")[1] levels = levels_str.split(",") if levels_str != "" else [] duration = duration_str if duration_str != "" else "Unspecified" nqf_lvl = int(nqf_str) if nqf_str != "" else 0 creds = int(creds_str) if creds_str != "" else 0 except ValueError: self.issues.append(f"Error for module {name}") purpose = "" pre_requisite = "" co_requisite = "" recommendation = "" for row in rows: data = row.find_all("td") for data_point in data: if "Pre-requisite:" in data_point.text: pre_requisite = data_point.text elif "Co-requisite:" in data_point.text: co_requisite = data_point.text elif "Recommendation:" in data_point.text: recommendation = data_point.text elif "Purpose:" in data_point.text: purpose = data_point.text module = Module( url=url, name=name, code=code, levels=levels, duration=duration, nqf_level=nqf_lvl, credits=creds, purpose=purpose, pre_requisite=pre_requisite, co_requisite=co_requisite, recommendation=recommendation, ) self.cache_module(module) return module
async def on_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg) user_first_name = msg['from']['first_name'] try: user = User.get(user_id=chat_id) except User.DoesNotExist: user = User.create(user_id=chat_id, auth_token='') user.save() # text only for now if content_type != 'text': return # process params content = msg['text'].split() command = content[0] params = content[1:] if command[0] != '/' and not user.auth_token: await self.sendMessage(chat_id, userstr.authenticate) if command == '/help': await self.sendMessage(chat_id, userstr.help) await self.sendMessage(chat_id, userstr.helpcmd) elif command == '/login': login_params = {'api_key': helper.API_KEY, 'chat_id': chat_id} markup = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='Login to IVLE', url='https://ivle.nus.edu.sg/api/login/?apikey={api_key}'.format(**login_params))]]) message = 'Hi {}! To get started, log in to IVLE with the link below.'.format(user_first_name) self._message_with_inline_keyboard = await self.sendMessage(chat_id, message, reply_markup=markup) await self.sendMessage(chat_id, 'When you are successfully redirected, copy the generated token and run /setup <token>.') elif command == '/setup': if not params: await self.sendMessage(chat_id, 'Usage: /setup <token>') else: token = params[0] success = False u_result, success = await helper.do(token, helper.setup_user, {'user': user, 'auth_token': token}) await self.sendMessage(chat_id, u_result) if not success: return await self.sendMessage(chat_id, userstr.setup_true) m_result, success = await helper.do(token, helper.setup_modules) await self.sendMessage(chat_id, m_result) elif command == '/gradebook': if not params or len(params) > 1: await self.sendMessage(chat_id, 'Usage: /gradebook <module>') else: module_code = params[0] await self.sendMessage(chat_id, 'Hold on, I\'m checking your grades for {}...'.format(module_code)) try: module_id = Module.select(Module.module_id). \ where(Module.module_code.contains(module_code)). \ order_by(Module.acad_year.desc(), Module.semester.desc()). \ get().module_id except Module.DoesNotExist: module_id = None if module_id is not None: result, _ = await helper.do(user.auth_token, helper.get_gradebook, { 'module_code': module_code, 'module_id': module_id}) else: result = 'Hmm, have you executed the /setup command? (You must also be taking the module {}. 😶)'.format(module_code) await self.sendMessage(chat_id, result) elif command == '/timetable': if not params: await self.sendMessage(chat_id, 'Usage: /timetable <module1> <module2> ...') else: modules = params await self.sendMessage(chat_id, 'Hold on, I\'m checking your timetable for {}...'.format( ', '.join(map(lambda m: str(m), modules)))) try: module_ids = [] for module_code in modules: module_id = Module.select(Module.module_id). \ where(Module.module_code.contains(module_code)). \ order_by(Module.acad_year.desc(), Module.semester.desc()). \ get().module_id module_ids.append(module_id) except: module_ids = [] if module_ids: result, _ = await helper.do(user.auth_token, helper.get_timetable, {'modules': module_ids}) else: result = userstr.module_ids_not_found await self.sendMessage(chat_id, result) elif command == '/examtime': if not params: await self.sendMessage(chat_id, 'Usage: /examtime <module1> <module2> ...') else: modules = params await self.sendMessage(chat_id, 'Hold on, I\'m checking the exam timetable for {}...'.format( ', '.join(map(lambda m: str(m), modules)))) try: module_ids = [] for module_code in modules: module_ids.append(Module.select(Module.module_id). \ where(Module.module_code.contains(module_code)). \ order_by(Module.acad_year.desc(), Module.semester.desc()). \ get().module_id) except: module_ids = [] if module_ids: result, _ = await helper.do(user.auth_token, helper.get_exam_timetable, {'modules': module_ids}) else: result = userstr.module_ids_not_found await self.sendMessage(chat_id, result) elif command == '/nextclass': if params: await self.sendMessage(chat_id, 'Usage: /nextclass') else: await self.sendMessage(chat_id, userstr.nextclass_wait) result, _ = await helper.do(user.auth_token, helper.get_next_class) await self.sendMessage(chat_id, result) elif command == '/announcements': if len(params) == 2: await self.sendMessage(chat_id, userstr.recent_ann_wait.format(params[0])) result, _ = await helper.do(user.auth_token, helper.get_recent_ann, { 'module_code': params[0], 'count': int(params[1])}) await self.sendMessage(chat_id, result) elif not params: await self.sendMessage(chat_id, userstr.unread_ann_wait) results, _ = await helper.do(user.auth_token, helper.get_unread_ann) if type(results) == str: await self.sendMessage(chat_id, results) else: for k, v in results.items(): await self.sendMessage(chat_id, "You\'ve not read these announcements from {}:\n".format(k)) await self.sendMessage(chat_id, v) else: await self.sendMessage(chat_id, 'Usage: /announcements for unread announcements, /announcements <module> <x> to retrieve the x most recent announcements') elif command == '/classestomorrow': if params: await self.sendMessage(chat_id, 'Usage: /classestomorrow') else: await self.sendMessage(chat_id, userstr.classes_tomorrow_wait) result, _ = await helper.do(user.auth_token, helper.get_classes_tomorrow) await self.sendMessage(chat_id, result) elif command == '/credits': await self.sendMessage(chat_id, userstr.credits) elif command == '/disclaimer': await self.sendMessage(chat_id, userstr.disclaimer) else: p = random.random() message = userstr.fortune1 if p > 0.5 else userstr.fortune2 await self.sendMessage(chat_id, message)
def __init__(self): """ Sigmoid constructor """ Module.__init__(self) self.s = None