Ejemplo n.º 1
0
class Message(db.Document):
    from_user = db.ReferenceField(User, db_field="fu", reverse_delete_rule=CASCADE)
    to_user = db.ReferenceField(User, db_field="tu", default=None, reverse_delete_rule=CASCADE)
    text = db.StringField(db_field="t", max_length=1024)
    live = db.BooleanField(db_field="l", default=True)
    create_date = db.LongField(db_field="c", default=now())
    parent = db.ObjectIdField(db_field="p", default=None)
    images = db.ListField(db_field="ii")
    message_type = db.IntField(db_field="mt", default=POST, choices=MESSAGE_TYPE)
    
    @property
    def text_linkified(self):
        return linkify(self.text)        
    
    @property
    def human_timestamp(self):
        return ms_stamp_humanize(self.create_date)
        
    @property
    def comments(self):
        return Message.objects.filter(parent=self.id, message_type=COMMENT).order_by('create_date')

    @property
    def likes(self):
        return Message.objects.filter(parent=self.id, message_type=LIKE).order_by('-create_date')

    def post_imgsrc(self, image_ts, size):
        if AWS_BUCKET:
            return os.path.join(AWS_CONTENT_URL, AWS_BUCKET, 'posts', '%s.%s.%s.png' % (self.id, image_ts, size))
        else:
            return url_for('static', filename=os.path.join(STATIC_IMAGE_URL, 'posts', '%s.%s.%s.png' % (self.id, image_ts, size)))

    meta = {
        'indexes': [('from_user', 'to_user', '-create_date', 'message_type', 'live')]
    }
Ejemplo n.º 2
0
class Feed(db.Document):
    user = db.ReferenceField(User, db_field="u", reverse_delete_rule=CASCADE)
    message = db.ReferenceField(Message,
                                db_field="m",
                                reverse_delete_rule=CASCADE)
    create_date = db.LongField(db_field="c", default=now())

    meta = {'indexes': [('user', '-create_date')]}
Ejemplo n.º 3
0
class Feed(db.Document):  # Representation of messages per user
    user = db.ReferenceField(User, db_field="u", reverse_delete_rule=CASCADE)
    message = db.ReferenceField(Message,
                                db_field="m",
                                reverse_delete_rule=CASCADE)
    create_date = db.LongField(db_field="c", default=now())

    meta = {"indexes": [("user", "-create_date")]}
Ejemplo n.º 4
0
class File_Record(db.Document):
    #store email
    from_user = db.ReferenceField(User, db_field="rfu")
    #store storecodes
    to_store = db.ReferenceField(Store, db_field="rt")
    date_time = db.StringField(db_field="dt")
    int_time = db.LongField(db_field="it")
    prize = db.StringField()
    size = db.StringField()
    descp = db.StringField()
    paid = db.BooleanField()
    type = db.StringField()
    parent = db.ObjectIdField(db_field="p")

    meta = {'indexes': ['type', 'to_store', 'from_user', 'int_time']}
Ejemplo n.º 5
0
class report_yearly(db.Document):
    stock_id = db.StringField(db_field="sid", max_length=10, required=True)
    data = db.DictField()
    report_name = db.StringField(db_field="rn", max_length=4, required=True)
    companyName = db.StringField(db_field="cn", max_length=160, required=True)
    companyNameEng = db.StringField(db_field="cne",
                                    max_length=160,
                                    required=True)
    industryName = db.StringField(db_field="indn",
                                  max_length=100,
                                  required=True)
    floor = db.StringField(db_field="floor", max_length=5, required=True)
    shares = db.LongField(db_field="share",
                          max_value=10000000000,
                          required=True)
    meta = {'indexes': ['stock_id', ('stock_id', 'report_name')]}
Ejemplo n.º 6
0
class Project(db.Document):

    """A course's Project."""
    LANGUAGES = [('J', 'Java Project')]
    created_at = db.DateTimeField(
        default=datetime.datetime.utcnow, required=True)
    due_date = db.DateTimeField(required=True)
    name = db.StringField(max_length=256, min_length=5, required=True)
    tests = db.ListField(db.FileField())
    published = db.BooleanField(default=True, required=True)
    language = db.StringField(
        max_length=3, min_length=1, choices=LANGUAGES, required=True)
    test_timeout_seconds = db.LongField(
        default=600, max_value=1800, required=True)
    submissions = db.ListField(
        db.ReferenceField('Submission', reverse_delete_rule=db.PULL))
    course = db.ReferenceField('Course')
    is_quiz = db.BooleanField(required=True)

    meta = {
        "indexes": [
            {
                "fields": ['name']
            },
            {
                "fields": ['course']
            }
        ]
    }

    @property
    def has_tests(self):
        return len(self.tests) >= 1

    @property
    def has_class_files(self):
        return any([t.filename.endswith('.class') for t in self.tests])

    @property
    def can_submit(self):
        return self.due_date >= datetime.datetime.utcnow()

    def student_results_for_csv(self):
        grades = TeamProjectGrade.objects(project=self)
        results = []
        for grade in grades:
            for student in grade.get_students():
                results.append({
                    "team_id": student.team_id,
                    "guc_id": student.guc_id,
                    "name": student.name,
                    "email": student.email,
                    "project": self.name,
                    "passed cases": grade.best_submission.passed_cases_count,
                    "total cases": grade.best_submission.cases_count,
                    "grade in percentage": grade.grade,
                    "submitter": grade.best_submission.submitter.name
                })
        return results

    def get_teams_canadite_submissions(self):
        """
        Gets teams candidate submissions for grading.
        Gets latest submission of each member of a team.
        returns a list of (team_id, submissions)
        """
        from itertools import groupby
        from operator import attrgetter
        key_func = attrgetter('team_id')
        submitters = sorted([subm.submitter for subm in Submission.objects(project=self, submitter__exists=True)],
                            key=key_func)
        submissions = []
        for _, team in groupby(submitters, key_func):
            if _ is None:
                continue
            team = list(set(list(team)))
            canadite_submissions = []
            for student in team:
                subms = (Submission.objects(
                            submitter=student,
                            project=self)
                         .order_by('-created_at').limit(1))
                if len(subms) > 0:
                    canadite_submissions.append(subms[0])

            submissions.append((_, canadite_submissions))
        return submissions

    def get_team_best_submissions(
            self,
            rerurn_submissions=False,
            only_rerun_compile_error=False,
            get_latest=True):
        """
        Cget team best submissions for grades, optionally reruns submissions.
        Please note that this function will block to submissions.
        returns a list of (team_id, submission)
        """
        from application.tasks import junit_actual
        canadite_submissions = self.get_teams_canadite_submissions()
        best_team_submissions = []
        if get_latest:
            for _, submissions in canadite_submissions:
                submissions = sorted(submissions,
                                     key=lambda subm:
                                     subm.created_at, reverse=True)
                submission = submissions[0]
                if rerurn_submissions:
                    if only_rerun_compile_error and submission.compile_status:
                        pass
                    else:
                        submission.reset()
                        junit_actual(submission.id)
                best_team_submissions.append((_, submission))
        else:
            for _, submissions in canadite_submissions:
                if rerurn_submissions:
                    for submission in submissions:
                        if only_rerun_compile_error\
                           and submission.compile_status:
                            continue
                        else:
                            submission.reset()
                            junit_actual(submission.id)
                passed_submissions = [s for s in canadite_submissions
                                      if s.compile_status]
                best_submissions = sorted(passed_submissions,
                                          key=lambda subm: len(
                                            subm.test_results))
                best_team_submissions.append((_, best_submissions[0]))
        return best_team_submissions

    def grade_teams(
            self,
            rerurn_submissions=False,
            only_rerun_compile_error=False,
            get_latest=True):
        """
        Computes team grades, optionally reruns submissions.
        Please note that this function will block to submissions.
        will attempt to find TeamGrade and update it if it already exists
        """

        best_team_submissions = self.get_team_best_submissions(
            rerurn_submissions, only_rerun_compile_error, get_latest)

        for team_id, best_submission in best_team_submissions:
            try:
                grade = TeamProjectGrade.objects.get(
                    team_id=team_id, project=self)
                if not rerurn_submissions:
                    app.logger.info("found grade nothing to change")
                    continue
                else:
                    app.logger.info("found grade updateing submission")
                    grade.best_submission = best_submission
            except TeamProjectGrade.DoesNotExist:
                grade = TeamProjectGrade(
                    team_id=team_id,
                    best_submission=best_submission,
                    project=self)
            grade.save()
            app.logger.info("graded team {0} in project {1}"
                            .format(team_id, self.name))

    def get_student_submissions(
            self,
            rerurn_submissions=False,
            only_rerun_compile_error=False,
            only_rerun_test_cases_zero=False,
            get_latest=True):
        """
        Computes latest grade for each student who submitted in this project, optionally reruns submissions.
        Please note that this function will block to submissions.
        will attempt to find TeamGrade and update it if it already exists
        """
        from application.tasks import junit_actual

        students = self.course.students
        submissions = []
        for student in students:
            subms = (Submission.objects(
                        submitter=student,
                        project=self)
                     .order_by('-created_at').limit(1))
            if len(subms) > 0:
                submissions.append(subms[0])

        for submission in submissions:
            if rerurn_submissions:
                if only_rerun_compile_error and submission.compile_status:
                    pass
                elif only_rerun_test_cases_zero and submission.cases_count > 0:
                    pass
                else:
                    submission.reset()
                    junit_actual(submission.id)

        return submissions

    def student_submissions_for_csv(self):

        results = []
        for submission in self.get_student_submissions():
            student = submission.submitter
            results.append({
                "guc_id": student.guc_id,
                "name": student.name,
                "email": student.email,
                "project": self.name,
                "passed cases": submission.passed_cases_count,
                "total cases": submission.cases_count,
                "grade in percentage": submission.passed_percentage,
            })
        return results


    def to_dict(self, **kwargs):
        dic = {
            "id": self.id,
            "name": self.name,
            "language": self.language,
            "created_at": self.created_at,
            "course": self.course.to_dict(),
            "can_submit": self.can_submit,
            "due_date": self.due_date,
            'published': self.published,
            "is_quiz": self.is_quiz,
            "rerurn_submissions": "no",
            'page': 1
        }
        dic['course_name'] = dic['course']['name']

        def file_to_dic(project_id, file):
            dic = {
                "name": file.filename,
                "mimetype": file.content_type,
                "project_id": project_id
            }
            return dic
        dic['tests'] = [file_to_dic(self.id, f) for f in self.tests]
        dic['has_class_files'] = self.has_class_files
        return dic
Ejemplo n.º 7
0
class File(db.Document):
    BW = 0
    CLR = 1

    COLOR = ((BW, 'BW'), (CLR, 'CLR'))

    PENDING = 1
    PRINTING = 0
    DONE = -1

    STATUS = ((PENDING, 'Pending'), (PRINTING, 'Printing'), (DONE, 'Done'))

    APPROVED = 1
    UNAPPROVE = 0
    APPROVED_END = 2

    APPROVE = ((APPROVED, 'approved'), (UNAPPROVE, 'unapprove'),
               (APPROVED_END, 'approve_end'))

    file = db.StringField(db_field="f", required=True, unique=True)
    file_tn = db.StringField(db_field="tn")
    file_tag = db.StringField(db_field="t")
    descp = db.StringField(db_field="d", max_length=200)
    prize = db.StringField(db_field="p")
    size = db.IntField(db_field="s", required=True)
    create_date = db.LongField(db_field="c", default=nowms())
    from_user = db.ReferenceField(User, db_field="fu")
    to_store = db.ReferenceField(Store, db_field="ts")
    clr = db.IntField(db_field="cl", choices=COLOR, required=True)
    #Status
    approve = db.IntField(db_field="ap", choices=APPROVE, default=UNAPPROVE)
    status = db.IntField(db_field='st', default=PENDING, choices=STATUS)

    #is from_user verify
    def is_from_verified(self):
        return Relationship.get_verification(self.from_user, self.to_store)

    # create file record and has a name called type to easily tell why file's record was made
    def file_record(self, type, approve=False, parent=None):

        record = File_Record(from_user=self.from_user,
                             to_store=self.to_store,
                             date_time=f'{human_date_ms(self.create_date)}',
                             prize=str(self.prize),
                             size=f'A{self.size}',
                             descp=self.descp,
                             type=type,
                             int_time=self.create_date,
                             parent=parent,
                             paid=approve)
        record.save()

    def file_src(self):
        return url_for('static',
                       filename=os.path.join(STATIC_FILE_URL,
                                             str(self.file))).replace(
                                                 '%5C', '/')

    meta = {
        'indexes': [
            'file', 'size', 'to_store', 'from_user', 'clr', 'prize',
            '-create_date'
        ]
    }