Ejemplo n.º 1
0
def list():
    """Seznam cvičení"""
    
    usr = getUser() 
    
    
    if request.params.get("activate"):
        lec = Lecture.get( request.params.get("activate") )
        lec.activate()
        msg("Cvičení %s bylo zapnuto" % lec.name,"success")
        redirect(request.path)
        
    if request.params.get("deactivate"):
        lec = Lecture.get( request.params.get("deactivate") )
        lec.deactivate()
        msg("Cvičení %s bylo vypnuto" % lec.name,"success")
        redirect(request.path)        
    
    # vložení nového cvičení
    if request.forms.get("add"):
        lec = Lecture.insert( request.forms.decode().get("add"), usr.login )
        if lec:
            msg("Cvičení %s vytvořeno" % lec.name,"success")
            redirect("/lectures/edit/%i" % lec.lecture_id )
        else:
            msg("Chyba při vytváření cvičení","error")
            redirect(request.path)
        
    lectures = Lecture.getAll() if usr.inRole("master") else Lecture.getAll(usr.login) 
    
    return template("lectures", {"lectures" : lectures, "showLector": usr.inRole("master") } )
Ejemplo n.º 2
0
def find_lectures(request):
    print 'webapp.views.find_lectures'
    client = request.session['dropbox_client']
    lectures = list()
    try:
        metadata = client.metadata('/')    
        if metadata.get('contents') is None:
            print 'webapp.views.find_lectures - No Content'
            return None
        for f in metadata['contents']:
            if f['is_dir'] == True:
                if not Lecture.objects.filter(user = request.user, name = f['path']).exists():
                    l = Lecture(user = request.user, 
                                name = f['path'], 
                                date = dateparse.parse_datetime(f['modified']),
                                done = False)
                    l.save()
                    lectures.append(l)
                else:
                    print 'webapp.views.find_lectures - lecture already exists'
        pprint.pprint(lectures)
        return lectures
    except Exception as e:
        print 'Exception: webapp.views.find_lectures - ' + str(e)
        return None
Ejemplo n.º 3
0
def list():
    """Seznam cvičení"""

    usr = getUser()

    if request.params.get("activate"):
        lec = Lecture.get(request.params.get("activate"))
        lec.activate()
        msg("Cvičení %s bylo zapnuto" % lec.name, "success")
        redirect(request.path)

    if request.params.get("deactivate"):
        lec = Lecture.get(request.params.get("deactivate"))
        lec.deactivate()
        msg("Cvičení %s bylo vypnuto" % lec.name, "success")
        redirect(request.path)

    # vložení nového cvičení
    if request.forms.get("add"):
        lec = Lecture.insert(request.forms.decode().get("add"), usr.login)
        if lec:
            msg("Cvičení %s vytvořeno" % lec.name, "success")
            redirect("/lectures/edit/%i" % lec.lecture_id)
        else:
            msg("Chyba při vytváření cvičení", "error")
            redirect(request.path)

    lectures = Lecture.getAll() if usr.inRole("master") else Lecture.getAll(
        usr.login)

    return template("lectures", {
        "lectures": lectures,
        "showLector": usr.inRole("master")
    })
Ejemplo n.º 4
0
def add_lecture(request):
    print 'webapp.views.add_lecture'
    if request.method == 'POST':
        lecture = Lecture(  user = request.user, 
                            name = '/Lecture_' + request.POST.get('name'),
                            done = False)
        lecture.save()
        return render_to_response('capture.html', RequestContext(request, locals()))
    else:
        return redirect('/')
Ejemplo n.º 5
0
def get_all_lectures():

    response = requests.get('http://curric.rithmschool.com/r13/lectures/')
    soup = BeautifulSoup(response.text)
    links = []

    # Drop current lecture table
    engine = create_engine(ProductionConfig.SQLALCHEMY_DATABASE_URI)
    Lecture.__table__.drop(engine)
    db.create_all()

    for link in soup.find_all('a'):
        links.append(link.get('href'))

    for link in links:
        if 'zip' in link:
            continue
        response = requests.get('http://curric.rithmschool.com/r13/lectures/' +
                                link)
        soup = BeautifulSoup(response.text)
        if (soup.title is None):
            continue
        if (soup.title.string == 'Rithm Curriculum'):
            continue
        else:
            new_lecture = Lecture(
                title=link,
                url='http://curric.rithmschool.com/r13/lectures/' + link)
            db.session.add(new_lecture)

    db.session.commit()
Ejemplo n.º 6
0
def edit(lecture_id):
    """Úprava specifické cvičení"""

    lecture = Lecture.get(lecture_id)
    form = LectureForm(request.forms.decode(), lecture)
    user = getUser()

    if not (user.inRole("master") or lecture.lector == user.login):
        return unauthorized()

    if request.method == 'POST' and form.validate():
        try:
            lecture.update(name=form.name.data,
                           nonterminal=form.nonterminal.data)
            msg("Cvičení aktualizováno", "success")
        except Exception as e:
            msg("Chyba při aktualizaci - %s" % e, "error")

        redirect(request.path)

    try:
        text = lecture.generate()
    except Exception as e:
        text = "Došlo k chybě : \n %s      \n %s" % (type(e).__name__, e)

    return template("lectures_edit", {
        "lecture": lecture,
        "form": form_renderer(form),
        "text": text
    })
Ejemplo n.º 7
0
def edit(lecture_id):
    """Úprava specifické cvičení"""
    
    lecture = Lecture.get( lecture_id )
    form = LectureForm(request.forms.decode(), lecture)
    user = getUser()

    if not ( user.inRole("master") or lecture.lector == user.login):
        return unauthorized()

    if request.method == 'POST' and form.validate():
        try:
            lecture.update( name = form.name.data, nonterminal = form.nonterminal.data )
            msg("Cvičení aktualizováno","success")
        except Exception as e:
            msg("Chyba při aktualizaci - %s" % e, "error")
        
        redirect(request.path)    
        
    try:
        text =  lecture.generate() 
    except Exception as e:
        text = "Došlo k chybě : \n %s      \n %s" % (type(e).__name__, e)        
         
    return template("lectures_edit", {"lecture" : lecture, "form": form_renderer(form), "text": text } )    
Ejemplo n.º 8
0
def get_teachers_report_file_path(from_date,to_date,std):

    syjc = std == "SYJC"
    query = Lecture.objects(date__gte=from_date,date__lte=to_date,syjc=syjc).only("division","lecturer","subject")
    df = pd.DataFrame(json.loads(query.to_json()))

    if len(df) == 0:
        return "NA"

    df.drop("_id",axis=1,inplace=True)

    df = df.rename({"subject":"Subject","lecturer":"Lecturer","division":"Division"},axis=1)
    # Use mongoDB framework aggregation for this
    a = df.groupby(["Division","Subject","Lecturer"]).size()
    b = pd.DataFrame(a,columns=["Count"])

    subjects_mapper = get_subjects_mapper()
    lecturers_mapper = get_lecturers_mapper()
    b.index = b.index.map(lambda x: index_mapper(x,subjects_mapper,lecturers_mapper))

    fd = from_date.strftime("%d_%m_%y")
    td = to_date.strftime("%d_%m_%y")

    in_memory_fp = BytesIO()
    b.to_excel(in_memory_fp)
    in_memory_fp.seek(0,0)
    file = in_memory_fp
    file_path = f"teachers_reports/{std}__{fd}__{td}.xlsx"
    default_storage.delete(file_path)
    file_name = default_storage.save(file_path, file)

    return "media/" + file_path
Ejemplo n.º 9
0
def get_lectures_data(date,std):
    syjc = std == "SYJC"
    query = Lecture.objects(date=date,syjc=syjc).only("division","subject","lecturer","date","start_time","end_time","num_students")
    data = []
    for lec in query:
        obj = {}
        obj["division"] = lec.division
        obj["subject"] = lec.subject
        obj["lecturer"] = lec.lecturer
        obj["date"] = lec.date
        obj["start_time"] = lec.start_time
        obj["end_time"] = lec.end_time
        obj["num_students"] = lec.num_students
        data.append(obj)

    df = pd.DataFrame(data)

    if len(df) == 0:
        return None

    df["date"] = df["date"].map(lambda x: x.strftime("%d/%m/%y"))
    df["start_time"] = df["start_time"].map(lambda x: str(x)[:2] + ":" + str(x)[2:])
    df["end_time"] = df["end_time"].map(lambda x: str(x)[:2] + ":" + str(x)[2:])
    df = df.rename(columns={"division":"Division","subject":"Subject","lecturer":"Lecturer","date":"Date","start_time":"From","end_time":"To","num_students":"Students"})
    df = df[["Division","Subject","Lecturer","Date","From","To","Students"]]

    df["Subject"] = df["Subject"].map(get_subjects_mapper())
    df["Lecturer"] = df["Lecturer"].map(get_lecturers_mapper())

    df = df.to_html(classes=["mystyle table table-bordered table-striped"],index=False,table_id="mytable")
    df = re.sub('<tbody>', '<tbody id="log">',df)

    replace = """
        <thead>
            <tr class="filters" style="text-align: right;">
                <th><input type="text" class="form-control" placeholder="Division" disabled></th>
                <th><input type="text" class="form-control" placeholder="Subject" disabled></th>
                <th><input type="text" class="form-control" placeholder="Lecturer" disabled></th>
                <th><input type="text" class="form-control" placeholder="Date" disabled></th>
                <th><input type="text" class="form-control" placeholder="From" disabled></th>
                <th><input type="text" class="form-control" placeholder="To" disabled></th>
                <th><input type="text" class="form-control" placeholder="Students" disabled></th>
            </tr>
        </thead>
    """

    df = re.sub(r"<thead>.+<\/thead>",replace,df,flags=re.S)
    df = df.replace("\\n","<br>")
    return df
Ejemplo n.º 10
0
def get_students_report_file_path(from_date,to_date,division,std):
    syjc = std == "SYJC"
    filtered = Lecture.objects(Q(date__lte=to_date) & Q(date__gte=from_date) & Q(division=division.name) & Q(syjc=syjc)).only("present")
    pipeline = [
        {
                "$project":{
                        "record": {
                                    "$objectToArray":"$present"
                                }
                        }
        },
        {
                "$unwind" : "$record"
        },
        {
                "$group" :{
                            "_id":"$record.k",
                            "count":{"$sum":1},
                            "present":{
                                        "$sum": {"$cond" : [ "$record.v", 1, 0 ] }
                                    }
                        }
        }
        ]

    ans = filtered.aggregate(pipeline)
    data = [i for i in ans]
    df = pd.DataFrame(data)

    if len(df) == 0:
        return "NA"

    df = df.rename(columns={"_id":"Roll","count":"Total","present":"Present"})
    df = df.sort_values("Roll")

    fd = from_date.strftime("%d_%m_%y")
    td = to_date.strftime("%d_%m_%y")

    in_memory_fp = BytesIO()
    df.to_excel(in_memory_fp,index=False)
    in_memory_fp.seek(0,0)
    file = in_memory_fp
    file_path = f"students_reports/{division}/{fd}__{td}.xlsx"
    default_storage.delete(file_path)
    file_name = default_storage.save(file_path, file)

    return "media/" + file_path
Ejemplo n.º 11
0
async def api_create_lecture(request, *, title, tim, place, url, content):
    check_admin(request)
    if not title or not title.strip():
        raise APIValueError('title', 'title cannot be empty.')
    if not tim or not tim.strip():
        raise APIValueError('tim', 'tim cannot be empty.')
    if not place or not place.strip():
        raise APIValueError('place', 'place cannot be empty.')
    if not url or not url.strip():
        raise APIValueError('url', 'url cannot be empty.')
    if not content or not content.strip():
        raise APIValueError('content', 'content cannot be empty.')
    lecture = Lecture(title=title.strip(),
                      tim=tim.strip(),
                      place=place.strip(),
                      url=url.strip(),
                      content=content.strip())
    await lecture.save()
    return lecture
Ejemplo n.º 12
0
def delete(lecture_id):
    """Smaže cvičení"""

    lecture = Lecture.get( lecture_id )
    user = getUser()

    if not ( user.inRole("master") or lecture.lector == user.login):
        return unauthorized()


    answer = request.forms.get("answer") 
    if answer:
        if answer == "Ne": redirect("/lectures")
        if answer == "Ano":
            lecture.remove()
            msg("Cvičení smazáno","success")
            redirect("/lectures")
            
    return template("question", {"question":"Skutečně chcete smazat cvičení '%s'" % lecture.name } )    
Ejemplo n.º 13
0
def delete(lecture_id):
    """Smaže cvičení"""

    lecture = Lecture.get(lecture_id)
    user = getUser()

    if not (user.inRole("master") or lecture.lector == user.login):
        return unauthorized()

    answer = request.forms.get("answer")
    if answer:
        if answer == "Ne": redirect("/lectures")
        if answer == "Ano":
            lecture.remove()
            msg("Cvičení smazáno", "success")
            redirect("/lectures")

    return template(
        "question",
        {"question": "Skutečně chcete smazat cvičení '%s'" % lecture.name})
Ejemplo n.º 14
0
def missedLectureCheck(user):
	day = datetime.date.today().weekday()
	hour = datetime.datetime.now().hour
	minute = datetime.datetime.now().minute
	if minute > 45:
		hour = hour + 1

	userQuery = User.query(User.userid == user.user_id())
	#gets the current user
	for userEntity in userQuery:
		#loops through the weeks that have occurred so far
		for i in range(1, getCurrentWeek()):
			#loops through the users lectures
			for lecture in userEntity.lectures:
				#sets the default value to not checked
				checked = False
				#loops through the lectures in history
				for attlecture in userEntity.history:
					#checks for a match
					if attlecture.week == i and attlecture.day == lecture.day and attlecture.time == lecture.time:
							#if one is found, there is an entry in the history so don't need to worry
							checked = True
				if not checked:
					#else we need to add that the user missed that lecture to the history
					missedLecture = Lecture(module=lecture.module, title=lecture.title, location=lecture.location, day=lecture.day, time=lecture.time, duration=lecture.duration)
					missedLecture.attended = False
					missedLecture.week = i
					userEntity.history.append(missedLecture)
					userEntity.streak = 0

		#does the same check for the current week
		for lecture in userEntity.lectures:
			#only applies to lectures that have already occured
			if lecture.day < day or (lecture.day == day and lecture.time+lecture.duration <= hour):
				#sets the default value to False
				checked = False
				for attlecture in userEntity.history:
					if attlecture.week == getCurrentWeek() and attlecture.day == lecture.day and attlecture.time == lecture.time:
						checked = True
				if not checked:
					missedLecture = Lecture(module=lecture.module, title=lecture.title, location=lecture.location, day=lecture.day, time=lecture.time, duration=lecture.duration)
					missedLecture.attended = False
					missedLecture.week = getCurrentWeek()
					userEntity.history.append(missedLecture)
					userEntity.streak = 0

		userEntity.put()
Ejemplo n.º 15
0
	def post(self):
		user = users.get_current_user()
		if user:
			missedLectureCheck(user)
			#logging.info(self.request.body)
			data = json.loads(self.request.body)
			latitude = data["lat"]
			longitude = data["lon"]

			day = datetime.date.today().weekday()
			hour = datetime.datetime.now().hour
			minute = datetime.datetime.now().minute
			if minute > 45:
				hour = hour + 1

			thisLecture = None
			thisUser = None
			poly = []			

			userQuery = User.query(User.userid == user.user_id())
			for userEntity in userQuery:
				thisUser = userEntity
				for lecture in userEntity.lectures:
					#checks for a lecture that matches the current day and time
					if(lecture.day == day and (lecture.time <= hour and lecture.time + lecture.duration > hour)):
						thisLecture = lecture
						locations = lecture.location.split(";");
						for location in locations:
							#need to make multiple polys for each lecture, for each possible location
							buildingQuery = Building.query(Building.number == location)
							for building in buildingQuery:
								buildingCoords = []
								for coordinate in building.coordinates:
									c = (coordinate.lon, coordinate.lat)
									buildingCoords.append(c)
								poly.append(buildingCoords)

			noLecture = False
			checkedIn = False

			#checks if there is no current lecture
			if thisLecture is None:
				noLecture = True
				self.response.out.write(json.dumps({"valid":3}))
			else:
				#checks if the user has already checked in to this lecture
				for pastLecture in thisUser.history:
					if pastLecture.week == getCurrentWeek() and pastLecture.time == thisLecture.time and pastLecture.day == thisLecture.day:
						checkedIn = True
				if checkedIn:
					self.response.out.write(json.dumps({"valid":4}))	
			if not checkedIn and not noLecture:
				inBuilding = False
				for coords in poly:
					#checks user is at the correct location(s) for the lecture
					if not inBuilding and point_in_poly(longitude, latitude, coords):
						inBuilding = True

						attendedLecture = Lecture(module=thisLecture.module, title=thisLecture.title, location=thisLecture.location, day=thisLecture.day, time=thisLecture.time, duration=thisLecture.duration)

						attendedLecture.attended = True
						attendedLecture.week = getCurrentWeek()

						checkin = CheckIn(student=thisUser, lecture=attendedLecture)
						checkin.put()

						thisUser.history.append(attendedLecture)

						completedChalls = challengecheck(thisUser, attendedLecture, checkin)

						pointsEarned = 0
						
						challIcons = []
						challTitles = []
						challDescs = []
						challPoints = []

						for challenge in completedChalls:
							pointsEarned += challenge.points
							challTitles.append(challenge.title)
							challIcons.append(challenge.badge.iconName)
							challDescs.append(challenge.description)
							challPoints.append(challenge.points)

						thisUser.score = thisUser.score + 10 + thisUser.streak + pointsEarned
						thisUser.streak = thisUser.streak + 1
						thisUser.count = thisUser.count + 1

						thisUser.put()
						
						self.response.out.write(json.dumps({"valid":1, "score":thisUser.score, "count":thisUser.count, "streak":thisUser.streak, "icons":challIcons, "titles":challTitles, "points":challPoints, "descriptions":challDescs}))
				if not inBuilding: 
					self.response.out.write(json.dumps({"valid":2}))	
		else:
			self.redirect(users.create_login_url(self.request.uri))