forked from avh4/khan-academy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
2418 lines (1889 loc) · 93.8 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime, logging
import math
import urllib
import pickle
import random
import itertools
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext.db import TransactionFailedError
from api.jsonify import jsonify
from google.appengine.ext import db
import object_property
import util
import user_util
import consts
import points
from search import Searchable
from app import App
import layer_cache
import request_cache
from discussion import models_discussion
from topics_list import all_topics_list
import nicknames
from counters import user_counter
from facebook_util import is_facebook_user_id
from accuracy_model import AccuracyModel, InvFnExponentialNormalizer
from templatefilters import slugify
from gae_bingo.gae_bingo import ab_test, bingo
from gae_bingo.models import GAEBingoIdentityModel, ConversionTypes
# Setting stores per-application key-value pairs
# for app-wide settings that must be synchronized
# across all GAE instances.
class Setting(db.Model):
value = db.StringProperty(indexed=False)
@staticmethod
def entity_group_key():
return db.Key.from_path('Settings', 'default_settings')
@staticmethod
def _get_or_set_with_key(key, val = None):
if val is None:
return Setting._cache_get_by_key_name(key)
else:
setting = Setting(Setting.entity_group_key(), key, value=str(val))
db.put(setting)
Setting._get_settings_dict(bust_cache=True)
return setting.value
@staticmethod
def _cache_get_by_key_name(key):
setting = Setting._get_settings_dict().get(key)
if setting is not None:
return setting.value
return None
@staticmethod
@request_cache.cache()
@layer_cache.cache(layer=layer_cache.Layers.Memcache)
def _get_settings_dict():
# ancestor query to ensure consistent results
query = Setting.all().ancestor(Setting.entity_group_key())
results = dict((setting.key().name(), setting) for setting in query.fetch(20))
return results
@staticmethod
def cached_library_content_date(val = None):
return Setting._get_or_set_with_key("cached_library_content_date", val)
@staticmethod
def cached_exercises_date(val = None):
return Setting._get_or_set_with_key("cached_exercises_date", val)
@staticmethod
def count_videos(val = None):
return Setting._get_or_set_with_key("count_videos", val) or 0
@staticmethod
def last_youtube_sync_generation_start(val = None):
return Setting._get_or_set_with_key("last_youtube_sync_generation_start", val) or 0
@staticmethod
def smarthistory_version(val = None):
return Setting._get_or_set_with_key("smarthistory_version", val) or 0
@staticmethod
def classtime_report_method(val = None):
return Setting._get_or_set_with_key("classtime_report_method", val)
@staticmethod
def classtime_report_startdate(val = None):
return Setting._get_or_set_with_key("classtime_report_startdate", val)
class Exercise(db.Model):
name = db.StringProperty()
short_display_name = db.StringProperty(default="")
prerequisites = db.StringListProperty()
covers = db.StringListProperty()
v_position = db.IntegerProperty() # actually horizontal position on knowledge map
h_position = db.IntegerProperty() # actually vertical position on knowledge map
seconds_per_fast_problem = db.FloatProperty(default = consts.MIN_SECONDS_PER_FAST_PROBLEM) # Seconds expected to finish a problem 'quickly' for badge calculation
# True if this exercise is live and visible to all users.
# Non-live exercises are only visible to admins.
live = db.BooleanProperty(default=False)
# True if this exercise is a quasi-exercise generated by
# combining the content of other exercises
summative = db.BooleanProperty(default=False)
# Teachers contribute raw html with embedded CSS and JS
# and we sanitize it with Caja before displaying it to
# students.
author = db.UserProperty()
raw_html = db.TextProperty()
last_modified = db.DateTimeProperty()
creation_date = db.DateTimeProperty(auto_now_add=True, default=datetime.datetime(2011, 1, 1))
_serialize_blacklist = [
"author", "raw_html", "last_modified",
"coverers", "prerequisites_ex", "assigned",
]
@property
def relative_url(self):
return "/exercises?exid=%s" % self.name
@property
def ka_url(self):
return util.absolute_url("/exercises?exid=%s" % self.name)
@staticmethod
def get_by_name(name):
dict_exercises = Exercise.__get_dict_use_cache_unsafe__()
if dict_exercises.has_key(name):
if dict_exercises[name].is_visible_to_current_user():
return dict_exercises[name]
return None
@staticmethod
def to_display_name(name):
if name:
return name.replace('_', ' ').capitalize()
return ""
@property
def display_name(self):
return Exercise.to_display_name(self.name)
# The number of "sub-bars" in a summative (equivalently, # of save points + 1)
@property
def num_milestones(self):
return len(self.prerequisites) if self.summative else 1
@property
def required_streak(self):
return consts.REQUIRED_STREAK * self.num_milestones
def min_problems_imposed(self):
return consts.MIN_PROBLEMS_IMPOSED
@staticmethod
def to_short_name(name):
exercise = Exercise.get_by_name(name)
if exercise:
return exercise.short_name()
return ""
def short_name(self):
if self.short_display_name:
return self.short_display_name[:11]
return self.display_name[:11]
def is_visible_to_current_user(self):
return self.live or user_util.is_current_user_developer()
def struggling_threshold(self):
# 96% of users have proficiency before they get to 30 problems
# return 3 * self.required_streak
# 85% of users have proficiency before they get to 19 problems
return 2 * self.required_streak
def summative_children(self):
if not self.summative:
return []
query = db.Query(Exercise)
query.filter("name IN ", self.prerequisites)
return query
def non_summative_exercise(self, problem_number):
if not self.summative:
return self
if len(self.prerequisites) <= 0:
raise Exception("Summative exercise '%s' does not include any other exercises" % self.name)
# For now we just cycle through all of the included exercises in a summative exercise
index = int(problem_number) % len(self.prerequisites)
exid = self.prerequisites[index]
query = Exercise.all()
query.filter('name =', exid)
exercise = query.get()
if not exercise:
raise Exception("Unable to find included exercise")
if exercise.summative:
return exercise.non_summative_exercise(problem_number)
else:
return exercise
def related_videos_query(self):
exercise_videos = None
query = ExerciseVideo.all()
query.filter('exercise =', self.key()).order('exercise_order')
return query
@layer_cache.cache_with_key_fxn(lambda self: "related_videos_%s" % self.key(), layer=layer_cache.Layers.Memcache)
def related_videos_fetch(self):
exercise_videos = self.related_videos_query().fetch(10)
for exercise_video in exercise_videos:
exercise_video.video # Pre-cache video entity
return exercise_videos
# followup_exercises reverse walks the prerequisites to give you
# the exercises that list the current exercise as its prerequisite.
# i.e. follow this exercise up with these other exercises
def followup_exercises(self):
return [exercise for exercise in Exercise.get_all_use_cache() if self.name in exercise.prerequisites]
@classmethod
def all(cls, live_only = False):
query = super(Exercise, cls).all()
if live_only or not user_util.is_current_user_developer():
query.filter("live =", True)
return query
@classmethod
def all_unsafe(cls):
return super(Exercise, cls).all()
@staticmethod
def get_all_use_cache():
if user_util.is_current_user_developer():
return Exercise.__get_all_use_cache_unsafe__()
else:
return Exercise.__get_all_use_cache_safe__()
@staticmethod
@layer_cache.cache_with_key_fxn(lambda *args, **kwargs: "all_exercises_unsafe_%s" % Setting.cached_exercises_date())
def __get_all_use_cache_unsafe__():
query = Exercise.all_unsafe().order('h_position')
return query.fetch(400)
@staticmethod
def __get_all_use_cache_safe__():
return filter(lambda exercise: exercise.live, Exercise.__get_all_use_cache_unsafe__())
@staticmethod
@layer_cache.cache_with_key_fxn(lambda *args, **kwargs: "all_exercises_dict_unsafe_%s" % Setting.cached_exercises_date())
def __get_dict_use_cache_unsafe__():
exercises = Exercise.__get_all_use_cache_unsafe__()
dict_exercises = {}
for exercise in exercises:
dict_exercises[exercise.name] = exercise
return dict_exercises
@staticmethod
@layer_cache.cache(expiration=3600)
def get_count():
return Exercise.all(live_only=True).count()
def put(self):
Setting.cached_exercises_date(str(datetime.datetime.now()))
db.Model.put(self)
Exercise.get_count(bust_cache=True)
@staticmethod
def get_dict(query, fxn_key):
exercise_dict = {}
for exercise in query.fetch(10000):
exercise_dict[fxn_key(exercise)] = exercise
return exercise_dict
def clamp(min_val, max_val):
def decorator(target_fn):
def wrapped(*arg, **kwargs):
return sorted((min_val, target_fn(*arg, **kwargs), max_val))[1]
return wrapped
return decorator
class UserExercise(db.Model):
user = db.UserProperty()
exercise = db.StringProperty()
exercise_model = db.ReferenceProperty(Exercise)
streak = db.IntegerProperty(default = 0)
_progress = db.FloatProperty(default = None, indexed=False) # A continuous value >= 0.0, where 1.0 means proficiency. This measure abstracts away the internal proficiency model.
longest_streak = db.IntegerProperty(default = 0, indexed=False)
# TODO(david): This property can be removed once we completely move off the streak display.
streak_start = db.FloatProperty(default = 0.0, indexed=False) # The starting point of the streak bar as it appears to the user, in [0,1)
first_done = db.DateTimeProperty(auto_now_add=True)
last_done = db.DateTimeProperty()
total_done = db.IntegerProperty(default = 0)
total_correct = db.IntegerProperty(default = 0)
last_review = db.DateTimeProperty(default=datetime.datetime.min)
review_interval_secs = db.IntegerProperty(default=(60 * 60 * 24 * consts.DEFAULT_REVIEW_INTERVAL_DAYS), indexed=False) # Default 7 days until review
proficient_date = db.DateTimeProperty()
seconds_per_fast_problem = db.FloatProperty(default = consts.MIN_SECONDS_PER_FAST_PROBLEM, indexed=False) # Seconds expected to finish a problem 'quickly' for badge calculation
summative = db.BooleanProperty(default=False, indexed=False)
_accuracy_model = object_property.ObjectProperty() # Stateful function object that estimates P(next problem correct). Only exists for new UserExercise objects.
_USER_EXERCISE_KEY_FORMAT = "UserExercise.all().filter('user = '%s')"
_serialize_blacklist = ["review_interval_secs", "_progress", "_accuracy_model"]
_MIN_PROBLEMS_FROM_ACCURACY_MODEL = AccuracyModel.min_streak_till_threshold(consts.PROFICIENCY_ACCURACY_THRESHOLD)
# A bound function object to normalize the progress bar display from a probability
_normalize_progress = InvFnExponentialNormalizer(
AccuracyModel(),
consts.PROFICIENCY_ACCURACY_THRESHOLD
).normalize
def proficiency_model(self):
user_data = UserData.current()
return user_data.proficiency_model if user_data else 'streak'
@property
def required_streak(self):
if self.summative:
return Exercise.get_by_name(self.exercise).required_streak
else:
return consts.REQUIRED_STREAK
@property
def exercise_states(self):
user_exercise_graph = self.get_user_exercise_graph()
if user_exercise_graph:
return user_exercise_graph.states(self.exercise)
return None
@property
def next_points(self):
user_data = self.get_user_data()
suggested = proficient = False
if user_data:
suggested = user_data.is_suggested(self.exercise)
proficient = user_data.is_proficient_at(self.exercise)
return points.ExercisePointCalculator(self, suggested, proficient)
@property
def num_milestones(self):
return self.exercise_model.num_milestones
def min_problems_imposed(self):
return self.exercise_model.min_problems_imposed()
def min_problems_required(self):
return max(self.min_problems_imposed(), UserExercise._MIN_PROBLEMS_FROM_ACCURACY_MODEL)
# Do not transition old objects that did not have the _accuracy_model
# property - only new UserExercise objects can use the new proficiency
# model.
def accuracy_model(self):
# TODO(david): When we fully switch away from the streak model,
# uncomment the lines below and refactor code to remove
# accuracy_model guards.
#if self._accuracy_model is None:
# self._accuracy_model = AccuracyModel(self)
return self._accuracy_model
def bingo_proficiency_model(self, test):
# We only want to score conversions for newly-created UserExercise
# objects that could actually use the new proficiency model behavior
# (all existing UserExercise objects use the old streak model to
# facilitate transitioning).
if self.accuracy_model():
bingo(test)
def use_streak_model(self):
return self.proficiency_model() == 'streak' or not self.accuracy_model()
# Faciliate transition for old objects that did not have the _progress property
@property
@clamp(0.0, 1.0)
def progress(self):
if self._progress is None:
self._progress = self._get_progress_from_current_state()
return self._progress
def bingo_prof_model_accuracy_threshold_tests(self):
if self.total_done < 5 or not self.accuracy_model():
return
accuracy = self.accuracy_model().predict()
if self.exercise in UserData.conversion_test_easy_exercises:
for threshold in UserData.prof_conversion_accuracy_thresholds:
if accuracy >= threshold:
self.bingo_proficiency_model('prof_accuracy_above_%s_easy' % threshold)
elif self.exercise in UserData.conversion_test_hard_exercises:
for threshold in UserData.prof_conversion_accuracy_thresholds:
if accuracy >= threshold:
self.bingo_proficiency_model('prof_accuracy_above_%s_hard' % threshold)
def update_proficiency_model(self, correct):
if not correct:
if self.summative:
# Reset to latest milestone
self.streak = (self.streak // consts.CHALLENGE_STREAK_BARRIER) * consts.CHALLENGE_STREAK_BARRIER
else:
self.streak = 0
if self.accuracy_model():
self.accuracy_model().update(correct)
self.bingo_prof_model_accuracy_threshold_tests()
self._progress = self._get_progress_from_current_state()
if self.use_streak_model():
self._update_progress_from_streak_model(correct)
@clamp(0.0, 1.0)
def _get_progress_from_current_state(self):
if self.use_streak_model():
if self._progress is not None:
return self._progress
if self.summative:
return float(self.streak) / self.required_streak
else:
return self.streak_start + (
float(self.streak) / self.required_streak * (1.0 - self.streak_start))
if self.total_correct == 0:
return 0.0
if self.accuracy_model().total_done <= self.accuracy_model().total_correct():
# Impose a minimum number of problems required to be done.
# If the user has no wrong answers yet, we can get a progress bar
# amount by just dividing correct answers by the # of problems
# required.
normalized_prediction = min(float(self.accuracy_model().total_correct()) / self.min_problems_required(), 1.0)
else:
prediction = self.accuracy_model().predict()
normalized_prediction = UserExercise._normalize_progress(prediction)
if self.summative:
if self._progress is None:
milestones_completed = self.streak // consts.CHALLENGE_STREAK_BARRIER
else:
milestones_completed = math.floor(self._progress * self.num_milestones)
if normalized_prediction >= 1.0:
# The user just crossed a challenge barrier. Reset their
# accuracy model to start fresh.
self._accuracy_model = AccuracyModel()
return float(milestones_completed + normalized_prediction) / self.num_milestones
else:
return normalized_prediction
def _update_progress_from_streak_model(self, correct):
assert self._progress is not None
if correct:
if self._progress >= 1.0:
self._progress = 1.0
return
if self.summative:
progress_increment = 1.0 / self.required_streak
else:
progress_increment = (1.0 - self._progress) / (self.required_streak - self.streak)
self._progress += progress_increment
else:
if self.summative:
self._progress = float(self.streak) / self.required_streak
else:
self._progress *= consts.STREAK_RESET_FACTOR
@staticmethod
def to_progress_display(num):
return '%.0f%%' % math.floor(num * 100.0) if num <= consts.MAX_PROGRESS_SHOWN else 'Max'
def progress_display(self):
return UserExercise.to_progress_display(self.progress)
@staticmethod
def get_key_for_email(email):
return UserExercise._USER_EXERCISE_KEY_FORMAT % email
@staticmethod
def get_for_user_data(user_data):
query = UserExercise.all()
query.filter('user =', user_data.user)
return query
def get_user_data(self):
user_data = None
if hasattr(self, "_user_data"):
user_data = self._user_data
else:
user_data = UserData.get_from_db_key_email(self.user.email())
if not user_data:
logging.critical("Empty user data for UserExercise w/ .user = %s" % self.user)
return user_data
def get_user_exercise_graph(self):
user_exercise_graph = None
if hasattr(self, "_user_exercise_graph"):
user_exercise_graph = self._user_exercise_graph
else:
user_exercise_graph = UserExerciseGraph.get(self.get_user_data())
return user_exercise_graph
def belongs_to(self, user_data):
return user_data and self.user.email().lower() == user_data.key_email.lower()
def struggling_threshold(self):
return self.exercise_model.struggling_threshold()
@staticmethod
def get_review_interval_from_seconds(seconds):
review_interval = datetime.timedelta(seconds=seconds)
if review_interval.days < consts.MIN_REVIEW_INTERVAL_DAYS:
review_interval = datetime.timedelta(days=consts.MIN_REVIEW_INTERVAL_DAYS)
elif review_interval.days > consts.MAX_REVIEW_INTERVAL_DAYS:
review_interval = datetime.timedelta(days=consts.MAX_REVIEW_INTERVAL_DAYS)
return review_interval
def has_been_proficient(self):
return self.proficient_date is not None
def get_review_interval(self):
return UserExercise.get_review_interval_from_seconds(self.review_interval_secs)
def schedule_review(self, correct, now=datetime.datetime.now()):
# If the user is not now and never has been proficient, don't schedule a review
if self.progress < 1.0 and not self.has_been_proficient():
return
# If the user is hitting a new streak either for the first time or after having lost
# proficiency, reset their review interval counter.
if self.progress >= 1.0:
self.review_interval_secs = 60 * 60 * 24 * consts.DEFAULT_REVIEW_INTERVAL_DAYS
review_interval = self.get_review_interval()
if correct and self.last_review != datetime.datetime.min:
time_since_last_review = now - self.last_review
if time_since_last_review >= review_interval:
review_interval = time_since_last_review * 2
if not correct:
review_interval = review_interval // 2
if correct:
self.last_review = now
else:
self.last_review = datetime.datetime.min
self.review_interval_secs = review_interval.days * 86400 + review_interval.seconds
def set_proficient(self, proficient, user_data):
if not proficient and not self.has_been_proficient():
# Not proficient and never has been so nothing to do
return
if proficient:
if self.exercise not in user_data.proficient_exercises:
self.proficient_date = datetime.datetime.now()
user_data.proficient_exercises.append(self.exercise)
user_data.need_to_reassess = True
user_data.put()
util_notify.update(user_data, self, False, True)
# Score conversions for A/B test
self.bingo_proficiency_model('prof_gained_proficiency_all')
if self.exercise in UserData.conversion_test_hard_exercises:
self.bingo_proficiency_model('prof_gained_proficiency_hard')
self.bingo_proficiency_model('prof_gained_proficiency_hard_binary')
bingo('hints_gained_proficiency_hard_binary')
elif self.exercise in UserData.conversion_test_easy_exercises:
self.bingo_proficiency_model('prof_gained_proficiency_easy')
self.bingo_proficiency_model('prof_gained_proficiency_easy_binary')
bingo('hints_gained_proficiency_easy_binary')
else:
if self.exercise in user_data.proficient_exercises:
user_data.proficient_exercises.remove(self.exercise)
user_data.need_to_reassess = True
user_data.put()
class CoachRequest(db.Model):
coach_requesting = db.UserProperty()
student_requested = db.UserProperty()
@property
def coach_requesting_data(self):
if not hasattr(self, "coach_user_data"):
self.coach_user_data = UserData.get_from_db_key_email(self.coach_requesting.email())
return self.coach_user_data
@property
def student_requested_data(self):
if not hasattr(self, "student_user_data"):
self.student_user_data = UserData.get_from_db_key_email(self.student_requested.email())
return self.student_user_data
@staticmethod
def key_for(user_data_coach, user_data_student):
return "%s_request_for_%s" % (user_data_coach.key_email, user_data_student.key_email)
@staticmethod
def get_for(user_data_coach, user_data_student):
return CoachRequest.get_by_key_name(CoachRequest.key_for(user_data_coach, user_data_student))
@staticmethod
def get_or_insert_for(user_data_coach, user_data_student):
return CoachRequest.get_or_insert(
key_name = CoachRequest.key_for(user_data_coach, user_data_student),
coach_requesting = user_data_coach.user,
student_requested = user_data_student.user,
)
@staticmethod
def get_for_student(user_data_student):
return CoachRequest.all().filter("student_requested = ", user_data_student.user)
@staticmethod
def get_for_coach(user_data_coach):
return CoachRequest.all().filter("coach_requesting = ", user_data_coach.user)
class StudentList(db.Model):
name = db.StringProperty()
coaches = db.ListProperty(db.Key)
def delete(self, *args, **kwargs):
self.remove_all_students()
db.Model.delete(self, *args, **kwargs)
def remove_all_students(self):
students = self.get_students_data()
for s in students:
s.student_lists.remove(self.key())
db.put(students)
@property
def students(self):
return UserData.all().filter("student_lists = ", self.key())
# these methods have the same interface as the methods on UserData
def get_students_data(self):
return [s for s in self.students]
@staticmethod
def get_for_coach(key):
query = StudentList.all()
query.filter("coaches = ", key)
return query
class UserVideoCss(db.Model):
user = db.UserProperty()
video_css = db.TextProperty()
pickled_dict = db.BlobProperty()
last_modified = db.DateTimeProperty(required=True, auto_now=True, indexed=False)
version = db.IntegerProperty(default=0, indexed=False)
STARTED, COMPLETED = range(2)
@staticmethod
def get_for_user_data(user_data):
p = pickle.dumps({'started': set([]), 'completed': set([])})
return UserVideoCss.get_or_insert(UserVideoCss._key_for(user_data),
user=user_data.user,
video_css='',
pickled_dict=p,
)
@staticmethod
def _key_for(user_data):
return 'user_video_css_%s' % user_data.key_email
@staticmethod
def set_started(user_data, video, version):
deferred.defer(set_css_deferred, user_data.key(), video.key(), UserVideoCss.STARTED, version)
@staticmethod
def set_completed(user_data, video, version):
deferred.defer(set_css_deferred, user_data.key(), video.key(), UserVideoCss.COMPLETED, version)
@staticmethod
def _chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
def load_pickled(self):
max_selectors = 20
css_list = []
css = pickle.loads(self.pickled_dict)
started_css = '{background-image:url(/images/video-indicator-started.png);padding-left:14px;}'
complete_css = '{background-image:url(/images/video-indicator-complete.png);padding-left:14px;}'
for id in UserVideoCss._chunker(list(css['started']), max_selectors):
css_list.append(','.join(id))
css_list.append(started_css)
for id in UserVideoCss._chunker(list(css['completed']), max_selectors):
css_list.append(','.join(id))
css_list.append(complete_css)
self.video_css = ''.join(css_list)
def set_css_deferred(user_data_key, video_key, status, version):
user_data = UserData.get(user_data_key)
uvc = UserVideoCss.get_for_user_data(user_data)
css = pickle.loads(uvc.pickled_dict)
id = '.v%d' % video_key.id()
if status == UserVideoCss.STARTED:
css['completed'].discard(id)
css['started'].add(id)
else:
css['started'].discard(id)
css['completed'].add(id)
uvc.pickled_dict = pickle.dumps(css)
uvc.load_pickled()
uvc.version = version
db.put(uvc)
PRE_PHANTOM_EMAIL = "http://nouserid.khanacademy.org/pre-phantom-user-2"
class UserData(GAEBingoIdentityModel, db.Model):
user = db.UserProperty()
user_id = db.StringProperty()
user_nickname = db.StringProperty(indexed=False)
current_user = db.UserProperty()
moderator = db.BooleanProperty(default=False)
developer = db.BooleanProperty(default=False)
joined = db.DateTimeProperty(auto_now_add=True)
last_login = db.DateTimeProperty(indexed=False)
proficient_exercises = object_property.StringListCompatTsvProperty() # Names of exercises in which the user is *explicitly* proficient
all_proficient_exercises = object_property.StringListCompatTsvProperty() # Names of all exercises in which the user is proficient
suggested_exercises = object_property.StringListCompatTsvProperty()
badges = object_property.StringListCompatTsvProperty() # All awarded badges
need_to_reassess = db.BooleanProperty(indexed=False)
points = db.IntegerProperty(default = 0)
total_seconds_watched = db.IntegerProperty(default = 0)
coaches = db.StringListProperty()
coworkers = db.StringListProperty()
student_lists = db.ListProperty(db.Key)
map_coords = db.StringProperty(indexed=False)
expanded_all_exercises = db.BooleanProperty(default=True, indexed=False)
videos_completed = db.IntegerProperty(default = -1)
last_daily_summary = db.DateTimeProperty(indexed=False)
last_badge_review = db.DateTimeProperty(indexed=False)
last_activity = db.DateTimeProperty(indexed=False)
start_consecutive_activity_date = db.DateTimeProperty(indexed=False)
count_feedback_notification = db.IntegerProperty(default = -1, indexed=False)
question_sort_order = db.IntegerProperty(default = -1, indexed=False)
user_email = db.StringProperty()
uservideocss_version = db.IntegerProperty(default = 0, indexed=False)
_serialize_blacklist = [
"badges", "count_feedback_notification",
"last_daily_summary", "need_to_reassess", "videos_completed",
"moderator", "expanded_all_exercises", "question_sort_order",
"last_login", "user", "current_user", "map_coords", "expanded_all_exercises",
"user_nickname", "user_email", "seconds_since_joined",
]
prof_conversion_accuracy_thresholds = [0.85, 0.90, 0.92, 0.94, 0.96]
_prof_model_conversion_tests = ([
('prof_gained_proficiency_all', ConversionTypes.Counting),
('prof_gained_proficiency_easy', ConversionTypes.Counting),
('prof_gained_proficiency_hard', ConversionTypes.Counting),
('prof_gained_proficiency_easy_binary', ConversionTypes.Binary),
('prof_gained_proficiency_hard_binary', ConversionTypes.Binary),
('prof_problems_done', ConversionTypes.Counting),
('prof_new_exercises_attempted', ConversionTypes.Counting),
('prof_does_problem_just_after_proficiency', ConversionTypes.Counting),
('prof_problem_correct_just_after_proficiency', ConversionTypes.Counting),
('prof_wrong_problems', ConversionTypes.Counting),
('prof_keep_going_after_wrong', ConversionTypes.Counting),
] + [('prof_accuracy_above_%s_easy' % p, ConversionTypes.Binary) for p in prof_conversion_accuracy_thresholds]
+ [('prof_accuracy_above_%s_hard' % p, ConversionTypes.Binary) for p in prof_conversion_accuracy_thresholds])
_prof_model_conversion_names, _prof_model_conversion_types = [list(x) for x in zip(*_prof_model_conversion_tests)]
conversion_test_hard_exercises = set(['order_of_operations', 'graphing_points',
'probability_1', 'domain_of_a_function', 'division_4',
'ratio_word_problems', 'writing_expressions_1', 'ordering_numbers',
'geometry_1', 'converting_mixed_numbers_and_improper_fractions'])
conversion_test_easy_exercises = set(['counting_1', 'significant_figures_1', 'subtraction_1'])
@property
@request_cache.cache()
def proficiency_model(self):
return ab_test("Proficiency Model", {"accuracy": 1, "streak": 9},
UserData._prof_model_conversion_names, UserData._prof_model_conversion_types)
@property
def nickname(self):
# Only return cached value if it exists and it wasn't cached during a Facebook API hiccup
if self.user_nickname and not is_facebook_user_id(self.user_nickname):
return self.user_nickname
else:
return nicknames.get_nickname_for(self)
@property
def email(self):
return self.user_email
@property
def key_email(self):
return self.user.email()
@property
def badge_counts(self):
return util_badges.get_badge_counts(self)
@staticmethod
@request_cache.cache()
def current():
user_id = util.get_current_user_id(bust_cache=True)
email = user_id
google_user = users.get_current_user()
if google_user:
email = google_user.email()
if user_id:
# Once we have rekeyed legacy entities,
# we will be able to simplify this.we make
return UserData.get_from_user_id(user_id) or \
UserData.get_from_db_key_email(email) or \
UserData.insert_for(user_id, email)
return None
@staticmethod
def pre_phantom():
return UserData.insert_for(PRE_PHANTOM_EMAIL, PRE_PHANTOM_EMAIL)
@property
def is_phantom(self):
return util.is_phantom_user(self.user_id)
@property
def is_pre_phantom(self):
return PRE_PHANTOM_EMAIL == self.user_email
@property
def seconds_since_joined(self):
return util.seconds_since(self.joined)
@staticmethod
@request_cache.cache_with_key_fxn(lambda user_id: "UserData_user_id:%s" % user_id)
def get_from_user_id(user_id):
if not user_id:
return None
query = UserData.all()
query.filter('user_id =', user_id)
query.order('-points') # Temporary workaround for issue 289
return query.get()
@staticmethod
def get_from_user_input_email(email):
if not email:
return None
query = UserData.all()
query.filter('user_email =', email)
query.order('-points') # Temporary workaround for issue 289
return query.get()
@staticmethod
def get_from_db_key_email(email):
if not email:
return None
query = UserData.all()
query.filter('user =', users.User(email))
query.order('-points') # Temporary workaround for issue 289
return query.get()
@staticmethod
def insert_for(user_id, email):
if not user_id or not email:
return None
user = users.User(email)
key = "user_id_key_%s" % user_id
user_data = UserData.get_or_insert(
key_name=key,
user=user,
current_user=user,
user_id=user_id,
moderator=False,
last_login=datetime.datetime.now(),
proficient_exercises=[],
suggested_exercises=[],
need_to_reassess=True,
points=0,
coaches=[],
user_email=email
)
if not user_data.is_phantom:
# Record that we now have one more registered user
if (datetime.datetime.now() - user_data.joined).seconds < 60:
# Extra safety check against user_data.joined in case some
# subtle bug results in lots of calls to insert_for for
# UserData objects with existing key_names.
user_counter.add(1)
return user_data
def delete(self):
logging.info("Deleting user data for %s with points %s" % (self.key_email, self.points))
logging.info("Dumping user data for %s: %s" % (self.user_id, jsonify(self)))
if not self.is_phantom:
user_counter.add(-1)
db.delete(self)
def get_or_insert_exercise(self, exercise, allow_insert = True):
if not exercise:
return None
exid = exercise.name
userExercise = UserExercise.get_by_key_name(exid, parent=self)
if not userExercise:
# There are some old entities lying around that don't have keys.
# We have to check for them here, but once we have reparented and rekeyed legacy entities,
# this entire function can just be a call to .get_or_insert()
query = UserExercise.all(keys_only = True)
query.filter('user =', self.user)
query.filter('exercise =', exid)
query.order('-total_done') # Temporary workaround for issue 289
# In order to guarantee consistency in the HR datastore, we need to query
# via db.get for these old, parent-less entities.
key_user_exercise = query.get()
if key_user_exercise:
userExercise = UserExercise.get(str(key_user_exercise))
if allow_insert and not userExercise:
userExercise = UserExercise.get_or_insert(
key_name=exid,
parent=self,
user=self.user,
exercise=exid,
exercise_model=exercise,
streak=0,
_progress=0.0,
streak_start=0.0,
longest_streak=0,
first_done=datetime.datetime.now(),
last_done=None,
total_done=0,
summative=exercise.summative,
_accuracy_model=AccuracyModel(),