<commit_before>import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q

from goals.models import CustomAction, UserAction
from utils.slack import post_private_message

logger = logging.getLogger("loggly_logs")


class Command(BaseCommand):
    help = 'Updates the next_trigger_date field for stale UserActions and CustomActions.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--user',
            action='store',
            dest='user',
            default=None,
            help=("Restrict this command to the given User. "
                  "Accepts a username, email, or id")
        )

    def _user_kwargs(self, user):
        User = get_user_model()

        kwargs = {}  # Keyword arguments that get passed to our action querysets.
        if user:
            try:
                if user.isnumeric():
                    criteria = Q(id=user)
                else:
                    criteria = (Q(username=user) | Q(email=user))
                kwargs['user'] = User.objects.get(criteria)
            except User.DoesNotExist:
                msg = "Could not find user: {0}".format(user)
                raise CommandError(msg)
        return kwargs

    def handle(self, *args, **options):
        count = 0
        kwargs = self._user_kwargs(options['user'])

        # Fetch the set of UserActions to refresh.
        useractions = UserAction.objects.stale(**kwargs).published()

        # If we're in staging or dev, only do this for our accounts.
        if settings.STAGING or settings.DEBUG:
            useractions = useractions.filter(user__email__icontains="<EMAIL>")

        for ua in useractions:
            count += 1
            ua.save(update_triggers=True)  # fields get refreshed on save.

        msg = "Refreshed Trigger Date for {0} UserActions".format(count)
        logger.error(msg)
        self.stderr.write(msg)
        #post_private_message("bkmontgomery", msg)

        count = 0
        for ca in CustomAction.objects.stale(**kwargs):
            count += 1
            ca.save()  # fields get refreshed on save.

        msg = "Refreshed Trigger Date for {0} CustomActions".format(count)
        logger.error(msg)
        self.stderr.write(msg)
        #post_private_message("bkmontgomery", msg)<commit_msg>updating refresh_useractions so we can limit the nubmer and age of updated objects<commit_after>import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q

from goals.models import CustomAction, UserAction

logger = logging.getLogger("loggly_logs")


class Command(BaseCommand):
    help = 'Updates the next_trigger_date field for stale UserActions and CustomActions.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--user',
            action='store',
            dest='user',
            default=None,
            help=("Restrict this command to the given User. "
                  "Accepts a username, email, or id")
        )
        parser.add_argument(
            '--hours',
            action='store',
            dest='hours',
            default=2,
            type=int,
            help="Limit to objects that are older than the given value (in hours)"
        )
        parser.add_argument(
            '--limit',
            action='store',
            dest='limit',
            default=100,
            type=int,
            help="Limit the number of objects that are modified"
        )

    def _user_kwargs(self, user):
        User = get_user_model()

        kwargs = {}  # Keyword arguments that get passed to our action querysets.
        if user:
            try:
                if user.isnumeric():
                    criteria = Q(id=user)
                else:
                    criteria = (Q(username=user) | Q(email=user))
                kwargs['user'] = User.objects.get(criteria)
            except User.DoesNotExist:
                msg = "Could not find user: {0}".format(user)
                raise CommandError(msg)
        return kwargs

    def handle(self, *args, **options):
        count = 0
        kwargs = self._user_kwargs(options['user'])
        limit = options.pop('limit')

        # Limit the refreshed objects to those that are at least 2 hours old.
        # (or to an age based on limit option)
        hours = options.pop('hours')
        kwargs['hours'] = hours

        # Fetch the set of UserActions to refresh.
        # We want to limit these to reduce the amount of time it takes to
        # complete execution of this script.
        useractions = UserAction.objects.stale(**kwargs).published()
        if limit:
            useractions = useractions[:limit]

        # If we're in staging or dev, only do this for our accounts.
        if settings.STAGING or settings.DEBUG:
            useractions = useractions.filter(user__email__icontains="<EMAIL>")

        for ua in useractions:
            count += 1
            ua.save(update_triggers=True)  # fields get refreshed on save.

        msg = "Refreshed Trigger Date for {0} UserActions".format(count)
        logger.error(msg)
        self.stderr.write(msg)

        count = 0
        for ca in CustomAction.objects.stale(**kwargs):
            count += 1
            ca.save()  # fields get refreshed on save.

        msg = "Refreshed Trigger Date for {0} CustomActions".format(count)
        logger.error(msg)
        self.stderr.write(msg)
{'fraction_non_alphanumeric': 0.09145586414293295, 'fraction_numerical': 0.0033610472315584645, 'mean_word_length': 2.047978436657682, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1087497', 'n_tokens_mistral': 1547, 'n_tokens_neox': 1489, 'n_words': 457}