Пример #1
0
def getCoursesByUser(token, userId):
    """
    <span class="card-title">This Call will return an array of all Courses of a certain User</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'<br>
        - userId: 1234354543<br>
    <br>
    <br>
    <b>Payload</b><br>
     - NONE <br>
    <br>
    <br>
    <b>Response</b>
    <br>
    200 - JSON Array, Example:<br>
    [<br>
    {
                'title': 'JCE',<br>
                'email_ending': '@post.jce.ac.il',<br>
                'master_user_id': 123453433341, (User that created the campus)<br>
                'avatar_url': 'http://some.domain.com/imagefile.jpg',<br>
                'id' : 1234567890<br>
    },<br>
    ....<br>
    {<br>
    ...<br>
    }req<br>
    ]<br>
    <br>
    403 - Invalid Token<br>
    """

    user = get_user_by_token(token)
    if user is None:
        return bad_request("Bad user Token")

    try:
        otherUser = User.get_by_id(int(userId))
    except Exception as e:
        return bad_request("Bad id format")

    otherUser = User.get_by_id(int(userId))
    if otherUser is None:
        return bad_request("Bad user Id")

    arr = []
    for i in otherUser.courses_id_list:
        print i
        course = Course.get_by_id(int(i))
        arr.append(dict(json.loads(course.to_JSON())))

    if len(arr) != 0:
        return Response(response=json.dumps(arr),
                        status=200,
                        mimetype="application/json")
    else:
        return Response(response='[]',
                        status=200,
                        mimetype="application/json")
Пример #2
0
 def publishTopic(self, topic):
     topicFolder = os.getcwd()
     courseFolder, topicFolderName = os.path.split(topicFolder)
     os.chdir(courseFolder)
     course = Course()
     os.chdir(topicFolder)
     self.publishTopicInCourse(course, topic)
Пример #3
0
    def get(self, username):
        """display profile of user with username, if None, display logged in user
        """
        mode = self.request.get('mode')
        upload_url = ""

        if mode == 'add_project':
            template = 'profile/add_project.html'
            upload_url = blobstore.create_upload_url(
                '/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
        elif mode == 'edit_project':
            template = 'profile/edit_project.html'
            upload_url = blobstore.create_upload_url(
                '/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
        elif mode == 'edit':
            template = 'profile/edit.html'
        else:
            template = 'profile/profile.html'

        user = User.get_user(username)

        if not user:
            user = User.save(username, '{}@someplace.com'.format(username),
                             'some long password')

        gravatar = user.avatar_url
        friends = []

        if user:
            all, ic, cc = self.organize_courses_for(user)

            if user.dob:
                dob = user.dob.strftime('%m/%d/%Y')
            else:
                dob = None

            projects = Project.get_projects_by_ids(user.projects)

            context = {
                'user': user,
                'dob': dob,
                'username': username,
                'gravatar': gravatar,
                'friends': friends,
                'friend_btn': False,
                'courses_all': Course.courses_to_dict(),
                'courses_completed': cc,
                'courses_incomplete': ic,
                'projects': projects,
                'upload_url': upload_url,
                'errors': {}
            }

            self.render(template, context)
        else:
            self.redirect('/logout')
Пример #4
0
    def get(self, username):
        """display profile of user with username, if None, display logged in user
        """
        mode = self.request.get('mode')
        upload_url = ""

        if mode == 'add_project':
            template = 'profile/add_project.html'
            upload_url = blobstore.create_upload_url('/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
        elif mode == 'edit_project':
            template = 'profile/edit_project.html'
            upload_url = blobstore.create_upload_url('/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
        elif mode == 'edit':
            template = 'profile/edit.html'
        else:
            template = 'profile/profile.html'

           

        user = User.get_user(username)

        if not user:
            user = User.save(username, '{}@someplace.com'.format(username), 'some long password')


        gravatar = user.avatar_url
        friends = []

        

        if user:
            all, ic, cc = self.organize_courses_for(user)

            if user.dob:
                dob = user.dob.strftime('%m/%d/%Y')
            else:
                dob = None

            projects = Project.get_projects_by_ids(user.projects)

            context = {'user': user,
                       'dob': dob,
                       'username': username,
                       'gravatar': gravatar,
                       'friends': friends,
                       'friend_btn': False,
                       'courses_all': Course.courses_to_dict(),
                       'courses_completed': cc,
                       'courses_incomplete': ic,
                       'projects': projects,
                       'upload_url': upload_url,
                       'errors': {}}

            self.render(template, context)
        else:
            self.redirect('/logout')
Пример #5
0
 def add_course(self, name, subject, language, author):
     course = Course()
     course.name = name
     course.subject = subject
     course.language = language
     course.author = author
     self.session.add(course)
Пример #6
0
def getAllCoursesByCampus(token, campusId):
    """
    <span class="card-title">>This Call will return an array of all courses in a given campus</span>
    <br>
    <b>Route Parameters</b><br>
        - campusId: 1234567890
    <br>
    <br>
    <b>Payload</b><br>
     - NONE
    <br>
    <br>
    <b>Response</b>
    <br>
    200 - JSON Example:<br>
    <code>
        {<br>
        'courseName': 'Advance Math',<br>
        'campusId': 1234567890,<br>
        'startDate': '2015-14-3'<br>
        'endDate': '2015-29-6'<br>
        'taskFlag': 'False'<br>
        'id' : 1234567890<br>

        }
    </code>
    <br>
    """

    if get_user_by_token(token) is None:
        return bad_request("Bad User Token")

    arr = []
    query = Course.all()

    try:
        query.filter("campusId = ", int(campusId))
    except Exception as e:
        return bad_request("Bad id format")


    for c in query.run():
        arr.append(dict(json.loads(c.to_JSON())))
    print arr
    if len(arr) != 0:
        return Response(response=json.dumps(arr),
                        status=200,
                        mimetype="application/json")
    else:
        return Response(response=[],
                        status=200,
                        mimetype="application/json")
	def post(self):
		course_id = self.request.get('course_id')
		course_name = self.request.get('course_name')
		class_per_week = int(self.request.get('class_per_week'))
		class_distribution_1 = int(self.request.get('class_distribution_1') or 0)
		class_distribution_2 = int(self.request.get('class_distribution_2') or 0)
		class_distribution_3 = int(self.request.get('class_distribution_3') or 0)
		class_distribution_4 = int(self.request.get('class_distribution_4') or 0)
		class_distribution = {
			"1": class_distribution_1,
			"2": class_distribution_2,
			"3": class_distribution_3,
			"4": class_distribution_4
		}

		course = Course(
			key_name = course_id,
			course_name = course_name,
			class_per_week = class_per_week,
			class_distribution = str(class_distribution)
		)
		course.put()
		self.response.write("success")
Пример #8
0
    def createNewAttempts(self):
        courses = Course.query()
        attempts = []
        for course in courses:
            k = self.u1.add_course(course.key)
            attempts.append(k)

        courses = self.u1.get_all_courses()
        try:
            o = [c for c in courses if c.course == ndb.Key(Course, 'udacitycs215')][0]
        except IndexError:
            raise ValueError("Test data is wrong")
        o.completed = False
        o.put()
        return attempts
Пример #9
0
def deleteCourse(token, courseId):
    """
    <span class="card-title">This Call will delete a specific Course</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'<br>
        - courseid: 'courseid'
    <br>
    <br>
    <b>Payload</b><br>
     - NONE <br>
    <br>
    <br>
    <b>Response</b>
    <br>
    202 - Deleted Course
    <br>
    ....<br>
    {<br>
    ...<br>
    }req<br>

    ]<br>
    400 - no such Course
    <br>
    403 - Invalid token or not a lecturer or lecturer is not owner of Course!<br>
    """

    if not is_lecturer(token):  #todo: change to lecturer id
        return forbidden("Invalid token or not a lecturer!")

    user = get_user_by_token(token)

    try:
        c = Course.get_by_id(int(courseId))
    except Exception as e:
        return bad_request("Bad id format")

    if c is None:
        return bad_request("no such course")


    if c.master_id == user.key().id():
        db.delete(c)
        db.save
        return accepted("course deleted")

    return forbidden("lecturer is not owner of course")
Пример #10
0
    def post(self, username):
        fields = self.get_params_dict((
            'real_name',
            'email',
            'short_about',
            'dob',
            'tools',
            'password',
            'password_confirm',
            'notify_on_msg'
            ))

        iclasses = self.request.get_all('classes_inprog')
        cclasses = self.request.get_all('classes_completed')
        fields['iclasses'] = iclasses
        fields['cclasses'] = cclasses
        fields['username'] = username

        user = Key(User, username).get()

        errors = self.clean_user_data(user, **fields)

        context = {
            'errors': errors,
            'user': user
        }

        if not errors:
            user.update(**fields)
            self.redirect('/{}'.format(username))
        else:

            if user.dob:
                dob = user.dob.strftime('%m/%d/%Y')
            else:
                dob = None
            all, ic, cc = self.organize_courses_for(user)
            context['courses_all'] = Course.courses_to_dict()
            context['courses_completed'] = cc
            context['courses_incomplete'] = ic
            context['dob'] = dob
            context['username'] = username
            context['gravatar'] = user.avatar_url
            context['friends'] = []
            context['friend_btn'] = False
            context['errors'] = errors
            self.render('profile/edit.html'.format(username), context)
Пример #11
0
def joinCourse(token, courseId):
    """
    <span class="card-title">This call will add the user (by token) to a specific course</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'<br>
        - courseId: 123456789
    <br>
    <br>
    <b>Payload</b><br>
     - None <br>
    <br>
    <b>Response</b>
    <br>
    202 - Accepted
    <br>
    400 - Bad Request
    <br>
    403 - Invalid token or not a lecturer
    """

    user = get_user_by_token(token)
    if user is None:
        return bad_request("Wrong user Token")

    try:
        course = Course.get_by_id(int(courseId))
    except Exception as e:
        return bad_request("Bad id format")

    if course is None:
        return bad_request("No such course")

    if str(user.key().id()) in course.membersId:
        return bad_request("User is already member in Course")

    course.membersId.append(str(user.key().id()))
    user.courses_id_list.append(str(course.key().id()))

    db.put(course)
    db.put(user)
    db.save

    return Response(response=course.to_JSON(),
                        status=202,
                        mimetype="application/json")
Пример #12
0
    def createNewAttempts(self):
        courses = Course.query()
        attempts = []
        for course in courses:
            k = self.u1.add_course(course.key)
            attempts.append(k)

        courses = self.u1.get_all_courses()
        try:
            o = [
                c for c in courses
                if c.course == ndb.Key(Course, 'udacitycs215')
            ][0]
        except IndexError:
            raise ValueError("Test data is wrong")
        o.completed = False
        o.put()
        return attempts
Пример #13
0
    def get(self, username):
        """display profile of user with username, if None, display logged in user
        """
        mode, = self.get_params(['mode'])


        if mode != 'edit':
            template = 'profile/profile.html'
        else:
            template = 'profile/edit.html'

        user = User.get_user(username)

        if not user:
            user = User.save(username, '{}@someplace.com'.format(username), 'some long password')


        gravatar = user.avatar_url
        friends = []

        if user:
            all, ic, cc = self.organize_courses_for(user)

            if user.dob:
                dob = user.dob.strftime('%m/%d/%Y')
            else:
                dob = None


            context = {'user': user,
                       'dob': dob,
                       'username': username,
                       'gravatar': gravatar,
                       'friends': friends,
                       'friend_btn': False,
                       'courses_all': Course.courses_to_dict(),
                       'courses_completed': cc,
                       'courses_incomplete': ic,
                       'errors': {}}

            self.render(template, context)
        else:
            self.redirect('/logout')
Пример #14
0
    def get(self, username):
        """display profile of user with username, if None, display logged in user
        """
        mode, = self.get_params(['mode'])

        if mode != 'edit':
            template = 'profile/profile.html'
        else:
            template = 'profile/edit.html'

        user = User.get_user(username)

        if not user:
            user = User.save(username, '{}@someplace.com'.format(username),
                             'some long password')

        gravatar = user.avatar_url
        friends = []

        if user:
            all, ic, cc = self.organize_courses_for(user)

            if user.dob:
                dob = user.dob.strftime('%m/%d/%Y')
            else:
                dob = None

            context = {
                'user': user,
                'dob': dob,
                'username': username,
                'gravatar': gravatar,
                'friends': friends,
                'friend_btn': False,
                'courses_all': Course.courses_to_dict(),
                'courses_completed': cc,
                'courses_incomplete': ic,
                'errors': {}
            }

            self.render(template, context)
        else:
            self.redirect('/logout')
Пример #15
0
def getCoursesByID(token, courseId):
    """
    <span class="card-title">This Call will return A Course By ID</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'<br>
        - courseId: 1234354543<br>
    <br>
    <br>
    <b>Payload</b><br>
     - NONE <br>
    <br>
    <br>
    <b>Response</b>
    <br>
    200 - JSON Array, Example:<br>
    { <br>
                'title': 'JCE',<br>
                'email_ending': '@post.jce.ac.il',<br>
                'master_user_id': 123453433341, (User that created the campus)<br>
                'avatar_url': 'http://some.domain.com/imagefile.jpg',<br>
                'id' : 1234567890<br>
    }<br>
    <br>
    403 - Invalid Token<br>
    """

    user = get_user_by_token(token)
    if user is None:
        return bad_request("Bad user Token")

    try:
        course = Course.get_by_id(int(courseId))
    except Exception as e:
        return bad_request("Bad id format")

    if course is None:
        return bad_request("Bad Course Id")

    return Response(response=course.to_JSON(),
                    status=200,
                    mimetype="application/json")
Пример #16
0
 def to_JSON(self):
     user = User.get_by_id(self.master_id)
     if self.isProject:
         group = Project.get_by_id(self.groupId)
     else:
         group = Course.get_by_id(self.groupId)
     data = {
             'groupId' : self.groupId,
             'message' : self.message,
             'date' : {
                 'year': self.msgDate.year,
                 'month': self.msgDate.month,
                 'day': self.msgDate.day,
                 'hour': self.msgDate.hour,
                 'minute': self.msgDate.minute
             },
             'id' : self.key().id(),
             'master_id' : self.master_id,
             'isProject' : self.isProject,
             'user': json.loads(user.to_JSON()),
             'group': json.loads(group.to_JSON())
     }
     return json.dumps(data)
Пример #17
0
    def post(self, username):
        fields = self.get_params_dict(
            ('real_name', 'email', 'short_about', 'dob', 'tools', 'password',
             'password_confirm', 'notify_on_msg'))

        iclasses = self.request.get_all('classes_inprog')
        cclasses = self.request.get_all('classes_completed')
        fields['iclasses'] = iclasses
        fields['cclasses'] = cclasses
        fields['username'] = username

        user = Key(User, username).get()

        errors = self.clean_user_data(user, **fields)

        context = {'errors': errors, 'user': user}

        if not errors:
            user.update(**fields)
            self.redirect('/{}'.format(username))
        else:

            if user.dob:
                dob = user.dob.strftime('%m/%d/%Y')
            else:
                dob = None
            all, ic, cc = self.organize_courses_for(user)
            context['courses_all'] = Course.courses_to_dict()
            context['courses_completed'] = cc
            context['courses_incomplete'] = ic
            context['dob'] = dob
            context['username'] = username
            context['gravatar'] = user.avatar_url
            context['friends'] = []
            context['friend_btn'] = False
            context['errors'] = errors
            self.render('profile/edit.html'.format(username), context)
Пример #18
0
def home():
    form = AddUserForm()
    if form.validate_on_submit():
        results = request.form

        global courses

        course_name = results['subject']
        course_number = results['course_no']
        course_section = results['course_section']

        new_course = Course(course_name, course_number, course_section)

        course_status = is_course_available(
            new_course
        )  # checks if course is already available or if it is on SSC
        if course_status != False:
            if course_status == True:
                return render_template('error.html',
                                       message='Course is already available!')
            elif course_status == 'Course does not exist!':
                return render_template('error.html', message=course_status)

        student_name = results['name']
        student_surname = results['surname']
        student_email = results['email']

        student = Student(student_name, student_surname, student_email)

        # gets the course from courses if the course exists, otherwise returns None
        existing_course = next(
            (course for course in courses if course == new_course), None)
        try:
            if existing_course is not None:
                add_student_to_course(existing_course, student)
            else:
                num_courses_in_db = get_number_of_courses()

                # Checks if the db and list is synchronized
                if len(courses) == num_courses_in_db:
                    courses.append(new_course)
                    add_student_to_course(new_course, student)
                else:
                    courses = get_courses()
                    existing_course = next(
                        (course for course in courses if course == new_course),
                        None)
                    if existing_course is not None:
                        add_student_to_course(existing_course, student)
                    else:
                        courses.append(new_course)
                        add_student_to_course(new_course, student)

        except StudentExistsException:
            return render_template(
                'error.html',
                message='A student with this email address exists.')
        except Exception as e:
            logging.error('Registration error', exc_info=True)
            return render_template(
                'error.html',
                message=
                'An error occurred during registration. Please try again.')
        return render_template('result.html')

    return render_template('seat_checker.html', form=form)
Пример #19
0
def create_course(token):
    """
    <span class="card-title">This call will create a new course in the DB</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'
    <br>
    <br>
    <b>Payload</b><br>
     - JSON Object, Example: <br>
         {<br>
         'courseName': 'Advance Math',<br>
         'campusId': 1234567890,<br>
         'startDate': {'year': 2015, 'month' : 4, 'day' : 3},<br>
         'endDate': {'year': 2016, 'month' : 5, 'day' : 14}<br>
        }<br>
    <br>
    <br>
    <b>Response</b>
    <br>
    201 - Created
    <br>
    400 - Bad Request
    <br>
    403 - Invalid token or not a lecturer
    """
    if not request.data:
        return bad_request("no data")
    if not is_lecturer(token):  #todo: change to lecturer id
        return forbidden("Invalid token or not a lecturer!")

    user = get_user_by_token(token)

    #try to parse payload
    try:
        payload = json.loads(request.data)
    except Exception as e:
        return bad_request("incorrect JSON format")

    try:
        start_date = datetime.date(payload['startDate']['year'],payload['startDate']['month'],payload['startDate']['day'])
        end_date = datetime.date(payload['endDate']['year'],payload['endDate']['month'],payload['endDate']['day'])

        if end_date <= start_date:
            return bad_request("end date cant be before (or same day) start date")

        course = Course(courseName=payload['courseName'], campusId=payload['campusId'], master_id=user.key().id(),
                        startDate=start_date, endDate=end_date)
        #check if name already exists
        try:
            query = Course.all()
            query.filter('campusId = ', payload['campusId'])
            query.filter("courseName = ", payload['courseName'])
            for c in query.run(limit=1):
                return forbidden("Course with same name already exists")
        except Exception as e:
            print e


    except Exception as e:
        print e
        return bad_request(2)

    #add user to course membersId list
    course.membersId.append(str(user.key().id()))
    db.put(course)

    #add course to user course list
    user.courses_id_list.append(str(course.key().id()))
    db.put(user)

    db.save
    return Response(response=course.to_JSON(),
                                status=201,
                                mimetype="application/json")
Пример #20
0
from models.Course import Course
from models.Concurrent import Concurrent
from models.Voiture import Voiture
from models.Pilote import Pilote
from models.Circuit import Circuit
import datetime

if __name__ == "__main__":

    spa = Circuit("Spa", 7004, 20)

    c = Course("TechnoBel", spa, 50, 42)

    v_nico = Voiture("Audi", "R8", 180, 300)
    p_nico = Pilote("Hello", "Nico", datetime.date(1995, 1, 1))
    nico = Concurrent(7, p_nico, v_nico)
    c.ajouter_participant(nico)

    v_mh = Voiture("Tesla", "S", 220, 240)
    p_mh = Pilote("World", "Marc-Henry", datetime.date(1993, 1, 1), 50)
    mh = Concurrent(21, p_mh, v_mh)
    c.ajouter_participant(mh)

    c.ajouter_participant(Concurrent(10, Pilote("F", "Francois", datetime.date(1990, 1, 1), 70), Voiture("Porsche", "911", 220, 230)))

    c.demarrer_course()

    for concurrent in c.concurrents:
        print(concurrent.nom, datetime.timedelta(seconds=concurrent.temps_total))

    winner = c.obtenir_vainqueur()
Пример #21
0
    def post(self, username):
        mode = self.request.get('mode')
        if mode == 'add_project':
            blob_info = None
            fileerror = 'Screenshot is mandatory'
            upload_files = self.get_uploads('screenshot')
            if upload_files:
                blob_info = upload_files[0]
                if 'image' in blob_info.content_type:
                    screenshot = blob_info.key()
                    screenshot_url = images.get_serving_url(screenshot)
                    fileerror = ''
                else:
                    # uploaded file wasn't an images, hence remove from the blobstore
                    blobstore.delete(blob_info.key())
                    fileerror = 'Invalid image type'
            else:
                fileerror = 'Please provide a screenshot of your project (max size: 1MB)'

            title = self.request.get('title').strip()
            titleerror = validate_project_title(title)

            url = self.request.get('url').strip()
            urlerror = validate_project_url(url)

            short_description = self.request.get('short_description').strip()
            sderror = validate_project_short_description(short_description)
            
            if titleerror or urlerror or sderror or fileerror:
                if blob_info and not fileerror:
                    # blob was okay but validation of some other field failed
                    # hence remove it to avoid orphaned entry
                    # also remove the serving url
                    Project.remove_screenshot_blob(blob_info.key())

                user = User.get_user(username)
                template = 'profile/add_project.html'
                upload_url = blobstore.create_upload_url('/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
                context = { 'user': user,
                            'username': username,
                            'title': title,
                            'url': url,
                            'short_description': short_description,
                            'upload_url': upload_url,
                            'titleerror': titleerror,
                            'urlerror': urlerror,
                            'sderror': sderror,
                            'fileerror': fileerror}
                self.render(template, context)
                return
            else:
                user = User.get_user(username)
                project_id = Project.add_project(title=title, screenshot=screenshot,
                    screenshot_url=screenshot_url, url=url, short_description=short_description, 
                    author=user.key)

                User.add_project(username, project_id)
                
        elif mode == 'edit_project':
            blob_info = None
            screenshot = None
            screenshot_url = None
            fileerror = ''

            upload_files = self.get_uploads('screenshot')
            if upload_files:
                blob_info = upload_files[0]
                if 'image' in blob_info.content_type:
                    screenshot = blob_info.key()
                    screenshot_url = images.get_serving_url(screenshot)
                else:
                    # uploaded file wasn't an images, hence remove from the blobstore
                    blobstore.delete(blob_info.key())
                    fileerror = 'Invalid image type'

            project_id = self.request.get('projects_dropdown')

            title = self.request.get('title').strip()
            titleerror = validate_project_title(title)

            url = self.request.get('url').strip()
            urlerror = validate_project_url(url)

            short_description = self.request.get('short_description').strip()
            sderror = validate_project_short_description(short_description)

            if titleerror or urlerror or sderror or fileerror:
                if blob_info and not fileerror:
                    # same as above
                    Project.remove_screenshot_blob(blob_info.key())
                
                user = User.get_user(username)
                projects = Project.get_projects_by_ids(user.projects)
                upload_url = blobstore.create_upload_url('/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
                template = 'profile/edit_project.html'
                context = { 'user': user,
                            'username': username,
                            'title': title,
                            'url': url,
                            'short_description': short_description,
                            'projects': projects,
                            'upload_url': upload_url,
                            'titleerror': titleerror,
                            'urlerror': urlerror,
                            'sderror': sderror,
                            'fileerror': fileerror }
                self.render(template, context)
                return
            else:
                Project.update_project(project_id, title=title, screenshot=screenshot, 
                    screenshot_url=screenshot_url, url=url, short_description=short_description)
        elif mode == 'remove_project':
            project_id = self.request.get('project_id')
            Project.remove_project(project_id)
            User.remove_project(username, project_id)
            
        elif mode == 'edit':
            fields = self.get_params_dict((
                'real_name',
                'email',
                'short_about',
                'dob',
                'tools',
                'password',
                'password_confirm',
                'notify_on_msg'
                ))
            logging.error(fields)

            iclasses = self.request.get_all('classes_inprog')
            cclasses = self.request.get_all('classes_completed')
            fields['iclasses'] = iclasses
            fields['cclasses'] = cclasses
            fields['username'] = username

            user = Key(User, username).get()

            errors = self.clean_user_data(user, **fields)

            context = {
                'errors': errors,
                'user': user
            }

            if not errors:
                user.update(**fields)
                self.redirect('/{}'.format(username))
            else:

                if user.dob:
                    dob = user.dob.strftime('%m/%d/%Y')
                else:
                    dob = None
                all, ic, cc = self.organize_courses_for(user)
                context['courses_all'] = Course.courses_to_dict()
                context['courses_completed'] = cc
                context['courses_incomplete'] = ic
                context['dob'] = dob
                context['username'] = username
                context['gravatar'] = user.avatar_url
                context['friends'] = []
                context['friend_btn'] = False
                context['errors'] = errors
                self.render('profile/edit.html'.format(username), context)
                return
        self.redirect('/'+username)
Пример #22
0
    def post(self, username):
        mode = self.request.get('mode')
        if mode == 'add_project':
            blob_info = None
            fileerror = 'Screenshot is mandatory'
            upload_files = self.get_uploads('screenshot')
            if upload_files:
                blob_info = upload_files[0]
                if 'image' in blob_info.content_type:
                    screenshot = blob_info.key()
                    screenshot_url = images.get_serving_url(screenshot)
                    fileerror = ''
                else:
                    # uploaded file wasn't an images, hence remove from the blobstore
                    blobstore.delete(blob_info.key())
                    fileerror = 'Invalid image type'
            else:
                fileerror = 'Please provide a screenshot of your project (max size: 1MB)'

            title = self.request.get('title').strip()
            titleerror = validate_project_title(title)

            url = self.request.get('url').strip()
            urlerror = validate_project_url(url)

            short_description = self.request.get('short_description').strip()
            sderror = validate_project_short_description(short_description)

            if titleerror or urlerror or sderror or fileerror:
                if blob_info and not fileerror:
                    # blob was okay but validation of some other field failed
                    # hence remove it to avoid orphaned entry
                    # also remove the serving url
                    Project.remove_screenshot_blob(blob_info.key())

                user = User.get_user(username)
                template = 'profile/add_project.html'
                upload_url = blobstore.create_upload_url(
                    '/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
                context = {
                    'user': user,
                    'username': username,
                    'title': title,
                    'url': url,
                    'short_description': short_description,
                    'upload_url': upload_url,
                    'titleerror': titleerror,
                    'urlerror': urlerror,
                    'sderror': sderror,
                    'fileerror': fileerror
                }
                self.render(template, context)
                return
            else:
                user = User.get_user(username)
                project_id = Project.add_project(
                    title=title,
                    screenshot=screenshot,
                    screenshot_url=screenshot_url,
                    url=url,
                    short_description=short_description,
                    author=user.key)

                User.add_project(username, project_id)

        elif mode == 'edit_project':
            blob_info = None
            screenshot = None
            screenshot_url = None
            fileerror = ''

            upload_files = self.get_uploads('screenshot')
            if upload_files:
                blob_info = upload_files[0]
                if 'image' in blob_info.content_type:
                    screenshot = blob_info.key()
                    screenshot_url = images.get_serving_url(screenshot)
                else:
                    # uploaded file wasn't an images, hence remove from the blobstore
                    blobstore.delete(blob_info.key())
                    fileerror = 'Invalid image type'

            project_id = self.request.get('projects_dropdown')

            title = self.request.get('title').strip()
            titleerror = validate_project_title(title)

            url = self.request.get('url').strip()
            urlerror = validate_project_url(url)

            short_description = self.request.get('short_description').strip()
            sderror = validate_project_short_description(short_description)

            if titleerror or urlerror or sderror or fileerror:
                if blob_info and not fileerror:
                    # same as above
                    Project.remove_screenshot_blob(blob_info.key())

                user = User.get_user(username)
                projects = Project.get_projects_by_ids(user.projects)
                upload_url = blobstore.create_upload_url(
                    '/' + username, max_bytes_per_blob=self.MAX_IMG_SIZE)
                template = 'profile/edit_project.html'
                context = {
                    'user': user,
                    'username': username,
                    'title': title,
                    'url': url,
                    'short_description': short_description,
                    'projects': projects,
                    'upload_url': upload_url,
                    'titleerror': titleerror,
                    'urlerror': urlerror,
                    'sderror': sderror,
                    'fileerror': fileerror
                }
                self.render(template, context)
                return
            else:
                Project.update_project(project_id,
                                       title=title,
                                       screenshot=screenshot,
                                       screenshot_url=screenshot_url,
                                       url=url,
                                       short_description=short_description)
        elif mode == 'remove_project':
            project_id = self.request.get('project_id')
            Project.remove_project(project_id)
            User.remove_project(username, project_id)

        elif mode == 'edit':
            fields = self.get_params_dict(
                ('real_name', 'email', 'short_about', 'dob', 'tools',
                 'password', 'password_confirm', 'notify_on_msg'))
            logging.error(fields)

            iclasses = self.request.get_all('classes_inprog')
            cclasses = self.request.get_all('classes_completed')
            fields['iclasses'] = iclasses
            fields['cclasses'] = cclasses
            fields['username'] = username

            user = Key(User, username).get()

            errors = self.clean_user_data(user, **fields)

            context = {'errors': errors, 'user': user}

            if not errors:
                user.update(**fields)
                self.redirect('/{}'.format(username))
            else:

                if user.dob:
                    dob = user.dob.strftime('%m/%d/%Y')
                else:
                    dob = None
                all, ic, cc = self.organize_courses_for(user)
                context['courses_all'] = Course.courses_to_dict()
                context['courses_completed'] = cc
                context['courses_incomplete'] = ic
                context['dob'] = dob
                context['username'] = username
                context['gravatar'] = user.avatar_url
                context['friends'] = []
                context['friend_btn'] = False
                context['errors'] = errors
                self.render('profile/edit.html'.format(username), context)
                return
        self.redirect('/' + username)
Пример #23
0
 def createNewCourses(self):
     for course in courses:
         c = Course.add_course(**course)
Пример #24
0
    def testGetAllCourses(self):
        courses = Course.query().count(10)

        self.assertEqual(courses, 3,
                         "Wrong number of courses %s should be 3" % courses)
Пример #25
0
 def createNewCourses(self):
     for course in courses:
         c = Course.add_course(**course)
Пример #26
0
def getUsersByCourse(token, courseId):
    """
    <span class="card-title">>This Call will return all users in Course</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'<br>
        - courseId: 123456789
    <br>
    <br>
    <b>Payload</b><br>
     - NONE
    <br>
    <br>
    <b>Response</b>
    <br>
    200 - JSON Example:<br>
    <code>
        {<br>
        'username': '******',<br>
        'name': 'Darth Vader',<br>
        'email': '[email protected],<br>
        'isLecturer': 'True',<br>
        'seToken': 'xxxxxx-xxxxx-xxxxx-xxxxxx',<br>
        'avatar_url': 'http://location.git.com/somthing'<br>
        'isFirstLogin': False,<br>
        'campuses_id_list': [1243567,7583584904],<br>
        'courses_id_list': [543543,54353453,543543534]<br>
        }
    </code>
    <br>
    403 - No User Found
    """
    if token is None:
        return no_content("Token Is Empty, No User Found")

    user = get_user_by_token(token)
    if user is None:
        return bad_request("Bad User Token")

    try:
        course = Course.get_by_id(int(courseId))
    except Exception as e:
        return bad_request("Bad id format")

    if course is None:
        return bad_request("No such Course")

    arr = []

    for u in enumerate(course.membersId):
        u = json.loads(User.get_by_id(int(u)).to_JSON())
        arr.append(dict(u))

    if len(arr) != 0:
            return Response(response=json.dumps(arr),
                            status=200,
                            mimetype="application/json")
    else:
        return Response(response=[],
                        status=200,
                        mimetype="application/json")
Пример #27
0
 def add_course_from_csv(self, course_headers, course_data):
     course = Course()
     course.from_csv(course_headers, course_data)
     self.session.add(course)
Пример #28
0
    def get(self):
        teachers = db.GqlQuery("Select * from Teacher")
        teachers_timing = {}
        for teacher in teachers:
            teachers_timing[teacher.key().id()] = eval(teacher.teaching_time)

        print teachers_timing
        classCourses = db.GqlQuery("Select * from ClassCourse")

        classes = {}
        for classCourse in classCourses:
            classes[classCourse.key().id()] = {
                "routine": {"sunday": [], "monday": [], "tuesday": [], "wednesday": [], "thursday": [], "friday": []},
                "class_distribution": {},
                "details": {"faculty": classCourse.faculty, "year": classCourse.year, "semester": classCourse.semester},
            }

            eCourse = eval(classCourse.course)
            for course in eCourse:
                # l = Teacher.get_by_id(eCourse[course])
                l = {
                    "distribution": eval(Course.get_by_key_name(course).class_distribution),
                    "teacher": eCourse[course],
                    "teaching_time": eval(Teacher.get_by_id(eCourse[course]).teaching_time),
                    "possibilities": {
                        "sunday": {},
                        "monday": {},
                        "tuesday": {},
                        "wednesday": {},
                        "thursday": {},
                        "friday": {},
                    },
                }
                # print l
                classes[classCourse.key().id()]["class_distribution"][course] = l

        for class_ in classes:
            class_distribution = classes[class_]["class_distribution"]
            routine = classes[class_]["routine"]
            for subject in class_distribution:
                distribution = class_distribution[subject]["distribution"]
                for i in range(4, 0, -1):
                    if distribution[str(i)] != 0:
                        # print "found " + str(i) + " " + str(distribution[str(i)]) + subject
                        findTeachingTime(
                            subject=subject,
                            available_teaching_time=class_distribution[subject]["teaching_time"],
                            routine=routine,
                            class_duration=i,
                            total_classes=distribution[str(i)],
                            possibilities=class_distribution[subject]["possibilities"],
                        )

        total_tries = 0
        original_classes = copy.deepcopy(classes)
        inner_fail = True
        while total_tries < 50 and inner_fail == True:
            inner_fail = False
            total_tries += 1
            classes = copy.deepcopy(original_classes)
            # classes =
            for class_ in classes:
                class_distribution = classes[class_]["class_distribution"]
                routine = classes[class_]["routine"]
                for subject in class_distribution:
                    distribution = class_distribution[subject]["distribution"]
                    for i in range(4, 0, -1):
                        tries = 0
                        while distribution[str(i)] != 0:
                            if tries > 10:
                                print "giving up"
                                inner_fail = True
                                break

                            try:
                                randomday, randomtime = get_random_day_for_duration(
                                    class_distribution[subject]["possibilities"], i, routine
                                )
                            except:
                                tries += 1
                                continue
                            t = Teacher.get_by_id(class_distribution[subject]["teacher"])
                            routine[randomday].append(
                                {
                                    "subject": subject,
                                    "teacher": {"id": t.key().id(), "name": t.teacher_name},
                                    "timing": copy.deepcopy(randomtime),
                                }
                            )
                            class_distribution[subject]["possibilities"][randomday] = {}
                            # print "--"
                            print routine

                            distribution[str(i)] -= 1  # reduce total classes
        self.response.headers["Content-Type"] = "application/json"
        # self.write(json.dumps(original_classes,sort_keys=True, indent=4))
        self.write(json.dumps(classes, sort_keys=True, indent=4))
Пример #29
0
    def testGetAllCourses(self):
        courses = Course.query().count(10)

        self.assertEqual(courses, 3, "Wrong number of courses %s should be 3" % courses)
Пример #30
0
    from os import path
    from controllers.App import App
    from models.Profile import Profile
    from models.Course import Course
    from models.Topic import Topic
    from models.Book import Book

    app = App(path.dirname(path.realpath(__file__)))

    if path.exists('profile.md'):
        print('Publishing Profile')
        profile = Profile()
        app.publishProfile(profile)
    else:
        if path.exists('course.md'):
            print('Publishing full course')
            course = Course()
            app.publishCourse(course)
        else:
            if path.exists('topic.md'):
                print('Publishing topic + contained books')
                fullPath = os.getcwd()
                path, folder = os.path.split(fullPath)
                topic = Topic(folder)
                app.publishTopic(topic)
            else:
                print('Publishing single book')
                book = Book()
                app.publishBook(book)
                app.publishLab(book)
Пример #31
0
from models.Course import Course
from models.Concurrent import Concurrent
from models.Voiture import Voiture
from models.Circuit import Circuit

if __name__ == "__main__":

    spa = Circuit("Spa", 7004, 20)

    c = Course("TechnoBel", spa, 5, 42)

    v_nico = Voiture("Audi", "R8", 180, 260)
    nico = Concurrent("Nico", 7, v_nico)
    c.ajouter_participant(nico)

    mh = Concurrent("Marc-Henry", 21, Voiture("Tesla", "S", 220, 240))
    c.ajouter_participant(mh)

    c.ajouter_participant(
        Concurrent("François", 10, Voiture("Porsche", "911", 225, 230)))

    c.demarrer_course()

    for concurrent in c.concurrents:
        print(concurrent.nom, concurrent.temps_total)

    winner = c.obtenir_vainqueur()
    print(winner.se_decrire())
Пример #32
0
def removeUserFromCourse(token, userId, courseId):
    """
    <span class="card-title">>This Call will remove a user from a course</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'<br>
        - userId: 0987654321,<br>
        - 'courseId': 1234567890<br>
    <br>
    <br>
    <b>Payload</b><br>
     - NONE
     {<br>
    }<br>
    <br>
    <b>Response</b>
    <br>
    200 - User updated
    <br>
    400 - Bad Request
    """

    requestingUser = get_user_by_token(token)
    if requestingUser is None:
        return bad_request("Bad User Token")

    try:
        userToRemove = User.get_by_id(int(userId))
    except Exception as e:
        return bad_request("Bad id format")

    if userToRemove is None:
        return bad_request("No such user to remove")

    #check Course Exists
    course = Course.get_by_id(int(courseId))
    if course is None:
        return bad_request("No such Course!")

    #check if user is owner of Course
    if requestingUser.key().id() != course.master_id:
        # check if user want to delete itself
        if requestingUser.key().id() != userToRemove.key().id():
            return forbidden("No permission to delete user")

    try:
        userToRemove.courses_id_list.remove(courseId)
        course.membersId.remove(userToRemove.key().id())
    except Exception as e:
        return bad_request("user is not listed to this course")

    #remove user from all projects in course
    projects = Project.all().filter("courseId =", course.key().id())
    for p in projects:
        if p.key().id() in userToRemove.projects_id_list:
            userToRemove.projects_id_list.remove(p.key().id())
            p.membersId.remove(userToRemove.key().id())
            db.put(p)


    db.put(userToRemove)
    db.put(course)
    db.save
    return Response(response=userToRemove.to_JSON(),
                            status=200,
                            mimetype="application/json")  # Real response!