def unstarred_word(word_id, user_id): word = UserWord.query.get(word_id) user = User.find_by_id(user_id) user.starred_words.remove(word) zeeguu.db.session.commit() print word + " is now *unstarred* for user " + user.name return "OK"
def change_password_if_code_is_correct(code, email, password): """ The params are the user input values :param code:string :param email: string :param password: string :return: """ last_code = UniqueCode.last_code(email) if code == last_code: if len(password) < 4: flash("Password must be at least 4 characters long") return flask.render_template("reset_pass.html", code_active=True, email=email, code=code) user = User.find(email) user.update_password(password) db.session.commit() # Delete all the codes for this user for x in UniqueCode.all_codes_for(email): db.session.delete(x) db.session.commit() flash("Password was reset successfully!") return flask.redirect('login') else: flask.flash("Code seems wrong. Did you check your email?") return flask.render_template("reset_pass.html", code_active=True, message=True, email=email)
def create_minimal_test_db(db): drop_current_tables(db) # Some common test fixtures de = Language("de", "German") en = Language("en", "English") nl = Language("nl", "Dutch") es = Language("es", "Spanish") fr = Language("fr", "French") db.session.add_all([en, de, nl, es, fr]) mir = User(TEST_EMAIL, "Mircea", TEST_PASS, de, en) db.session.add(mir) show_solution = ExerciseOutcome("Show solution") retry = ExerciseOutcome("Retry") correct = ExerciseOutcome("Correct") wrong = ExerciseOutcome("Wrong") typo = ExerciseOutcome("Typo") too_easy = ExerciseOutcome("Too easy") outcomes = [show_solution, retry, correct, wrong, typo, too_easy] db.session.add_all(outcomes) recognize = ExerciseSource("Recognize") translate = ExerciseSource("Translate") sources = [recognize, translate] db.session.add_all(sources) b1 = add_bookmark(db, mir, de, "Schaf", en, "sheep", datetime.datetime(2011, 1, 1, 1, 1, 1), "Bitte... zeichne mir ein Schaf!", "http://www.derkleineprinz-online.de/text/2-kapitel/", "Der Kleine Prinz - Kapitel 2") b2 = add_bookmark(db, mir, de, "sprang", en, "jumped", datetime.datetime(2011, 1, 1, 1, 1, 1), "Ich sprang auf die Fusse.", "http://www.derkleineprinz-online.de/text/2-kapitel/", "Der Kleine Prinz - Kapitel 2") bookmarks = [b1, b2] for i in range(0, 5): random_source = sources[random.randint(0, len(sources) - 1)] random_outcome = outcomes[random.randint(0, len(outcomes) - 1)] random_solving_speed = random.randint(500, 5000) exercise = Exercise(random_outcome, random_source, random_solving_speed, datetime.datetime.now()) random_bookmark = bookmarks[random.randint(0, len(bookmarks) - 1)] random_bookmark.add_new_exercise(exercise) global TEST_BOOKMARKS_COUNT TEST_BOOKMARKS_COUNT = 2 db.session.commit()
def set_default_encounter_based_prob(): zeeguu.app.test_request_context().push() zeeguu.db.session.commit() default_probability = 0.5 languages = Language.all() users = User.find_all() for user in users: for lang in languages: marked_words_of_user_in_text = [] words_of_all_bookmarks_content = [] for bookmark in Bookmark.find_by_specific_user(user): if bookmark.origin.language == lang: # bookmark_content_words = re.sub("[^\w]", " ", bookmark.text.content).split() bookmark_content_words = re.findall( r'(?u)\w+', bookmark.text.content) words_of_all_bookmarks_content.extend( bookmark_content_words) marked_words_of_user_in_text.append(bookmark.origin.word) words_known_from_user = [ word for word in words_of_all_bookmarks_content if word not in marked_words_of_user_in_text ] for word_known in words_known_from_user: if RankedWord.exists(word_known, lang): rank = RankedWord.find(word_known, lang) if EncounterBasedProbability.exists(user, rank): prob = EncounterBasedProbability.find( user, rank, default_probability) prob.not_looked_up_counter += 1 else: prob = EncounterBasedProbability.find( user, rank, default_probability) zeeguu.db.session.add(prob) zeeguu.db.session.commit() print 'job2'
def set_default_encounter_based_prob(): zeeguu.app.test_request_context().push() zeeguu.db.session.commit() default_probability = 0.5 languages = Language.all() users = User.find_all() for user in users: for lang in languages: marked_words_of_user_in_text = [] words_of_all_bookmarks_content = [] for bookmark in Bookmark.find_by_specific_user(user): if bookmark.origin.language == lang: # bookmark_content_words = re.sub("[^\w]", " ", bookmark.text.content).split() bookmark_content_words = re.findall(r'(?u)\w+', bookmark.text.content) words_of_all_bookmarks_content.extend(bookmark_content_words) marked_words_of_user_in_text.append(bookmark.origin.word) words_known_from_user= [word for word in words_of_all_bookmarks_content if word not in marked_words_of_user_in_text] for word_known in words_known_from_user: if RankedWord.exists(word_known, lang): rank = RankedWord.find(word_known, lang) if EncounterBasedProbability.exists(user, rank): prob = EncounterBasedProbability.find(user,rank, default_probability) prob.not_looked_up_counter +=1 else: prob = EncounterBasedProbability.find(user,rank,default_probability) zeeguu.db.session.add(prob) zeeguu.db.session.commit() print 'job2'
def change_password_if_code_is_correct(code, email, password): """ The params are the user input values :param code:string :param email: string :param password: string :return: """ last_code = UniqueCode.last_code(email) if code == last_code: if len(password) < 4: flash("Password must be at least 4 characters long") return flask.render_template("reset_pass.html", code_active=True, email=email, code=code) user = User.find(email) user.update_password(password) db.session.commit() # Delete all the codes for this user for x in UniqueCode.all_codes_for(email): db.session.delete(x) db.session.commit() flash("Password was reset successfully!") return flask.redirect('login') else: flask.flash("Code seems wrong. Did you check your email?") return flask.render_template("reset_pass.html", code_active=True, message=True, email=email)
def create_account(): # A cool way of passing the arguments to the flask template template_arguments = dict ( languages= Language.all(), native_languages = Language.native_languages(), default_learned= Language.default_learned() ) # GET if flask.request.method == "GET": return flask.render_template("create_account.html", **template_arguments) # POST form = flask.request.form password = form.get("password", None) email = form.get("email", None) name = form.get("name", None) code = form.get("code", None) language = Language.find(form.get("language", None)) native_language = Language.find(form.get("native_language", None)) if not (code == "Kairo" or code == "unibe" or code == "rug" or code =="42"): flash("Invitation code is not recognized. Please contact us.") elif password is None or email is None or name is None: flash("Please enter your name, email address, and password") else: try: zeeguu.db.session.add(User(email, name, password, language, native_language)) zeeguu.db.session.commit() user = User.authorize(email, password) flask.session["user"] = user.id return flask.redirect(flask.url_for("account.my_account")) except ValueError: flash("Username could not be created. Please contact us.") except sqlalchemy.exc.IntegrityError: flash(email + " is already in use. Please select a different email.") except: flash("Something went wrong. Please contact us.") finally: zeeguu.db.session.rollback() return flask.render_template("create_account.html", **template_arguments)
def setUp(self): # Superclass does prepare the DB before each of the tests super(Dbtest, self).setUp() # Some common test fixtures self.mir = User.find("*****@*****.**") assert self.mir self.de = Language.find("de")
def setUp(self): # Superclass does prepare the DB before each of the tests super(Dbtest, self).setUp() # Some common test fixtures self.mir = User.find("*****@*****.**") assert self.mir self.de = Language.find("de")
def test_user_session(self): user = User.find("*****@*****.**") with zeeguu.app.app_context(): s = Session.find_for_user(user) s2 = Session.find_for_id(s.id) assert (s2.user == user) s3 = Session.find_for_id(3) assert not s3
def test_password_hash(self): p1 = "test" p2 = "pass" with zeeguu.app.app_context(): user = User.find("*****@*****.**") hash1 = util.password_hash(p1, user.password_salt) hash2 = util.password_hash(p2, user.password_salt) assert hash1 != hash2 assert user.authorize("*****@*****.**", "pass") != None
def test_login_with_session(self): self.logout() result = self.api_post("/login_with_session", dict(session_id="101")) assert (result.data == "FAIL") result = self.api_get("/m_recognize") assert "Redirecting..." in result.data user = User.find("*****@*****.**") with zeeguu.app.app_context(): actual_session = str(Session.find_for_user(user).id) result = self.api_post("/login_with_session", dict(session_id=actual_session)) assert result.data == "OK" result = self.api_get("/m_recognize") assert "Redirecting..." not in result.data
def add_user(email): """ Creates user, then redirects to the get_session endpoint. Returns a session """ password = request.form.get("password", None) username = request.form.get("username", None) if password is None: flask.abort(400) try: zeeguu.db.session.add(User(email, username, password)) zeeguu.db.session.commit() except ValueError: flask.abort(400) except sqlalchemy.exc.IntegrityError: flask.abort(400) return get_session(email)
def login(): form = flask.request.form if flask.request.method == "POST" and form.get("login", False): password = form.get("password", None) email = form.get("email", None) if password is None or email is None: flask.flash("Please enter your email address and password") else: user = User.authorize(email, password) if user is None: flask.flash("Invalid email and password combination") else: flask.session["user"] = user.id flask.session.permanent = True return flask.redirect( flask.request.args.get("next") or flask.url_for("account.my_account")) return flask.render_template("login.html")
def get_session(email): """ If the email and password match, a new sessionId is created, and returned as a string. This sessionId has to be passed along all the other requests that are annotated with @with_user in this file """ password = request.form.get("password", None) if password is None: flask.abort(400) user = User.authorize(email, password) if user is None: flask.abort(401) session = Session.for_user(user) zeeguu.db.session.add(session) zeeguu.db.session.commit() return str(session.id)
def get_session(email): """ If the email and password match, a new sessionId is created, and returned as a string. This sessionId has to be passed along all the other requests that are annotated with @with_user in this file """ password = request.form.get("password", None) if password is None: flask.abort(400) user = User.authorize(email, password) if user is None: flask.abort(401) session = Session.for_user(user) zeeguu.db.session.add(session) zeeguu.db.session.commit() return str(session.id)
def _create_model_object(self): random_email = self.faker.simple_profile()['mail'] random_name = self.faker.name() random_password = self.faker.password() random_learned_language = LanguageRule().random random_native_language = LanguageRule().random while random_native_language.id == random_learned_language.id: random_native_language = LanguageRule().random user = User(random_email, random_name, random_password, learned_language=random_learned_language, native_language=random_native_language) if self._exists_in_db(user): return self._create_model_object() return user
def set_default_exercise_based_prob(): zeeguu.app.test_request_context().push() zeeguu.db.session.commit() users = User.find_all() languages = Language.all() for user in users: for language in languages: user_words_by_language = UserWord.find_by_language(language) for word in user_words_by_language: if ExerciseBasedProbability.exists(user, word): prob = ExerciseBasedProbability.find(user, word) bookmarks_by_user_and_word = Bookmark.find_all_by_user_and_word( user, word) total_prob = 0 for bookmark in bookmarks_by_user_and_word: prob.calculate_known_bookmark_probability(bookmark) total_prob += float(prob.probability) if bookmarks_by_user_and_word: prob.probability = total_prob / len( bookmarks_by_user_and_word) zeeguu.db.session.commit() print('job1')
def starred_word(word_id, user_id): word = UserWord.query.get(word_id) user = User.find_by_id(user_id) user.star(word) zeeguu.db.session.commit() return "OK"
def _exists_in_db(obj): return User.exists(obj)
def create_test_db(db): drop_current_tables(db) de = Language("de", "German") da = Language("da", "Danish") en = Language("en", "English") es = Language("es", "Spanish") fr = Language("fr", "French") it = Language("it", "Italian") no = Language("no", "Norwegian") nl = Language("nl", "Dutch") pt = Language("pt", "Portughese") ro = Language("ro", "Romanian") db.session.add(de) db.session.add(da) db.session.add(en) db.session.add(es) db.session.add(fr) db.session.add(it) db.session.add(no) db.session.add(nl) db.session.add(pt) db.session.add(ro) db.session.commit() show_solution = ExerciseOutcome("Show solution") retry = ExerciseOutcome("Retry") correct = ExerciseOutcome("Correct") wrong = ExerciseOutcome("Wrong") typo = ExerciseOutcome("Typo") too_easy = ExerciseOutcome("Too easy") recognize = ExerciseSource("Recognize") translate = ExerciseSource("Translate") zeekoe = ExerciseSource("ZeeKoe") db.session.add(show_solution) db.session.add(retry) db.session.add(correct) db.session.add(wrong) db.session.add(typo) db.session.add(too_easy) db.session.add(recognize) db.session.add(translate) db.session.add(zeekoe) user = User(TEST_EMAIL, "Mircea", TEST_PASS, de, ro) user2 = User("*****@*****.**", "Ada", "pass", fr) db.session.add(user) db.session.add(user2) jan111 = datetime.datetime(2011, 0o1, 0o1, 0o1, 0o1, 0o1) ian101 = datetime.datetime(2001, 0o1, 0o1, 0o1, 0o1, 0o1) jan14 = datetime.datetime(2014, 1, 14, 0o1, 0o1, 0o1) today_dict = { 'sogar': 'actually', 'sperren': 'to lock, to close', 'Gitter': 'grates', 'erfahren': 'to experience', 'treffen': 'hit', 'jeweils': 'always', 'Darstellung': 'presentation', 'Vertreter': 'representative', 'Knecht': 'servant', 'der': 'the' } dict = { 'Spaß': 'fun', 'solche': 'suchlike', 'ehemaliger': 'ex', 'betroffen': 'affected', 'Ufer': 'shore', 'höchstens': 'at most' } french_dict = {'jambes': 'legs', 'de': 'of', 'et': 'and'} story_url = 'http://www.gutenberg.org/files/23393/23393-h/23393-h.htm' japanese_story = [ # ['recht', 'right', 'Du hast recht', story_url], [ 'Holzhauer', 'wood choppers', 'Da waren einmal zwei Holzhauer können', story_url ], ['Da', 'there', 'Da waren einmal zwei Holzhauer können', story_url], ['zwei', 'two', 'Da waren einmal zwei Holzhauer können', story_url], [ 'Wald', 'to arrive', 'Um in den Walden zu gelangen, mußten sie einen großen Fluß passieren. Um in den Walden zu gelangen, mußten sie einen großen Fluß passieren. Um in den Walden zu gelangen, mußten sie einen großen Fluß passieren. Um in den Walden zu gelangen, mußten sie einen großen Fluß passieren', story_url ], [ 'eingerichtet', 'established', 'Um in den Wald zu gelangen, mußten sie einen großen Fluß passieren, über den eine Fähre eingerichtet war', story_url ], [ 'vorläufig', 'temporary', 'von der er des rasenden Sturmes wegen vorläufig nicht zurück konnte', story_url ], [ 'werfen', 'to throw', 'Im Hause angekommen, warfen sie sich zur Erde,', story_url ], [ 'Tosen', 'roar', 'sie Tür und Fenster wohl verwahrt hatten und lauschten dem Tosen des Sturmes.sie Tür und Fenster wohl verwahrt hatten und lauschten dem Tosen des Sturmes.sie Tür und Fenster wohl verwahrt hatten und lauschten dem Tosen des Sturmes', story_url ], [ 'Entsetzen', 'horror', 'Entsetzt starrte Teramichi auf die Wolke', story_url ] ] for key in today_dict: add_bookmark( db, user, de, key, en, today_dict[key], jan111, "Keine bank durfe auf immunitat pochen, nur weil sie eine besonders herausgehobene bedeutung fur das finanzsystem habe, sagte holder, ohne namen von banken zu nennen", "http://url2", "title of url2") for key in dict: add_bookmark( db, user, de, key, en, dict[key], ian101, "Deutlich uber dem medianlohn liegen beispielsweise forschung und entwicklung, tabakverarbeitung, pharma oder bankenwesen, am unteren ende der skala liegen die tieflohnbranchen detailhandel, gastronomie oder personliche dienstleistungen. ", "http://url1", "title of url1") for key in french_dict: add_bookmark( db, user, de, key, en, french_dict[key], ian101, "Deutlich uber dem medianlohn liegen beispielsweise forschung und entwicklung, tabakverarbeitung, pharma oder bankenwesen, am unteren ende der skala liegen die tieflohnbranchen detailhandel, gastronomie oder personliche dienstleistungen. ", "http://url1", "title of url1") for w in japanese_story: add_bookmark(db, user, de, w[0], en, w[1], jan14, w[2], w[3], "japanese story") db.session.commit()