예제 #1
0
def compareMP(user):
    # Calculating MP match in real time. Should do this once, when votes are inserted.
    questions = Question.all()

    # Get UserVotes and capture the IDs
    user_votes = UserVote.all().filter('user_username ='******'question =', u_vote.question)
        if mp_vote.count() > 0:
            both_voted_on = both_voted_on + 1
            if score == 100:
                exact_match_on = exact_match_on + 1
            score = score + calculate_score(mp_vote[0].selection,
                                            u_vote.selection)

    if user_votes.count() > 0:
        score = score / user_votes.count()

    return {
        'both_voted_on': both_voted_on,
        'exact_match_on': exact_match_on,
        'politmus_score': score
    }
예제 #2
0
파일: utils.py 프로젝트: ahume/politmus-api
def compareMP(user):
	# Calculating MP match in real time. Should do this once, when votes are inserted.
	questions = Question.all()

	# Get UserVotes and capture the IDs
	user_votes = UserVote.all().filter('user_username ='******'question =', u_vote.question)
		if mp_vote.count() > 0:
			both_voted_on = both_voted_on + 1
			if score == 100:
				exact_match_on = exact_match_on + 1
			score = score + calculate_score(mp_vote[0].selection, u_vote.selection)

	if user_votes.count() > 0:
		score = score / user_votes.count()

	return {
		'both_voted_on': both_voted_on,
		'exact_match_on': exact_match_on,
		'politmus_score': score
	}
def get_question():
    questions = Question.all()
    if questions.count() == 0:
        new_question = Question(text="Dummy text")
        new_question.save()
    else:
        new_question = questions[0]
    return new_question
예제 #4
0
파일: utils.py 프로젝트: ahume/politmus-api
def getUnansweredQuestionsFor(username):
	vote_ids = [a.question for a in getAnsweredQuestionsFor(username)]

	question_ids = [str(q.key()) for q in Question.all()]
	filtered_ids = []
	for qid in question_ids:
		if qid not in vote_ids:
			filtered_ids.append(qid)
	questions = Question.get(filtered_ids)
	return questions
예제 #5
0
def getUnansweredQuestionsFor(username):
    vote_ids = [a.question for a in getAnsweredQuestionsFor(username)]

    question_ids = [str(q.key()) for q in Question.all()]
    filtered_ids = []
    for qid in question_ids:
        if qid not in vote_ids:
            filtered_ids.append(qid)
    questions = Question.get(filtered_ids)
    return questions
예제 #6
0
    def get(self):

        response = {}

        self.query = Question.all()
        response['total'] = self.query.count()
        response = self.addPagingFilters(response)
        response['questions'] = [utils.question_to_dict(q) for q in self.query]

        self.returnJSON(200, response)
예제 #7
0
	def get(self):

		response = {}

		self.query = Question.all()
		response['total'] = self.query.count()
		response = self.addPagingFilters(response)
		response['questions'] = [utils.question_to_dict(q) for q in self.query]

		self.returnJSON(200, response)
예제 #8
0
파일: cron.py 프로젝트: BarbaraEMac/TrivBot
    def get(self):
        # Fetch question
        q = get_question()

        # And mark it as used!
        if q:
            q.state = 'used'
            q.put()

        # Get a new question
        new_q = Question.all().filter("state = ", 'unused').get()

        # Set the day to today!
        new_q.day = triv_today()
        new_q.state = 'in_use'

        # Save the new question
        new_q.put()

        if Question.all().filter('state = ', 'unused').count() <= 3:
            Emailer.outOfQuestions()
예제 #9
0
파일: cron.py 프로젝트: BarbaraEMac/TrivBot
    def get( self ):
        # Fetch question
        q = get_question()
        
        # And mark it as used!
        if q:
            q.state = 'used'
            q.put()

        # Get a new question
        new_q = Question.all().filter("state = ", 'unused').get()
        
        # Set the day to today!
        new_q.day   = triv_today( )
        new_q.state = 'in_use'

        # Save the new question
        new_q.put()

        if Question.all().filter('state = ', 'unused').count() <= 3:
            Emailer.outOfQuestions()
예제 #10
0
	def getUnansweredQuestions(self):

		if self.answered_ids is None:
			self.getAnsweredQuestions()

		question_ids = [str(q.key()) for q in Question.all()]

		filtered_ids = []
		for q in question_ids:
			if q not in self.answered_ids:
				filtered_ids.append(q)

		return Question.get(filtered_ids)
예제 #11
0
    def getUnansweredQuestions(self):

        if self.answered_ids is None:
            self.getAnsweredQuestions()

        question_ids = [str(q.key()) for q in Question.all()]

        filtered_ids = []
        for q in question_ids:
            if q not in self.answered_ids:
                filtered_ids.append(q)

        return Question.get(filtered_ids)
예제 #12
0
    def get( self ):
        qwe = Question.all()
        for q in qwe:
            if hasattr(q, 'used'):
                logging.error("Deleting 1 %s" % q.question)
                delattr(q, 'used')
                delattr(q, 'offer_id')
                q.put()
            #q.state = 'used'
            #q.delete()
        
        path = os.path.join(os.path.split(__file__)[0], 'next_q.csv')
        f = open( path, 'r' )

        items = f.read().split('\n')
        logging.error("NUM QUERIOSN %d" % len(items) )

        j = qwe.count()
        for i in items:
            if len(i) == 0:
                break

            logging.error("LINE: %s" % i)
            tmp = i.split(',')
            
            random.seed( str(j) )
            a = random.randint( 3, 6 )
            b = random.randint( 3, 6 )
            while b == a:
                b = random.randint( 3, 6 )
            c = random.randint( 3, 6 )
            while c == a or c == b:
                c = random.randint( 3, 6 )
            d = random.randint( 3, 6 )
            while d == a or d == b or d == c:
                d = random.randint( 3, 6 )
            
            q = Question( key_name=str(j), 
            question=tmp[2], 
            opt_1=tmp[a], 
            opt_2=tmp[b], 
            opt_3=tmp[c], 
            opt_4=tmp[d], 
            answer=tmp[6], 
            difficulty=tmp[0],
            category=tmp[1])
            
            q.put()
            logging.error("PUTTING 1")
            j += 1
        self.response.out.write( "done" )
예제 #13
0
    def dailyEmail( user ):
        question = Question.all().filter('day = ', triv_today()).get()
        #logging.error('question %s %s %s' % (question.question, question.category, question.difficulty))
        to_addr  = user.email
        subject  = '[TrivBot] Today\'s Question'
        body     = """ <html> <head><style type="text/css"> body {background-image: url("http://www.trivbot.com/images/question_grey3.png");
        background-repeat: no-repeat; background-attachment: fixed; background-position: bottom right; font-family: monaco, monospace; font-size: 1.1em;
        background-color: black; color: yellow; border: 5px solid #0e53a7; border-radius: 20px;}</style></head><body><center><div><div><h2>Morning %s
        %s!</h2></div> </div> <div> <p>Here is today's (%s) category:</p> <h1>%s</h1> <p>and difficulty: <h1>%s / 3.</h1></p> <p> Visit <a
        href="http://www.trivbot.com">www.trivbot.com</a> today to increase your score!</p><p>Remember: if you PASS, you still get points!</p><p> -- TrivBot Team</p> </div><div><a href="http://www.trivbot.com"><img alt="TrivBot" height="100px" src="http://www.trivbot.com/images/logo_bot5.png"></a></img><p>To stop receiving these emails, uncheck the 'Daily Email' box on the Account page.</p></div> </center></body> </html> 
        """ % ( user.first_name, user.last_name, datetime.date( datetime.today() ).strftime( '%A %B %d, %Y' ), question.category, question.difficulty )
        
        #logging.error(body)

        Emailer.send_email( from_addr, to_addr, subject, body )
예제 #14
0
    def get(self):

        questions = list(Question.all())
        questions = sorted(questions, key=lambda x: x.last_modified, reverse=True)

        q_dict = OrderedDict()
        for question in questions:
            answers = question.answers
            answers = list(db.get(answers))
            if answers is not None:
                answers = filter(lambda x: x is not None, answers)
                answers = sorted(answers, key=lambda answer: answer.get_votes(), reverse=True)
                if len(answers) != 0:
                    q_dict[question] = answers[0].answer
                else:
                    q_dict[question] = "No answers yet"
        self.render("quora_homepage.html", q_dict=q_dict)
예제 #15
0
    def dailyEmail(user):
        question = Question.all().filter('day = ', triv_today()).get()
        #logging.error('question %s %s %s' % (question.question, question.category, question.difficulty))
        to_addr = user.email
        subject = '[TrivBot] Today\'s Question'
        body = """ <html> <head><style type="text/css"> body {background-image: url("http://www.trivbot.com/images/question_grey3.png");
        background-repeat: no-repeat; background-attachment: fixed; background-position: bottom right; font-family: monaco, monospace; font-size: 1.1em;
        background-color: black; color: yellow; border: 5px solid #0e53a7; border-radius: 20px;}</style></head><body><center><div><div><h2>Morning %s
        %s!</h2></div> </div> <div> <p>Here is today's (%s) category:</p> <h1>%s</h1> <p>and difficulty: <h1>%s / 3.</h1></p> <p> Visit <a
        href="http://www.trivbot.com">www.trivbot.com</a> today to increase your score!</p><p>Remember: if you PASS, you still get points!</p><p> -- TrivBot Team</p> </div><div><a href="http://www.trivbot.com"><img alt="TrivBot" height="100px" src="http://www.trivbot.com/images/logo_bot5.png"></a></img><p>To stop receiving these emails, uncheck the 'Daily Email' box on the Account page.</p></div> </center></body> </html> 
        """ % (user.first_name, user.last_name, datetime.date(
            datetime.today()).strftime('%A %B %d, %Y'), question.category,
               question.difficulty)

        #logging.error(body)

        Emailer.send_email(from_addr, to_addr, subject, body)
예제 #16
0
파일: users.py 프로젝트: Cojuvy/pggame
    def get(self):
        user = users.get_current_user()
        result = {'questions': [],
                  'answers': []}
        questions = Question.all()
        questions = questions.filter('user', user)
        questions = questions.fetch(5)
        for q in questions:
            result['questions'].append(q.json)

        answers = Answer.all()
        answers = answers.filter('user', user)
        answers = answers.filter('is_done', True)
        answers = answers.fetch(5)
        for a in answers:
            result['answers'].append(a.json)

        return result
예제 #17
0
파일: views.py 프로젝트: ahbuntu/ece1779
def get_questions():
    """returns the questions in JSON format"""
    lat = request.args.get('lat', 0, type=float)
    lon = request.args.get('lon', 0, type=float)
    radius = request.args.get('radius', 0, type=float)

    if lat == 0 and lon == 0 and radius == 0:
        questions = Question.all()
    else:
        radius_in_metres = float(radius) * 1000.0
        q = "distance(location, geopoint(%f, %f)) <= %f" % (float(lat), float(lon), float(radius_in_metres))

        # build the index if not already done
        if search.get_indexes().__len__() == 0:
            rebuild_question_search_index()

        index = search.Index(name="myQuestions")
        results = index.search(q)

        # TODO: replace this with a proper .query
        questions = [Question.get_by_id(long(r.doc_id)) for r in results]
        questions = filter(None, questions) # filter deleted questions
        if questions:
            questions = sorted(questions, key=lambda question: question.timestamp)

    dataset = []
    for question in questions:
        # This conversion can be performed using a custom JsonEncoder implementation,
        # but I didn't have much success. Some good links below -
        # http://stackoverflow.com/questions/1531501/json-serialization-of-google-app-engine-models
        # https://gist.github.com/erichiggins/8969259
        # https://gist.github.com/bengrunfeld/062d0d8360667c47bc5b
        details = {'key': question.key.id(),
                   'added_by': question.added_by.nickname(),
                   'content': question.content,
                   'timestamp': question.timestamp.strftime('%m-%d-%y'),
                   'location': {'lat': question.location.lat,
                                'lon': question.location.lon}
                   }
        dataset.append(details)

    return jsonify(result=dataset)
예제 #18
0
파일: views.py 프로젝트: ahbuntu/ece1779
def list_questions():
    """Lists all questions posted on the site - available to anonymous users"""
    form = QuestionForm()
    search_form = QuestionSearchForm()
    user = users.get_current_user()
    login_url = users.create_login_url(url_for('home'))

    query_string = request.query_string
    latitude = request.args.get('lat')
    longitude = request.args.get('lon')
    radius = request.args.get('r')

    # If searching w/ params (GET)
    if request.method == 'GET' and all(v is not None for v in (latitude, longitude, radius)):
        radius_in_metres = float(radius) * 1000.0
        q = "distance(location, geopoint(%f, %f)) <= %f" % (float(latitude), float(longitude), float(radius_in_metres))

        # build the index if not already done
        if search.get_indexes().__len__() == 0:
            rebuild_question_search_index()

        index = search.Index(name="myQuestions")
        results = index.search(q)

        # TODO: replace this with a proper .query
        questions = [Question.get_by_id(long(r.doc_id)) for r in results]
        questions = filter(None, questions) # filter deleted questions
        if questions:
            questions = sorted(questions, key=lambda question: question.timestamp)

        search_form.latitude.data = float(latitude)
        search_form.longitude.data = float(longitude)
        search_form.distance_in_km.data = radius_in_metres/1000.0
    else:
        questions = Question.all()

    channel_token = None
    if (user):
        channel_token = safe_channel_create(user_channel_id(user))
    return render_template('list_questions.html', questions=questions, form=form, user=user, login_url=login_url, search_form=search_form, channel_token=channel_token)
예제 #19
0
def setup():
    User.collection.remove({})
    Question.collection.remove({})

    assert User.all({}).count() == 0
    assert Question.all({}).count() == 0
예제 #20
0
파일: helpers.py 프로젝트: ahbuntu/Skoozi
def api_rebuild_question_search_index():
    """Used to generate/build the geo-search index."""
    questions = Question.all()
    [api_add_question_to_search_index(q) for q in questions]
예제 #21
0
 def get_questions_by_set(self, set_obj):
     questions = Question.all().filter('set_name =',
                                       set_obj).order('last_edited')
     return questions
예제 #22
0
파일: views.py 프로젝트: ahbuntu/ece1779
def rebuild_question_search_index():
    """Used to generate/build the geo-search index."""
    questions = Question.all()
    [add_question_to_search_index(q) for q in questions]
    return redirect(url_for('list_questions'))
    def get(self):
        questions = Question.all()
        responseSets = ResponseSet.all()

        values = {'questions': questions, 'responseSets': responseSets}
        self.response.out.write(template.render('templates/questionAdmin.html', values))