示例#1
0
def filesizeformat(bytes, filesize_number_format):
    try:
        bytes = float(bytes)
    except (TypeError, ValueError, UnicodeDecodeError):
        return ungettext_lazy("%(size)d Byte",
                              "%(size)d Bytes", 0) % {'size': 0}

    if bytes == float('inf'):
        return _('Infinity')
    if bytes < units.Ki:
        bytes = int(bytes)
        return ungettext_lazy("%(size)d Byte",
                              "%(size)d Bytes", bytes) % {'size': bytes}
    if bytes < units.Mi:
        return _("%s KB") % filesize_number_format(bytes / units.Ki)
    if bytes < units.Gi:
        return _("%s MB") % filesize_number_format(bytes / units.Mi)
    if bytes < units.Ti:
        return _("%s GB") % filesize_number_format(bytes / units.Gi)
    if bytes < units.Pi:
        return _("%s TB") % filesize_number_format(bytes / units.Ti)
    if bytes < units.Ei:
        return _("%s PB") % filesize_number_format(bytes / units.Pi)
    if bytes < units.Zi:
        return _("%s EB") % filesize_number_format(bytes / units.Ei)
    if bytes < units.Yi:
        return _("%s ZB") % filesize_number_format(bytes / units.Zi)
    return _("%s YB") % filesize_number_format(bytes / units.Yi)
示例#2
0
def filesizeformat(bytes, filesize_number_format):
    try:
        bytes = float(bytes)
    except (TypeError, ValueError, UnicodeDecodeError):
        return ungettext_lazy("%(size)d Byte",
                "%(size)d Bytes", 0) % {'size': 0}

    if bytes < 1024:
        bytes = int(bytes)
        return ungettext_lazy("%(size)d Byte",
                "%(size)d Bytes", bytes) % {'size': bytes}
    if bytes < 1024 * 1024:
        return _("%s KB") % \
            filesize_number_format(bytes / 1024)
    if bytes < 1024 * 1024 * 1024:
        return _("%s MB") % \
            filesize_number_format(bytes / (1024 * 1024))
    if bytes < 1024 * 1024 * 1024 * 1024:
        return _("%s GB") % \
            filesize_number_format(bytes / (1024 * 1024 * 1024))
    if bytes < 1024 * 1024 * 1024 * 1024 * 1024:
        return _("%s TB") % \
            filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024))
    return _("%s PB") % \
        filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024))
示例#3
0
def diff_date(date, use_on_prefix = False):
    now = datetime.datetime.now()#datetime(*time.localtime()[0:6])#???
    diff = now - date
    days = diff.days
    hours = int(diff.seconds/3600)
    minutes = int(diff.seconds/60)

    if days > 2:
        if date.year == now.year:
            date_token = date.strftime("%b %d")
        else:
            date_token = date.strftime("%b %d '%y")
        if use_on_prefix:
            return _('on %(date)s') % { 'date': date_token }
        else:
            return date_token
    elif days == 2:
        return _('2 days ago')
    elif days == 1:
        return _('yesterday')
    elif minutes >= 60:
        return ungettext_lazy(
            '%(hr)d hour ago',
            '%(hr)d hours ago',
            hours
        ) % {'hr':hours}
    else:
        return ungettext_lazy(
            '%(min)d min ago',
            '%(min)d mins ago',
            minutes
        ) % {'min':minutes}
示例#4
0
文件: forms.py 项目: afdelgado/askbot
    def clean(self, value):
        #todo: this field must be adapted to work with Chinese, etc.
        #for that we'll have to count characters instead of words
        if value is None:
            value = ''

        value = value.strip()

        word_count = len(value.split())
        if word_count < self.min_words:
            msg = ungettext_lazy(
                'must be > %d word',
                'must be > %d words',
                self.min_words - 1
            ) % (self.min_words - 1)
            #todo - space is not used in Chinese
            raise forms.ValidationError(
                string_concat(self.field_name, ' ', msg)
            )

        if word_count > self.max_words:
            msg = ungettext_lazy(
                'must be < %d word',
                'must be < %d words',
                self.max_words + 1
            ) % (self.max_words + 1)
            raise forms.ValidationError(
                string_concat(self.field_name, ' ', msg)
            )
        return value
示例#5
0
def access_redeem_view(request, token):
    with transaction.atomic():
        try:
            token = AccessPermissionToken.objects.select_for_update().get(token=token, redeemed=False,
                                                                          valid_until__gte=timezone.now())
        except AccessPermissionToken.DoesNotExist:
            messages.error(request, _('This token does not exist or was already redeemed.'))
            return redirect('site.index')

        num_restrictions = len(token.restrictions)

        if request.method == 'POST':
            if not request.user.is_authenticated:
                messages.info(request, _('You need to log in to unlock areas.'))
                request.session['redeem_token_on_login'] = str(token.token)
                token.redeem()
                return redirect('site.login')

            token.redeem(request.user)
            token.save()

            messages.success(request, ungettext_lazy('Area successfully unlocked.',
                                                     'Areas successfully unlocked.', num_restrictions))
            return redirect('site.index')

    return render(request, 'site/confirm.html', {
        'title': ungettext_lazy('Unlock area', 'Unlock areas', num_restrictions),
        'texts': (ungettext_lazy('You have been invited to unlock the following area:',
                                 'You have been invited to unlock the following areas:',
                                 num_restrictions),
                  ', '.join(str(restriction.title) for restriction in token.restrictions)),
    })
    def clean(self):
        cleaned_data = super(forms.Form, self).clean()

        if scope == SCOPE.SADMIN:
            # Do not enforce max/min for admin
            return cleaned_data

        if option_group_instance.minimum_selected <= 0 and option_group_instance.maximum_selected <= 0:
            return cleaned_data

        selected = 0

        for option in options:
            field_id = _pack_id('option', option.pk)

            if getattr(option, scope):
                # field is editable
                value = cleaned_data.get(field_id, None)
            else:
                value = self.initial.get(field_id, None)

            selected += 1 if self._selected_callbacks[field_id](value) else 0

        if option_group_instance.minimum_selected > 0 and selected < option_group_instance.minimum_selected:
            raise forms.ValidationError(ungettext_lazy('You must select at least %d option.',
                                                       'You must select at least %d options.',
                                                       option_group_instance.minimum_selected) % option_group_instance.minimum_selected)

        if 0 < option_group_instance.maximum_selected < selected:
            raise forms.ValidationError(ungettext_lazy('You must select at most %d option.',
                                                       'You must select at most %d options.',
                                                       option_group_instance.maximum_selected) % option_group_instance.maximum_selected)

        return cleaned_data
    def clean(self, value):
        value = super(TagNamesField, self).clean(value)
        data = value.strip()
        if len(data) < 1:
            raise forms.ValidationError(_('tags are required'))

        split_re = re.compile(const.TAG_SPLIT_REGEX)
        tag_strings = split_re.split(data)
        entered_tags = []
        tag_count = len(tag_strings)
        if tag_count > askbot_settings.MAX_TAGS_PER_POST:
            max_tags = askbot_settings.MAX_TAGS_PER_POST
            msg = ungettext_lazy(
                        'please use %(tag_count)d tag or less',
                        'please use %(tag_count)d tags or less',
                        tag_count) % {'tag_count':max_tags}
            raise forms.ValidationError(msg)
        for tag in tag_strings:
            tag_length = len(tag)
            if tag_length > askbot_settings.MAX_TAG_LENGTH:
                #singular form is odd in english, but required for pluralization
                #in other languages
                msg = ungettext_lazy('each tag must be shorter than %(max_chars)d character',#odd but added for completeness
                                'each tag must be shorter than %(max_chars)d characters',
                                tag_length) % {'max_chars':tag_length}
                raise forms.ValidationError(msg)

            #todo - this needs to come from settings
            tagname_re = re.compile(const.TAG_REGEX, re.UNICODE)
            if not tagname_re.search(tag):
                raise forms.ValidationError(_('use-these-chars-in-tags'))
            #only keep unique tags
            if tag not in entered_tags:
                entered_tags.append(tag)

        #normalize character case of tags
        cleaned_entered_tags = list()
        if askbot_settings.FORCE_LOWERCASE_TAGS:
            #a simpler way to handle tags - just lowercase thew all
            for name in entered_tags:
                lowercased_name = name.lower()
                if lowercased_name not in cleaned_entered_tags:
                    cleaned_entered_tags.append(lowercased_name)
        else:
            #make names of tags in the input to agree with the database
            for entered_tag in entered_tags:
                try:
                    #looks like we have to load tags one-by one
                    #because we need tag name cases to be the same
                    #as those stored in the database
                    stored_tag = models.Tag.objects.get(
                                            name__iexact = entered_tag
                                        )
                    if stored_tag.name not in cleaned_entered_tags:
                        cleaned_entered_tags.append(stored_tag.name)
                except models.Tag.DoesNotExist:
                    cleaned_entered_tags.append(entered_tag)

        return u' '.join(cleaned_entered_tags)
def transmit_shipments(queryset=None, send_msg=None):
    log.info("transmit_shipments invoked")
    log.debug("queryset: %s", str(queryset))
    if send_msg is None:
        send_msg = lambda x: x

    if queryset is None:
        queryset = OrderShippingService.objects.all()

    from satchmo_store.shop.models import Config
    shop_details = Config.objects.get_current()
    settings = config_get_group('canada_post_dp_shipping')
    cpa_kwargs = canada_post_api_kwargs(settings)
    cpa = CanadaPostAPI(**cpa_kwargs)
    origin = get_origin(shop_details)

    groups = []
    order_shippings = []

    for order_shipping in queryset.filter(
            transmitted=False):
        log.debug("processing order shipping: %s", order_shipping)
        if order_shipping.shipments_created():
            log.debug("shipments created")
            group = unicode(order_shipping.shipping_group())
            groups.append(group)
            order_shippings.append(order_shipping)
        else:
            log.debug("shipments not created")
    log.debug("using groups: %s", groups)
    if groups:
        log.info("transmitting shipments")
        links = time_f(cpa.transmit_shipments,
                       'canada-post-dp-shipping.transmit-shipments',
                       origin, groups)
        log.debug("received manifests: %s", links)
        log.debug("marking order shippings as transmitted")
        for order_shipping in order_shippings:
            order_shipping.transmitted = True
            order_shipping.save()
        manifest_count = len(links)
        log.info("received %d manifests", manifest_count)
        send_msg(ungettext_lazy(
            "{count} manifest generated. It will be sent via email in a "
            "couple of minutes".format(count=manifest_count),
            "{count} manifests generated. They will be sent via email in a "
            "couple of minutes".format(count=manifest_count), manifest_count))
        if USE_CELERY:
            get_manifests_async.apply_async(args=(links,), cowntdown=1)
        else:
            get_manifests(links)

    group_count = len(groups)
    send_msg(ungettext_lazy(
        "Transmitted shipments for {count} group".format(count=group_count),
        "Transmitted shipments for {count} groups".format(count=group_count),
        group_count))
示例#9
0
 def harvest(self, request, queryset):
     feeds_count = queryset.count()
     if not feeds_count:
         return
     count = 0
     for feed in queryset:
         count += feed.harvest()
     message = ungettext_lazy(u"%(count)d item was harvested", u"%(count)d items were harvested", count) % {'count': count}
     message += ungettext_lazy(u" from %(count)d feed.", u" from %(count)d feeds.", feeds_count) % {'count': feeds_count}
     self.message_user(request, message)
示例#10
0
    def extend_round(self, request, queryset):
        form = None

        if 'submit' in request.POST:
            form = ExtendRoundForm(request.contest, request.POST)

            if form.is_valid():
                round = form.cleaned_data['round']
                extra_time = form.cleaned_data['extra_time']

                users = [participant.user for participant in queryset]
                existing_extensions = RoundTimeExtension.objects \
                        .filter(round=round, user__in=users)
                for extension in existing_extensions:
                    extension.extra_time += extra_time
                    extension.save()
                existing_count = existing_extensions.count()

                new_extensions = [RoundTimeExtension(user=user, round=round,
                        extra_time=extra_time) for user in users
                        if not existing_extensions.filter(user=user).exists()]
                RoundTimeExtension.objects.bulk_create(new_extensions)

                if existing_count:
                    if existing_count > 1:
                        name = capfirst(
                            RoundTimeExtension._meta.verbose_name_plural)
                    else:
                        name = RoundTimeExtension._meta.verbose_name
                    self.message_user(request, ungettext_lazy(
                        "Updated one %(name)s.",
                        "%(name)s updated: %(existing_count)d.",
                        existing_count
                    ) % {'existing_count': existing_count, 'name': name})
                if new_extensions:
                    if len(new_extensions) > 1:
                        name = capfirst(
                            RoundTimeExtension._meta.verbose_name_plural)
                    else:
                        name = RoundTimeExtension._meta.verbose_name
                    self.message_user(request, ungettext_lazy(
                        "Created one %(name)s.",
                        "%(name)s created: %(new_count)d.",
                        len(new_extensions)
                    ) % {'new_count': len(new_extensions), 'name': name})

                return HttpResponseRedirect(request.get_full_path())

        if not form:
            form = ExtendRoundForm(request.contest,
                    initial={'_selected_action': [p.id for p in queryset]})

        return TemplateResponse(request,
                                'admin/participants/extend_round.html',
                                {'form': form})
示例#11
0
    def get_form(self, request, obj=None, **kwargs):
        def get_column_width(prefix):
            # full_context from closure
            column_width = full_context.get('{0}-column-width'.format(prefix)) or '12'
            return int(string.replace(column_width, 'col-{0}-'.format(prefix), ''))

        self.partial_fields = [self.default_width_widget]
        if obj:
            full_context = obj.get_full_context()
            breakpoint = full_context.get('breakpoint')
            if breakpoint in ('lg', 'md', 'sm',):
                xs_column_width = get_column_width('xs')
                choices = (('', _('Unset')),) + tuple(('col-sm-{0}'.format(i), ungettext_lazy('{0} unit', '{0} units', i).format(i))
                                   for i in range(1, xs_column_width + 1))
                self.partial_fields.append(PartialFormField('sm-column-width',
                    widgets.Select(choices=choices), label=_('Width for Devices >768px'),
                    help_text=_('Column width for all devices wider than 768 pixels, such as tablets.')
                ))
                choices = (('', _('No offset')),) + tuple(('col-sm-offset-{0}'.format(i), ungettext_lazy('{0} unit', '{0} units', i).format(i))
                                   for i in range(1, xs_column_width))
                self.partial_fields.append(PartialFormField('sm-column-offset',
                    widgets.Select(choices=choices), label=_('Offset for Devices >768px'),
                    help_text=_('Column offset for all devices wider than 768 pixels, such as tablets.')
                ))
            if breakpoint in ('lg', 'md',):
                sm_column_width = get_column_width('sm')
                choices = (('', _('Unset')),) + tuple(('col-md-{0}'.format(i), ungettext_lazy('{0} unit', '{0} units', i).format(i))
                                   for i in range(1, sm_column_width + 1))
                self.partial_fields.append(PartialFormField('md-column-width',
                    widgets.Select(choices=choices), label=_('Width for Devices >992px'),
                    help_text=_('Column width for all devices wider than 992 pixels, such as laptops.')
                ))
                choices = (('', _('No offset')),) + tuple(('col-md-offset-{0}'.format(i), ungettext_lazy('{0} unit', '{0} units', i).format(i))
                                   for i in range(1, sm_column_width))
                self.partial_fields.append(PartialFormField('md-column-offset',
                    widgets.Select(choices=choices), label=_('Offset for Devices >992px'),
                    help_text=_('Column offset for all devices wider than 992 pixels, such as laptops.')
                ))
            if breakpoint in ('lg',):
                md_column_width = get_column_width('md')
                choices = (('', _('Unset')),) + tuple(('col-lg-{0}'.format(i), ungettext_lazy('{0} unit', '{0} units', i).format(i))
                                   for i in range(1, md_column_width + 1))
                self.partial_fields.append(PartialFormField('lg-column-width',
                    widgets.Select(choices=choices), label=_('Width for Devices >1200px'),
                    help_text=_('Column width for all devices wider than 1200 pixels, such as large desktops.'),
                ))
                choices = (('', _('No offset')),) + tuple(('col-lg-offset-{0}'.format(i), ungettext_lazy('{0} unit', '{0} units', i).format(i))
                                   for i in range(1, md_column_width))
                self.partial_fields.append(PartialFormField('lg-column-offset',
                    widgets.Select(choices=choices), label=_('Offset for Devices >1200px'),
                    help_text=_('Column offset for all devices wider than 1200 pixels, such as large desktops.')
                ))
        return super(BootstrapColumnPlugin, self).get_form(request, obj, **kwargs)
示例#12
0
def time_amount(value):
    delta = timedelta(seconds=value)

    units_dict = {
        'd': delta.days,
        'h': 0,
        'm': 0,
        's': delta.seconds,
    }

    if units_dict['s'] >= 3600:
        units_dict['h'] = units_dict['s'] / 3600
        units_dict['s'] -= units_dict['h'] * 3600

    if units_dict['s'] >= 60:
        units_dict['m'] = units_dict['s'] / 60
        units_dict['s'] -= units_dict['m'] * 60

    precisions = []

    if units_dict['d']:
        string = ungettext_lazy(
            '%(days)s day', '%(days)s days', units_dict['d'])
        precisions.append(string % {'days': units_dict['d']})

    if units_dict['h']:
        string = ungettext_lazy(
            '%(hours)s hour', '%(hours)s hours', units_dict['h'])
        precisions.append(string % {'hours': units_dict['h']})

    if units_dict['m']:
        string = ungettext_lazy(
            '%(minutes)s minute', '%(minutes)s minutes', units_dict['m'])
        precisions.append(string % {'minutes': units_dict['m']})

    if units_dict['s']:
        string = ungettext_lazy(
            '%(seconds)s second', '%(seconds)s seconds', units_dict['s'])
        precisions.append(string % {'seconds': units_dict['s']})

    if not precisions:
        precisions.append(_("0 seconds"))

    if len(precisions) == 1:
        return precisions[0]
    else:
        formats = {
            'first_part': ', '.join(precisions[:-1]),
            'and_part': precisions[-1],
        }

        return _("%(first_part)s and %(and_part)s") % formats
示例#13
0
 def action_present(count):
     return (
         ungettext_lazy(
             u"Disable Light-Snapshot",
             u"Disable Light-Snapshot",
             count
         ),
         ungettext_lazy(
             u"Enable Light-Snapshot",
             u"Enable Light-Snapshot",
             count
         ),
     )
 def action_past(count):
     return (
         ungettext_lazy(
             u"Shelved Instance",
             u"Shelved Instances",
             count
         ),
         ungettext_lazy(
             u"Unshelved Instance",
             u"Unshelved Instances",
             count
         ),
     )
示例#15
0
 def action_past(count):
     return (
         ungettext_lazy(
             u"Disable Light-Snapshot for instance Successfully",
             u"Disable Light-Snapshot for instances Successfully",
             count
         ),
         ungettext_lazy(
             u"Enable Light_Snapshot for instance Successfully",
             u"Enable Light_Snapshot for instances Successfully",
             count
         ),
     )
示例#16
0
 def action_past(count):
     return (
         ungettext_lazy(
             u"Enabled Module",
             u"Enabled Modules",
             count
         ),
         ungettext_lazy(
             u"Disabled Module",
             u"Disabled Modules",
             count
         ),
     )
 def action_present(count):
     return (
         ungettext_lazy(
             u"Pause Instance",
             u"Pause Instances",
             count
         ),
         ungettext_lazy(
             u"Resume Instance",
             u"Resume Instances",
             count
         ),
     )
示例#18
0
 def action_past(count):
     return (
         ungettext_lazy(
             u"Enabled User",
             u"Enabled Users",
             count
         ),
         ungettext_lazy(
             u"Disabled User",
             u"Disabled Users",
             count
         ),
     )
 def action_past(count):
     return (
         ungettext_lazy(
             u"Suspended Instance",
             u"Suspended Instances",
             count
         ),
         ungettext_lazy(
             u"Resumed Instance",
             u"Resumed Instances",
             count
         ),
     )
示例#20
0
文件: forms.py 项目: afdelgado/askbot
    def clean(self, value):
        if value is None:
            value = ''
        if len(value) < askbot_settings.MIN_TITLE_LENGTH:
            msg = ungettext_lazy(
                'title must be > %d character',
                'title must be > %d characters',
                askbot_settings.MIN_TITLE_LENGTH
            ) % askbot_settings.MIN_TITLE_LENGTH
            raise forms.ValidationError(msg)
        encoded_value = value.encode('utf-8')
        if len(value) == len(encoded_value):
            if len(value) > self.max_length:
                raise forms.ValidationError(
                    _(
                        'The title is too long, maximum allowed size is '
                        '%d characters'
                    ) % self.max_length
                )
        elif len(encoded_value) > self.max_length:
            raise forms.ValidationError(
                _(
                    'The title is too long, maximum allowed size is '
                    '%d bytes'
                ) % self.max_length
            )

        return value.strip() # TODO: test me
示例#21
0
 def action_past(count):
     # Translators: test code, don't really have to translate
     return ungettext_lazy(
         u"Sold Puppy",
         u"Sold Puppies",
         count
     )
示例#22
0
    def send_update(cls, req_event_dict, user=None, email=None,
                    template=None):
        if user is None and email is None:
            return
        if template is None:
            template = 'foirequestfollower/update_follower.txt'

        count = len(req_event_dict)
        subject = ungettext_lazy(
            "%(site_name)s: Update on one followed request",
            "%(site_name)s: Update on %(count)s followed requests",
            count) % {
                'site_name': settings.SITE_NAME,
                'count': count
            }
        send_mail(subject,
            render_to_string(template,
                {
                    "req_event_dict": req_event_dict,
                    "count": count,
                    "user": user,
                    "site_name": settings.SITE_NAME
                }
            ),
            settings.DEFAULT_FROM_EMAIL,
            [email or user.email]
        )
示例#23
0
文件: admin.py 项目: hnejadi/EShop-2
 def make_active(self, request, queryset):
     n_done = queryset.update(active=True)
     message = ungettext_lazy(u"%(count)d offer activated", u"%(count)d offers activated", n_done) % {
         "count": n_done
     }
     self.message_user(request, message)
     return HttpResponseRedirect("")
示例#24
0
    def _check_quotas(self, cleaned_data):
        count = cleaned_data.get("count", 1)

        # Prevent launching more instances than the quota allows
        usages = quotas.tenant_quota_usages(self.request)
        available_count = usages["instances"]["available"]
        if available_count < count:
            error_message = ungettext_lazy(
                "The requested instance cannot be launched as you only " "have %(avail)i of your quota available. ",
                "The requested %(req)i instances cannot be launched as you "
                "only have %(avail)i of your quota available.",
                count,
            )
            params = {"req": count, "avail": available_count}
            raise forms.ValidationError(error_message % params)

        source_type = cleaned_data.get("source_type")
        if source_type in ("volume_image_id", "volume_snapshot_id"):
            available_volume = usages["volumes"]["available"]
            if available_volume < count:
                msg = _(
                    "The requested instance cannot be launched. "
                    "Requested volume exceeds quota: Available: "
                    "%(avail)s, Requested: %(req)s."
                ) % {"avail": available_volume, "req": count}
                raise forms.ValidationError(msg)

        flavor_id = cleaned_data.get("flavor")
        flavor = self._get_flavor(flavor_id)

        count_error = []
        # Validate cores and ram.
        available_cores = usages["cores"]["available"]
        if flavor and available_cores < count * flavor.vcpus:
            count_error.append(
                _("Cores(Available: %(avail)s, " "Requested: %(req)s)")
                % {"avail": available_cores, "req": count * flavor.vcpus}
            )

        available_ram = usages["ram"]["available"]
        if flavor and available_ram < count * flavor.ram:
            count_error.append(
                _("RAM(Available: %(avail)s, " "Requested: %(req)s)")
                % {"avail": available_ram, "req": count * flavor.ram}
            )

        if count_error:
            value_str = ", ".join(count_error)
            msg = (
                _(
                    "The requested instance cannot be launched. "
                    "The following requested resource(s) exceed "
                    "quota(s): %s."
                )
                % value_str
            )
            if count == 1:
                self._errors["flavor"] = self.error_class([msg])
            else:
                self._errors["count"] = self.error_class([msg])
示例#25
0
    def clean(self, value):
        """cleans the field for minimum and maximum length
        also is supposed to work for unicode non-ascii characters"""
        if value is None:
            value = ''
        if len(value) < openode_settings.MIN_TITLE_LENGTH:
            msg = ungettext_lazy(
                'title must be > %d character',
                'title must be > %d characters',
                openode_settings.MIN_TITLE_LENGTH
            ) % openode_settings.MIN_TITLE_LENGTH
            raise forms.ValidationError(msg)
        encoded_value = value.encode('utf-8')
        if len(value) == len(encoded_value):
            if len(value) > self.max_length:
                raise forms.ValidationError(
                    _(
                        'The title is too long, maximum allowed size is '
                        '%d characters'
                    ) % self.max_length
                )
        elif len(encoded_value) > self.max_length:
            raise forms.ValidationError(
                _(
                    'The title is too long, maximum allowed size is '
                    '%d bytes'
                ) % self.max_length
            )

        return value.strip()  # TODO: test me
示例#26
0
    def modify(self, ids):
        ret = []

        if not self.is_valid():
            ret.append(Message(_('Entered data was invalid, no changes made.'), type=Message.ERROR))
            for field, errors in self.errors.items():
                for error in errors:
                    ret.append(Message(error=error, field=self.fields[field].label))
            return ret

        matches = Match.objects.filter(id__in=ids)

        if self.cleaned_data['event'] != 0:
            try:
                event = Event.objects.get(id=self.cleaned_data['event'])
                matches.update(eventobj=event)
            except:
                pass

        if self.cleaned_data['date'] != None:
            matches.update(date=self.cleaned_data['date'])

        if self.cleaned_data['offline'] != 'nochange':
            matches.update(offline=(self.cleaned_data['offline']=='offline'))

        if self.cleaned_data['game'] != 'nochange':
            matches.update(game=self.cleaned_data['game'])

        return [Message(
            ungettext_lazy('Updated %i match.', 'Updated %i matches.', matches.count()) % matches.count(), 
            type=Message.SUCCESS
        )]
示例#27
0
def ticket_badge_view(request, pk):
    if isinstance(pk, models.query.QuerySet):
        ticket = pk
    else:
        ticket = VenueTicket.objects.filter(pk=pk).select_related('purchase')

    ticket = ticket.filter(canceled=False)

    count = ticket.count()
    if count == 0:
        raise Http404

    if ticket[0].purchase.state != 'payment_received':
        messages.error(request, _('Invoice not yet paid.'))
        url = reverse('checkin_purchase_detail', kwargs={'pk': ticket[0].purchase_id})
        return HttpResponseRedirect(url)

    be = BadgeExporter(ticket, 'https://ep14.org/u{uid}', indent=False)
    data = be.export()
    pdf = generate_badge(data)
    if pdf is not None:
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="badge.pdf"'
        response.write(pdf)
        return response
    else:
        msg = ungettext_lazy('Error generating the badge',
                             'Error generating the badges',
                             count)
        messages.error(request, msg)
        url = reverse('checkin_purchase_detail', kwargs={'pk': ticket[0].purchase_id})
        return HttpResponseRedirect(url)
示例#28
0
    def rejudge_view(self, request):
        tests = request.POST.getlist('tests', [])
        subs_ids = [int(x) for x in request.POST.getlist('submissions', [])]
        rejudge_type = request.POST['rejudge_type']
        submissions = Submission.objects.in_bulk(subs_ids)
        all_reports_exist = True
        for sub in submissions.values():
            if not SubmissionReport.objects.filter(submission=sub,
                                                   status='ACTIVE') \
                                           .exists():
                all_reports_exist = False
                break

        if all_reports_exist or rejudge_type == 'FULL':
            for sub in submissions.values():
                sub.problem_instance.controller.judge(sub,
                                 is_rejudge=True,
                                 extra_args={'tests_to_judge': tests,
                                             'rejudge_type': rejudge_type})

            counter = len(submissions)
            self.message_user(
                request,
                ungettext_lazy("Queued one submission for rejudge.",
                               "Queued %(counter)d submissions for rejudge.",
                               counter) % {'counter': counter})
        else:
            self.message_user(
                request,
                _("Cannot rejudge submissions due to lack of active reports "
                  "for one or more submissions"))

        return redirect('oioioiadmin:contests_submission_changelist')
示例#29
0
    def clean(self):
        cleaned_data = super(SetInstanceDetailsAction, self).clean()

        count = cleaned_data.get('count', 1)
        # Prevent launching more instances than the quota allows
        usages = quotas.tenant_quota_usages(self.request)
        available_count = usages['instances']['available']
        if available_count < count:
            error_message = ungettext_lazy('The requested instance '
                                           'cannot be launched as you only '
                                           'have %(avail)i of your quota '
                                           'available. ',
                                           'The requested %(req)i instances '
                                           'cannot be launched as you only '
                                           'have %(avail)i of your quota '
                                           'available.',
                                           count)
            params = {'req': count,
                      'avail': available_count}
            raise forms.ValidationError(error_message % params)

        # Validate our instance source.
        source_type = self.data.get('source_type', None)

        return cleaned_data
示例#30
0
    def clean(self, value):
        from openode import models
        value = super(TagNamesField, self).clean(value)
        data = value.strip()
        split_re = re.compile(const.TAG_SPLIT_REGEX)
        tag_strings = split_re.split(data)
        # entered_tags = []
        tag_count = len(tag_strings)
        if tag_count > openode_settings.MAX_TAGS_PER_POST:
            max_tags = openode_settings.MAX_TAGS_PER_POST
            msg = ungettext_lazy(
                        'please use %(tag_count)d tag or less',
                        'please use %(tag_count)d tags or less',
                        tag_count) % {'tag_count': max_tags}
            raise forms.ValidationError(msg)

        cleaned_entered_tags = list()
        for tag in tag_strings:
            cleaned_tag = clean_tag(tag)
            if cleaned_tag not in cleaned_entered_tags:
                cleaned_entered_tags.append(clean_tag(tag))

        result = u' '.join(cleaned_entered_tags)

        if len(result) > 125:  # magic number!, the same as max_length in db
            raise forms.ValidationError(self.error_messages['max_length'])

        return u' '.join(cleaned_entered_tags)
示例#31
0
 def action_past(count):
     return ungettext_lazy(
         u"Scheduled deletion of Firewall",
         u"Scheduled deletion of Firewalls",
         count
     )
示例#32
0
 def action_present(count):
     return ungettext_lazy(u"Unlock Instance", u"Unlock Instances", count)
示例#33
0
文件: tables.py 项目: gyromaker/gyro1
 def action_past(count):
     return ungettext_lazy(
         u"Deleted Subnet",
         u"Deleted Subnets",
         count
     )
示例#34
0
 def action_past(count):
     return ungettext_lazy(
         u"Scheduled deletion of Policy",
         u"Scheduled deletion of Policies",
         count
     )
示例#35
0
 def action_past(count):
     return ungettext_lazy(u"Deleted Metadata", u"Deleted Metadata", count)
示例#36
0
 def action_past(count):
     return ungettext_lazy(u"Deleted address pair",
                           u"Deleted address pairs", count)
示例#37
0
 def action_past(count):
     return ungettext_lazy(u"Deleted Domain", u"Deleted Domains", count)
示例#38
0
 def action_present(count):
     return (
         ungettext_lazy(u"Pause Instance", u"Pause Instances", count),
         ungettext_lazy(u"Resume Instance", u"Resume Instances", count),
     )
示例#39
0
 def action_past(count):
     return ungettext_lazy(u"Deleted Action Execution",
                           u"Deleted Action Executions", count)
示例#40
0
 def action_present(count):
     return ungettext_lazy(u"Delete Action Execution",
                           u"Delete Action Executions", count)
示例#41
0
 def action_past(count):
     return ungettext_lazy(u"Deleted Object", u"Deleted Objects", count)
示例#42
0
 def action_present(count):
     return ungettext_lazy(u"Delete Object", u"Delete Objects", count)
示例#43
0
 def action_past(count):
     return ungettext_lazy(u"Deleted Container", u"Deleted Containers",
                           count)
示例#44
0
 def action_present(count):
     return ungettext_lazy(u"Delete Metadata", u"Delete metadata", count)
示例#45
0
 def action_present(count):
     return ungettext_lazy(u"Delete Domain", u"Delete Domains", count)
示例#46
0
 def action_present(count):
     return ungettext_lazy(u"Delete Container", u"Delete Containers", count)
示例#47
0
 def action_past(count):
     return (
         ungettext_lazy(u"Shelved Instance", u"Shelved Instances", count),
         ungettext_lazy(u"Unshelved Instance", u"Unshelved Instances",
                        count),
     )
示例#48
0
 def action_past(count):
     return (
         ungettext_lazy(u"Suspended Instance", u"Suspended Instances",
                        count),
         ungettext_lazy(u"Resumed Instance", u"Resumed Instances", count),
     )
示例#49
0
 def action_present(count):
     return ungettext_lazy(
         u"Delete Firewall",
         u"Delete Firewalls",
         count
     )
示例#50
0
 def action_present(count):
     return ungettext_lazy(
         u"Delete Policy",
         u"Delete Policies",
         count
     )
示例#51
0
文件: tables.py 项目: yhtsnda/horizon
 def action_past(count):
     return ungettext_lazy(u"Deleted Network", u"Deleted Networks", count)
示例#52
0
文件: tables.py 项目: yhtsnda/horizon
 def action_present(count):
     return ungettext_lazy(u"Delete Network", u"Delete Networks", count)
示例#53
0
 def action_present(count):
     return ungettext_lazy(
         u"Delete Interface",
         u"Delete Interfaces",
         count
     )
示例#54
0
文件: tables.py 项目: gyromaker/gyro1
 def action_present(count):
     return ungettext_lazy(
         u"Delete Subnet",
         u"Delete Subnets",
         count
     )
示例#55
0
 def action_past(count):
     return ungettext_lazy(
         u"Deleted Interface",
         u"Deleted Interfaces",
         count
     )
示例#56
0
 def action_present(count):
     return ungettext_lazy(
         u"Delete Rule",
         u"Delete Rules",
         count
     )
示例#57
0
 def action_past(count):
     return ungettext_lazy(u"Unlocked Instance", u"Unlocked Instances",
                           count)
示例#58
0
 def action_past(count):
     return ungettext_lazy(
         u"Scheduled deletion of Rule",
         u"Scheduled deletion of Rules",
         count
     )
示例#59
0
 def action_past(count):
     return ungettext_lazy(u"Soft Rebooted Instance",
                           u"Soft Rebooted Instances", count)
示例#60
0
 def action_past(count):
     return ungettext_lazy(u"Deleted Router Rule", u"Deleted Router Rules",
                           count)