コード例 #1
0
    def isvalid(questionnaire):
        """isvalid(questionnaire:Questionnaire)
		Returns true if the questionnaire is valid, false otherwise.
		"""
        valid, message = True, None
        if questionnaire is not None:
            if questionnaire.questions is not None:
                for question in questionnaire.questions.values():
                    valid, message = Question.isvalid(question)
                    if not valid:
                        break

                # If the questionnaire entries are valid, validate the control flow.
                if valid and questionnaire.controlflow is not None:
                    for k in [
                            k for k in questionnaire.controlflow.values()
                            if k is not None
                    ]:
                        valid, message = questionnaire.isbranchablekey(k)
                        if not valid:
                            break
            else:
                valid, message = False, "Error! Empty questionnaire. A questionnaire must contain at least one question."
        else:
            valid, message = False, "Error! A 'NoneType' object is not considered a questionnaire."

        return (valid, message)
コード例 #2
0
ファイル: xmppHandler.py プロジェクト: MrCoder/CodeReview
  def tellme_command(self, message=None):
    im_from = db.IM("xmpp", message.sender)
    asked_question = self._GetAsked(im_from)
    currently_answering = self._GetAnswering(im_from)

    if asked_question:
      # Already have a question
      message.reply(WAIT_MSG)
    else:
      # Asking a question
      asked_question = Question(question=message.arg, asker=im_from)
      asked_question.put()

      if not currently_answering:
        # Try and find one for them to answer
        question = Question.assignQuestion(im_from)
        if question:
          message.reply(TELLME_MSG % (question.question,))
          return
      message.reply(PONDER_MSG)
コード例 #3
0
ファイル: xmppHandler.py プロジェクト: MrCoder/CodeReview
 def askme_command(self, message=None):
   im_from = db.IM("xmpp", message.sender)
   currently_answering = self._GetAnswering(im_from)
   question = Question.assignQuestion(im_from)
   if question:
     message.reply(TELLME_MSG % (question.question,))
   else:
     message.reply(EMPTYQ_MSG)
   # Don't unassign their current question until we've picked a new one.
   if currently_answering:
     currently_answering.unassign(im_from)
コード例 #4
0
    def __init__(self, questions):
        """__init__(questions:list)
		Instantiates a Questionnaire object from the list of specified questions.
		"""
        assert isinstance(questions,
                          list), "Error! The 'questions' field must be a list."
        if len(questions) < 1:
            raise Exception(
                "Error! A questionnaire requires one or more questions.")
        else:
            import collections

            self.questions = collections.OrderedDict()
            self.controlflow = {}
            self.questiontypes = set()

            for configuration in questions:
                assert isinstance(
                    configuration,
                    dict), "Error! A question entry must be a dictionary."

                # Check for mandatory keys.
                for field in ["key", "type", "question"]:
                    if field not in configuration:
                        raise Exception(
                            "Error! A questionnaire entry is missing the field '{}'."
                            .format(field))

                key = configuration["key"]
                key = str(key).strip() if isinstance(key, basestring) else None

                valid, message = self.iskey(key, configuration["question"])
                if valid:
                    question = Question(key, configuration)
                    self.questions[key] = question
                    self.controlflow[key] = configuration.get("branch")
                    self.questiontypes.add(question.type)
                else:
                    raise Exception(message)

            # Convert the strings used as conditions in conditional branches to
            # lowercase. This will allow the template scripts to perform
            # case-insensitive string comparisons.
            for branch in [
                    b for b in self.controlflow.values()
                    if b is not None and isinstance(b, dict)
            ]:
                for key in branch.keys():
                    branch[key.lower()] = branch.pop(key)

            valid, message = Questionnaire.isvalid(self)
            if not valid:
                raise Exception(message)
コード例 #5
0
    def iskey(self, key, question=None):
        """iskey(key:string, question:string)
		Returns true if the specified key is valid, false otherwise.
		In addition to being a non-empty string and not a reserved keyword, keys
		must also be unique in each questionnaire.
		"""
        valid, message = Question.iskey(key)
        if not valid:
            return (False, message)
        elif key in self.questions:
            return (
                False,
                """Error! The key '{0}' is used to identify the following questions:
				\r    - {1}
				\r    - {2}
				\rPlease make sure each question has a unique key.""".format(
                    key, self.questions[key].question, question))
        return (True, None)
コード例 #6
0
	def iskey(self, key, question=None):
		"""iskey(key:string, question:string)
		Returns true if the specified key is valid, false otherwise.
		In addition to being a non-empty string and not a reserved keyword, keys
		must also be unique in each questionnaire.
		"""
		valid, message = Question.iskey(key)
		if not valid:
			return (False, message)
		elif key in self.questions:
			return (
				False,
				"""Error! The key '{0}' is used to identify the following questions:
				\r    - {1}
				\r    - {2}
				\rPlease make sure each question has a unique key.""".format(
					key,
					self.questions[key].question,
					question
				)
			)
		return (True, None)
コード例 #7
0
	def isvalid(questionnaire):
		"""isvalid(questionnaire:Questionnaire)
		Returns true if the questionnaire is valid, false otherwise.
		"""
		valid, message = True, None
		if questionnaire is not None:
			if questionnaire.questions is not None:
				for question in questionnaire.questions.values():
					valid, message = Question.isvalid(question)
					if not valid:
						break

				# If the questionnaire entries are valid, validate the control flow.
				if valid and questionnaire.controlflow is not None:
					for k in [k for k in questionnaire.controlflow.values() if k is not None]:
						valid, message = questionnaire.isbranchablekey(k)
						if not valid:
							break
			else:
				valid, message = False, "Error! Empty questionnaire. A questionnaire must contain at least one question."
		else:
			valid, message = False, "Error! A 'NoneType' object is not considered a questionnaire."

		return (valid, message)
コード例 #8
0
ファイル: xmppHandler.py プロジェクト: MrCoder/CodeReview
 def _GetAnswering(self, user):
   """Returns the question the user is answering, if any."""
   q = Question.all()
   q.filter("assignees =", user)
   q.filter("answer =", None)
   return q.get()
コード例 #9
0
ファイル: xmppHandler.py プロジェクト: MrCoder/CodeReview
 def _GetAsked(self, user):
   """Returns the user's outstanding asked question, if any."""
   q = Question.all()
   q.filter("asker =", user)
   q.filter("answer =", None)
   return q.get()
コード例 #10
0
from unittest import TestCase

from src.teacher import Teacher
from src.student import Student
from src.question import Question
from src.quiz import Quiz
from src.classroom import Classroom

jude = Student('Jude Arroyo')
carlee = Student('Carlee Holloway')
julia = Student('Julia Henderson')
earl = Student('Earl Christensen')

question_one = Question('What is the national sport in Japan?', 'Judo')
question_one.add_option('Judo')
question_one.add_option('Baseball')
question_one.add_option('Sumo Wrestling')

question_two = Question('How many minutes is a rugby match?', 80)
question_two.add_option(70)
question_two.add_option(80)
question_two.add_option(90)

question_three = Question(
    'Which car won Fernando Alonso his first tittle in Formula 1 with?',
    'Renault')
question_three.add_option('Renault')
question_three.add_option('Ford')
question_three.add_option('Peugeot')

question_four = Question('In which sport can you win the Davis Cup?', 'Tennis')
コード例 #11
0
def generate_test(config, variants):
    test = {
        'general': {
            'discipline': config['discipline'],
            'title': config['title'],
            'course': config['course'],
            'filename': config['course'] + "_" + config['name']
        }
    }
    questions = [[] for x in range(variants)]
    quest_indices = []
    for i in range(len(config['pools'])):
        pool = config['pools'][i]
        size = len(pool['items'])
        if pool['number'] > size:
            print(
                "Error: number don't match to questions count of {0} pool in {1}/{2}.yaml"
                .format(i, config['course'], config['name']))
        elif pool['number'] == size:
            quest_indices = [[x for x in range(size)] for y in range(variants)]
        elif pool['select'] == 'random':
            quest_indices = [
                random.sample(range(0, size), pool['number'])
                for x in range(variants)
            ]
        elif pool['select'][0] == '[' and pool['select'][-1] == ']':
            res = [[int(y) for y in x.split(',')]
                   for x in pool['select'][1:-1].split(';')]
            quest_indices = [res[x % len(res)] for x in range(variants)]
        else:
            quest_indices = [[] for x in range(variants)]
            p_index = 0
            for k in range(pool['number'] * variants):
                while p_index in quest_indices[k % variants]:
                    p_index += 1
                    p_index %= size
                quest_indices[k % variants].append(p_index)
                p_index += 1
                p_index %= size

        for row in range(len(quest_indices)):
            for index in quest_indices[row]:
                tmp = pool['items'][index]
                qtmp = Question(tmp)
                if 'app' in tmp:
                    path = 'src' + os.path.sep + 'scripts' + os.path.sep + config[
                        'course'] + os.path.sep + tmp['script']
                    if os.path.isfile(path + '.py'):
                        function_string = path.replace(
                            os.path.sep, '.') + '.' + tmp['script']
                        qtmp.execute(function_string, tmp['parameters'])
                    else:
                        print("Error: script of {0} pool not exists".format(i))
                else:
                    qtmp.shuffle()
                qtmp.index = index
                questions[row].append(qtmp)

    [random.shuffle(x) for x in questions]
    test['questions'] = questions
    return test
コード例 #12
0
ファイル: guru.py プロジェクト: MrCoder/CodeReview
 def get(self):
   q = Question.all().order('-answered').filter('answered >', None)
   template_values = {
     'questions': q.fetch(20),
   }
   self.Render("latest.html", template_values)
コード例 #13
0
def ask(article_path, num_questions):
    u = Util()
    q = Question(Article(u.load_txt_article(article_path)))
    questions = q.generate(int(num_questions))
    for question in questions:
        print(question)