<commit_before>from builtins import str
from builtins import range
from builtins import object
import os
import random
import string
import uuid
import datetime

from django.conf import settings
from django.contrib.auth.models import (
    AbstractBaseUser, PermissionsMixin, BaseUserManager
)
from django.core.mail.message import EmailMessage
from django.db import models
from django.utils import timezone
from django.utils.functional import lazy, cached_property
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields import ModificationDateTimeField
from djchoices.choices import DjangoChoices, ChoiceItem

from future.utils import python_2_unicode_compatible
from rest_framework_jwt.settings import api_settings

from bluebottle.bb_accounts.utils import valid_email
from bluebottle.initiatives.models import Theme
from bluebottle.clients import properties
from bluebottle.members.tokens import login_token_generator
from bluebottle.utils.fields import ImageField
from bluebottle.utils.validators import FileMimetypeValidator, validate_file_infection


def generate_picture_filename(instance, filename):
    """
    Creates a random directory and file name for uploaded pictures.

    The random directory allows the uploaded images to be evenly spread over
    1296 directories. This allows us to host more files before hitting bad
    performance of the OS filesystem and/or utility programs which can occur
    when a directory has thousands of files.

    An example return value is of this method is:
        'profiles/tw/tws9ea4eqaj37xnu24svp2vwndsytzysa.jpg'
    """
    # Create the upload directory string.
    char_set = string.ascii_lowercase + string.digits
    random_string = ''.join(random.choice(char_set) for i in range(33))
    upload_directory = os.path.join('profiles', random_string[0:2])

    # Get the file extension from the original filename.
    original_filename = os.path.basename(filename)
    file_extension = os.path.splitext(original_filename)[1]

    # Create the normalized path.
    normalized_filename = random_string + file_extension
    return os.path.normpath(os.path.join(upload_directory, normalized_filename))


# Our custom user model is based on option 3 from Two Scoops of Django
# - Chapter 16: Dealing With the User Model.
class BlueBottleUserManager(BaseUserManager):
    def create_user(self, email, password=<PASSWORD>, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email address must be set')
        email = BlueBottleUserManager.normalize_email(email)
        user = self.model(email=email, is_staff=False, is_active=True,
                          is_superuser=False,
                          last_login=now, date_joined=now, **extra_fields)
        user.set_password(password)
        user.generate_username()
        user.reset_disable_token()
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, **extra_fields):
        u = self.create_user(email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u


def get_language_choices():
    """ Lazyly get the language choices."""
    return properties.LANGUAGES


def get_default_language():
    """ Lazyly get the default language."""
    return properties.LANGUAGE_CODE


@python_2_unicode_compatible
class BlueBottleBaseUser(AbstractBaseUser, PermissionsMixin):
    """
    Custom user model for BlueBottle.

    When extending the user model, the serializer should extend too.
    We provide a default base serializer in sync with the base user model
    The Django Meta attribute seems the best place for this configuration, so we
    have to add this.
    """
    class Gender(DjangoChoices):
        male = ChoiceItem('male', label=_('Male'))
        female = ChoiceItem('female', label=_('Female'))

    class UserType(DjangoChoices):
        person = ChoiceItem('person', label=_('Person'))
        company = ChoiceItem('company', label=_('Company'))
        foundation = ChoiceItem('foundation', label=_('Foundation'))
        school = ChoiceItem('school', label=_('School'))
        group = ChoiceItem('group', label=_('Club / association'))

    email = models.EmailField(_('email address'), db_index=True, max_length=254, unique=True)
    username = models.CharField(_('username'), max_length=254, unique=True)

    is_staff = models.BooleanField(_('staff status'),
                                   default=False,
                                   help_text=_('Designates whether the user can log into this admin site.'))
    is_active = models.BooleanField(_('active'),
                                    default=False,
                                    help_text=_('Designates whether this user should be treated as active. Unselect '
                                                'this instead of deleting accounts.'))
    disable_token = models.CharField(blank=True, max_length=32, null=True)

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    updated = ModificationDateTimeField()
    last_seen = models.DateTimeField(_('Last Seen'), blank=True, null=True)
    deleted = models.DateTimeField(_('deleted'), blank=True, null=True)

    user_type = models.CharField(_('Member Type'), choices=UserType.choices, default=UserType.person, max_length=25)

    first_name = models.CharField(_('first name'), blank=True, max_length=100)
    last_name = models.CharField(_('last name'), blank=True, max_length=100)
    place = models.CharField(_('Location your at now'), blank=True, max_length=100)
    location = models.ForeignKey(
        'geo.Location', blank=True,
        verbose_name=_('Office'),
        null=True, on_delete=models.SET_NULL)
    favourite_themes = models.ManyToManyField(Theme, blank=True)
    skills = models.ManyToManyField('time_based.Skill', blank=True)
    phone_number = models.CharField(_('phone number'), blank=True, max_length=50)
    gender = models.CharField(_('gender'), blank=True, choices=Gender.choices, max_length=6)
    birthdate = models.DateField(_('birthdate'), blank=True, null=True)
    about_me = models.TextField(_('about me'), blank=True, max_length=265)
    # TODO Use generate_picture_filename (or something) for upload_to
    picture = ImageField(
        _('picture'), blank=True, upload_to='profiles',

        validators=[
            FileMimetypeValidator(
                allowed_mimetypes=settings.IMAGE_ALLOWED_MIME_TYPES,
            ),
            validate_file_infection
        ]
    )

    is_co_financer = models.BooleanField(_('Co-financer'),
                                         default=False,
                                         help_text=_('Donations by co-financers are shown in a separate list on the '
                                                     'project page. These donation will always be visible.'))
    can_pledge = models.BooleanField(_('Can pledge'), default=False, help_text=_('User can create a pledge donation.'))

    # Use lazy for the choices and default, so that tenant properties
    # will be correctly loaded
    primary_language = models.CharField(_('primary language'),
                                        choices=lazy(get_language_choices, tuple)(),
                                        default=lazy(get_default_language, str)(),
                                        help_text=_('Language used for website and emails.'),
                                        max_length=5)
    share_time_knowledge = models.BooleanField(_('share time and knowledge'), default=False)
    share_money = models.BooleanField(_('share money'), default=False)
    newsletter = models.BooleanField(_('newsletter'), default=True, help_text=_('Subscribe to newsletter.'))
    campaign_notifications = models.BooleanField(_('Project Notifications'), default=True)

    website = models.URLField(_('website'), blank=True)
    facebook = models.CharField(_('facebook profile'), blank=True, max_length=50)
    twitter = models.CharField(_('twitter profile'), blank=True, max_length=15)
    skypename = models.CharField(_('skype profile'), blank=True, max_length=32)<commit_msg>Always show can pledge option<commit_after>import datetime
import os
import random
import string
import uuid
from builtins import object
from builtins import range
from builtins import str

from django.conf import settings
from django.contrib.auth.models import (
    AbstractBaseUser, PermissionsMixin, BaseUserManager
)
from django.core.mail.message import EmailMessage
from django.db import models
from django.utils import timezone
from django.utils.functional import lazy, cached_property
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields import ModificationDateTimeField
from djchoices.choices import DjangoChoices, ChoiceItem
from future.utils import python_2_unicode_compatible
from rest_framework_jwt.settings import api_settings

from bluebottle.bb_accounts.utils import valid_email
from bluebottle.clients import properties
from bluebottle.initiatives.models import Theme
from bluebottle.members.tokens import login_token_generator
from bluebottle.utils.fields import ImageField
from bluebottle.utils.validators import FileMimetypeValidator, validate_file_infection


def generate_picture_filename(instance, filename):
    """
    Creates a random directory and file name for uploaded pictures.

    The random directory allows the uploaded images to be evenly spread over
    1296 directories. This allows us to host more files before hitting bad
    performance of the OS filesystem and/or utility programs which can occur
    when a directory has thousands of files.

    An example return value is of this method is:
        'profiles/tw/tws9ea4eqaj37xnu24svp2vwndsytzysa.jpg'
    """
    # Create the upload directory string.
    char_set = string.ascii_lowercase + string.digits
    random_string = ''.join(random.choice(char_set) for i in range(33))
    upload_directory = os.path.join('profiles', random_string[0:2])

    # Get the file extension from the original filename.
    original_filename = os.path.basename(filename)
    file_extension = os.path.splitext(original_filename)[1]

    # Create the normalized path.
    normalized_filename = random_string + file_extension
    return os.path.normpath(os.path.join(upload_directory, normalized_filename))


# Our custom user model is based on option 3 from Two Scoops of Django
# - Chapter 16: Dealing With the User Model.
class BlueBottleUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email address must be set')
        email = BlueBottleUserManager.normalize_email(email)
        user = self.model(email=email, is_staff=False, is_active=True,
                          is_superuser=False,
                          last_login=now, date_joined=now, **extra_fields)
        user.set_password(password)
        user.generate_username()
        user.reset_disable_token()
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, **extra_fields):
        u = self.create_user(email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u


def get_language_choices():
    """ Lazyly get the language choices."""
    return properties.LANGUAGES


def get_default_language():
    """ Lazyly get the default language."""
    return properties.LANGUAGE_CODE


@python_2_unicode_compatible
class BlueBottleBaseUser(AbstractBaseUser, PermissionsMixin):
    """
    Custom user model for BlueBottle.

    When extending the user model, the serializer should extend too.
    We provide a default base serializer in sync with the base user model
    The Django Meta attribute seems the best place for this configuration, so we
    have to add this.
    """
    class Gender(DjangoChoices):
        male = ChoiceItem('male', label=_('Male'))
        female = ChoiceItem('female', label=_('Female'))

    class UserType(DjangoChoices):
        person = ChoiceItem('person', label=_('Person'))
        company = ChoiceItem('company', label=_('Company'))
        foundation = ChoiceItem('foundation', label=_('Foundation'))
        school = ChoiceItem('school', label=_('School'))
        group = ChoiceItem('group', label=_('Club / association'))

    email = models.EmailField(_('email address'), db_index=True, max_length=254, unique=True)
    username = models.CharField(_('username'), max_length=254, unique=True)

    is_staff = models.BooleanField(_('staff status'),
                                   default=False,
                                   help_text=_('Designates whether the user can log into this admin site.'))
    is_active = models.BooleanField(_('active'),
                                    default=False,
                                    help_text=_('Designates whether this user should be treated as active. Unselect '
                                                'this instead of deleting accounts.'))
    disable_token = models.CharField(blank=True, max_length=32, null=True)

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    updated = ModificationDateTimeField()
    last_seen = models.DateTimeField(_('Last Seen'), blank=True, null=True)
    deleted = models.DateTimeField(_('deleted'), blank=True, null=True)

    user_type = models.CharField(_('Member Type'), choices=UserType.choices, default=UserType.person, max_length=25)

    first_name = models.CharField(_('first name'), blank=True, max_length=100)
    last_name = models.CharField(_('last name'), blank=True, max_length=100)
    place = models.CharField(_('Location your at now'), blank=True, max_length=100)
    location = models.ForeignKey(
        'geo.Location', blank=True,
        verbose_name=_('Office'),
        null=True, on_delete=models.SET_NULL)
    favourite_themes = models.ManyToManyField(Theme, blank=True)
    skills = models.ManyToManyField('time_based.Skill', blank=True)
    phone_number = models.CharField(_('phone number'), blank=True, max_length=50)
    gender = models.CharField(_('gender'), blank=True, choices=Gender.choices, max_length=6)
    birthdate = models.DateField(_('birthdate'), blank=True, null=True)
    about_me = models.TextField(_('about me'), blank=True, max_length=265)
    # TODO Use generate_picture_filename (or something) for upload_to
    picture = ImageField(
        _('picture'), blank=True, upload_to='profiles',

        validators=[
            FileMimetypeValidator(
                allowed_mimetypes=settings.IMAGE_ALLOWED_MIME_TYPES,
            ),
            validate_file_infection
        ]
    )

    is_co_financer = models.BooleanField(
        _('Co-financer'),
        default=False,
        help_text=_('Donations by co-financers are shown in a separate list on the '
                    'project page. These donation will always be visible.'))
    can_pledge = models.BooleanField(
        _('Can pledge'),
        default=False,
        help_text=_('User can create a pledge donation.'))

    # Use lazy for the choices and default, so that tenant properties
    # will be correctly loaded
    primary_language = models.CharField(_('primary language'),
                                        choices=lazy(get_language_choices, tuple)(),
                                        default=lazy(get_default_language, str)(),
                                        help_text=_('Language used for website and emails.'),
                                        max_length=5)
    share_time_knowledge = models.BooleanField(_('share time and knowledge'), default=False)
    share_money = models.BooleanField(_('share money'), default=False)
    newsletter = models.BooleanField(_('newsletter'), default=True, help_text=_('Subscribe to newsletter.'))
    campaign_notifications = models.BooleanField(_('Project Notifications'), default=True)

    website = models.URLField(_('website'), blank=True)
    facebook = models.CharField(_('facebook profile'), blank=True, max_length=50)
    twitter = models.CharField(_('twitter profile'), blank=True, max_length=15)
    skypename = models.CharField(_('skype profile'), blank=True, max_length=32)
{'fraction_non_alphanumeric': 0.0927192035504378, 'fraction_numerical': 0.006357202830754468, 'mean_word_length': 3.274544988464496, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '103904', 'n_tokens_mistral': 4554, 'n_tokens_neox': 4413, 'n_words': 1225}