<commit_before># Copyright 2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import datetime
import flask
from flask.ext import sqlalchemy
import hashlib
import hmac
import os
import pbkdf2
import re
import time
import utils
from sqlalchemy import exc
from sqlalchemy.orm import exc as orm_exc

from scoreboard.app import app
from scoreboard import errors

db = sqlalchemy.SQLAlchemy(app)


class Team(db.Model):
    """A Team of Players (Team of 1 if not using Teams)."""
    tid = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), unique=True, nullable=False)
    score = db.Column(db.Integer, default=0)  # Denormalized
    players = db.relationship(
        'User', backref=db.backref('team', lazy='joined'), lazy='dynamic')
    answers = db.relationship('Answer', backref='team', lazy='dynamic')

    def __repr__(self):
        return '<Team: %s>' % self.name

    def __str__(self):
        return self.name

    @property
    def code(self):
        return hmac.new(app.config['SECRET_KEY'], self.name).hexdigest()[:12]

    @property
    def solves(self):
        return self.answers.count()

    @classmethod
    def create(cls, name):
        team = cls()
        db.session.add(team)
        team.name = name
        return team

    @classmethod
    def enumerate(cls):
        return enumerate(cls.query.order_by(cls.score.desc()).all(), 1)


class User(db.Model):
    """A single User for login.  Player or admin."""

    uid = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    nick = db.Column(db.String(80), unique=True, nullable=False)
    pwhash = db.Column(db.String(48))  # pbkdf2.crypt == 48 bytes
    admin = db.Column(db.Boolean, default=False)
    team_tid = db.Column(db.Integer, db.ForeignKey('team.tid'))

    def set_password(self, password):
        self.pwhash = pbkdf2.crypt(password)

    def __repr__(self):
        return '<User: %s <%s>>' % (self.nick, self.email)

    def __str__(self):
        return self.nick

    def promote(self):
        """Promote a user to admin."""
        empty_team = self.team and set(self.team.players.all()) == set([self])
        self.admin = True
        team = self.team
        self.team = None
        if empty_team:
            db.session.delete(team)

    def get_token(self, token_type='pwreset', expires=None):
        """Generate a user-specific token."""
        expires = expires or int(time.time()) + 7200  # 2 hours
        token_plain = '%d:%d:%s:%s' % (
                self.uid, expires, token_type, self.pwhash)
        mac = hmac.new(
                app.config['SECRET_KEY'], token_plain, hashlib.sha1).digest()
        token = '%d:%s' % (expires, mac)
        return base64.urlsafe_b64encode(token)

    def verify_token(self, token, token_type='pwreset'):
        """Verify a user-specific token."""
        token = str(token)
        decoded = base64.urlsafe_b64decode(token)
        expires, mac = decoded.split(':')
        if expires > time.time():
            raise errors.ValidationError('Expired token.')
        expected = self.get_token(token_type=token_type, expires=int(expires))
        if not utils.compare_digest(expected, token):
            raise errors.ValidationError('Invalid token.')
        return True

    @classmethod
    def get_by_email(cls, email):
        try:
            return cls.query.filter_by(email=email).one()
        except exc.InvalidRequestError:
            return None

    @classmethod
    def login_user(cls, email, password):
        try:
            user = cls.query.filter_by(email=email).one()
        except exc.InvalidRequestError:
            return None
        if pbkdf2.crypt(password, user.pwhash) == user.pwhash:
            return user
        return None

    @classmethod
    def create(cls, email, nick, password, team=None):
        first_user = True if not cls.query.count() else False
        user = cls()<commit_msg>change comparison from string and float to float and float<commit_after># Copyright 2014 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import datetime
import flask
from flask.ext import sqlalchemy
import hashlib
import hmac
import os
import pbkdf2
import re
import time
import utils
from sqlalchemy import exc
from sqlalchemy.orm import exc as orm_exc

from scoreboard.app import app
from scoreboard import errors

db = sqlalchemy.SQLAlchemy(app)


class Team(db.Model):
    """A Team of Players (Team of 1 if not using Teams)."""
    tid = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), unique=True, nullable=False)
    score = db.Column(db.Integer, default=0)  # Denormalized
    players = db.relationship(
        'User', backref=db.backref('team', lazy='joined'), lazy='dynamic')
    answers = db.relationship('Answer', backref='team', lazy='dynamic')

    def __repr__(self):
        return '<Team: %s>' % self.name

    def __str__(self):
        return self.name

    @property
    def code(self):
        return hmac.new(app.config['SECRET_KEY'], self.name).hexdigest()[:12]

    @property
    def solves(self):
        return self.answers.count()

    @classmethod
    def create(cls, name):
        team = cls()
        db.session.add(team)
        team.name = name
        return team

    @classmethod
    def enumerate(cls):
        return enumerate(cls.query.order_by(cls.score.desc()).all(), 1)


class User(db.Model):
    """A single User for login.  Player or admin."""

    uid = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    nick = db.Column(db.String(80), unique=True, nullable=False)
    pwhash = db.Column(db.String(48))  # pbkdf2.crypt == 48 bytes
    admin = db.Column(db.Boolean, default=False)
    team_tid = db.Column(db.Integer, db.ForeignKey('team.tid'))

    def set_password(self, password):
        self.pwhash = pbkdf2.crypt(password)

    def __repr__(self):
        return '<User: %s <%s>>' % (self.nick, self.email)

    def __str__(self):
        return self.nick

    def promote(self):
        """Promote a user to admin."""
        empty_team = self.team and set(self.team.players.all()) == set([self])
        self.admin = True
        team = self.team
        self.team = None
        if empty_team:
            db.session.delete(team)

    def get_token(self, token_type='pwreset', expires=None):
        """Generate a user-specific token."""
        expires = expires or int(time.time()) + 7200  # 2 hours
        token_plain = '%d:%d:%s:%s' % (
                self.uid, expires, token_type, self.pwhash)
        mac = hmac.new(
                app.config['SECRET_KEY'], token_plain, hashlib.sha1).digest()
        token = '%d:%s' % (expires, mac)
        return base64.urlsafe_b64encode(token)

    def verify_token(self, token, token_type='pwreset'):
        """Verify a user-specific token."""
        token = str(token)
        decoded = base64.urlsafe_b64decode(token)
        expires, mac = decoded.split(':')
        if float(expires) > time.time():
            raise errors.ValidationError('Expired token.')
        expected = self.get_token(token_type=token_type, expires=int(expires))
        if not utils.compare_digest(expected, token):
            raise errors.ValidationError('Invalid token.')
        return True

    @classmethod
    def get_by_email(cls, email):
        try:
            return cls.query.filter_by(email=email).one()
        except exc.InvalidRequestError:
            return None

    @classmethod
    def login_user(cls, email, password):
        try:
            user = cls.query.filter_by(email=email).one()
        except exc.InvalidRequestError:
            return None
        if pbkdf2.crypt(password, user.pwhash) == user.pwhash:
            return user
        return None

    @classmethod
    def create(cls, email, nick, password, team=None):
        first_user = True if not cls.query.count() else False
        user = cls()
{'fraction_non_alphanumeric': 0.11822005756032765, 'fraction_numerical': 0.009962364401151207, 'mean_word_length': 2.8414115646258504, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1417498', 'n_tokens_mistral': 2835, 'n_tokens_neox': 2715, 'n_words': 770}