Ejemplo n.º 1
0
 def __unicode__(self):
     unr = UslugaNaRezerwacji.objects.filter(rezerwacja=self.rezerwacja)
     if unr:
         for i in range(0, len(unr)):
             if unr[i] == self:
                 return _u('Usluga %d') % (i+1,)
     return _u('Usluga na rezerwacji')
Ejemplo n.º 2
0
class Feedback(UUIDModel, TimeStampedModel):
    HAPPY = 1
    GOOD = 0
    SAD = -1

    SERVICE_CHOICES = ((HAPPY, _u("Happy")), (GOOD, _u("Good")), (SAD,
                                                                  _u("Sad")))

    user = models.ForeignKey(User,
                             related_name="user_feedbacks",
                             on_delete=models.CASCADE)
    realty = models.ForeignKey(Realty,
                               related_name="realty_feedbacks",
                               on_delete=models.CASCADE)
    service_rate = models.CharField(max_length=1,
                                    choices=SERVICE_CHOICES,
                                    default=GOOD)
    rating = models.IntegerField(validators=[
        MinValueValidator(1, message=_u("Minimun rate is 1")),
        MaxValueValidator(5, message=_u("Maximum rate is 5")),
    ])
    review = models.TextField(max_length=300)

    def __str__(self):
        return self.user.username + "-" + self.realty.name
Ejemplo n.º 3
0
    def __unicode__(self):
        pnr = PokojNaRezerwacji.objects.filter(rezerwacja=self.rezerwacja)

        # Na wszelki wypadek jesli z jakiegos powodu jest 0
        if pnr:
            for i in range(0, len(pnr)):
                if pnr[i] == self:
                    return _u('Pokoj %d') % (i+1,)
        return _u('Pokoj na rezerwacji')
Ejemplo n.º 4
0
    def update(self, request, *args, **kwargs):
        task = self.get_object()
        if task.state != Task.NEW:
            raise NotAcceptable(_u("You can't edit task."))

        if task.state == Task.DONE:
            raise PermissionDenied(_u("Task Done"))

        serializer = self.get_serializer(task, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(_u("Task updated successfully!"))
Ejemplo n.º 5
0
 def create_superuser(self, email, password, **extra_fields):
     """
     Create and save a SuperUser with the given email and password.
     """
     extra_fields.setdefault('is_staff', True)
     extra_fields.setdefault('is_superuser', True)
     extra_fields.setdefault('is_active', True)
     if extra_fields.get('is_staff') is not True:
         raise ValueError(_u('Superuser must have is_staff=True.'))
     if extra_fields.get('is_superuser') is not True:
         raise ValueError(_u('Superuser must have is_superuser=True.'))
     return self.create_user(email, password, **extra_fields)
Ejemplo n.º 6
0
    def load_or_create(cls, protein_name, user):
        # extract Uniprot accession data from the measurement name, if present
        accession_match = cls.accession_pattern.match(protein_name)
        proteins = cls.objects.none()
        if accession_match:
            short_name = accession_match.group(1)
            proteins = cls.objects.filter(short_name=short_name)
        else:
            proteins = cls.objects.filter(short_name=protein_name)

        # force query to LIMIT 2
        proteins = proteins[:2]

        if len(proteins) > 1:
            # fail if protein couldn't be uniquely matched
            raise ValidationError(
                _u('More than one match was found for protein name "%(type_name)s".'
                   ) % {
                       'type_name': protein_name,
                   })
        elif len(proteins) == 0:
            # try to create a new protein
            link = ProteinStrainLink()
            if accession_match:
                # if it looks like a UniProt ID, look up in UniProt
                short_name = accession_match.group(1)
                accession_id = protein_name
                return cls._load_uniprot(short_name, accession_id)
            elif link.check_ice(user.email, protein_name):
                # if it is found in ICE, create based on ICE info
                return cls._load_ice(link)
            elif getattr(settings, 'REQUIRE_UNIPROT_ACCESSION_IDS', True):
                raise ValidationError(
                    _u('Protein name "%(type_name)s" is not a valid UniProt accession id.'
                       ) % {
                           'type_name': protein_name,
                       })
            logger.info('Creating a new ProteinIdentifier for %(name)s' % {
                'name': protein_name,
            })
            # not requiring accession ID or ICE entry; just create protein with arbitrary name
            datasource = Datasource.objects.create(name=user.username,
                                                   url=user.email)
            return cls.objects.create(
                type_name=protein_name,
                short_name=protein_name,
                accession_id=protein_name,
                type_source=datasource,
            )
        return proteins[0]
Ejemplo n.º 7
0
 def load_or_create(cls, pubchem_cid):
     match = cls.pubchem_pattern.match(pubchem_cid)
     if match:
         cid = match.group(1)
         # try to find existing Metabolite record
         try:
             return cls.objects.get(pubchem_cid=cid)
         except cls.DoesNotExist:
             return cls._load_pubchem(cid)
         except Exception:
             logger.exception('Error loading Metabolite with cid %s', pubchem_cid)
             raise ValidationError(_u('There was a problem looking up %s') % pubchem_cid)
     raise ValidationError(
         _u('Metabolite lookup failed: %s must match pattern "cid:0000"') % pubchem_cid
     )
Ejemplo n.º 8
0
 def load_or_create(cls, pubchem_cid):
     match = cls.pubchem_pattern.match(pubchem_cid)
     if match:
         cid = match.group(1)
         label = match.group(2)
         # try to find existing Metabolite record
         metabolite, created = cls.objects.get_or_create(
             pubchem_cid=cid,
             defaults={
                 "carbon_count": 0,
                 "charge": 0,
                 "molar_mass": 1,
                 "molecular_formula": "",
                 "provisional": True,
                 "type_group": MeasurementType.Group.METABOLITE,
                 "type_name": label or "Unknown Metabolite",
             },
         )
         if created:
             transaction.on_commit(
                 lambda: metabolite_load_pubchem.delay(metabolite.pk))
         return metabolite
     raise ValidationError(
         _u('Metabolite lookup failed: {pubchem} must match pattern "cid:0000"'
            ).format(pubchem=pubchem_cid))
Ejemplo n.º 9
0
 def _load_ice(cls, identifier, user):
     try:
         return cls.objects.get(type_name=identifier,
                                strainlink__isnull=False)
     except cls.DoesNotExist:
         # actually check ICE
         link = GeneStrainLink()
         if link.check_ice(user.email, identifier):
             # save link if found in ICE
             datasource = Datasource.objects.create(
                 name="ICE Registry", url=link.strain.registry_url)
             gene = cls.objects.create(
                 type_name=identifier,
                 type_source=datasource,
                 gene_length=link.strain.part.bp_count,
             )
             link.gene = gene
             link.save()
             return gene
     except Exception:
         # fall through to raise ValidationError
         pass
     raise ValidationError(
         _u('Could not load gene "{identifier}"').format(
             identifier=identifier))
Ejemplo n.º 10
0
def _send_decision_email(instance):
    """ Send an email to requesting user with the decision made about their request. """
    context = {
        'name': instance.user.username,
        'api_management_url': urlunsplit(
            (
                'https' if settings.HTTPS == 'on' else 'http',
                instance.site.domain,
                reverse('api_admin:api-status'),
                '',
                '',
            )
        ),
        'authentication_docs_url': settings.AUTH_DOCUMENTATION_URL,
        'api_docs_url': settings.API_DOCUMENTATION_URL,
        'support_email_address': settings.API_ACCESS_FROM_EMAIL,
        'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)
    }

    message = render_to_string(
        'api_admin/api_access_request_email_{status}.txt'.format(status=instance.status),
        context
    )
    try:
        send_mail(
            _u('API access request'),
            message,
            settings.API_ACCESS_FROM_EMAIL,
            [instance.user.email],
            fail_silently=False
        )
        instance.contacted = True
    except SMTPException:
        log.exception(u'Error sending API user notification email for request [%s].', instance.id)
Ejemplo n.º 11
0
def _send_new_pending_email(instance):
    """ Send an email to settings.API_ACCESS_MANAGER_EMAIL with the contents of this API access request. """
    context = {
        'approval_url':
        urlunsplit((
            'https' if settings.HTTPS == 'on' else 'http',
            instance.site.domain,
            reverse('admin:api_admin_apiaccessrequest_change',
                    args=(instance.id, )),
            '',
            '',
        )),
        'api_request':
        instance
    }

    message = render_to_string(
        'api_admin/api_access_request_email_new_request.txt', context)
    try:
        send_mail(_u(u'API access request from {company}').format(
            company=instance.company_name),
                  message,
                  settings.API_ACCESS_FROM_EMAIL,
                  [settings.API_ACCESS_MANAGER_EMAIL],
                  fail_silently=False)
    except SMTPException:
        log.exception(
            u'Error sending API user notification email for request [%s].',
            instance.id)
Ejemplo n.º 12
0
def logout(request, next_page = None):
	if not request.user.is_anonymous:
		user_email = request.user.email
		user_id = request.user.id
	else:
		user_email = None
		user_id = 0

	logout_user(request)

	if not user_email is None:
		users = User.objects.all().exclude(email = user_email)
	else:
		users = User.objects.all()

	notification = {
		"type": "user_status",
		"user_id": str(user_id),
		"status": _u("Offline"),
		"status_class": "",
		"remove_class": "away"
	}

	notification = json.dumps(notification)

	for u in users:
		Group("user-%s" % u.id).send({'text': notification})

	if next_page:
		return redirect(next_page)

	return redirect(reverse('users:login'))
Ejemplo n.º 13
0
 def _load_pubchem(cls, pubchem_cid):
     try:
         base_url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug'
         url = '%s/compound/cid/%s/JSON' % (base_url, pubchem_cid)
         response = requests.post(url, data={'cid': pubchem_cid})
         record = response.json()['PC_Compounds'][0]
         properties = {
             item['urn']['label']: list(item['value'].values())[0]
             for item in record['props']
         }
         datasource = Datasource.objects.create(name='PubChem', url=url)
         return cls.objects.create(
             type_name=properties['IUPAC Name'],
             short_name=pubchem_cid,
             type_source=datasource,
             charge=record.get('charge', 0),
             carbon_count=len([a for a in record['atoms']['element'] if a == 6]),
             molar_mass=properties['Molecular Weight'],
             molecular_formula=properties['Molecular Formula'],
             smiles=properties['SMILES'],
             pubchem_cid=pubchem_cid,
         )
     except Exception:
         logger.exception('Failed loading PubChem %s', pubchem_cid)
         raise ValidationError(
             _u('Could not load information on %s from PubChem') % pubchem_cid
         )
Ejemplo n.º 14
0
class Transaction(UUIDModel, TimeStampedModel):
    PAY_CASH = "c"
    PAY_CREDIT = "r"

    PAYMENT_CHOICES = (
        (PAY_CASH, _u("Cash")),
        (PAY_CREDIT, _u("Credit Card")),
    )

    reservation = models.OneToOneField(
        Reservation, related_name="transaction", on_delete=models.CASCADE
    )
    payment_fees = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    paid = models.BooleanField(default=False)
    payment_method = models.CharField(
        max_length=1, choices=PAYMENT_CHOICES, default=PAY_CASH
    )
    total_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
Ejemplo n.º 15
0
 def _load_fallback(cls, identifier, user):
     try:
         return cls.objects.get(type_name=identifier, type_source__created__mod_by=user)
     except cls.DoesNotExist:
         datasource = Datasource.objects.create(name=user.username)
         return cls.objects.create(type_name=identifier, type_source=datasource)
     except Exception:
         logger.exception('Failed to load GeneIdentifier "%s"', identifier)
         raise ValidationError(_u('Could not load gene "%s"') % identifier)
Ejemplo n.º 16
0
 def _select(self, obj):
     from django.contrib.admin.views.main import IS_POPUP_VAR
     if IS_POPUP_VAR in self.request.GET and self.request.GET[IS_POPUP_VAR] == '3':
         return '<span class="fb_icon"> \
         <button class="button fb_selectlink" onclick="OpenFile(\'' \
             + escapejs(obj.url) + \
         '\');return false;">' + _u('Select') + '</button> \
         </span>'
     else:
         return '-'
Ejemplo n.º 17
0
 def _load_uniprot(cls, uniprot_id, accession_id):
     try:
         protein = cls._get_or_create_from_uniprot(uniprot_id, accession_id)
         lookup_protein_in_uniprot.delay(protein.id)
         return protein
     except Exception:
         logger.exception(f"Failed to create from UniProt {uniprot_id}")
         raise ValidationError(
             _u("Could not create Protein from {uniprot_id}").format(
                 uniprot_id=uniprot_id))
Ejemplo n.º 18
0
 def create_user(self, email, password, **extra_fields):
     """
     Create and save a User with the given email and password.
     """
     if not email:
         raise ValueError(_u('The Email must be set'))
     email = self.normalize_email(email)
     user = self.model(email=email, **extra_fields)
     user.set_password(password)
     user.save()
     return user
Ejemplo n.º 19
0
def check_arguments_for_rescoring(course_id, problem_url):
    """
    Do simple checks on the descriptor to confirm that it supports rescoring.

    Confirms first that the problem_url is defined (since that's currently typed
    in).  An ItemNotFoundException is raised if the corresponding module
    descriptor doesn't exist.  NotImplementedError is raised if the
    corresponding module doesn't support rescoring calls.
    """
    descriptor = modulestore().get_instance(course_id, problem_url)
    if not hasattr(descriptor, 'module_class') or not hasattr(descriptor.module_class, 'rescore_problem'):
        msg = _u("Specified module does not support rescoring.")
        raise NotImplementedError(msg)
Ejemplo n.º 20
0
class Task(TimeStampedModel, UUIDModel):
    NEW = "n"
    INPROGRESS = "p"
    DONE = "d"

    STATE_CHOICES = (
        (NEW, _u("New")),
        (INPROGRESS, _u("In Progress")),
        (DONE, _u("Done")),
    )

    title = models.CharField(max_length=250)
    description = models.TextField()
    state = models.CharField(max_length=1, choices=STATE_CHOICES, default=NEW)
    parent = models.ForeignKey("self",
                               related_name="linked",
                               on_delete=models.CASCADE,
                               blank=True,
                               null=True)

    def __str__(self):
        return self.title
Ejemplo n.º 21
0
    def approve(self, moderated_by=None, reason=None):
        crx = CrxFile(self.changed_object.crx)
        try:
            launch_url = crx.manifest["app"]["launch"]["web_url"]
        except KeyError:
            launch_url = None
        if is_redundant_item(self.changed_object.__class__, self.changed_object, appid=crx.get_appid()):
            return self.reject(reason=_u("Private key already exists."))
        if launch_url and is_redundant_item(self.changed_object.__class__, self.changed_object, launch_url=launch_url):
            return self.reject(reason=_u("Hosted application with the same URL already exists."))

        pre_moderation.send(sender=self.content_object.__class__,
                            instance=self.changed_object,
                            status=MODERATION_STATUS_APPROVED)

        self._moderate(MODERATION_STATUS_APPROVED, moderated_by, reason)

        post_moderation.send(sender=self.content_object.__class__,
                             instance=self.content_object,
                             status=MODERATION_STATUS_APPROVED)

        return _("Item approved: %s") % reason
Ejemplo n.º 22
0
    def pokoje_verbose(self):
        pv = ''
        i = 0
        for pnr in self.pokojnarezerwacji_set.all():
            if 0 < i < self.pokojnarezerwacji_set.count() - 1:
                pv += ', '
            elif i == self.pokojnarezerwacji_set.count() - 1 and not i == 0:
                pv += ' ' + _u('i') + ' '

            pv += '%d (' % (pnr.pokoj.numer,)
            pv += ungettext('%d osoba', '%d osoby', pnr.osob()) % (pnr.osob(),)
            pv += ')'
            i += 1

        return pv
Ejemplo n.º 23
0
 def _load_uniprot(cls, uniprot_id, accession_id):
     try:
         url = cls._uniprot_url(uniprot_id)
         values = cls._load_uniprot_values(uniprot_id)
         values.update(
             accession_id=accession_id,
             type_source=Datasource.objects.create(name="UniProt", url=url),
         )
         protein, created = cls.objects.update_or_create(
             accession_code=uniprot_id, defaults=values)
         return protein
     except Exception:
         logger.exception(f"Failed to create from UniProt {uniprot_id}")
         raise ValidationError(
             _u("Could not create Protein from {uniprot_id}").format(
                 uniprot_id=uniprot_id))
Ejemplo n.º 24
0
def login(request):
    context = {}
    context['title'] = _('Log In')
    security = Security.objects.get(id=1)

    context['deny_register'] = security.allow_register

    if request.POST:
        username = request.POST['email']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if not security.maintence or user.is_staff:
                login_user(request, user)

                users = User.objects.all().exclude(email=username)

                notification = {
                    "type": "user_status",
                    "user_id": str(user.id),
                    "status": _u("Online"),
                    "status_class": "active",
                    "remove_class": "away"
                }

                notification = json.dumps(notification)

                for u in users:
                    Group("user-%s" % u.id).send({'text': notification})

                next_url = request.GET.get('next', None)

                if next_url:
                    return redirect(next_url)

                return redirect(reverse("home"))
            else:
                messages.error(request,
                               _('System under maintenance. Try again later'))
        else:
            messages.error(request, _('E-mail or password are incorrect.'))
            context["username"] = username
    elif request.user.is_authenticated:
        return redirect(reverse('home'))

    return render(request, "users/login.html", context)
Ejemplo n.º 25
0
def login(request):
	context = {}
	context['title'] = _('Log In')
	security = Security.objects.get(id = 1)

	context['deny_register'] = security.allow_register

	if request.POST:
		username = request.POST['email']
		password = request.POST['password']
		user = authenticate(username=username, password=password)

		if user is not None:
			if not security.maintence or user.is_staff:
				login_user(request, user)

				users = User.objects.all().exclude(email = username)

				notification = {
					"type": "user_status",
					"user_id": str(user.id),
					"status": _u("Online"),
					"status_class": "active",
					"remove_class": "away"
				}

				notification = json.dumps(notification)

				for u in users:
					Group("user-%s" % u.id).send({'text': notification})

				next_url = request.GET.get('next', None)

				if next_url:
					return redirect(next_url)

				return redirect(reverse("home"))
			else:
				messages.error(request, _('System under maintenance. Try again later'))
		else:
			messages.error(request, _('E-mail or password are incorrect.'))
			context["username"] = username
	elif request.user.is_authenticated:
		return redirect(reverse('home'))

	return render(request, "users/login.html", context)
Ejemplo n.º 26
0
def auth_redirect(request):
    from ..middleware import JsonResponse
    if request.is_ajax():
        # Will use viewmodel framework to display client-side alert.
        return JsonResponse({
            'view': 'alert_error',
            'message': _u('Access to current url is denied')
        })
    # Borrowed from django.contrib.auth.decorators.user_passes_test()
    path = request.build_absolute_uri()
    resolved_login_url = resolve_url(settings.LOGIN_URL)
    # If the login url is the same scheme and net location then just
    # use the path as the "next" url.
    login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
    current_scheme, current_netloc = urlparse(path)[:2]
    if ((not login_scheme or login_scheme == current_scheme)
            and (not login_netloc or login_netloc == current_netloc)):
        path = request.get_full_path()
    from django.contrib.auth.views import redirect_to_login
    return redirect_to_login(path, resolved_login_url, REDIRECT_FIELD_NAME)
Ejemplo n.º 27
0
 def _load_uniprot(cls, uniprot_id, accession_id):
     url = 'http://www.uniprot.org/uniprot/%s.rdf' % uniprot_id
     # define some RDF predicate terms
     fullname_predicate = URIRef('http://purl.uniprot.org/core/fullName')
     mass_predicate = URIRef('http://purl.uniprot.org/core/mass')
     name_predicate = URIRef('http://purl.uniprot.org/core/recommendedName')
     sequence_predicate = URIRef('http://purl.uniprot.org/core/sequence')
     value_predicate = URIRef(
         'http://www.w3.org/1999/02/22-rdf-syntax-ns#value')
     # build the RDF graph
     try:
         graph = Graph()
         graph.parse(url)
         # find top-level references
         subject = URIRef('http://purl.uniprot.org/uniprot/%s' % uniprot_id)
         name_ref = graph.value(subject, name_predicate)
         isoform = graph.value(subject, sequence_predicate)
         # find values of interest
         values = {'accession_id': accession_id}
         name = graph.value(name_ref, fullname_predicate)
         if name:
             values.update(type_name=name.value)
         sequence = graph.value(isoform, value_predicate)
         if sequence:
             values.update(length=len(sequence.value))
         mass = graph.value(isoform, mass_predicate)
         if mass:
             values.update(mass=mass.value)
         # build the ProteinIdentifier
         datasource = Datasource.objects.create(name='UniProt', url=url)
         values.update(type_source=datasource)
         protein, created = cls.objects.update_or_create(
             short_name=uniprot_id,
             defaults=values,
         )
         return protein
     except Exception:
         logger.exception('Failed to read UniProt: %s', uniprot_id)
         raise ValidationError(
             _u('Could not load information on %s from UniProt') %
             uniprot_id)
Ejemplo n.º 28
0
	def process_request(self, request):
		if not request.user.is_authenticated():
			return

		now = datetime.now()

		if '_session_security' not in request.session:
			return
		
		delta = now - get_last_activity(request.session)
		expire_seconds = EXPIRE_AFTER

		if delta >= timedelta(seconds = expire_seconds):
			log = Log()
			log.user = str(request.user)
			log.user_id = request.user.id
			log.user_email = request.user.email
			log.context = {'condition': 'session_expire'}
			log.component = "user"
			log.action = "logout"
			log.resource = "system"

			log.save()

			users = User.objects.all().exclude(email = request.user.email)

			notification = {
				"type": "user_status",
				"user_id": str(request.user.id),
				"status": _u("Offline"),
				"status_class": "",
				"remove_class": "away"
			}

			notification = json.dumps(notification)

			for u in users:
				Group("user-%s" % u.id).send({'text': notification})
Ejemplo n.º 29
0
    def process_request(self, request):
        if not request.user.is_authenticated():
            return

        now = datetime.now()

        if '_session_security' not in request.session:
            return

        delta = now - get_last_activity(request.session)
        expire_seconds = EXPIRE_AFTER

        if delta >= timedelta(seconds=expire_seconds):
            log = Log()
            log.user = str(request.user)
            log.user_id = request.user.id
            log.user_email = request.user.email
            log.context = {'condition': 'session_expire'}
            log.component = "user"
            log.action = "logout"
            log.resource = "system"

            log.save()

            users = User.objects.all().exclude(email=request.user.email)

            notification = {
                "type": "user_status",
                "user_id": str(request.user.id),
                "status": _u("Offline"),
                "status_class": "",
                "remove_class": "away"
            }

            notification = json.dumps(notification)

            for u in users:
                Group("user-%s" % u.id).send({'text': notification})
Ejemplo n.º 30
0
 def _load_ice(cls, link):
     # strain found in ICE, but may not yet be linked to EDD protein
     existing = ProteinStrainLink.objects.filter(strain=link.strain)[:2]
     if len(existing) == 1:
         # existing link found, return the protein
         return existing[0].protein
     elif len(existing) == 0:
         # no existing link found, create the protein and link
         datasource = Datasource.objects.create(
             name="Part Registry", url=link.strain.registry_url
         )
         protein = cls.objects.create(
             type_name=link.strain.name,
             type_source=datasource,
             accession_id=link.strain.part.part_id,
         )
         link.protein = protein
         link.save()
         return protein
     raise ValidationError(
         _u("Multiple entries found for '{part_id}'.").format(
             part_id=link.strain.part.part_id
         )
     )
Ejemplo n.º 31
0
 def __str__(self):
     # In django 1.7 we can't use lazy
     return _u('Podcast Configuration')
Ejemplo n.º 32
0
def course_wiki_redirect(request, course_id):
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(course_id)
    course_slug = course_wiki_slug(course)
    valid_slug = True
    if not course_slug:
        log.exception("This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception("This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens.")
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")


    # The wiki needs a Site object created. We make sure it exists here
    try:
        site = Site.objects.get_current()
    except Site.DoesNotExist:
        new_site = Site()
        new_site.domain = settings.SITE_NAME
        new_site.name = "edX"
        new_site.save()
        if str(new_site.id) != str(settings.SITE_ID):
            raise ImproperlyConfigured("No site object was created and the SITE_ID doesn't match the newly created one. " + str(new_site.id) + "!=" + str(settings.SITE_ID))

    try:
        urlpath = URLPath.get_by_path(course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course_slug,
            content=cgi.escape(_u("This is the wiki for **{0}**'s _{1}_.").format(course.display_org_with_default, course.display_name_with_default)),
            user_message=_u("Course page automatically created."),
            user=None,
            ip_address=None,
            article_kwargs={'owner': None,
                            'group': None,
                            'group_read': True,
                            'group_write': True,
                            'other_read': True,
                            'other_write': True,
                            })

    return redirect("wiki:get", path=urlpath.path)
Ejemplo n.º 33
0
 def __str__(self):
     return _u('Global Configuration')
Ejemplo n.º 34
0
 def __str__(self):
     return _u('Radiocom Configuration')
Ejemplo n.º 35
0
 def __str__(self):
     return _u('Calendar Configuration')
Ejemplo n.º 36
0
 def __str__(self):
     # In django 1.7 we can't use lazy
     return _u('Podcast Configuration')
Ejemplo n.º 37
0
 def __unicode__(self):
     return _u('Calendar Configuration')
Ejemplo n.º 38
0
    def run_init(self):
        from lib6ko.run import Executer
        from lib6ko.protocol import ScriptError
        from lib6ko.transport import TransportException

        #Make params dict
        params = self.get_param_dict()

        # Use the supported protocols
        protocols = self.protocol_support.all()

        # If there are no defined protocols, create them
        if len(protocols) == 0:
            for protocol in Protocol.objects.filter(mode__isnull=False):
                ap_pro_sup = APProtocolSupport.objects.create(
                    ap = self,
                    protocol = protocol,
                )

            protocols = self.protocol_support.all()

        executer = Executer(
            protocol_classes=[ p.protocol for p in protocols if p.is_usable ],
            )

        # Go through all init sections
        # Run sections ordered by section name
        for init_section in self.architecture.initsection_set.order_by('section__name'):
            try:
                apinit = self.archinitresult_set.get(section=init_section)
                apinit.status = -1
                apinit.output = _u(u"Initialization has not finished")
                apinit.save()
            except ArchInitResult.DoesNotExist:
                apinit = self.archinitresult_set.create(
                    section=init_section,
                    status=-1,
                    output=_u(u"Initialization has not finished"),
                    )

            # Execute the section
            try:
                apinit.output = executer.execute_template(
                    init_section.compile_template(),
                    self,
                    params,
                    context_factory=Context,
                    )
                apinit.status = 0
            except TemplateSyntaxError as e:
                # TemplateSyntaxError wraps the inner exception as provided
                # in the __exit__ of contextlib, see
                #http://docs.python.org/reference/datamodel.html#object.__exit__
                exc_type, exc_value, trace_obj = e.exc_info
                if exc_type is ScriptError:
                    apinit.output = exc_value.traceback
                    apinit.status = -1
                else:
                    apinit.output = traceback.format_exc()
                    apinit.status = -1
            except ScriptError as e:
                apinit.output = "{0}\n{0.traceback}".format(e)
                apinit.status = -1
            except TransportException as e:
                apinit.output = str(e)
                apinit.status = -1
            except Exception as e:
                apinit.output = traceback.format_exc()
                apinit.status = -1

            apinit.save()
        return
Ejemplo n.º 39
0
 def table_view_header():
     return "".join(["<th>%s</th>" % i for i in (_u(u'Name') + "&nbsp;".join(['' for i in range(10)]), ) 
         ])
Ejemplo n.º 40
0
 def __unicode__(self):
     return _u('Global Configuration')
Ejemplo n.º 41
0
 def __unicode__(self):
     return _u('Radiocom Configuration')
Ejemplo n.º 42
0
 def __str__(self):
     return _u('Global Configuration')
Ejemplo n.º 43
0
 def __unicode__(self):
     return _u('Global Configuration')
Ejemplo n.º 44
0
 def __str__(self):
     return _u('Calendar Configuration')
Ejemplo n.º 45
0
 def __unicode__(self):
     ret = _('Numer: %(numer)d, rozmiar: %(rozmiar)d') % {'numer': self.numer, 'rozmiar': self.rozmiar, }
     if not self.dostepnosc:
         ret += ' (' + _u('Niedostepny!') + ')'
     return ret
Ejemplo n.º 46
0
 def __str__(self):
     return _u('Radiocom Configuration')
Ejemplo n.º 47
0
 def __unicode__(self):
     return _u(u"Group: %s") % (self.name)
Ejemplo n.º 48
0
 def __unicode__(self):
     return _u('Calendar Configuration')
Ejemplo n.º 49
0
translation_module_2.ugettext_lazy('tm2_utest_lazy')
translation_module_2.ugettext_noop('tm2_utest_noop')
translation_module_2.pgettext('context', 'tm2_ptest')
translation_module_2.pgettext_lazy('context', 'tm2_ptest_lazy')
translation_module_2.ngettext('tm2_ntest', 'tm2_ntests', 42)
translation_module_2.ngettext_lazy('tm2_ntest_lazy', 'tm2_ntests_lazy', 42)
translation_module_2.ungettext('tm2_untest', 'tm2_untests', 42)
translation_module_2.ungettext_lazy('tm2_untest_lazy', 'tm2_untests_lazy', 42)
translation_module_2.npgettext('context', 'tm2_nptest', 'tm2_nptests', 42)
translation_module_2.npgettext_lazy('context', 'tm2_nptest_lazy',
                                    'tm2_nptests_lazy', 42)

_('alias_test')
_l('alias_test_lazy')
_0x90('alias_test_noop')
_u('alias_utest')
_ul('alias_utest_lazy')
_u0x90('alias_utest_noop')
_p('context', 'alias_ptest')
_pl('context', 'alias_ptest_lazy')
_n('alias_ntest', 'alias_ntests', 42)
_nl('alias_ntest_lazy', 'alias_ntests_lazy', 42)
_un('alias_untest', 'alias_untests', 42)
_unl('alias_untest_lazy', 'alias_untests_lazy', 42)
_np('context', 'alias_nptest', 'alias_nptests', 42)
_npl('context', 'alias_nptest_lazy', 'alias_nptests_lazy', 42)


def gettext(message):
    pass