def _show_new_release_notification(self): """When upgraded to new release, show a notification.""" from plinth.notification import Notification try: note = Notification.get('upgrades-new-release') if note.data['version'] == plinth.__version__: # User already has notification for update to this version. It # may be dismissed or not yet dismissed return # User currently has a notification for an older version, update. dismiss = False except KeyError: # Don't show notification for the first version user runs, create # but don't show it. dismiss = True data = { 'version': plinth.__version__, 'app_name': 'translate:' + gettext_noop('Software Update'), 'app_icon': 'fa-refresh' } title = gettext_noop('FreedomBox Updated') note = Notification.update_or_create( id='upgrades-new-release', app_id='upgrades', severity='info', title=title, body_template='upgrades-new-release.html', data=data, group='admin') note.dismiss(should_dismiss=dismiss)
class AccountFormView(FormView): """The form to create or update an account.""" model = Account form_class = AccountForm not_modified_message = gettext_noop("This account was not modified.") success_message = gettext_noop("This account was saved successfully.") def make_form_from_post(self, post: Dict[str, str]) -> AccountForm: """Creates and returns the form from the POST data.""" form = AccountForm(post) form.account = self.object return form def make_form_from_model(self, obj: Account) -> AccountForm: """Creates and returns the form from a data model.""" form = AccountForm({ "code": obj.code, "title": obj.title, }) form.account = obj return form def get_object(self) -> Optional[Account]: """Returns the current object, or None on a create form.""" return self.kwargs.get("account") def get_success_url(self) -> str: """Returns the URL on success.""" return reverse("accounting:accounts.detail", args=[self.object], current_app=self.request.resolver_match.namespace)
def add_gpg_key(self, keys, fingerprint, address): if isinstance(keys, str): keys = keys.encode('utf-8') # convert to bytes imported = [] with self.gpg_keyring(init=False) as backend: for key in keys.split(_gpg_key_delimiter): try: imp_key = backend.import_key(keys)[0] imported.append((key, imp_key.fp, imp_key.expires)) except Exception as e: log.exception(e) err = gettext_noop('Error importing GPG key.') self.log(err, address=address) # log entry in "Recent activity" self.message(messages.ERROR, err) # message to user raise for key, fp, expires in imported: if expires: # None if the key does not expire expires = timezone.make_aware(expires) # Create or update the GPG key dbkey, created = GpgKey.objects.update_or_create( user=self, fingerprint=fp, defaults={'key': key, 'expires': expires, }) payload = {'fingerprint': fp, } if created is True: message = gettext_noop('Added GPG key 0x%(fingerprint)s.') else: message = gettext_noop('Updated GPG key 0x%(fingerprint)s.') self.log(message, address=address, **payload) self.message(messages.INFO, message, **payload)
def _show_schedule_setup_notification(): """Show a notification hinting to setup a remote backup schedule.""" from plinth.notification import Notification message = gettext_noop( 'Enable an automatic backup schedule for data safety. Prefer an ' 'encrypted remote backup location or an extra attached disk.') data = { 'app_name': 'translate:' + gettext_noop('Backups'), 'app_icon': 'fa-files-o' } title = gettext_noop('Enable a Backup Schedule') actions_ = [{ 'type': 'link', 'class': 'primary', 'text': gettext_noop('Go to {app_name}'), 'url': 'backups:index' }, { 'type': 'dismiss' }] Notification.update_or_create(id='backups-remote-schedule', app_id='backups', severity='info', title=title, message=message, actions=actions_, data=data, group='admin')
def common(request): """Add additional context values to RequestContext for use in templates. Any resources referenced in the return value are expected to have been initialized or configured externally beforehand. """ # Allow a value in configuration file to be translated. Allow # the brand name 'FreedomBox' itself to be translated. gettext_noop('FreedomBox') from plinth.notification import Notification notifications_context = Notification.get_display_context(request, user=request.user) slash_indices = [match.start() for match in re.finditer('/', request.path)] active_menu_urls = [request.path[:index + 1] for index in slash_indices] return { 'cfg': cfg, 'submenu': menu.main_menu.active_item(request), 'active_menu_urls': active_menu_urls, 'box_name': _(cfg.box_name), 'user_is_admin': is_user_admin(request, True), 'notifications': notifications_context['notifications'], 'notifications_max_severity': notifications_context['max_severity'] }
class SimprintsIntegrationForm(forms.Form): is_enabled = forms.BooleanField( label=gettext_noop("Enable Simprints Integration"), required=False) project_id = forms.CharField( label=gettext_noop("Project ID"), required=False, ) user_id = forms.CharField( label=gettext_noop("User ID"), required=False, ) module_id = forms.CharField( label=gettext_noop("Module ID"), required=False, ) def __init__(self, data, *args, **kwargs): self._domain = kwargs.pop('domain') super(SimprintsIntegrationForm, self).__init__(data, *args, **kwargs) self.helper = hqcrispy.HQFormHelper() self.helper.form_method = 'POST' self.helper.layout = crispy.Layout( hqcrispy.B3MultiField( _("Simprints Integration"), hqcrispy.InlineField('is_enabled', data_bind="checked: isEnabled"), ), crispy.Div(crispy.Field('project_id', data_bind="value: projectId"), crispy.Field('user_id', data_bind="value: userId"), crispy.Field('module_id', data_bind="value: moduleId"), data_bind="visible: isEnabled"), hqcrispy.FormActions( crispy.ButtonHolder(Submit('submit', gettext_lazy("Update"))))) @property @memoized def _existing_integration(self): existing, _created = SimprintsIntegration.objects.get_or_create( domain=self._domain, ) return existing @property def initial_data(self): return { 'is_enabled': self._existing_integration.is_enabled, 'project_id': self._existing_integration.project_id, 'user_id': self._existing_integration.user_id or "global_user", 'module_id': self._existing_integration.module_id or "global_module", } def save(self): self._existing_integration.is_enabled = self.cleaned_data['is_enabled'] self._existing_integration.project_id = self.cleaned_data['project_id'] self._existing_integration.user_id = self.cleaned_data['user_id'] self._existing_integration.module_id = self.cleaned_data['module_id'] self._existing_integration.save()
def get_subpages(cls): return [{ 'title': gettext_noop('Case Options'), 'urlname': 'excel_config' }, { 'title': gettext_noop('Match Excel Columns to Case Properties'), 'urlname': 'excel_fields' }]
def options(self): return [ (MessagingEvent.CONTENT_SMS_SURVEY, gettext_noop('SMS Survey')), (MessagingEvent.CONTENT_SMS_CALLBACK, gettext_noop('SMS Callback')), (MessagingEvent.CONTENT_SMS, gettext_noop('Other SMS')), (MessagingEvent.CONTENT_EMAIL, gettext_noop('Email')), ]
def spawn_workflow_graph_jobs(self, workflow_jobs): for workflow_job in workflow_jobs: if workflow_job.cancel_flag: logger.debug('Not spawning jobs for %s because it is pending cancelation.', workflow_job.log_format) continue dag = WorkflowDAG(workflow_job) spawn_nodes = dag.bfs_nodes_to_run() if spawn_nodes: logger.debug('Spawning jobs for %s', workflow_job.log_format) else: logger.debug('No nodes to spawn for %s', workflow_job.log_format) for spawn_node in spawn_nodes: if spawn_node.unified_job_template is None: continue kv = spawn_node.get_job_kwargs() job = spawn_node.unified_job_template.create_unified_job(**kv) spawn_node.job = job spawn_node.save() logger.debug('Spawned %s in %s for node %s', job.log_format, workflow_job.log_format, spawn_node.pk) can_start = True if isinstance(spawn_node.unified_job_template, WorkflowJobTemplate): workflow_ancestors = job.get_ancestor_workflows() if spawn_node.unified_job_template in set(workflow_ancestors): can_start = False logger.info( 'Refusing to start recursive workflow-in-workflow id={}, wfjt={}, ancestors={}'.format( job.id, spawn_node.unified_job_template.pk, [wa.pk for wa in workflow_ancestors] ) ) display_list = [spawn_node.unified_job_template] + workflow_ancestors job.job_explanation = gettext_noop( "Workflow Job spawned from workflow could not start because it " "would result in recursion (spawn order, most recent first: {})" ).format(', '.join(['<{}>'.format(tmp) for tmp in display_list])) else: logger.debug( 'Starting workflow-in-workflow id={}, wfjt={}, ancestors={}'.format( job.id, spawn_node.unified_job_template.pk, [wa.pk for wa in workflow_ancestors] ) ) if not job._resources_sufficient_for_launch(): can_start = False job.job_explanation = gettext_noop( "Job spawned from workflow could not start because it " "was missing a related resource such as project or inventory" ) if can_start: if workflow_job.start_args: start_args = json.loads(decrypt_field(workflow_job, 'start_args')) else: start_args = {} can_start = job.signal_start(**start_args) if not can_start: job.job_explanation = gettext_noop( "Job spawned from workflow could not start because it " "was not in the right state or required manual credentials" ) if not can_start: job.status = 'failed' job.save(update_fields=['status', 'job_explanation']) job.websocket_emit_status('failed')
class ErrorCodeFilter(BaseMultipleOptionFilter): label = gettext_noop('Error') default_text = gettext_noop('Select Error...') slug = 'error_code' options = [ (code, message.split(".")[0]) # shorten multi-sentence messages for code, message in MessagingEvent.ERROR_MESSAGES.items() if code != MessagingEvent.ERROR_SUBEVENT_ERROR ]
class UserPropertyFilter(BaseSingleOptionFilter): label = gettext_noop('Modified Property') default_text = gettext_noop('Select Property') slug = 'user_property' @property def options(self): from corehq.apps.reports.standard.users.reports import UserHistoryReport properties = UserHistoryReport.get_primary_properties(self.domain) properties.pop("username", None) return list(properties.items())
def _n2w(n, to): try: return num2words(n, lang=to_locale(get_language()), to=to) except NotImplementedError: # fall back to gettext for these words gettext_noop("first") gettext_noop("second") gettext_noop("third") gettext_noop("fourth") gettext_noop("fifth") return _(num2words(n, lang="en", to=to))
class DateRangePickerWidget(Input): """ Extends the standard input widget to render a Date Range Picker Widget. Documentation and Demo here: http://www.daterangepicker.com/ usage: apply the following decorator to your view's dispatch method @use_daterangepicker def dispatch(self, request, *args, **kwargs): super(self, MyView).dispatch(request, *args, **kwargs) """ class Range(object): LAST_7 = 'last_7_days' LAST_MONTH = 'last_month' LAST_30_DAYS = 'last_30_days' range_labels = { Range.LAST_7: gettext_noop('Last 7 Days'), Range.LAST_MONTH: gettext_noop('Last Month'), Range.LAST_30_DAYS: gettext_noop('Last 30 Days'), } separator = gettext_noop(' to ') def __init__(self, attrs=None, default_datespan=None): self.default_datespan = default_datespan super(DateRangePickerWidget, self).__init__(attrs=attrs) def render(self, name, value, attrs=None, renderer=None): startdate = '' enddate = '' if isinstance(self.default_datespan, DateSpan): if self.default_datespan.startdate is not None: startdate = self.default_datespan.startdate.strftime( '%m/%d/%Y') if self.default_datespan.enddate is not None: enddate = self.default_datespan.enddate.strftime('%m/%d/%Y') attrs.update({ 'data-separator': self.separator, 'data-labels': json.dumps(self.range_labels), 'data-start-date': startdate, 'data-end-date': enddate, }) output = super(DateRangePickerWidget, self).render(name, value, attrs, renderer) return format_html( '<div class="input-group hqwebapp-datespan">' ' <span class="input-group-addon"><i class="fa fa-calendar"></i></span>' ' {}' '</div>', output)
def post(self, request, *unused_args, **unused_kwargs): # lint-amnesty, pylint: disable=unused-argument """Create a new bookmark for a user. The POST request only needs to contain one parameter "usage_id". Http400 is returned if the format of the request is not correct, the usage_id is invalid or a block corresponding to the usage_id could not be found. **Example Requests** POST /api/bookmarks/v1/bookmarks/ Request data: {"usage_id": <usage-id>} """ if not request.data: return self.error_response(gettext_noop('No data provided.'), DEFAULT_USER_MESSAGE) usage_id = request.data.get('usage_id', None) if not usage_id: return self.error_response( gettext_noop('Parameter usage_id not provided.'), DEFAULT_USER_MESSAGE) try: usage_key = UsageKey.from_string(unquote_slashes(usage_id)) except InvalidKeyError: error_message = gettext_noop( 'Invalid usage_id: {usage_id}.').format(usage_id=usage_id) log.error(error_message) return self.error_response(error_message, DEFAULT_USER_MESSAGE) try: bookmark = api.create_bookmark(user=self.request.user, usage_key=usage_key) except ItemNotFoundError: error_message = gettext_noop( 'Block with usage_id: {usage_id} not found.').format( usage_id=usage_id) log.error(error_message) return self.error_response(error_message, DEFAULT_USER_MESSAGE) except BookmarksLimitReachedError: error_message = gettext_noop( 'You can create up to {max_num_bookmarks_per_course} bookmarks.' ' You must remove some bookmarks before you can add new ones.' ).format( max_num_bookmarks_per_course=settings.MAX_BOOKMARKS_PER_COURSE) log.info('Attempted to create more than %s bookmarks', settings.MAX_BOOKMARKS_PER_COURSE) return self.error_response(error_message) return Response(bookmark, status=status.HTTP_201_CREATED)
def check_dist_upgrade(_): """Check for upgrade to new stable release.""" from plinth.notification import Notification if is_dist_upgrade_enabled(): output = actions.superuser_run('upgrades', ['start-dist-upgrade']) result = json.loads(output) dist_upgrade_started = result['dist_upgrade_started'] reason = result['reason'] if 'found-previous' in reason: logger.info( 'Found previous dist-upgrade. If it was interrupted, it will ' 'be restarted.') elif 'already-' in reason: logger.info('Skip dist upgrade: System is already up-to-date.') elif 'codename-not-found' in reason: logger.warning('Skip dist upgrade: Codename not found in release ' 'file.') elif 'upgrades-not-enabled' in reason: logger.info('Skip dist upgrade: Automatic updates are not ' 'enabled.') elif 'test-not-set' in reason: logger.info('Skip dist upgrade: --test is not set.') elif 'not-enough-free-space' in reason: logger.warning('Skip dist upgrade: Not enough free space in /.') title = gettext_noop('Could not start distribution update') message = gettext_noop( 'There is not enough free space in the root partition to ' 'start the distribution update. Please ensure at least 5 GB ' 'is free. Distribution update will be retried after 24 hours,' ' if enabled.') Notification.update_or_create( id='upgrades-dist-upgrade-free-space', app_id='upgrades', severity='warning', title=title, message=message, actions=[{ 'type': 'dismiss' }], group='admin') elif 'started-dist-upgrade' in reason: logger.info('Started dist upgrade.') title = gettext_noop('Distribution update started') message = gettext_noop( 'Started update to next stable release. This may take a long ' 'time to complete.') Notification.update_or_create(id='upgrades-dist-upgrade-started', app_id='upgrades', severity='info', title=title, message=message, actions=[{ 'type': 'dismiss' }], group='admin') else: logger.warning('Unhandled result of start-dist-upgrade: %s, %s', dist_upgrade_started, reason)
def _get_result_data(results): return { 'categories': [ # Using gettext_noop here since this will be tacked into the cache, so it must be language neutral. # The caller, SubmissionList.get_result_data will run ugettext on the name. {'code': 'AC', 'name': gettext_noop('Accepted'), 'count': results['AC']}, {'code': 'WA', 'name': gettext_noop('Wrong'), 'count': results['WA']}, {'code': 'CE', 'name': gettext_noop('Compile Error'), 'count': results['CE']}, {'code': 'TLE', 'name': gettext_noop('Timeout'), 'count': results['TLE']}, {'code': 'ERR', 'name': gettext_noop('Error'), 'count': results['MLE'] + results['OLE'] + results['IR'] + results['RTE'] + results['AB'] + results['IE']}, ], 'total': sum(results.values()), }
class EventContentFilter(BaseMultipleOptionFilter): label = gettext_noop('Content Type') default_text = gettext_noop('All') slug = 'content_type' @property def options(self): return [ (MessagingEvent.CONTENT_SMS_SURVEY, gettext_noop('SMS Survey')), (MessagingEvent.CONTENT_SMS_CALLBACK, gettext_noop('SMS Callback')), (MessagingEvent.CONTENT_SMS, gettext_noop('Other SMS')), (MessagingEvent.CONTENT_EMAIL, gettext_noop('Email')), ]
def get_result_data(*args, **kwargs): if args: submissions = args[0] if kwargs: raise ValueError(_("Can't pass both queryset and keyword filters")) else: submissions = Submission.objects.filter( **kwargs) if kwargs is not None else Submission.objects raw = submissions.values('result').annotate( count=Count('result')).values_list('result', 'count') results = defaultdict(int, raw) return { 'categories': [ # Using gettext_noop here since this will be tacked into the cache, so it must be language neutral. # The caller, SubmissionList.get_result_data will run ugettext on the name. { 'code': 'AC', 'name': gettext_noop('Accepted'), 'count': results['AC'] }, { 'code': 'WA', 'name': gettext_noop('Wrong'), 'count': results['WA'] }, { 'code': 'CE', 'name': gettext_noop('Compile Error'), 'count': results['CE'] }, { 'code': 'TLE', 'name': gettext_noop('Timeout'), 'count': results['TLE'] }, { 'code': 'ERR', 'name': gettext_noop('Error'), 'count': results['MLE'] + results['OLE'] + results['IR'] + results['RTE'] + results['AB'] + results['IE'] }, ], 'total': sum(results.values()), }
class SimplifiedInventoryReport(GenericTabularReport, CommtrackReportMixin): name = gettext_noop('Inventory by Location') slug = SimplifiedInventoryDataSource.slug special_notice = gettext_noop( 'A maximum of 100 locations will be shown. ' 'Filter by location if you need to see more.') exportable = True emailable = True fields = [ 'corehq.apps.reports.filters.fixtures.AsyncLocationFilter', 'corehq.apps.reports.filters.commtrack.ProgramFilter', 'corehq.apps.reports.filters.dates.SingleDateFilter', ] @property @memoized def products(self): products = SQLProduct.active_objects.filter(domain=self.domain) if self.program_id: products = products.filter(program_id=self.program_id) return list(products.order_by('name')) @property def headers(self): columns = [ DataTablesColumn(_('Location')), ] columns += [DataTablesColumn(p.name) for p in self.products] return DataTablesHeader(*columns) @property def rows(self): config = { 'domain': self.domain, 'location_id': self.request.GET.get('location_id'), 'program_id': self.program_id, 'date': self.request.GET.get('date', None), 'max_rows': 100 } data = SimplifiedInventoryDataSource(config).get_data() for loc_name, loc_data in data: yield [loc_name] + [ loc_data.get(p.product_id, _('No data')) for p in self.products ]
def run_on_all_enabled_modules(): """Run diagnostics on all the enabled modules and store the result.""" global current_results # Four result strings returned by tests, mark for translation and # translate later. gettext_noop('passed') gettext_noop('failed') gettext_noop('error') gettext_noop('warning') apps = [] with results_lock: current_results = { 'apps': [], 'results': collections.OrderedDict(), 'progress_percentage': 0 } for app in app_module.App.list(): # Don't run diagnostics on apps have not been setup yet. # However, run on apps that need an upgrade. if app.needs_setup(): continue if not app.is_enabled(): continue if not app.has_diagnostics(): continue apps.append((app.app_id, app)) app_name = app.info.name or app.app_id current_results['results'][app.app_id] = {'name': app_name} current_results['apps'] = apps for current_index, (app_id, app) in enumerate(apps): app_results = { 'diagnosis': None, 'exception': None, } try: app_results['diagnosis'] = app.diagnose() except Exception as exception: logger.exception('Error running %s diagnostics - %s', app_id, exception) app_results['exception'] = str(exception) with results_lock: current_results['results'][app_id].update(app_results) current_results['progress_percentage'] = \ int((current_index + 1) * 100 / len(apps)) global running_task running_task = None
class SimpleCrispyFormView(BaseSimpleCrispyFormSectionView): """This shows example usage for crispy forms in an HQ template view. """ page_title = gettext_noop("Register a New User") urlname = 'ex_simple_crispy_forms' template_name = 'styleguide/examples/simple_crispy_form/base.html' @property @memoized def simple_crispy_form(self): initial_data = {} if self.request.method == 'POST': return ExampleUserLoginForm(self.request.POST, initial=initial_data) return ExampleUserLoginForm(initial=initial_data) @property def page_context(self): return { 'simple_crispy_form': self.simple_crispy_form, } def post(self, request, *args, **kwargs): if self.simple_crispy_form.is_valid(): # do something to process the data # It's always best practice to give some sort of feedback to the # user that the form was successfully processed. messages.success(request, _("Form processed successfully.")) return HttpResponseRedirect(self.page_url) return self.get(request, *args, **kwargs)
class BuildAppError(BuildBaseException): GENERIC_WITH_BUILD_ID = gettext_noop( 'There was a problem with Read the Docs while building your documentation. ' 'Please try again later. ' 'If this problem persists, ' 'report this error to us with your build id ({build_id}).', )
def set_email_task(self, user_pk, to, language, address, fingerprint=None, key=None, **payload): """A custom task because we might need to send the email with a custom set of GPG keys.""" user = User.objects.get(pk=user_pk) address = Address.objects.get_or_create(address=address)[0] if key: payload['gpg_recv_pub'] = key elif fingerprint: try: payload['gpg_recv_pub'] = self.fetch_key(fingerprint, user) payload['gpg_recv_fp'] = fingerprint # just so we know what was submitted except (URLError, socket.timeout): payload['gpg_recv_pub'] = False # do not encrypt else: payload['gpg_recv_pub'] = False # do not encrypt conf = Confirmation.objects.create(user=user, purpose=PURPOSE_SET_EMAIL, language=language, to=to, address=address, payload=payload) try: conf.send() except UnknownGpgliblibError as e: log.exception(e) msg = gettext_noop('Unexpected error importing GPG key.') user.log(msg) user.message(messages.ERROR, msg)
class SingleFormByApplicationFilter(FormsByApplicationFilter): """ Same as its superclass, except you _must_ select one form by the end of it. """ label = gettext_noop("Choose a Form") use_only_last = True show_global_hide_fuzzy_checkbox = False
class PhoneNumberReportFilter(BaseReportFilter): label = gettext_noop("Phone Number") slug = "phone_number_filter" template = "sms/phone_number_filter.html" @property def filter_context(self): return { "initial_value": self.get_value(self.request, self.domain), "groups": [{ '_id': '', 'name': '' }] + GroupES().domain(self.domain).source(['_id', 'name']).run().hits, } @classmethod def get_value(cls, request, domain): return { 'filter_type': request.GET.get('filter_type'), 'phone_number_filter': request.GET.get('phone_number_filter'), 'contact_type': request.GET.get('contact_type'), 'selected_group': request.GET.get('selected_group'), 'has_phone_number': request.GET.get('has_phone_number'), 'verification_status': request.GET.get('verification_status'), }
def export_ora2_summary(entry_id, xmodule_instance_args): """ Generate a CSV of ora2/student summaries and push it to S3. """ action_name = gettext_noop('generated') task_fn = partial(upload_ora2_summary, xmodule_instance_args) return run_main_task(entry_id, task_fn, action_name)
class EditProgramView(NewProgramView): urlname = 'commtrack_program_edit' page_title = gettext_noop("Edit Program") DEFAULT_LIMIT = 10 @property def page(self): return self.request.GET.get('page', 1) @property def limit(self): return self.request.GET.get('limit', self.DEFAULT_LIMIT) @property def page_context(self): return { 'program': self.program, 'has_data_list': True, 'pagination_limit_options': list(range(self.DEFAULT_LIMIT, 51, self.DEFAULT_LIMIT)), 'form': self.new_program_form, 'program_product_options': { 'total': self.program.get_products_count(), 'start_page': self.page, 'limit': self.limit, 'list_url': reverse('commtrack_product_for_program_fetch', args=[self.domain, self.program.get_id]), }, } @property def program_id(self): try: return self.kwargs['prog_id'] except KeyError: raise Http404() @property @memoized def program(self): try: return Program.get(self.program_id) except ResourceNotFound: raise Http404() @property def page_name(self): return _("Edit %s") % self.program.name @property def page_url(self): return reverse(self.urlname, args=[self.domain, self.program_id])
def send_update_notification_email(): gs = GlobalSettings() if not gs.settings.update_check_email: return mail_send_task.apply_async( kwargs={ "to": [gs.settings.update_check_email], "subject": _("pretalx update available"), "body": str( LazyI18nString.from_gettext( gettext_noop( "Hi!\n\nAn update is available for pretalx or for one of the plugins you installed in your " "pretalx installation at {base_url}.\nPlease follow this link for more information:\n\n {url} \n\n" "You can always find information on the latest updates in the changelog:\n\n" " https://docs.pretalx.org/changelog.html\n\n" "Larger updates are also announced with upgrade notes on the pretalx.com blog:\n\n" " https://pretalx.com/p/news" "\n\nBest regards,\nyour pretalx developers" ), ) ).format( base_url=settings.SITE_URL, url=settings.SITE_URL + reverse("orga:admin.update"), ), "html": None, } )
class DownloadLocationStatusView(BaseLocationView): urlname = 'download_org_structure_status' page_title = gettext_noop('Download Organization Structure Status') @method_decorator(require_can_edit_or_view_locations) def dispatch(self, request, *args, **kwargs): return super(BaseLocationView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): context = super(DownloadLocationStatusView, self).main_context next_url = reverse(FilteredLocationDownload.urlname, args=[self.domain]) next_url_text = _("Go back to organization download") context.update({ 'domain': self.domain, 'download_id': kwargs['download_id'], 'poll_url': reverse('org_download_job_poll', args=[self.domain, kwargs['download_id']]), 'title': _("Download Organization Structure Status"), 'progress_text': _("Preparing organization structure download."), 'error_text': _("There was an unexpected error! Please try again or report an issue."), 'next_url': next_url, 'next_url_text': next_url_text, }) return render(request, 'hqwebapp/soil_status_full.html', context) def page_url(self): return reverse(self.urlname, args=self.args, kwargs=self.kwargs)
class ProgressTab(EnrolledTab): """ The course progress view. """ type = 'progress' title = gettext_noop('Progress') priority = 20 view_name = 'progress' is_hideable = True is_default = False def __init__(self, tab_dict): def link_func(course, reverse_func): if course_home_mfe_progress_tab_is_active(course.id): return get_learning_mfe_home_url(course_key=course.id, url_fragment=self.view_name) else: return reverse_func(self.view_name, args=[str(course.id)]) tab_dict['link_func'] = link_func super().__init__(tab_dict) # pylint: disable=super-with-arguments @classmethod def is_enabled(cls, course, user=None): if not super().is_enabled(course, user=user): return False return not course.hide_progress_tab
def jumpstart(request): context = RequestContext(request, { 'settings': settings, 'languages': ( ('en', gettext_noop('English')) ), 'timezones': common_timezones }) return render_to_response('jumpstart/index.html', context)
def i18n(request): """ Send gettext-translated data in javascript format for various UI components. """ regular = [gettext_noop('Comments'),gettext_noop('Send'),gettext_noop('No comments posted yet')] trans={'$.dpText.TEXT_CHOOSE_DATE': _('Choose date'), '$.dpText.TEXT_PREV_MONTH': _('Previous month'), '$.dpText.TEXT_PREV_YEAR': _('Previous year'), '$.dpText.TEXT_NEXT_MONTH': _('Next month'), '$.dpText.TEXT_NEXT_YEAR': _('Next year'), '$.dpText.TEXT_CLOSE': _('Close'), 'Date.dayNames': [_('Sunday'),_('Monday'),_('Tuesday'),_('Wednesday'),_('Thursday'),_('Friday'),_('Saturday'),], 'Date.monthNames': [_('January'), _('February'), _('March'), _('April'), _('May'), _('June'), _('July'), _('August'), _('September'), _('October'), _('November'), _('December')], } for i in regular: trans["tuit.translations[" + to_json(i)+"]"] = _(i) # Cache-Control: private, max-age=3600, must-revalidate return tuit_render('i18n.js', {'strings':trans}, request)
def get_result_data(*args, **kwargs): if args: submissions = args[0] if kwargs: raise ValueError(_("Can't pass both queryset and keyword filters")) else: submissions = Submission.objects.filter(**kwargs) if kwargs is not None else Submission.objects raw = submissions.values('result').annotate(count=Count('result')).values_list('result', 'count') results = defaultdict(int, raw) return { 'categories': [ # Using gettext_noop here since this will be tacked into the cache, so it must be language neutral. # The caller, SubmissionList.get_result_data will run ugettext on the name. {'code': 'AC', 'name': gettext_noop('Accepted'), 'count': results['AC']}, {'code': 'WA', 'name': gettext_noop('Wrong'), 'count': results['WA']}, {'code': 'CE', 'name': gettext_noop('Compile Error'), 'count': results['CE']}, {'code': 'TLE', 'name': gettext_noop('Timeout'), 'count': results['TLE']}, {'code': 'ERR', 'name': gettext_noop('Error'), 'count': results['MLE'] + results['OLE'] + results['IR'] + results['RTE'] + results['AB'] + results['IE']}, ], 'total': sum(results.values()), }
'djangocms_inherit', 'djangocms_link', 'cmsplugin_filer_file', 'cmsplugin_filer_folder', 'cmsplugin_filer_image', 'cmsplugin_filer_teaser', 'cmsplugin_filer_video', 'vodantoc', 'zinnia', 'calendarium', 'reversion', ) LANGUAGES = [ ('fr', gettext_noop('French')), ] CMS_LANGUAGES = { ## Customize this 'default': { 'public': True, 'hide_untranslated': False, 'redirect_on_fallback': True, }, 1: [ { 'public': True, 'code': 'fr', 'hide_untranslated': False, 'name': gettext('fr'),
# -*- coding: utf-8 -*- from django.utils.translation import gettext_noop gettext_noop("Produção")
# Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGES = ( ('ru', gettext_noop('Russian')), ) LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/
# https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: _STATIC_ROOT = os.path.join(ROOT_DIR, 'static') STATICFILES_DIRS = (_STATIC_ROOT,) else: STATIC_ROOT = os.path.join(ROOT_DIR, 'static') MEDIA_ROOT = os.path.join(ROOT_DIR, 'media') LOGIN_REDIRECT_URL = '/survey/dashboard/' TPL_NAME = 'smarty/' LANGUAGES = [ ('en', gettext_noop('English')), ('pt-br', gettext_noop('Brazilian Portuguese')) ] # REDACTOR REDACTOR_OPTIONS = {'lang': 'pt_br'} REDACTOR_UPLOAD = 'uploads/' FILE_UPLOAD_HANDLERS = ( "django.core.files.uploadhandler.MemoryFileUploadHandler", ) # LOG ------------------------------------------------------------------------------------------------------------------ LOGGING = { 'version': 1, 'disable_existing_loggers': False,
def name(self): return gettext_noop("SSL with certificates")
def __i18n_keydates(): gettext_noop("256 colors, irc proxy, rmodifier, redirection of irc commands.") gettext_noop("Add hook \"line\".") gettext_noop("Add support of TOTP (Time-based One Time Password).") gettext_noop("Aspell plugin.") gettext_noop("Command /eval, aspell suggestions, IPv6 in relay, irc backlog in relay.") gettext_noop("Dcc chat and file, fifo plugin.") gettext_noop("Dynamic allocation and attributes for colors.") gettext_noop("First line of code.") gettext_noop("First version.") gettext_noop("Fset plugin (fast set of WeeChat and plugins options), PHP plugin.") gettext_noop("Full UTF-8 support.") gettext_noop("Gaps in buffers numbers, IPv6 for DCC file/chat, command /print.") gettext_noop("Guile plugin, support of python 3.x, weechat protocol in relay (remote interfaces), URL transfer in API.") gettext_noop("Headless mode, creation of buffers with commands /buffer and /print.") gettext_noop("Incremental text search in buffers.") gettext_noop("Indexed ban list in IRC plugin, support of IRCv3.2 Client Capability Negotiation, invite-notify and chghost.") gettext_noop("Inherited values in options.") gettext_noop("Javascript plugin, IRC SASL mechanism \"ecdsa-nist256p-challenge\".") gettext_noop("Last version before a major rewrite of WeeChat.") gettext_noop("Lua plugin.") gettext_noop("Mouse support, cursor mode.") gettext_noop("Multiple layouts, auto-unmask IRC joins, WebSocket support in relay.") gettext_noop("New site weechat.org, major rewrite of WeeChat with new plugin API, tcl plugin.") gettext_noop("Perl plugin.") gettext_noop("Plugin \"buflist\" (list of buffers).") gettext_noop("Plugin \"script\" (scripts manager), SSL in relay.") gettext_noop("Proxy support, IPv6, SSL.") gettext_noop("Python plugin.") gettext_noop("Ruby plugin.") gettext_noop("SASL authentication.") gettext_noop("Secured data, search of regular expression in buffer with text emphasis, dynamic day change message.") gettext_noop("Trigger and Exec plugins, bare display, hidden buffers, unit tests.")
from django.conf import settings from django.core.urlresolvers import reverse from django.core.validators import RegexValidator from django.db import models from django.utils.translation import ugettext_lazy as _, gettext_noop gettext_noop("projects") PROJECT_SLUG_RE = r"[-\w]{3,20}" class Project(models.Model): title = models.CharField(_("title"), max_length=400) slug = models.CharField(_("slug"), max_length=60, validators=[ RegexValidator(PROJECT_SLUG_RE)]) is_published = models.BooleanField(_("published"), default=False) main_url = models.URLField(_("main url"), null=True, blank=True) github_url = models.URLField(_("github url"), null=True, blank=True) summary = models.TextField(_("summary"), null=True, blank=True) description = models.TextField(_("description"), null=True, blank=True) launch_date = models.DateField(_("launch date"), null=True, blank=True) def get_absolute_url(self): return reverse('project:view', kwargs={'slug': self.slug}) def get_edit_url(self): return reverse('project:edit', kwargs={'slug': self.slug}) def __unicode__(self): return self.title
def default(cls): return cls.LIMITED_WORKING_PROFICIENCY class StudentReferralStatus(object): CREATED = 'created' UNPAID = 'unpaid' PAID = 'paid' @classmethod def default(cls): return cls.CREATED LANGUAGES = ( ('af', gettext_noop('Afrikaans')), ('ar', gettext_noop('Arabic')), ('az', gettext_noop('Azerbaijani')), ('bg', gettext_noop('Bulgarian')), ('be', gettext_noop('Belarussian')), ('bn', gettext_noop('Bengali')), ('br', gettext_noop('Breton')), ('bs', gettext_noop('Bosnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-au', gettext_noop('Australian English')),
def __i18n_security(): gettext_noop("/set irc.network.colors_receive off") gettext_noop("Buffer overflow when decoding IRC colors in strings.") gettext_noop("Buffer overflow when removing quotes in DCC filename.") gettext_noop("Buffer overflows in build of strings.") gettext_noop("Crash when receiving special chars in IRC messages.") gettext_noop("Create a trigger (with WeeChat >= 1.1): /trigger add irc_dcc_quotes modifier \"irc_in_privmsg\" \"${arguments} =~ ^[^ ]+ :${\\x01}DCC SEND ${\\x22} \" \"/.*//\"") gettext_noop("Date/time conversion specifiers are expanded after replacing buffer local variables in name of log files. In some cases, this can lead to an error in function strftime and a crash caused by the use of an uninitialized buffer.") gettext_noop("Do not use command /notify with nicks containing formatting chars like \"%\".") gettext_noop("Do not use irc protocol in relay plugin.") gettext_noop("Missing verifications in SSL certificate, which allows man-in-the-middle attackers to spoof an SSL chat server via an arbitrary certificate.") gettext_noop("Remove/unload all scripts calling function hook_process (for maximum safety).") gettext_noop("Turn off option \"irc.network.send_unknown_commands\" or do not use formatting chars like \"%\" when sending unknown commands to server.") gettext_noop("Uncontrolled format string in API function infobar_printf.") gettext_noop("Uncontrolled format string when IRC commands are redirected by relay plugin. If the output or redirected command contains formatting chars like \"%\", this can lead to a crash of WeeChat.") gettext_noop("Uncontrolled format string when sending IRC \"ison\" command for nicks monitored with command /notify.") gettext_noop("Uncontrolled format string when sending unknown IRC command to server (if option \"irc.network.send_unknown_commands\" is on).") gettext_noop("Unload the logger plugin: /plugin unload logger") gettext_noop("Untrusted command for function hook_process could lead to execution of commands, because of shell expansions (so the problem is only caused by some scripts, not by WeeChat itself).")
def name(self): return gettext_noop('Password')
def name(self): return gettext_noop('SAML 2.0')
from django.utils.translation import gettext_noop gettext_noop("AppName") from django.conf import settings settings.TEMPLATE_CONTEXT_PROCESSORS += ("catalogo.views.categorias_list",)
"django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages" , "mytools.context_processors.section", "mytools.context_processors.my_vars", 'django.core.context_processors.request', ) #https://github.com/django/django/blob/master/django/conf/global_settings.py LANGUAGES = ( ('ca', gettext_noop('Catalan')), ('de', gettext_noop('German')), ('en-gb', gettext_noop('British English')), ('es', gettext_noop('Spanish')), ('fr', gettext_noop('French')), ('it', gettext_noop('Italian')), ('nl', gettext_noop('Dutch')), ('ru', gettext_noop('Russian')), ) THUMBNAIL_ALIASES = { '': { 'collogo': {'size': (100, 100), 'crop': True}, 'premi': {'size': (200, 200), 'crop': True}, 'premithumb': {'size': (50, 50), 'crop': True}, },
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"}, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, ] AUTH_USER_MODEL = "auth.User" # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = "uk" LANGUAGES = [("uk", gettext_noop("Ukrainian"))] TIME_ZONE = "Europe/Kiev" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = "staticfiles" STATIC_URL = "/static/"
import json import django.conf.locale from django.conf import global_settings BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Add Tetun as a selectable language along with ID, EN and PT language codes EXTRA_LANG_INFO = { 'tet': { u'bidi': False, u'code': 'tet', u'name': 'Tetun', u'name_local': u'Tetun', }, } global_settings.LANGUAGES += ('tet', gettext_noop('Tetun')) # global_settings.LANGUAGES += ('ind', gettext_noop('Indonesian')), LANGUAGES = ( ('tet', gettext_noop('Tetun')), ('en', gettext_noop('English')), ('pt', gettext_noop('Portugese')), ('id', gettext_noop('Indonesian')), ) LANGUAGES_FIX_ID = ( ('tet', gettext_noop('Tetun')), ('en', gettext_noop('English')), ('pt', gettext_noop('Portugese')), ('ind', gettext_noop('Indonesian')), )
# coding: utf-8 from django.apps.config import AppConfig from django.utils.translation import gettext_noop __version__ = (1, 2016, 1) gettext_noop("Approval") class ApprovalConfig(AppConfig): """ Configuration de l'application Dating """ name = 'approval' label = 'approval' def ready(self): """ Le registre des applications est prêt """ from django.conf import settings if not getattr(settings, 'APPROVAL_DISABLE_SIGNALS', False): # If you absolutely need disabling signals for a while from approval import listeners # Charger la configuration ci-dessus par défaut default_app_config = 'approval.ApprovalConfig'
from urlparse import urlparse from django.contrib.auth.models import User, Group from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import gettext_noop LANGUAGES = ( ('en', gettext_noop('English')), ('es', gettext_noop('Spanish')), ('he', gettext_noop('Hebrew')), ) DEFAULT_GROUP_NAME = 'Users' def get_default_group(): return Group.objects.get(name=DEFAULT_GROUP_NAME) def get_default_proxy(): from proxy.models import ProxyServer return ProxyServer.objects.order_by('-priority')[0] class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) proxy_server = models.ForeignKey('proxy.ProxyServer', null=True, blank=True, default=get_default_proxy) session_duration = models.SmallIntegerField(null=True, blank=True) setup_shown = models.BooleanField(default=False) date_joined = models.DateTimeField(null=True, blank=True)
}, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ COUNTRY_CODE = 'TL' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en' LANGUAGES = ( ('tet', gettext_noop('Tetun')), ('en', gettext_noop('English')), ('pt', gettext_noop('Portugese')), ('id', gettext_noop('Indonesian')), ) DATE_FORMATS = ['%d/%m/%Y', '%d/%m/%y'] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
def name(self): return gettext_noop('One time password')
"""Translations for the apps that we use.""" from django.contrib.contenttypes import generic from django.utils.translation import gettext_noop from document_library.models import Attachment, DocumentCategory from multilingual_events.models import Event Event.add_to_class('attachments', generic.GenericRelation(Attachment)) DocumentCategory.add_to_class('generic_position', generic.GenericRelation( 'generic_positions.ObjectPosition')) gettext_noop('Auth') gettext_noop('auth') gettext_noop('Cms') gettext_noop('cms') gettext_noop('Cmsplugin_Filer_Image') gettext_noop('cmsplugin_filer_image') gettext_noop('Document_Library') gettext_noop('document_library') gettext_noop('Hero_Slider') gettext_noop('hero_slider') gettext_noop('Filer')