def __init__(self, question=None, timestamp=None): if question is None: self.question = self.generate_question() else: self.question = question if timestamp is None: self.timestamp = time.time() else: self.timestamp = timestamp if not self.operators_display: self.operators_display = { "+": icon("plus.svg"), "-": icon("minus.svg"), "*": icon("close.svg"), }
def __init__(self, question=None, timestamp=None): if question is None: self.question = self.generate_question() else: self.question = question if timestamp is None: self.timestamp = time.time() else: self.timestamp = timestamp if not self.operators_display: self.operators_display = { '+': icon('plus.svg'), '-': icon('minus.svg'), '*': icon('close.svg'), }
def get_plural_label(self, idx): """Return label for plural form.""" return PLURAL_TITLE.format( name=self.get_plural_name(idx), icon=icon("info.svg"), # Translators: Label for plurals with example counts examples=_("For example: {0}").format(", ".join( self.examples.get(idx, []))), )
class MathCaptcha(object): """Simple match captcha object.""" operators = ('+', '-', '*') operators_display = { '+': icon('plus.svg'), '-': icon('minus.svg'), '*': icon('close.svg'), } interval = (1, 10) def __init__(self, question=None, timestamp=None): if question is None: self.question = self.generate_question() else: self.question = question if timestamp is None: self.timestamp = time.time() else: self.timestamp = timestamp def generate_question(self): """Generate random question.""" generator = SystemRandom() operation = generator.choice(self.operators) first = generator.randint(self.interval[0], self.interval[1]) second = generator.randint(self.interval[0], self.interval[1]) # We don't want negative answers if operation == '-': first += self.interval[1] return ' '.join((str(first), operation, str(second))) @staticmethod def from_hash(hashed): """Create object from hash.""" question, timestamp = unhash_question(hashed) return MathCaptcha(question, timestamp) @property def hashed(self): """Return hashed question.""" return hash_question(self.question, self.timestamp) def validate(self, answer): """Validate answer.""" return (self.result == answer and self.timestamp + TIMEDELTA > time.time()) @property def result(self): """Return result.""" return eval_expr(self.question) @property def display(self): """Get unicode for display.""" parts = self.question.split() return ' '.join(( parts[0], self.operators_display[parts[1]], parts[2], ))