class Feed(db.Document): title = db.StringField() url = db.StringField(required=True) articles = db.ListField(db.ReferenceField("Article")) users = db.ListField(db.ReferenceField("User")) def as_dict(self): return dict(title=self.title, url=self.url) def __repr__(self): return '<Feed %r (%s)>' % (self.title, self.url)
class Order(db.Document): user_id = db.StringField() status = db.StringField(choices=tuple( types.get_events(types.EventType.Order())), default=types.EventType.Order.CREATED) expires_at = db.DateTimeField( default=datetime.datetime.now() + datetime.timedelta(minutes=Config.ORDER_EXPIRE_TIME_MIN)) ticket = db.ReferenceField('Ticket') version = db.IntField(default=0) def response(self): return { "id": str(self.id), "user_id": self.user_id, "status": self.status, "expires_at": str(self.expires_at), "ticket": self.ticket.response(), "version": self.version } def update_version_if_record_exists(self): if not self.id: return existing_record = Order.objects(id=self.id) if existing_record: self.version += 1 def save(self, *args, **kwargs): self.update_version_if_record_exists() super().save(*args, **kwargs)
class Subscriber(BaseDocument): cellphone = db.StringField() email = db.EmailField() vaccine_site = db.ListField(db.ReferenceField(Maps)) def to_mongo(self, *args, **kwargs): data = super().to_mongo(*args, **kwargs) data["vaccine_site"] = [s.name for s in self.vaccine_site] return data
class Hacker(BaseDocument): # Stored in the "user" collection meta = {"indexes": ["email"]} private_fields = ["id", "email_token_hash"] first_name = db.StringField() last_name = db.StringField() birthday = db.DateTimeField() country = db.StringField() phone_number = db.StringField() isaccepted = db.BooleanField(default=False) can_share_info = db.BooleanField(default=False) rsvp_status = db.BooleanField(default=False) beginner = db.BooleanField(default=False) ethnicity = db.StringField() pronouns = db.StringField() edu_info = db.EmbeddedDocumentField(Education_Info) resume = db.ReferenceField(Resume) socials = db.EmbeddedDocumentField(Socials) why_attend = db.StringField() what_learn = db.ListField() in_person = db.BooleanField(default=False) dietary_restrictions = db.StringField() email = db.EmailField(unique=True, required=True) date = db.DateTimeField(default=datetime.utcnow) mlh = db.EmbeddedDocumentField(MLH_Authorizations) def encode_email_token(self) -> str: """Encode the email token""" email_token = encode_jwt(sub=self.email) conf = app.config["BCRYPT_LOG_ROUNDS"] email_token_hash = bcrypt.generate_password_hash(email_token, conf) self.modify(set__email_token_hash=email_token_hash) self.save() return email_token @staticmethod def decode_email_token(email_token: str) -> str: """Decodes the email token""" return decode_jwt(email_token)["sub"] @classmethod def pre_delete(cls, sender, document, **kwargs): if document.resume: document.resume.delete()
class User(db.Document): uid = db.UUIDField(required=True, primary_key=True) player_ids = db.ListField(db.UUIDField(required=True)) read = db.MapField(field=db.BooleanField(default=False, required=True)) notifications = db.ListField(db.ReferenceField(GenericNotification, reverse_delete_rule=mongoengine.PULL)) def read_notifications(self): for notification in self.notifications: self.read[str(notification.id)] = True self.update(read=self.read) def serialize_notifications(self): notifications = self.notifications[-PER_PAGE:] utils.populate_name_cache(notifications) serialized_notifications = [] for notification in notifications: serialized_notification = notification.serialize() read = str(notification.nid) in self.read serialized_notification['read'] = read serialized_notifications.append(serialized_notification) return serialized_notifications[::-1]
class Vote(db.Document): like = db.BooleanField() article = db.ReferenceField(Article) user = db.ReferenceField(User)
class Article(db.Document): feed = db.ReferenceField(Feed, required=True) source_id = db.StringField(required=True) url = db.StringField() title = db.StringField() top_image = db.StringField() movies = db.ListField() keywords = db.ListField() tags = db.ListField() authors = db.ListField() publish_date = db.DateTimeField() summary = db.StringField() html = db.StringField() meta_data = db.DictField() language = db.StringField() text = db.StringField() active = db.BooleanField(default=True) vector = db.ListField(db.FloatField()) vector_2d = db.ListField(db.FloatField()) def as_dict(self): return dict(feed=self.feed.url, source_id=self.source_id, url=self.url, title=self.title, top_image=self.top_image, movies=self.movies, keywords=self.keywords, tags=self.tags, authors=self.authors, publish_date='%s' % self.publish_date, summary=self.summary, html=self.html, meta_data=self.meta_data, language=self.language, text=self.text, vector=self.vector, vector_2d=self.vector_2d) @staticmethod def update_vectors(model, vectors_2d=[]): # https://stackoverflow.com/questions/30943076/mongoengine-bulk-update-without-objects-update bulk_operations = [] keys = model.docvecs.doctags.keys() vectors = model.docvecs.vectors_docs for key, vector, vector_2d in zip(keys, vectors, vectors_2d): bulk_operations.append( UpdateOne({'_id': key}, { '$set': dict(vector=vector.tolist(), vector_2d=vector_2d) })) if bulk_operations: collection = Article._get_collection() \ .bulk_write(bulk_operations, ordered=False)
class Exam(db.Document): user = db.ReferenceField('User') type = db.StringField(choices=EXAM_TYPE) pure_tone = db.EmbeddedDocumentField('PureTone') speech_noise = db.EmbeddedDocumentField('SpeechNoise') dichotic = db.EmbeddedDocumentField('Dichotic') def __repr__(self): return '[Exam] user :{} type:{} pure_tone:{}'.format( self.user, self.type, self.pure_tone) @classmethod def passed_exam_before(cls, userid): return cls.objects.get(user=userid) if cls.objects( user=userid) else False @classmethod def passed_pure_before(cls, userid): return cls.objects.get( user=userid, type=EXAM_TYPE['PURE_TONE']) if cls.objects( user=userid, pure_tone__exists=True) else False @classmethod def passed_dichotic_before(cls, userid): return cls.objects.get( user=userid, type=EXAM_TYPE['DICHOTIC']) if cls.objects( user=userid, dichotic__exists=True) else False @classmethod def passed_dicho_type_before(cls, userid, dicho_type): dicho_type_phrase = 'dichotic__' + dicho_type + '__exists' args = {'user': userid, dicho_type_phrase: True} return cls.objects.get(user=userid) if cls.objects(**args) else False @classmethod def passed_speech_noise_before(cls, userid): return cls.objects.get( user=userid, speech_noise__exists=True) if cls.objects.get( user=userid, speech_noise__exists=True) else False @classmethod def get_puretone_by_user_id(cls, userid): return cls.objects.get(user=userid, type=EXAM_TYPE['PURE_TONE']) def pure_tone_report(self): result = {} result['Right_250'] = self.pure_tone.Right_250 result['Right_500'] = self.pure_tone.Right_500 result['Right_1000'] = self.pure_tone.Right_1000 result['Right_2000'] = self.pure_tone.Right_2000 result['Right_4000'] = self.pure_tone.Right_4000 result['Right_8000'] = self.pure_tone.Right_8000 result['Left_250'] = self.pure_tone.Left_250 result['Left_500'] = self.pure_tone.Left_500 result['Left_1000'] = self.pure_tone.Left_1000 result['Left_2000'] = self.pure_tone.Left_2000 result['Left_4000'] = self.pure_tone.Left_4000 result['Left_8000'] = self.pure_tone.Left_8000 lentgh = 0 for i in result: if result[i] != None: lentgh = lentgh + 1 count = 0 for i in result: if result[i] == False: count += 1 if count >= 1: need_to_clinic = True elif lentgh != 12: need_to_clinic = True else: need_to_clinic = False return {'result': result, 'need': need_to_clinic} @classmethod def get_dichotic_by_user_id(cls, userid): return cls.objects.get(user=userid, dichotic__exists=True) def dichotic_report(self): self.result = {} self.result['Single'] = {} self.result['Binary'] = {} self.result['Ternary'] = {} # print(self.dichotic.Ternary) if self.dichotic.Single != None: for i in self.dichotic.Single: self.result['Single'][i] = self.dichotic.Single[i] if self.dichotic.Binary != None: for i in self.dichotic.Binary: self.result['Binary'][i] = self.dichotic.Binary[i] if self.dichotic.Ternary != None: for i in self.dichotic.Ternary: self.result['Ternary'][i] = self.dichotic.Ternary[i] return {'result': self.result} def count_dichotic_score(self): self.dichotic_report() if self.result['Single'] != {}: pass elif self.result['Binary'] != {}: score_left = 0 score_right = 0 right_answer = 0 left_answer = 0 count = 0 for i, j in self.result['Binary'].items(): if i == 'start_time': continue right_flag = 0 left_flag = 0 for key, value in enumerate(j): if value in right_dichotic_binary[count]: if right_flag >= 2: continue right_flag += 1 right_answer += 1 if right_flag == 2: score_right = score_right + 4 elif value in left_dichotic_binary[count]: if left_flag >= 2: continue left_flag += 1 left_answer += 1 if left_flag == 2: score_left = score_left + 4 count += 1 return (score_right, score_left, right_answer, left_answer) elif self.result['Ternary'] != {}: score_left = 0 score_right = 0 right_answer = 0 left_answer = 0 count = 0 for i, j in self.result['Ternary'].items(): if i == 'start_time': continue right_flag = 0 left_flag = 0 for key, value in enumerate(j): if value in right_dichotic_ternary[count]: if right_flag >= 3: continue right_flag += 1 right_answer += 1 if right_flag == 3: score_right = score_right + 4 elif value in left_dichotic_ternary[count]: if left_flag >= 3: continue left_flag += 1 left_answer += 1 if left_flag == 3: score_left = score_left + 4 count += 1 return (score_right, score_left, right_answer, left_answer) def speech_noise_report(self): right_silence_score = 0 left_silence_score = 0 right_noise_score = 0 left_noise_score = 0 for i in self.speech_noise: if i == 'start_time': continue elif i == 'right_silence': for k, v in enumerate(self.speech_noise[i]): if v in right_silence: right_silence_score += 1 elif i == 'left_silence': for k, v in enumerate(self.speech_noise[i]): if v in left_silence: left_silence_score += 1 elif i == 'right_noise': for k, v in enumerate(self.speech_noise[i]): if v in right_noise: right_noise_score += 1 elif i == 'left_noise': for k, v in enumerate(self.speech_noise[i]): if v in left_noise: left_noise_score += 1 return (right_silence_score, left_silence_score, right_noise_score, left_noise_score)