id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
141,848 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/setup.py
|
setup.BuildAgentsCommand
|
class BuildAgentsCommand(distutils.cmd.Command):
"""Instruction to compile Kappa agents"""
description = 'compile Kappa agents'
user_options = [
]
def initialize_options(self):
()
def finalize_options(self):
()
def run(self):
if should_build_agents():
try:
subprocess.check_call(["make","all","agents"])
except subprocess.CalledProcessError:
print("Failed to compile Kappa agents. Installing Python " \
"wrapper only.")
|
class BuildAgentsCommand(distutils.cmd.Command):
'''Instruction to compile Kappa agents'''
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
pass
| 4 | 1 | 4 | 0 | 4 | 0 | 2 | 0.07 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 33 | 20 | 4 | 15 | 6 | 11 | 1 | 13 | 6 | 9 | 3 | 1 | 2 | 5 |
141,849 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0011_auto_20200228_1605.py
|
karaage.plugins.kgapplications.migrations.0011_auto_20200228_1605.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0010_applicants"),
]
operations = [
migrations.RemoveField(
model_name="application",
name="content_type",
),
migrations.RemoveField(
model_name="application",
name="object_id",
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 1 | 14 | 3 | 13 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,850 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/migrations/0001_initial.py
|
karaage.plugins.kgsoftware.migrations.0001_initial.Migration
|
class Migration(migrations.Migration):
dependencies = [
("karaage", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Software",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("name", models.CharField(unique=True, max_length=200)),
("description", models.TextField(null=True, blank=True)),
("homepage", models.URLField(null=True, blank=True)),
("tutorial_url", models.URLField(null=True, blank=True)),
("academic_only", models.BooleanField(default=False)),
("restricted", models.BooleanField(default=False, help_text="Will require admin approval")),
],
options={
"ordering": ["name"],
"db_table": "software",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="SoftwareCategory",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("name", models.CharField(max_length=100)),
],
options={
"ordering": ["name"],
"db_table": "software_category",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="SoftwareLicense",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("version", models.CharField(max_length=100, null=True, blank=True)),
("date", models.DateField(null=True, blank=True)),
("text", models.TextField()),
("software", models.ForeignKey(to="kgsoftware.Software", on_delete=models.CASCADE)),
],
options={
"ordering": ["-version"],
"db_table": "software_license",
"get_latest_by": "date",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="SoftwareLicenseAgreement",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("date", models.DateField()),
("license", models.ForeignKey(to="kgsoftware.SoftwareLicense", on_delete=models.CASCADE)),
("person", models.ForeignKey(to="karaage.Person", on_delete=models.CASCADE)),
],
options={
"db_table": "software_license_agreement",
"get_latest_by": "date",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="SoftwareVersion",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("version", models.CharField(max_length=100)),
("module", models.CharField(max_length=100, null=True, blank=True)),
("last_used", models.DateField(null=True, blank=True)),
("machines", models.ManyToManyField(to="karaage.Machine")),
("software", models.ForeignKey(to="kgsoftware.Software", on_delete=models.CASCADE)),
],
options={
"ordering": ["-version"],
"db_table": "software_version",
},
bases=(models.Model,),
),
migrations.AddField(
model_name="software",
name="category",
field=models.ForeignKey(blank=True, to="kgsoftware.SoftwareCategory", null=True, on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name="software",
name="group",
field=models.ForeignKey(blank=True, to="karaage.Group", null=True, on_delete=models.CASCADE),
preserve_default=True,
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 94 | 1 | 93 | 3 | 92 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,851 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/migrations/0002_auto_20141216_1507.py
|
karaage.plugins.kgsoftware.migrations.0002_auto_20141216_1507.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgsoftware", "0001_initial"),
]
operations = [
migrations.RunPython(fix_applications),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 1 | 7 | 3 | 6 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,852 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0007_auto_20190315_1515.py
|
karaage.plugins.kgapplications.migrations.0007_auto_20190315_1515.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0006_auto_20190312_0805"),
]
operations = [
migrations.AlterField(
model_name="applicant",
name="full_name",
field=models.CharField(max_length=100),
),
migrations.AlterField(
model_name="applicant",
name="short_name",
field=models.CharField(max_length=100),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 17 | 1 | 16 | 3 | 15 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,853 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0012_projectapplication_rcao.py
|
karaage.plugins.kgapplications.migrations.0012_projectapplication_rcao.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0011_auto_20200228_1605"),
]
operations = [
migrations.AddField(
model_name="projectapplication",
name="rcao",
field=models.EmailField(blank=True, max_length=254, null=True, verbose_name="RCAO Email"),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 1 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,854 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/models.py
|
karaage.plugins.kgapplications.models.Applicant
|
class Applicant(models.Model):
"""A person who has completed an application however is not yet officially
registered on the system yet."""
email = models.EmailField(unique=False)
email_verified = models.BooleanField(editable=False, default=False)
username = models.CharField(max_length=255, unique=False, null=True, blank=True)
title = models.CharField(choices=TITLES, max_length=10, null=True, blank=True)
short_name = models.CharField(max_length=100)
full_name = models.CharField(max_length=100)
institute = models.ForeignKey(
Institute, limit_choices_to={"is_active": True}, null=True, blank=True, on_delete=models.CASCADE
)
department = models.CharField(max_length=200, null=True, blank=True)
position = models.CharField(max_length=200, null=True, blank=True)
telephone = models.CharField("Office Telephone", max_length=200, null=True, blank=True)
mobile = models.CharField(max_length=200, null=True, blank=True)
supervisor = models.CharField(max_length=100, null=True, blank=True)
address = models.CharField(max_length=200, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
postcode = models.CharField(max_length=8, null=True, blank=True)
country = models.CharField(max_length=2, choices=COUNTRIES, null=True, blank=True)
fax = models.CharField(max_length=50, null=True, blank=True)
saml_id = models.CharField(max_length=200, null=True, blank=True, editable=False, unique=False)
class Meta:
db_table = "applications_applicant"
def __str__(self):
full_name = self.get_full_name()
if full_name:
return full_name
return self.email
def has_account(self):
return False
def get_full_name(self):
"""Get the full name of the person."""
return self.full_name
def get_short_name(self):
"""Get the abbreviated name of the person."""
return self.short_name
def check_valid(self):
errors = []
if not self.username:
errors.append("Username not completed")
if not self.short_name:
errors.append("Short name not completed")
if not self.full_name:
errors.append("Full name not completed")
if not self.email:
errors.append("EMail not completed")
# check for username conflict
query = Person.objects.filter(username=self.username)
if self.username and query.count() > 0:
errors.append("Application username address conflicts with existing person.")
# check for saml_id conflict
query = Person.objects.filter(saml_id=self.saml_id)
if self.saml_id and query.count() > 0:
errors.append("Application saml_id address conflicts with existing person.")
# check for email conflict
query = Person.objects.filter(email=self.email)
if self.email and query.count() > 0:
errors.append("Application email address conflicts with existing person.")
return errors
def approve(self, approved_by):
"""Create a new user from an applicant."""
data = {
"email": self.email,
"username": self.username,
"title": self.title,
"short_name": self.short_name,
"full_name": self.full_name,
"institute": self.institute,
"department": self.department,
"position": self.position,
"telephone": self.telephone,
"mobile": self.mobile,
"supervisor": self.supervisor,
"address": self.address,
"city": self.city,
"postcode": self.postcode,
"country": self.country,
"fax": self.fax,
"saml_id": self.saml_id,
"is_active": False,
}
person = Person.objects.create_user(**data)
person.activate(approved_by)
return person
approve.alters_data = True
def similar_people(self):
term = False
query = Q()
if self.username:
query = query | Q(username__iexact=self.username)
term = True
if self.saml_id:
query = query | Q(saml_id=self.saml_id)
term = True
if self.email:
query = query | Q(email__iexact=self.email)
term = True
if self.short_name:
query = query | Q(full_name__iexact=self.short_name)
term = True
if self.full_name:
query = query | Q(full_name__iexact=self.full_name)
term = True
if not term:
return Person.objects.none()
return Person.objects.filter(query)
|
class Applicant(models.Model):
'''A person who has completed an application however is not yet officially
registered on the system yet.'''
class Meta:
def __str__(self):
pass
def has_account(self):
pass
def get_full_name(self):
'''Get the full name of the person.'''
pass
def get_short_name(self):
'''Get the abbreviated name of the person.'''
pass
def check_valid(self):
pass
def approve(self, approved_by):
'''Create a new user from an applicant.'''
pass
def similar_people(self):
pass
| 9 | 4 | 12 | 1 | 11 | 1 | 3 | 0.08 | 1 | 1 | 1 | 0 | 7 | 0 | 7 | 7 | 123 | 15 | 100 | 35 | 91 | 8 | 79 | 35 | 70 | 8 | 1 | 1 | 21 |
141,855 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/models.py
|
karaage.plugins.kgapplications.models.Application
|
class Application(TrackingModelMixin, models.Model):
"""Generic application for anything."""
WAITING_FOR_ADMIN = "K"
COMPLETED = "C"
ARCHIVED = "A"
DECLINED = "R"
secret_token = models.CharField(max_length=64, default=new_random_token, editable=False, unique=True)
expires = models.DateTimeField(editable=False)
created_by = models.ForeignKey(
Person, editable=False, null=True, blank=True, on_delete=models.SET_NULL, related_name="created_applications"
)
created_date = models.DateTimeField(auto_now_add=True, editable=False)
submitted_date = models.DateTimeField(null=True, blank=True)
state = models.CharField(max_length=5)
complete_date = models.DateTimeField(null=True, blank=True, editable=False)
new_applicant = models.OneToOneField("Applicant", null=True, blank=True, on_delete=models.SET_NULL)
existing_person = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
header_message = models.TextField(
"Message",
null=True,
blank=True,
help_text=six.u("Message displayed at top of application form for the invitee and also in invitation email"),
)
_class = models.CharField(max_length=100, editable=False)
objects = ApplicationManager()
class Meta:
db_table = "applications_application"
def __str__(self):
return "Application #%s" % self.id
def info(self):
return six.text_type(self)
def get_type(self):
return self._class
def get_absolute_url(self):
return reverse("kg_application_detail", args=[self.id])
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
if not self.expires:
self.expires = timezone.now() + datetime.timedelta(days=7)
if not self.pk:
self.created_by = get_current_person()
fields = [
f
for f in Application._meta.get_fields()
if isinstance(f, OneToOneRel) and f.field.primary_key and f.auto_created
]
for rel in fields:
related_model = getattr(rel, "related_model", rel.model)
# if we find it, save the name
if related_model == type(self):
self._class = rel.get_accessor_name()
break
super(Application, self).save(*args, **kwargs)
if created:
log.add(self.application_ptr, "Created")
for field in changed.keys():
log.change(self.application_ptr, "Changed %s to %s" % (field, getattr(self, field)))
save.alters_data = True
def delete(self, *args, **kwargs):
log.delete(self, "Deleted")
super(Application, self).delete(*args, **kwargs)
def get_object(self):
if self._class:
return getattr(self, self._class)
return self
def reopen(self):
self.submitted_date = None
self.complete_date = None
self.expires = timezone.now() + datetime.timedelta(days=7)
self.save()
def extend(self):
self.expires = timezone.now() + datetime.timedelta(days=7)
self.save()
def submit(self):
self.submitted_date = timezone.now()
self.save()
def approve(self, approved_by):
if self.existing_person:
person = self.existing_person
created_person = False
elif self.new_applicant:
person = self.new_applicant.approve(approved_by)
self.existing_person = person
created_person = True
else:
assert False
self.complete_date = timezone.now()
self.save()
return created_person, False
approve.alters_data = True
def decline(self):
self.complete_date = timezone.now()
self.save()
decline.alters_data = True
def check_valid(self):
errors = []
if self.existing_person is None:
if self.new_applicant is None:
errors.append("Applicant not set.")
else:
errors.extend(self.new_applicant.check_valid())
return errors
def get_roles_for_person(self, person):
roles = set()
if person == self.existing_person:
roles.add("is_applicant")
roles.add("is_authorised")
return roles
@property
def applicant(application):
applicant = application.existing_person
if applicant is None:
applicant = application.new_applicant
assert applicant is not None
return applicant
|
class Application(TrackingModelMixin, models.Model):
'''Generic application for anything.'''
class Meta:
def __str__(self):
pass
def info(self):
pass
def get_type(self):
pass
def get_absolute_url(self):
pass
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
def get_object(self):
pass
def reopen(self):
pass
def extend(self):
pass
def submit(self):
pass
def approve(self, approved_by):
pass
def decline(self):
pass
def check_valid(self):
pass
def get_roles_for_person(self, person):
pass
@property
def applicant(application):
pass
| 18 | 1 | 7 | 1 | 6 | 0 | 2 | 0.03 | 2 | 5 | 1 | 2 | 15 | 0 | 15 | 15 | 151 | 32 | 117 | 45 | 99 | 3 | 101 | 44 | 84 | 8 | 1 | 3 | 29 |
141,856 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/models.py
|
karaage.plugins.kgapplications.models.ApplicationManager
|
class ApplicationManager(models.Manager):
def get_for_applicant(self, person):
query = self.get_queryset()
query = query.filter(existing_person_id=person.pk)
query = query.exclude(state__in=[Application.COMPLETED, Application.ARCHIVED, Application.DECLINED])
return query
def requires_attention(self, request):
person = request.user
query = Q(projectapplication__project__in=person.leads.all(), state=ProjectApplication.WAITING_FOR_LEADER)
query = query | Q(
projectapplication__institute__in=person.delegate_for.all(), state=ProjectApplication.WAITING_FOR_DELEGATE
)
if is_admin(request):
query = query | Q(state=Application.WAITING_FOR_ADMIN)
query = query | Q(state=ProjectApplication.DUPLICATE, projectapplication__isnull=False)
return self.get_queryset().filter(query)
|
class ApplicationManager(models.Manager):
def get_for_applicant(self, person):
pass
def requires_attention(self, request):
pass
| 3 | 0 | 8 | 0 | 8 | 0 | 2 | 0 | 1 | 2 | 2 | 0 | 2 | 0 | 2 | 2 | 17 | 1 | 16 | 6 | 13 | 0 | 14 | 6 | 11 | 2 | 1 | 1 | 3 |
141,857 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/models.py
|
karaage.plugins.kgapplications.models.ProjectApplication
|
class ProjectApplication(Application):
type = "project"
OPEN = "O"
WAITING_FOR_LEADER = "L"
WAITING_FOR_DELEGATE = "D"
PASSWORD = "P"
DUPLICATE = "DUP"
""" Application for an Applicant or a Person to create a new project or
join an existing project. """
# common properties
needs_account = models.BooleanField(
six.u("Do you need a personal cluster account?"),
help_text=six.u("Required if you will be working on the project yourself."),
default=True,
)
make_leader = models.BooleanField(help_text="Make this person a project leader", default=False)
# new project request
name = models.CharField("Title", max_length=200)
institute = models.ForeignKey(
Institute, limit_choices_to={"is_active": True}, null=True, blank=True, on_delete=models.CASCADE
)
description = models.TextField(null=True, blank=True)
additional_req = models.TextField(null=True, blank=True)
pid = models.CharField(max_length=50, null=True, blank=True)
rcao = models.EmailField(null=True, blank=True, verbose_name="RCAO Email")
# existing project request
project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE)
objects = ApplicationManager()
class Meta:
db_table = "applications_projectapplication"
def info(self):
if self.project is not None:
return six.u("join project '%s'") % self.project.pid
elif self.name:
return six.u("create project '%s'") % self.name
else:
return six.u("create/join a project")
def approve(self, approved_by):
created_person, created_account = super(ProjectApplication, self).approve(approved_by)
assert self.existing_person is not None
person = self.existing_person
if self.project is None:
assert self.institute is not None
from karaage.projects.utils import get_new_pid
project = Project(
pid=self.pid or get_new_pid(self.institute),
name=self.name,
description=self.description,
institute=self.institute,
additional_req=self.additional_req,
start_date=datetime.datetime.today(),
end_date=datetime.date.today() + datetime.timedelta(days=365),
rcao=self.rcao,
)
project.activate(approved_by) # Activate has implied call to save().
self.project = project
self.save()
if self.make_leader:
self.project.leaders.add(person)
if self.needs_account:
if not person.has_account():
log.add(self.application_ptr, "Created account.")
Account.create(person, self.project)
created_account = True
else:
log.change(self.application_ptr, "Account already exists")
self.project.group.members.add(person)
return created_person, created_account
approve.alters_data = True
def get_roles_for_person(self, person):
roles = super(ProjectApplication, self).get_roles_for_person(person)
if self.project is not None:
if person in self.project.leaders.all():
roles.add("is_leader")
roles.add("is_authorised")
if self.institute is not None:
if person in self.institute.delegates.all():
roles.add("is_delegate")
roles.add("is_authorised")
return roles
def check_valid(self):
errors = super(ProjectApplication, self).check_valid()
if self.project is None:
if not self.name:
errors.append("New project application with no name")
if self.institute is None:
errors.append("New project application with no institute")
return errors
|
class ProjectApplication(Application):
class Meta:
def info(self):
pass
def approve(self, approved_by):
pass
def get_roles_for_person(self, person):
pass
def check_valid(self):
pass
| 6 | 0 | 16 | 2 | 14 | 0 | 4 | 0.07 | 1 | 7 | 3 | 0 | 4 | 0 | 4 | 19 | 105 | 17 | 83 | 29 | 76 | 6 | 65 | 29 | 58 | 5 | 2 | 2 | 17 |
141,858 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/migrations/0003_auto_20150205_1544.py
|
karaage.plugins.kgsoftware.migrations.0003_auto_20150205_1544.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgsoftware", "0002_auto_20141216_1507"),
]
operations = [
migrations.AlterField(
model_name="software",
name="group",
field=models.ForeignKey(
on_delete=django.db.models.deletion.SET_NULL, blank=True, to="karaage.Group", null=True
),
preserve_default=True,
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 1 | 14 | 3 | 13 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,859 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0009_auto_20200227_1655.py
|
karaage.plugins.kgapplications.migrations.0009_auto_20200227_1655.Migration
|
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("kgapplications", "0008_auto_20190605_0827"),
]
operations = [
migrations.AddField(
model_name="application",
name="existing_person",
field=models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL
),
),
migrations.AddField(
model_name="application",
name="new_applicant",
field=models.OneToOneField(
blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to="kgapplications.Applicant"
),
),
migrations.AlterField(
model_name="application",
name="created_by",
field=models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="created_applications",
to=settings.AUTH_USER_MODEL,
),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 34 | 1 | 33 | 3 | 32 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,860 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/models.py
|
karaage.plugins.kgsoftware.models.SoftwareVersion
|
class SoftwareVersion(models.Model):
software = models.ForeignKey(Software, on_delete=models.CASCADE)
version = models.CharField(max_length=100)
machines = models.ManyToManyField(Machine)
module = models.CharField(max_length=100, blank=True, null=True)
last_used = models.DateField(blank=True, null=True)
class Meta:
db_table = "software_version"
ordering = ["-version"]
def __str__(self):
return "%s - %s" % (self.software.name, self.version)
def get_absolute_url(self):
return self.software.get_absolute_url()
def machine_list(self):
machines = ""
if self.machines.all():
for m in self.machines.all():
machines += "%s, " % m.name
return machines
|
class SoftwareVersion(models.Model):
class Meta:
def __str__(self):
pass
def get_absolute_url(self):
pass
def machine_list(self):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 23 | 4 | 19 | 14 | 14 | 0 | 19 | 14 | 14 | 3 | 1 | 2 | 5 |
141,861 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/models.py
|
karaage.plugins.kgsoftware.models.Software
|
class Software(TrackingModelMixin, models.Model):
category = models.ForeignKey(SoftwareCategory, blank=True, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, unique=True)
description = models.TextField(blank=True, null=True)
group = models.ForeignKey(Group, blank=True, null=True, on_delete=models.SET_NULL)
homepage = models.URLField(blank=True, null=True)
tutorial_url = models.URLField(blank=True, null=True)
academic_only = models.BooleanField(default=False)
restricted = models.BooleanField(help_text="Will require admin approval", default=False)
class Meta:
ordering = ["name"]
db_table = "software"
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
# save the object
super(Software, self).save(*args, **kwargs)
if created:
log.add(self, "Created")
for field in changed.keys():
log.change(self, "Changed %s to %s" % (field, getattr(self, field)))
save.alters_data = True
def delete(self, *args, **kwargs):
# delete the object
log.delete(self, "Deleted")
super(Software, self).delete(*args, **kwargs)
delete.alters_data = True
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("kg_software_detail", args=[self.id])
def get_current_license(self):
try:
return self.softwarelicense_set.latest()
except SoftwareLicense.DoesNotExist:
return None
def group_name(self):
return self.group.name
def get_group_members(self):
if self.group is None:
return Group.objects.none()
else:
return self.group.members.all()
|
class Software(TrackingModelMixin, models.Model):
class Meta:
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
def __str__(self):
pass
def get_absolute_url(self):
pass
def get_current_license(self):
pass
def group_name(self):
pass
def get_group_members(self):
pass
| 9 | 0 | 5 | 0 | 4 | 0 | 2 | 0.05 | 2 | 4 | 3 | 0 | 7 | 0 | 7 | 7 | 58 | 12 | 44 | 21 | 35 | 2 | 42 | 21 | 33 | 4 | 1 | 1 | 12 |
141,862 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/templatetags/karaage_tags.py
|
karaage.templatetags.karaage_tags.UrlWithParamNode
|
class UrlWithParamNode(template.Node):
def __init__(self, copy, nopage, changes):
self.copy = copy
self.nopage = nopage
self.changes = []
for key, newvalue in changes:
newvalue = template.Variable(newvalue)
self.changes.append(
(
key,
newvalue,
)
)
def render(self, context):
if "request" not in context:
return ""
request = context["request"]
result = {}
if self.copy:
result = request.GET.copy()
else:
result = QueryDict("", mutable=True)
if self.nopage:
result.pop("page", None)
for key, newvalue in self.changes:
newvalue = newvalue.resolve(context)
result[key] = newvalue
return "?" + result.urlencode()
|
class UrlWithParamNode(template.Node):
def __init__(self, copy, nopage, changes):
pass
def render(self, context):
pass
| 3 | 0 | 17 | 3 | 14 | 0 | 4 | 0 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 2 | 35 | 7 | 28 | 10 | 25 | 0 | 22 | 10 | 19 | 5 | 1 | 1 | 7 |
141,863 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/templatetags/karaage_tags.py
|
karaage.templatetags.karaage_tags.SearchFormNode
|
class SearchFormNode(template.Node):
def __init__(self, post_url):
self.post_url = post_url
def render(self, context):
template_obj = template.loader.get_template("karaage/common/search_form.html")
context.push()
context["post_url"] = self.post_url
output = template_obj.render(context)
context.pop()
return output
|
class SearchFormNode(template.Node):
def __init__(self, post_url):
pass
def render(self, context):
pass
| 3 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 11 | 1 | 10 | 6 | 7 | 0 | 10 | 6 | 7 | 1 | 1 | 0 | 2 |
141,864 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/templatetags/karaage_tags.py
|
karaage.templatetags.karaage_tags.ForEachAppIncludeNode
|
class ForEachAppIncludeNode(template.Node):
def __init__(self, template_name):
self.template_name = template.Variable(template_name)
def render(self, context):
template_name = self.template_name.resolve(context)
result = []
for label in get_app_labels():
template_path = os.path.join(label, template_name)
try:
template_obj = template.loader.get_template(template_path)
except template.TemplateDoesNotExist:
pass
else:
context.push()
output = template_obj.render(context.flatten())
result.append(output)
context.pop()
return "".join(result)
|
class ForEachAppIncludeNode(template.Node):
def __init__(self, template_name):
pass
def render(self, context):
pass
| 3 | 0 | 10 | 1 | 9 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 21 | 3 | 18 | 10 | 15 | 0 | 18 | 10 | 15 | 3 | 1 | 2 | 4 |
141,865 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/templatetags/forms.py
|
karaage.templatetags.forms.FormFieldNode
|
class FormFieldNode(template.Node):
def __init__(self, field):
self.field = template.Variable(field)
def get_template(self, class_name):
try:
template_name = "formfield/%s.html" % class_name
return template.loader.get_template(template_name)
except template.TemplateDoesNotExist:
return template.loader.get_template("formfield/default.html")
def render(self, context):
try:
field = self.field.resolve(context)
except template.VariableDoesNotExist:
return ""
label_class_names = []
if field.field.required:
label_class_names.append("required")
widget_class_name = field.field.widget.__class__.__name__.lower()
if widget_class_name == "checkboxinput":
label_class_names.append("vCheckboxLabel")
class_str = label_class_names and six.u(" ").join(label_class_names) or six.u("")
context.push()
context.push()
context["class"] = class_str
context["formfield"] = field
output = self.get_template(field.field.widget.__class__.__name__.lower()).render(context.flatten())
context.pop()
context.pop()
return output
|
class FormFieldNode(template.Node):
def __init__(self, field):
pass
def get_template(self, class_name):
pass
def render(self, context):
pass
| 4 | 0 | 11 | 1 | 9 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 35 | 6 | 29 | 11 | 25 | 0 | 29 | 11 | 25 | 4 | 1 | 1 | 7 |
141,866 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/tables.py
|
karaage.projects.tables.ProjectColumn
|
class ProjectColumn(tables.Column):
def __init__(self, *args, **kwargs):
super(ProjectColumn, self).__init__(*args, empty_values=(), **kwargs)
def render_link(self, uri, value, attrs=None):
attrs = AttributeDict(attrs if attrs is not None else self.attrs.get("a", {}))
attrs["href"] = uri
return format_html(
"<a {attrs}>{text}</a>",
attrs=attrs.as_html(),
text=value,
)
def render(self, value):
if value is not None:
url = reverse("kg_project_detail", args=[value.id])
link = self.render_link(url, value=six.text_type(value.pid))
return link
else:
return "—"
|
class ProjectColumn(tables.Column):
def __init__(self, *args, **kwargs):
pass
def render_link(self, uri, value, attrs=None):
pass
def render_link(self, uri, value, attrs=None):
pass
| 4 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 3 | 21 | 3 | 18 | 6 | 14 | 0 | 13 | 6 | 9 | 2 | 1 | 1 | 5 |
141,867 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/tables.py
|
karaage.projects.tables.ActiveFilter
|
class ActiveFilter(django_filters.ChoiceFilter):
def __init__(self, *args, **kwargs):
choices = [
("", "Unknown"),
("deleted", "Deleted"),
("yes", "Yes"),
]
super(ActiveFilter, self).__init__(*args, choices=choices, **kwargs)
def filter(self, qs, value):
if value == "deleted":
qs = qs.filter(is_active=False)
elif value == "yes":
qs = qs.filter(is_active=True)
return qs
|
class ActiveFilter(django_filters.ChoiceFilter):
def __init__(self, *args, **kwargs):
pass
def filter(self, qs, value):
pass
| 3 | 0 | 8 | 1 | 7 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 17 | 3 | 14 | 4 | 11 | 0 | 9 | 4 | 6 | 3 | 1 | 1 | 4 |
141,868 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/models.py
|
karaage.projects.models.Project
|
class Project(TrackingModelMixin, models.Model):
pid = models.CharField(max_length=255, unique=True)
name = models.CharField(max_length=200)
group = models.ForeignKey(Group, on_delete=models.PROTECT)
institute = models.ForeignKey(Institute, on_delete=models.CASCADE)
leaders = models.ManyToManyField(Person, related_name="leads")
description = models.TextField(null=True, blank=True)
is_approved = models.BooleanField(default=False)
start_date = models.DateField(default=datetime.datetime.today)
end_date = models.DateField(null=True, blank=True)
additional_req = models.TextField(null=True, blank=True)
is_active = models.BooleanField(default=False)
approved_by = models.ForeignKey(
Person, related_name="project_approver", null=True, blank=True, editable=False, on_delete=models.SET_NULL
)
date_approved = models.DateField(null=True, blank=True, editable=False)
deleted_by = models.ForeignKey(
Person, related_name="project_deletor", null=True, blank=True, editable=False, on_delete=models.SET_NULL
)
date_deleted = models.DateField(null=True, blank=True, editable=False)
last_usage = models.DateField(null=True, blank=True, editable=False)
has_notified_pending_expiration = models.BooleanField(default=False)
rcao = models.EmailField(null=True, blank=True, verbose_name="RCAO Email")
objects = models.Manager()
active = ActiveProjectManager()
deleted = DeletedProjectManager()
class Meta:
ordering = ["pid"]
db_table = "project"
app_label = "karaage"
def __str__(self):
return "%s - %s" % (self.pid, self.name)
def get_absolute_url(self):
return reverse("kg_project_detail", args=[self.id])
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
# set group if not already set
if self.group_id is None:
name = self.pid
self.group, _ = Group.objects.get_or_create(name=name)
# save the object
super(Project, self).save(*args, **kwargs)
if created:
log.add(self, "Created")
for field in changed.keys():
log.change(self, "Changed %s to %s" % (field, getattr(self, field)))
# has pid changed?
if "pid" in changed:
old_pid = changed["pid"]
if old_pid is not None:
from karaage.datastores import set_project_pid
set_project_pid(self, old_pid, self.pid)
log.change(self, "Renamed %s to %s" % (old_pid, self.pid))
# update the datastore
from karaage.datastores import save_project
save_project(self)
# has group changed?
if "group_id" in changed:
old_group_pk = changed.get("group_id")
new_group = self.group
if old_group_pk is not None:
old_group = Group.objects.get(pk=old_group_pk)
from karaage.datastores import remove_accounts_from_project
query = Account.objects.filter(person__groups=old_group)
remove_accounts_from_project(query, self)
if new_group is not None:
from karaage.datastores import add_accounts_to_project
query = Account.objects.filter(person__groups=new_group)
add_accounts_to_project(query, self)
save.alters_data = True
def delete(self, *args, **kwargs):
# ensure nothing connects to this project
query = Account.objects.filter(default_project=self)
query.update(default_project=None)
# Get list of accounts.
# We do this here to ensure nothing gets deleted when
# we call the super method.
old_group_pk = self.tracker.changed.get("group_id", self.group_id)
if old_group_pk is not None:
old_group = Group.objects.get(pk=old_group_pk)
query = Account.objects.filter(person__groups=old_group)
query = query.filter(date_deleted__isnull=True)
accounts = list(query)
else:
accounts = []
# delete the object
log.delete(self, "Deleted")
super(Project, self).delete(*args, **kwargs)
# update datastore associations
for account in accounts:
from karaage.datastores import remove_account_from_project
remove_account_from_project(account, self)
# update the datastore
from karaage.datastores import delete_project
delete_project(self)
delete.alters_data = True
# Can user view this self record?
def can_view(self, request):
person = request.user
if not person.is_authenticated:
return False
if is_admin(request):
return True
if not self.is_active:
return False
if not person.is_active:
return False
if person.is_locked():
return False
# Institute delegate==person can view any member of institute
if self.institute.is_active:
if person in self.institute.delegates.all():
return True
# Leader==person can view projects they lead
tmp = self.leaders.filter(pk=person.pk)
if tmp.count() > 0:
return True
# person can view own projects
tmp = self.group.members.filter(pk=person.pk)
if tmp.count() > 0:
return True
return False
# Can user view this self record?
def can_edit(self, request):
# The same as can_view, except normal project members cannot edit
person = request.user
if not person.is_authenticated:
return False
if is_admin(request):
return True
if not self.is_active:
return False
if not person.is_active:
return False
if person.is_locked():
return False
# Institute delegate==person can edit any member of institute
if self.institute.is_active:
if person in self.institute.delegates.all():
return True
# Leader==person can edit projects they lead
tmp = self.leaders.filter(pk=person.pk)
if tmp.count() > 0:
return True
return False
def activate(self, approved_by):
if self.is_active is True:
# Call to save() required to keep API consistent.
self.save()
return
self.is_active = True
self.is_approved = True
self.date_approved = datetime.datetime.today()
self.approved_by = approved_by
self.has_notified_pending_expiration = False
# if activating project that has already expired, make sure we
# don't automatically expire it immediately.
if self.end_date is not None and self.end_date <= datetime.date.today():
self.end_date = None
self.save()
log.change(self, "Activated by %s" % approved_by)
activate.alters_data = True
def deactivate(self, deleted_by):
self.is_active = False
self.deleted_by = deleted_by
self.date_deleted = datetime.datetime.today()
self.group.members.clear()
self.has_notified_pending_expiration = False
self.save()
log.change(self, "Deactivated by %s" % deleted_by)
deactivate.alters_data = True
def days_until_expiration(self):
if self.end_date is None:
return None
return (self.end_date - datetime.date.today()).days
|
class Project(TrackingModelMixin, models.Model):
class Meta:
def __str__(self):
pass
def get_absolute_url(self):
pass
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
def can_view(self, request):
pass
def can_edit(self, request):
pass
def activate(self, approved_by):
pass
def deactivate(self, deleted_by):
pass
def days_until_expiration(self):
pass
| 11 | 0 | 20 | 4 | 14 | 2 | 4 | 0.15 | 2 | 7 | 3 | 0 | 9 | 0 | 9 | 9 | 226 | 47 | 156 | 59 | 139 | 23 | 150 | 59 | 133 | 10 | 1 | 2 | 40 |
141,869 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/managers.py
|
karaage.projects.managers.DeletedProjectManager
|
class DeletedProjectManager(models.Manager):
def get_queryset(self):
query = super(DeletedProjectManager, self).get_queryset()
return query.filter(is_active=False)
|
class DeletedProjectManager(models.Manager):
def get_queryset(self):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
141,870 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/managers.py
|
karaage.projects.managers.ActiveProjectManager
|
class ActiveProjectManager(models.Manager):
def get_queryset(self):
query = super(ActiveProjectManager, self).get_queryset()
return query.filter(is_active=True)
|
class ActiveProjectManager(models.Manager):
def get_queryset(self):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
141,871 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/lookups.py
|
karaage.projects.lookups.ProjectLookup
|
class ProjectLookup(LookupChannel):
model = Project
def get_query(self, q, request):
"""return a query set searching for the query string q
either implement this method yourself or set the search_field
in the LookupChannel class definition
"""
return Project.objects.filter(Q(pid__icontains=q) | Q(name__icontains=q))
def get_result(self, obj):
"""
result is the simple text that is the completion of what the person
typed
"""
return obj.pid
def format_match(self, obj):
"""
(HTML) formatted item for display in the dropdown
"""
return escape(six.u("%s") % obj)
def format_item_display(self, obj):
"""
(HTML) formatted item for displaying item in the selected deck area
"""
return escape(six.u("%s") % obj)
|
class ProjectLookup(LookupChannel):
def get_query(self, q, request):
'''return a query set searching for the query string q
either implement this method yourself or set the search_field
in the LookupChannel class definition
'''
pass
def get_result(self, obj):
'''
result is the simple text that is the completion of what the person
typed
'''
pass
def format_match(self, obj):
'''
(HTML) formatted item for display in the dropdown
'''
pass
def format_item_display(self, obj):
'''
(HTML) formatted item for displaying item in the selected deck area
'''
pass
| 5 | 4 | 6 | 0 | 2 | 4 | 1 | 1.4 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 5 | 28 | 4 | 10 | 6 | 5 | 14 | 10 | 6 | 5 | 1 | 2 | 0 | 4 |
141,872 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/lookups.py
|
karaage.projects.lookups.LookupChannel
|
class LookupChannel(ajax_select.LookupChannel):
"""Base clase for lookups."""
def check_auth(self, request):
"""
to ensure that nobody can get your data via json simply by knowing the
URL. public facing forms should write a custom LookupChannel to
implement as you wish. also you could choose to return
HttpResponseForbidden("who are you?") instead of raising
PermissionDenied (401 response)
"""
if not request.user.is_authenticated:
raise PermissionDenied
if not is_admin(request):
raise PermissionDenied
|
class LookupChannel(ajax_select.LookupChannel):
'''Base clase for lookups.'''
def check_auth(self, request):
'''
to ensure that nobody can get your data via json simply by knowing the
URL. public facing forms should write a custom LookupChannel to
implement as you wish. also you could choose to return
HttpResponseForbidden("who are you?") instead of raising
PermissionDenied (401 response)
'''
pass
| 2 | 2 | 12 | 0 | 5 | 7 | 3 | 1.33 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 15 | 1 | 6 | 2 | 4 | 8 | 6 | 2 | 4 | 3 | 1 | 1 | 3 |
141,873 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/forms.py
|
karaage.projects.forms.ProjectForm
|
class ProjectForm(forms.ModelForm):
pid = forms.RegexField(
"^%s$" % settings.PROJECT_VALIDATION_RE,
max_length=settings.PROJECT_ID_MAX_LENGTH,
required=False,
label="PID",
help_text="Leave blank for auto generation",
error_messages={"invalid": settings.PROJECT_VALIDATION_ERROR_MSG},
)
name = forms.CharField(label="Project Title", widget=forms.TextInput(attrs={"size": 60}))
description = forms.CharField(
widget=forms.Textarea(attrs={"class": "vLargeTextField", "rows": 10, "cols": 40}), required=False
)
institute = forms.ModelChoiceField(queryset=Institute.active.all())
additional_req = forms.CharField(
widget=forms.Textarea(attrs={"class": "vLargeTextField", "rows": 10, "cols": 40}), required=False
)
leaders = ajax_select.fields.AutoCompleteSelectMultipleField("person", required=True)
start_date = forms.DateField(initial=datetime.datetime.today)
end_date = forms.DateField(required=False)
class Meta:
model = Project
fields = (
"pid",
"name",
"institute",
"leaders",
"description",
"start_date",
"end_date",
"additional_req",
"rcao",
)
def __init__(self, *args, **kwargs):
# Make PID field read only if we are editing a project
super(ProjectForm, self).__init__(*args, **kwargs)
instance = getattr(self, "instance", None)
if instance and instance.pid:
self.fields["pid"].widget.attrs["readonly"] = "readonly"
self.fields["pid"].help_text = "You can't change the PID of an existing project"
del self.fields["leaders"]
def clean_pid(self):
pid = self.cleaned_data["pid"]
try:
Institute.objects.get(name=pid)
raise forms.ValidationError(six.u("Project ID not available"))
except Institute.DoesNotExist:
return pid
|
class ProjectForm(forms.ModelForm):
class Meta:
def __init__(self, *args, **kwargs):
pass
def clean_pid(self):
pass
| 4 | 0 | 8 | 0 | 7 | 1 | 2 | 0.02 | 1 | 2 | 1 | 0 | 2 | 0 | 2 | 2 | 51 | 3 | 47 | 16 | 43 | 1 | 26 | 16 | 22 | 2 | 1 | 1 | 4 |
141,874 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/projects/forms.py
|
karaage.projects.forms.AddPersonForm
|
class AddPersonForm(forms.Form):
person = ajax_select.fields.AutoCompleteSelectField("person", required=True, label="Add user to project")
|
class AddPersonForm(forms.Form):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
141,875 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/tests/test_software.py
|
karaage.plugins.kgsoftware.tests.test_software.SoftwareTestCase
|
class SoftwareTestCase(TestCase):
def test_change_group(self):
"""Check that when changing an software group, old accounts are
removed from the software and new ones are added.
"""
account1 = simple_account()
group1 = GroupFactory()
group1.add_person(account1.person)
# Test during initial creation of the software
software = SoftwareFactory(group=group1)
# Test changing an existing software group
account2 = simple_account()
group2 = GroupFactory()
group2.add_person(account2.person)
software.group = group2
software.save()
|
class SoftwareTestCase(TestCase):
def test_change_group(self):
'''Check that when changing an software group, old accounts are
removed from the software and new ones are added.
'''
pass
| 2 | 1 | 18 | 3 | 10 | 5 | 1 | 0.45 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 1 | 19 | 3 | 11 | 7 | 9 | 5 | 11 | 7 | 9 | 1 | 1 | 0 | 1 |
141,876 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/tests/test_all_pages.py
|
karaage.plugins.kgsoftware.tests.test_all_pages.TestKgApplicationPages
|
class TestKgApplicationPages(TestAllPagesCase):
"""Discover all URLs, do a HTTP GET and
confirm 200 OK and no DB changes."""
fixtures = [
"test_karaage.json",
"test_kgsoftware.json",
]
variables = {
"software_id": "1",
"category_id": "1",
"license_id": "1",
"version_id": "1",
"person_id": "1",
}
module = "karaage.plugins.kgsoftware"
|
class TestKgApplicationPages(TestAllPagesCase):
'''Discover all URLs, do a HTTP GET and
confirm 200 OK and no DB changes.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.15 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 16 | 1 | 13 | 4 | 12 | 2 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,877 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/__init__.py
|
karaage.plugins.kgsoftware.plugin
|
class plugin(BasePlugin):
name = "karaage.plugins.kgsoftware"
|
class plugin(BasePlugin):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
141,878 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/__init__.py
|
karaage.plugins.kgapplications.plugin
|
class plugin(BasePlugin):
name = "karaage.plugins.kgapplications"
template_context_processors = ("karaage.plugins.kgapplications.context_processor",)
settings = {
"ALLOW_REGISTRATIONS": False,
"ALLOW_NEW_PROJECTS": True,
"APPROVE_ACCOUNTS_EMAIL": None,
}
def ready(self):
from . import signals
|
class plugin(BasePlugin):
def ready(self):
pass
| 2 | 0 | 2 | 0 | 2 | 1 | 1 | 0.1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 12 | 2 | 10 | 6 | 7 | 1 | 6 | 6 | 3 | 1 | 2 | 0 | 1 |
141,879 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/models.py
|
karaage.plugins.kgsoftware.models.SoftwareLicense
|
class SoftwareLicense(models.Model):
software = models.ForeignKey(Software, on_delete=models.CASCADE)
version = models.CharField(max_length=100, blank=True, null=True)
date = models.DateField(blank=True, null=True)
text = models.TextField()
class Meta:
db_table = "software_license"
get_latest_by = "date"
ordering = ["-version"]
def __str__(self):
return "%s - %s" % (self.software.name, self.version)
def get_absolute_url(self):
return reverse("kg_software_license_detail", args=[self.id])
|
class SoftwareLicense(models.Model):
class Meta:
def __str__(self):
pass
def get_absolute_url(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 16 | 3 | 13 | 11 | 9 | 0 | 13 | 11 | 9 | 1 | 1 | 0 | 2 |
141,880 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/models.py
|
karaage.plugins.kgsoftware.models.SoftwareCategory
|
class SoftwareCategory(models.Model):
name = models.CharField(max_length=100)
class Meta:
db_table = "software_category"
ordering = ["name"]
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("kg_software_category_list")
|
class SoftwareCategory(models.Model):
class Meta:
def __str__(self):
pass
def get_absolute_url(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 12 | 3 | 9 | 7 | 5 | 0 | 9 | 7 | 5 | 1 | 1 | 0 | 2 |
141,881 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0008_auto_20190605_0827.py
|
karaage.plugins.kgapplications.migrations.0008_auto_20190605_0827.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0007_auto_20190315_1515"),
]
operations = [
migrations.AlterField(
model_name="applicant",
name="institute",
field=models.ForeignKey(
blank=True,
limit_choices_to={"is_active": True},
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="karaage.Institute",
),
),
migrations.AlterField(
model_name="application",
name="content_type",
field=models.ForeignKey(
blank=True,
limit_choices_to={"model__in": ["person", "applicant"]},
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="contenttypes.ContentType",
),
),
migrations.AlterField(
model_name="projectapplication",
name="institute",
field=models.ForeignKey(
blank=True,
limit_choices_to={"is_active": True},
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="karaage.Institute",
),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | 1 | 39 | 3 | 38 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,882 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/tables.py
|
karaage.plugins.kgapplications.tables.ApplicationTable
|
class ApplicationTable(tables.Table):
id = tables.LinkColumn("kg_application_detail", args=[A("pk")], verbose_name="ID")
action = tables.Column(empty_values=(), order_by=("_class"))
applicant = tables.Column(linkify=True, order_by=("new_applicant", "existing_person"))
def render_action(self, record):
return record.get_object().info()
def render_state(self, record):
state_machine = get_state_machine(record)
state = state_machine.get_state(record)
return state.name
class Meta:
model = Application
fields = ("id", "action", "applicant", "state", "expires")
empty_text = "No items"
|
class ApplicationTable(tables.Table):
def render_action(self, record):
pass
def render_state(self, record):
pass
class Meta:
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 2 | 0 | 2 | 2 | 17 | 3 | 14 | 11 | 10 | 0 | 14 | 11 | 10 | 1 | 1 | 0 | 2 |
141,883 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/aed.py
|
karaage.plugins.kgapplications.views.aed.StateStepApplicant
|
class StateStepApplicant(Step):
"""Application is open and user is can edit it."""
name = "Open"
def view(self, request, application, label, roles, actions):
"""Django view method."""
# Get the appropriate form
status = None
form = None
if application.existing_person is not None:
status = "You are already registered in the system."
else:
if application.new_applicant.saml_id is not None:
form_class = forms.AafApplicantForm
else:
form_class = forms.UserApplicantForm
form = form_class(request.POST or None, instance=application.new_applicant)
# Process the form, if there is one
if form is not None and request.method == "POST":
if form.is_valid():
form.save(commit=True)
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
else:
# if form didn't validate and we want to go back or cancel,
# then just do it.
if "cancel" in request.POST:
return "cancel"
if "prev" in request.POST:
return "prev"
# If we don't have a form, we can just process the actions here
if form is None:
for action in actions:
if action in request.POST:
return action
# Render the response
return render(
template_name="kgapplications/project_aed_applicant.html",
context={
"form": form,
"application": application,
"status": status,
"actions": actions,
"roles": roles,
},
request=request,
)
|
class StateStepApplicant(Step):
'''Application is open and user is can edit it.'''
def view(self, request, application, label, roles, actions):
'''Django view method.'''
pass
| 2 | 2 | 50 | 5 | 38 | 7 | 12 | 0.2 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 2 | 55 | 7 | 40 | 7 | 38 | 8 | 27 | 7 | 25 | 12 | 2 | 4 | 12 |
141,884 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/tests/fixtures.py
|
karaage.plugins.kgapplications.tests.fixtures.ExistingProjectApplicationFactory
|
class ExistingProjectApplicationFactory(ProjectApplicationFactory):
project = factory.SubFactory(ProjectFactory)
|
class ExistingProjectApplicationFactory(ProjectApplicationFactory):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 3 | 0 | 0 |
141,885 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateWaitingForDelegate
|
class StateWaitingForDelegate(StateWaitingForApproval):
"""We need the delegate to provide approval."""
name = "Waiting for delegate"
authorised_text = "an institute delegate"
authorised_role = "institute delegate"
def get_authorised_persons(self, application):
return application.institute.delegates.filter(is_active=True, login_enabled=True)
def get_email_persons(self, application):
return application.institute.delegates.filter(
institutedelegate__send_email=True, is_active=True, login_enabled=True
)
def get_approve_form(self, request, application, roles):
return forms.approve_project_form_generator(application, roles)
|
class StateWaitingForDelegate(StateWaitingForApproval):
'''We need the delegate to provide approval.'''
def get_authorised_persons(self, application):
pass
def get_email_persons(self, application):
pass
def get_approve_form(self, request, application, roles):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.08 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 16 | 17 | 4 | 12 | 7 | 8 | 1 | 10 | 7 | 6 | 1 | 3 | 0 | 3 |
141,886 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateWaitingForAdminSoftware
|
class StateWaitingForAdminSoftware(StateWaitingForApproval):
"""We need the administrator to provide approval."""
name = "Waiting for administrator"
authorised_text = "an administrator"
authorised_role = "administrator"
def get_authorised_persons(self, application):
return Person.objects.filter(is_admin=True)
def check_can_approve(self, request, application, roles):
"""Check the person's authorization."""
return "is_admin" in roles
def get_approve_form(self, request, application, roles):
return ApproveSoftwareForm
|
class StateWaitingForAdminSoftware(StateWaitingForApproval):
'''We need the administrator to provide approval.'''
def get_authorised_persons(self, application):
pass
def check_can_approve(self, request, application, roles):
'''Check the person's authorization.'''
pass
def get_approve_form(self, request, application, roles):
pass
| 4 | 2 | 2 | 0 | 2 | 0 | 1 | 0.2 | 1 | 2 | 2 | 0 | 3 | 0 | 3 | 16 | 16 | 4 | 10 | 7 | 6 | 2 | 10 | 7 | 6 | 1 | 3 | 0 | 3 |
141,887 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateWaitingForAdmin
|
class StateWaitingForAdmin(StateWaitingForApproval):
"""We need the administrator to provide approval."""
name = "Waiting for administrator"
authorised_text = "an administrator"
authorised_role = "administrator"
def get_authorised_persons(self, application):
return Person.objects.filter(is_admin=True, is_active=True, login_enabled=True)
def check_authorised(self, request, application, roles):
"""Check the person's authorization."""
return "is_admin" in roles
def get_approve_form(self, request, application, roles):
return forms.admin_approve_project_form_generator(application, roles)
def get_request_email_link(self, application):
link, is_secret = base.get_admin_email_link(application)
return link, is_secret
|
class StateWaitingForAdmin(StateWaitingForApproval):
'''We need the administrator to provide approval.'''
def get_authorised_persons(self, application):
pass
def check_authorised(self, request, application, roles):
'''Check the person's authorization.'''
pass
def get_approve_form(self, request, application, roles):
pass
def get_request_email_link(self, application):
pass
| 5 | 2 | 3 | 0 | 2 | 0 | 1 | 0.15 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 17 | 20 | 5 | 13 | 9 | 8 | 2 | 13 | 9 | 8 | 1 | 3 | 0 | 4 |
141,888 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StatePassword
|
class StatePassword(base.State):
"""This application is completed and processed."""
name = "Password"
actions = {"submit"}
def get_actions(self, request, application, roles):
actions = set(self.actions)
if "is_applicant" not in roles:
actions.remove("submit")
return actions
def get_next_action(self, request, application, label, roles):
"""Django view method."""
actions = self.get_actions(request, application, roles)
if label is None and "is_applicant" in roles:
assert application.existing_person is not None
has_usable_password = application.existing_person.has_usable_password()
if has_usable_password:
form_class = forms.PersonVerifyPassword
form_type = "verify"
else:
form_class = forms.PersonSetPassword
form_type = "set"
form = form_class(
data=request.POST or None,
person=application.existing_person,
)
if request.method == "POST":
if form.is_valid():
form.save()
messages.success(request, "Password updated. New accounts activated.")
link, is_secret = base.get_email_link(application)
emails.send_completed_email(application, has_usable_password, link, is_secret)
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
return render(
template_name="kgapplications/common_password.html",
context={
"application": application,
"form": form,
"actions": actions,
"roles": roles,
"type": form_type,
},
request=request,
)
return super(StatePassword, self).get_next_action(request, application, label, roles)
|
class StatePassword(base.State):
'''This application is completed and processed.'''
def get_actions(self, request, application, roles):
pass
def get_next_action(self, request, application, label, roles):
'''Django view method.'''
pass
| 3 | 2 | 24 | 2 | 21 | 1 | 5 | 0.04 | 1 | 4 | 2 | 0 | 2 | 0 | 2 | 7 | 54 | 7 | 45 | 13 | 42 | 2 | 31 | 13 | 28 | 7 | 2 | 5 | 9 |
141,889 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateIntroduction
|
class StateIntroduction(base.State):
"""Invitation has been sent to applicant."""
name = "Read introduction"
actions = {"cancel", "submit"}
def get_next_action(self, request, application, label, roles):
"""Django get_next_action method."""
actions = self.get_actions(request, application, roles)
if label is None and "is_applicant" in roles and "is_admin" not in roles:
for action in actions:
if action in request.POST:
return action
link, is_secret = base.get_email_link(application)
return render(
template_name="kgapplications/software_introduction.html",
context={
"actions": actions,
"application": application,
"roles": roles,
"link": link,
"is_secret": is_secret,
},
request=request,
)
return super(StateIntroduction, self).get_next_action(request, application, label, roles)
|
class StateIntroduction(base.State):
'''Invitation has been sent to applicant.'''
def get_next_action(self, request, application, label, roles):
'''Django get_next_action method.'''
pass
| 2 | 2 | 20 | 0 | 19 | 1 | 4 | 0.09 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 6 | 26 | 2 | 22 | 7 | 20 | 2 | 12 | 7 | 10 | 4 | 2 | 3 | 4 |
141,890 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateDuplicateApplicant
|
class StateDuplicateApplicant(base.State):
"""Somebody has declared application is existing user."""
name = "Duplicate Applicant"
actions = {"cancel", "reopen"}
def get_actions(self, request, reapplication, roles):
actions = set(self.actions)
if "is_admin" not in roles:
actions.remove("reopen")
return actions
def enter_state(self, request, application):
authorised_persons = Person.objects.filter(is_admin=True, is_active=True, login_enabled=True)
link, is_secret = base.get_registration_email_link(application)
emails.send_duplicate_email(
"an administrator", "administrator", authorised_persons, application, link, is_secret
)
def get_next_action(self, request, application, label, roles):
# if not admin, don't allow reopen
actions = self.get_actions(request, application, roles)
if label is None and "is_admin" in roles:
form = forms.ApplicantReplace(data=request.POST or None, application=application)
if request.method == "POST":
if "replace" in request.POST:
if form.is_valid():
form.save()
return "reopen"
else:
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
return render(
template_name="kgapplications/project_duplicate_applicant.html",
context={
"application": application,
"form": form,
"actions": actions,
"roles": roles,
},
request=request,
)
return super(StateDuplicateApplicant, self).get_next_action(request, application, label, roles)
|
class StateDuplicateApplicant(base.State):
'''Somebody has declared application is existing user.'''
def get_actions(self, request, reapplication, roles):
pass
def enter_state(self, request, application):
pass
def get_next_action(self, request, application, label, roles):
pass
| 4 | 1 | 13 | 1 | 12 | 0 | 3 | 0.05 | 1 | 4 | 2 | 0 | 3 | 0 | 3 | 8 | 47 | 6 | 39 | 12 | 35 | 2 | 27 | 12 | 23 | 7 | 2 | 5 | 10 |
141,891 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateWaitingForLeader
|
class StateWaitingForLeader(StateWaitingForApproval):
"""We need the leader to provide approval."""
name = "Waiting for leader"
authorised_text = "a project leader"
authorised_role = "project leader"
def get_authorised_persons(self, application):
return application.project.leaders.filter(is_active=True, login_enabled=True)
def get_approve_form(self, request, application, roles):
return forms.approve_project_form_generator(application, roles)
|
class StateWaitingForLeader(StateWaitingForApproval):
'''We need the leader to provide approval.'''
def get_authorised_persons(self, application):
pass
def get_approve_form(self, request, application, roles):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.13 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 15 | 12 | 3 | 8 | 6 | 5 | 1 | 8 | 6 | 5 | 1 | 3 | 0 | 2 |
141,892 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateDeclined
|
class StateDeclined(base.State):
"""This application declined."""
name = "Declined"
actions = {"reopen", "archive"}
def get_actions(self, request, application, roles):
actions = set(self.actions)
if "is_admin" not in roles:
actions.remove("archive")
return actions
def enter_state(self, request, application):
"""This is becoming the new current state."""
application.decline()
def get_next_action(self, request, application, label, roles):
"""Django view method."""
actions = self.get_actions(request, application, roles)
if label is None and "is_applicant" in roles and "is_admin" not in roles:
# applicant, admin, leader can reopen an application
for action in actions:
if action in request.POST:
return action
return render(
template_name="kgapplications/common_declined.html",
context={"application": application, "actions": actions, "roles": roles},
request=request,
)
return super(StateDeclined, self).get_next_action(request, application, label, roles)
|
class StateDeclined(base.State):
'''This application declined.'''
def get_actions(self, request, application, roles):
pass
def enter_state(self, request, application):
'''This is becoming the new current state.'''
pass
def get_next_action(self, request, application, label, roles):
'''Django view method.'''
pass
| 4 | 3 | 7 | 0 | 6 | 1 | 2 | 0.18 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 8 | 30 | 4 | 22 | 9 | 18 | 4 | 18 | 9 | 14 | 4 | 2 | 3 | 7 |
141,893 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateArchived
|
class StateArchived(StateCompleted):
"""This application is archived."""
name = "Archived"
actions = {}
def get_actions(self, request, application, roles):
actions = set(self.actions)
return actions
|
class StateArchived(StateCompleted):
'''This application is archived.'''
def get_actions(self, request, application, roles):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.17 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 7 | 9 | 2 | 6 | 5 | 4 | 1 | 6 | 5 | 4 | 1 | 3 | 0 | 1 |
141,894 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/base.py
|
karaage.plugins.kgapplications.views.base.StateMachine
|
class StateMachine(object):
"""State machine, for processing states."""
##################
# PUBLIC METHODS #
##################
def __init__(self, config):
self._first_state = {
"type": "goto",
"key": "start",
}
self._config = config
super(StateMachine, self).__init__()
def get_state(self, application):
if application.state not in self._config:
raise RuntimeError("Invalid state '%s'" % application.state)
config = self._config[application.state]
instance = load_state_instance(config)
return instance
def start(self, request, application, extra_roles=None):
"""Continue the state machine at first state."""
# Get the authentication of the current user
roles = self._get_roles_for_request(request, application)
if extra_roles is not None:
roles.update(extra_roles)
# Ensure current user is authenticated. If user isn't applicant,
# leader, delegate or admin, they probably shouldn't be here.
if "is_authorised" not in roles:
return HttpResponseForbidden("<h1>Access Denied</h1>")
# Go to first state.
return self._next(request, application, roles, self._first_state)
def process(self, request, application, expected_state, label, extra_roles=None):
"""Process the view request at the current state."""
# Get the authentication of the current user
roles = self._get_roles_for_request(request, application)
if extra_roles is not None:
roles.update(extra_roles)
# Ensure current user is authenticated. If user isn't applicant,
# leader, delegate or admin, they probably shouldn't be here.
if "is_authorised" not in roles:
return HttpResponseForbidden("<h1>Access Denied</h1>")
# If user didn't supply state on URL, redirect to full URL.
if expected_state is None:
url = get_url(request, application, roles, label)
return HttpResponseRedirect(url)
# Check that the current state is valid.
if application.state not in self._config:
raise RuntimeError("Invalid current state '%s'" % application.state)
# If state user expected is different to state we are in, warn user
# and jump to expected state.
if expected_state != application.state:
# post data will be lost
if request.method == "POST":
messages.warning(request, "Discarding request and jumping to current state.")
# note we discard the label, it probably isn't relevant for new
# state
url = get_url(request, application, roles)
return HttpResponseRedirect(url)
# Get the current state for this application
state_config = self._config[application.state]
# Finally do something
instance = load_state_instance(state_config)
if request.method == "GET":
# if method is GET, state does not ever change.
response = instance.get_next_config(request, application, label, roles)
assert isinstance(response, HttpResponse)
return response
elif request.method == "POST":
# if method is POST, it can return a HttpResponse or a string
response = instance.get_next_config(request, application, label, roles)
if isinstance(response, HttpResponse):
# If it returned a HttpResponse, state not changed, just
# display
return response
else:
# If it returned a string, lookit up in the actions for this
# state
next_config = response
# Go to the next state
return self._next(request, application, roles, next_config)
else:
# Shouldn't happen, user did something weird
return HttpResponseBadRequest("<h1>Bad Request</h1>")
###################
# PRIVATE METHODS #
###################
@staticmethod
def _get_roles_for_request(request, application):
"""Check the authentication of the current user."""
roles = application.get_roles_for_person(request.user)
if common.is_admin(request):
roles.add("is_admin")
roles.add("is_authorised")
return roles
def _next(self, request, application, roles, next_config):
"""Continue the state machine at given state."""
# we only support state changes for POST requests
if request.method == "POST":
key = None
# If next state is a transition, process it
while True:
# We do not expect to get a direct state transition here.
assert next_config["type"] in ["goto", "transition"]
while next_config["type"] == "goto":
key = next_config["key"]
next_config = self._config[key]
instance = load_instance(next_config)
if not isinstance(instance, Transition):
break
next_config = instance.get_next_config(request, application, roles)
# lookup next state
assert key is not None
state_key = key
# enter that state
instance.enter_state(request, application)
application.state = state_key
application.save()
# log details
log.change(application.application_ptr, "state: %s" % instance.name)
# redirect to this new state
url = get_url(request, application, roles)
return HttpResponseRedirect(url)
else:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
|
class StateMachine(object):
'''State machine, for processing states.'''
def __init__(self, config):
pass
def get_state(self, application):
pass
def start(self, request, application, extra_roles=None):
'''Continue the state machine at first state.'''
pass
def process(self, request, application, expected_state, label, extra_roles=None):
'''Process the view request at the current state.'''
pass
@staticmethod
def _get_roles_for_request(request, application):
'''Check the authentication of the current user.'''
pass
def _next(self, request, application, roles, next_config):
'''Continue the state machine at given state.'''
pass
| 8 | 5 | 23 | 4 | 13 | 6 | 4 | 0.52 | 1 | 4 | 2 | 0 | 5 | 2 | 6 | 6 | 152 | 29 | 81 | 24 | 73 | 42 | 73 | 23 | 66 | 10 | 1 | 3 | 23 |
141,895 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/base.py
|
karaage.plugins.kgapplications.views.base.State
|
class State(object):
"""A abstract class that is the base for all application states."""
name = "Abstract State"
actions = set()
def __init__(self, config):
self.context = {}
self._config = config
for action_key in self.actions:
key = "on_%s" % action_key
assert key in config
actions = self.actions
for key, value in config.items():
if key.startswith("on_"):
action_key = key[3:]
assert action_key in actions
def get_actions(self, request, application, roles):
return self.actions
def enter_state(self, request, application):
"""This is becoming the new current state."""
pass
def get_next_config(self, request, application, label, roles):
response = self.get_next_action(request, application, label, roles)
if isinstance(response, HttpResponse):
return response
assert response in self.get_actions(request, application, roles)
key = "on_%s" % response
return self._config[key]
def get_next_action(self, request, application, label, roles):
"""Django view method. We provide a default detail view for
applications."""
# We only provide a view for when no label provided
if label is not None:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
# only certain actions make sense for default view
actions = self.get_actions(request, application, roles)
# process the request in default view
if request.method == "GET":
context = self.context
context.update({"application": application, "actions": actions, "state": self.name, "roles": roles})
return render(template_name="kgapplications/common_detail.html", context=context, request=request)
elif request.method == "POST":
for action in actions:
if action in request.POST:
return action
# we don't know how to handle this request.
return HttpResponseBadRequest("<h1>Bad Request</h1>")
|
class State(object):
'''A abstract class that is the base for all application states.'''
def __init__(self, config):
pass
def get_actions(self, request, application, roles):
pass
def enter_state(self, request, application):
'''This is becoming the new current state.'''
pass
def get_next_config(self, request, application, label, roles):
pass
def get_next_action(self, request, application, label, roles):
'''Django view method. We provide a default detail view for
applications.'''
pass
| 6 | 3 | 9 | 1 | 7 | 1 | 3 | 0.21 | 1 | 0 | 0 | 7 | 5 | 2 | 5 | 5 | 56 | 10 | 38 | 19 | 32 | 8 | 37 | 19 | 31 | 6 | 1 | 3 | 14 |
141,896 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/aed.py
|
karaage.plugins.kgapplications.views.aed.StateStepIntroduction
|
class StateStepIntroduction(Step):
"""Invitation has been sent to applicant."""
name = "Read introduction"
def view(self, request, application, label, roles, actions):
"""Django get_next_action method."""
if application.new_applicant is not None:
if not application.new_applicant.email_verified:
application.new_applicant.email_verified = True
application.new_applicant.save()
for action in actions:
if action in request.POST:
return action
link, is_secret = base.get_email_link(application)
return render(
template_name="kgapplications/project_aed_introduction.html",
context={
"actions": actions,
"application": application,
"roles": roles,
"link": link,
"is_secret": is_secret,
},
request=request,
)
|
class StateStepIntroduction(Step):
'''Invitation has been sent to applicant.'''
def view(self, request, application, label, roles, actions):
'''Django get_next_action method.'''
pass
| 2 | 2 | 21 | 0 | 20 | 1 | 5 | 0.09 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 26 | 2 | 22 | 5 | 20 | 2 | 12 | 5 | 10 | 5 | 2 | 2 | 5 |
141,897 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/aed.py
|
karaage.plugins.kgapplications.views.aed.StateStepProject
|
class StateStepProject(Step):
"""Applicant is able to choose the project for the application."""
name = "Choose project"
def handle_ajax(self, request, application):
resp = {}
if "leader" in request.POST:
leader = Person.objects.get(pk=request.POST["leader"])
project_list = leader.leads.filter(is_active=True)
resp["project_list"] = [(p.pk, six.text_type(p)) for p in project_list]
elif "terms" in request.POST:
terms = request.POST["terms"].lower()
try:
project = Project.active.get(pid__icontains=terms)
resp["project_list"] = [(project.pk, six.text_type(project))]
except Project.DoesNotExist:
resp["project_list"] = []
except Project.MultipleObjectsReturned:
resp["project_list"] = []
leader_list = Person.active.filter(
institute=application.applicant.institute, leads__is_active=True
).distinct()
if len(terms) >= 3:
query = Q()
for term in terms.split(" "):
q = Q(username__icontains=term)
q = q | Q(short_name__icontains=term)
q = q | Q(full_name__icontains=term)
query = query & q
leader_list = leader_list.filter(query)
resp["leader_list"] = [(p.pk, "%s (%s)" % (p, p.username)) for p in leader_list]
else:
resp["error"] = "Please enter at lease three characters for search."
resp["leader_list"] = []
return resp
def view(self, request, application, label, roles, actions):
"""Django view method."""
if "ajax" in request.POST:
resp = self.handle_ajax(request, application)
return HttpResponse(json.dumps(resp), content_type="application/json")
form_models = {
"common": forms.CommonApplicationForm,
"new": forms.NewProjectApplicationForm,
"existing": forms.ExistingProjectApplicationForm,
}
project_forms = {}
for key, form in six.iteritems(form_models):
project_forms[key] = form(request.POST or None, instance=application)
if application.project is not None:
project_forms["common"].initial = {"application_type": "U"}
elif application.name != "":
project_forms["common"].initial = {"application_type": "P"}
if "application_type" in request.POST:
at = request.POST["application_type"]
valid = True
if at == "U":
# existing project
if project_forms["common"].is_valid():
project_forms["common"].save(commit=False)
else:
valid = False
if project_forms["existing"].is_valid():
project_forms["existing"].save(commit=False)
else:
valid = False
elif at == "P":
# new project
if project_forms["common"].is_valid():
project_forms["common"].save(commit=False)
else:
valid = False
if project_forms["new"].is_valid():
project_forms["new"].save(commit=False)
else:
valid = False
application.institute = application.applicant.institute
else:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
# reset hidden forms
if at != "U":
# existing project form was not displayed
project_forms["existing"] = form_models["existing"](instance=application)
application.project = None
if at != "P":
# new project form was not displayed
project_forms["new"] = form_models["new"](instance=application)
application.name = ""
application.institute = None
application.description = None
application.additional_req = None
application.machine_categories = []
application.pid = None
application.rcao = None
# save the values
application.save()
if project_forms["new"].is_valid() and at == "P":
project_forms["new"].save_m2m()
# we still need to process cancel and prev even if form were
# invalid
if "cancel" in request.POST:
return "cancel"
if "prev" in request.POST:
return "prev"
# if forms were valid, jump to next state
if valid:
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
else:
# we still need to process cancel, prev even if application type
# not given
if "cancel" in request.POST:
return "cancel"
if "prev" in request.POST:
return "prev"
# lookup the project based on the form data
project_id = project_forms["existing"]["project"].value()
project = None
if project_id:
try:
project = Project.objects.get(pk=project_id)
except Project.DoesNotExist:
pass
# render the response
return render(
template_name="kgapplications/project_aed_project.html",
context={
"forms": project_forms,
"project": project,
"actions": actions,
"roles": roles,
"application": application,
},
request=request,
)
|
class StateStepProject(Step):
'''Applicant is able to choose the project for the application.'''
def handle_ajax(self, request, application):
pass
def view(self, request, application, label, roles, actions):
'''Django view method.'''
pass
| 3 | 2 | 74 | 8 | 59 | 7 | 16 | 0.13 | 1 | 5 | 5 | 0 | 2 | 0 | 2 | 3 | 154 | 19 | 120 | 22 | 117 | 15 | 94 | 22 | 91 | 24 | 2 | 4 | 31 |
141,898 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0010_applicants.py
|
karaage.plugins.kgapplications.migrations.0010_applicants.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0009_auto_20200227_1655"),
]
operations = [
migrations.RunPython(forward, reverse),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 1 | 7 | 3 | 6 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,899 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateCompleted
|
class StateCompleted(base.State):
"""This application is completed and processed."""
name = "Completed"
actions = {"archive"}
def get_actions(self, request, application, roles):
actions = set(self.actions)
if "is_admin" not in roles:
actions.remove("archive")
return actions
|
class StateCompleted(base.State):
'''This application is completed and processed.'''
def get_actions(self, request, application, roles):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 2 | 0.13 | 1 | 1 | 0 | 1 | 1 | 0 | 1 | 6 | 11 | 2 | 8 | 5 | 6 | 1 | 8 | 5 | 6 | 2 | 2 | 1 | 2 |
141,900 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/templatetags/applications.py
|
karaage.plugins.kgapplications.templatetags.applications.ApplicationActionsPlus
|
class ApplicationActionsPlus(template.Node):
"""Node for rendering actions available with extra text."""
def __init__(self, nodelist):
super(ApplicationActionsPlus, self).__init__()
self.nodelist = nodelist
def render(self, context):
extra = self.nodelist.render(context)
nodelist = template.loader.get_template("kgapplications/common_actions.html")
new_context = {
"roles": context["roles"],
"extra": extra,
"actions": context["actions"],
}
output = nodelist.render(new_context)
return output
|
class ApplicationActionsPlus(template.Node):
'''Node for rendering actions available with extra text.'''
def __init__(self, nodelist):
pass
def render(self, context):
pass
| 3 | 1 | 7 | 0 | 7 | 0 | 1 | 0.07 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 17 | 2 | 14 | 8 | 11 | 1 | 10 | 8 | 7 | 1 | 1 | 0 | 2 |
141,901 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/states.py
|
karaage.plugins.kgapplications.views.states.StateWithSteps
|
class StateWithSteps(base.State):
"""A state that has a number of steps to complete."""
def __init__(self, config):
self._first_step = None
self._steps = {}
self._order = []
super(StateWithSteps, self).__init__(config)
def add_step(self, step, step_id):
"""Add a step to the list. The first step added becomes the initial
step."""
assert step_id not in self._steps
assert step_id not in self._order
assert isinstance(step, Step)
self._steps[step_id] = step
self._order.append(step_id)
def get_next_action(self, request, application, label, roles):
"""Process the get_next_action request at the current step."""
actions = self.get_actions(request, application, roles)
# if the user is not the applicant, the steps don't apply.
if "is_applicant" not in roles:
return super(StateWithSteps, self).get_next_action(request, application, label, roles)
# was label supplied?
if label is None:
# no label given, find first step and redirect to it.
this_id = self._order[0]
url = base.get_url(request, application, roles, this_id)
return HttpResponseRedirect(url)
else:
# label was given, get the step position and id for it
this_id = label
if this_id not in self._steps:
return HttpResponseBadRequest("<h1>Bad Request</h1>")
position = self._order.index(this_id)
# get the step given the label
this_step = self._steps[this_id]
# define list of allowed actions for step
step_actions = {}
if "cancel" in actions:
step_actions["cancel"] = "state:cancel"
if "submit" in actions and position == len(self._order) - 1:
step_actions["submit"] = "state:submit"
if position > 0:
step_actions["prev"] = self._order[position - 1]
if position < len(self._order) - 1:
step_actions["next"] = self._order[position + 1]
# process the request
if request.method == "GET":
# if GET request, state changes are not allowed
response = this_step.view(request, application, this_id, roles, step_actions.keys())
assert isinstance(response, HttpResponse)
return response
elif request.method == "POST":
# if POST request, state changes are allowed
response = this_step.view(request, application, this_id, roles, step_actions.keys())
assert response is not None
# If it was a HttpResponse, just return it
if isinstance(response, HttpResponse):
return response
else:
# try to lookup the response
if response not in step_actions:
raise RuntimeError("Invalid response '%s' from step '%s'" % (response, this_step))
action = step_actions[response]
# process the required action
if action.startswith("state:"):
return action[6:]
else:
url = base.get_url(request, application, roles, action)
return HttpResponseRedirect(url)
# Something went wrong.
return HttpResponseBadRequest("<h1>Bad Request</h1>")
|
class StateWithSteps(base.State):
'''A state that has a number of steps to complete.'''
def __init__(self, config):
pass
def add_step(self, step, step_id):
'''Add a step to the list. The first step added becomes the initial
step.'''
pass
def get_next_action(self, request, application, label, roles):
'''Process the get_next_action request at the current step.'''
pass
| 4 | 3 | 26 | 3 | 18 | 5 | 5 | 0.31 | 1 | 3 | 1 | 1 | 3 | 3 | 3 | 8 | 83 | 12 | 54 | 15 | 50 | 17 | 50 | 15 | 46 | 13 | 2 | 3 | 15 |
141,902 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/transitions.py
|
karaage.plugins.kgapplications.views.transitions.TransitionOpen
|
class TransitionOpen(base.Transition):
"""A transition after application opened."""
actions = {"success"}
def get_next_action(self, request, application, roles):
"""Retrieve the next state."""
application.reopen()
link, is_secret = base.get_email_link(application)
emails.send_invite_email(application, link, is_secret)
messages.success(request, "Sent an invitation to %s." % application.applicant.email)
return "success"
|
class TransitionOpen(base.Transition):
'''A transition after application opened.'''
def get_next_action(self, request, application, roles):
'''Retrieve the next state.'''
pass
| 2 | 2 | 7 | 0 | 6 | 1 | 1 | 0.25 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 12 | 2 | 8 | 4 | 6 | 2 | 8 | 4 | 6 | 1 | 2 | 0 | 1 |
141,903 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/tests/fixtures.py
|
karaage.plugins.kgapplications.tests.fixtures.NewProjectApplicationFactory
|
class NewProjectApplicationFactory(ProjectApplicationFactory):
name = fuzzy_lower_text(prefix="projectapplication-")
description = FuzzyText()
institute = factory.SubFactory(InstituteFactory)
|
class NewProjectApplicationFactory(ProjectApplicationFactory):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 3 | 0 | 0 |
141,904 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/tests/test_all_pages.py
|
karaage.plugins.kgapplications.tests.test_all_pages.TestKgApplicationPages
|
class TestKgApplicationPages(TestAllPagesCase):
"""Discover all URLs, do a HTTP GET and
confirm 200 OK and no DB changes."""
fixtures = [
"test_karaage.json",
"test_kgapplications.json",
]
variables = {
"application_id": "1",
"project_id": "1",
"token": "27e889413e2d302b9b2a66c63b208962a3788730",
"state": "D",
"label": "woof",
}
module = "karaage.plugins.kgapplications"
def setUp(self):
super(TestKgApplicationPages, self).setUp()
# we have to make sure the application isn't expired
new_expires = timezone.now() + datetime.timedelta(days=7)
Application.objects.all().update(expires=new_expires)
|
class TestKgApplicationPages(TestAllPagesCase):
'''Discover all URLs, do a HTTP GET and
confirm 200 OK and no DB changes.'''
def setUp(self):
pass
| 2 | 1 | 6 | 1 | 4 | 1 | 1 | 0.18 | 1 | 3 | 1 | 0 | 1 | 0 | 1 | 2 | 23 | 3 | 17 | 6 | 15 | 3 | 8 | 6 | 6 | 1 | 2 | 0 | 1 |
141,905 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/tests/test_applications.py
|
karaage.plugins.kgapplications.tests.test_applications.ProjectApplicationTestCase
|
class ProjectApplicationTestCase(TestCase):
def setUp(self):
call_command("loaddata", "test_karaage", **{"verbosity": 0})
def tearDown(self):
set_admin()
def test_register_account(self):
if django.VERSION >= (1, 9):
url_prefix = ""
else:
url_prefix = "http://testserver"
set_no_admin()
with self.assertRaises(Person.DoesNotExist):
Person.objects.get(username="jimbob")
self.assertEqual(len(mail.outbox), 0)
response = self.client.get(reverse("kg_application_new"))
self.assertEqual(response.status_code, 200)
a = response.content.find(b'name="captcha_0" value="') + 24
b = a + 40
hash_ = response.content[a:b].decode("ascii")
captcha_text = CaptchaStore.objects.get(hashkey=hash_).response
# OPEN APPLICATION
form_data = {
"email": "jim.bob@example.com",
"captcha_0": hash_,
"captcha_1": captcha_text,
}
response = self.client.post(reverse("kg_application_new"), form_data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.redirect_chain[0][0], url_prefix + reverse("index"))
token = Application.objects.get().secret_token
self.assertEqual(len(mail.outbox), 1)
self.assertTrue(mail.outbox[0].subject.startswith("TestOrg invitation"))
self.assertEqual(mail.outbox[0].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[0].to[0], "jim.bob@example.com")
# SUBMIT APPLICANT DETAILS
form_data = {
"title": "Mr",
"short_name": "Jim",
"full_name": "Jim Bob",
"position": "Researcher",
"institute": 1,
"department": "Maths",
"telephone": "4444444",
"username": "jimbob",
"next": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "O", "applicant"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0],
url_prefix + reverse("kg_application_unauthenticated", args=[token, "O", "project"]),
)
# SUBMIT PROJECT DETAILS
form_data = {
"application_type": "P",
"name": "NewProject1",
"description": "I like chocolate.",
"aup": True,
"additional_req": "Meow",
"needs_account": False,
"machine_categories": [1],
"rcao": "email@example.org",
"submit": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "O", "project"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_unauthenticated", args=[token, "D"])
)
applicant = Applicant.objects.get(username="jimbob")
application = applicant.application
self.assertEqual(application.state, ProjectApplication.WAITING_FOR_DELEGATE)
self.assertEqual(len(mail.outbox), 2)
self.assertTrue(mail.outbox[1].subject.startswith("TestOrg request"))
self.assertEqual(mail.outbox[1].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[1].to[0], "leader@example.com")
# DELEGATE LOGS IN TO APPROVE
logged_in = self.client.login(username="kgtestuser1", password="aq12ws")
self.assertEqual(logged_in, True)
# DELEGATE GET DETAILS
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "D"]))
self.assertEqual(response.status_code, 200)
# DELEGATE GET DECLINE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "D", "cancel"]))
self.assertEqual(response.status_code, 200)
# DELEGATE GET APPROVE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "D", "approve"]))
self.assertEqual(response.status_code, 200)
# DELEGATE APPROVE
form_data = {
"additional_req": "Meow",
"needs_account": False,
"machine_categories": [1],
"approve": True,
}
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "D", "approve"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "K"])
)
application = Application.objects.get(pk=application.id)
self.assertEqual(application.state, Application.WAITING_FOR_ADMIN)
self.assertEqual(len(mail.outbox), 3)
self.client.logout()
# ADMIN LOGS IN TO APPROVE
set_admin()
logged_in = self.client.login(username="kgsuper", password="aq12ws")
self.assertEqual(logged_in, True)
# ADMIN GET DETAILS
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K"]))
self.assertEqual(response.status_code, 200)
# ADMIN GET DECLINE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K", "cancel"]))
self.assertEqual(response.status_code, 200)
# ADMIN GET APPROVE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K", "approve"]))
self.assertEqual(response.status_code, 200)
# ADMIN APPROVE
form_data = {
"additional_req": "Woof",
"needs_account": False,
"machine_categories": [1],
"approve": True,
}
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "K", "approve"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "P"])
)
application = Application.objects.get(pk=application.id)
self.assertEqual(application.state, ProjectApplication.PASSWORD)
self.assertEqual(len(mail.outbox), 4)
self.client.logout()
set_no_admin()
# APPLICANT GET PASSWORD
response = self.client.get(reverse("kg_application_unauthenticated", args=[token, "P"]))
self.assertEqual(response.status_code, 200)
# APPLICANT SET PASSWORD
form_data = {
"new_password1": "Exaiquouxei0",
"new_password2": "Exaiquouxei0",
"submit": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "P"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_unauthenticated", args=[token, "C"])
)
# APPLICANT GET COMPLETE
response = self.client.get(reverse("kg_application_unauthenticated", args=[token, "C"]))
self.assertEqual(response.status_code, 200)
# APPLICANT SET ARCHIVE
form_data = {
"archive": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "C"]), form_data, follow=False
)
# applicant not allowed to do this
self.assertEqual(response.status_code, 400)
self.client.logout()
# ADMIN ARCHIVE
set_admin()
logged_in = self.client.login(username="kgsuper", password="aq12ws")
self.assertEqual(logged_in, True)
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "C"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "A"])
)
self.client.logout()
set_no_admin()
# APPLICANT GET ARCHIVE
response = self.client.get(reverse("kg_application_unauthenticated", args=[token, "A"]))
self.assertEqual(response.status_code, 200)
person = Person.objects.get(username="jimbob")
self.assertEqual(person.title, "Mr")
self.assertEqual(person.short_name, "Jim")
self.assertEqual(person.full_name, "Jim Bob")
self.assertEqual(person.institute.name, "Example")
self.assertEqual(person.telephone, "4444444")
self.assertEqual(person.approved_by.username, "kgsuper")
self.assertEqual(person.account_set.count(), 0)
self.assertIsNotNone(person.date_approved)
def _test_project_approval(self, application):
admin = fixtures.PersonFactory(username="admin")
admin.is_admin = True
admin.save()
application.approve(admin)
def _test_project_make_leader(self, application):
self._test_project_approval(application)
if application.make_leader:
self.assertIn(application.existing_person, application.project.leaders.all())
else:
self.assertNotIn(application.existing_person, application.project.leaders.all())
def test_new_project_make_leader(self, make_leader=True):
application = ExistingProjectApplicationFactory()
application.make_leader = make_leader
self._test_project_make_leader(application)
def test_new_project_make_leader_false(self):
self.test_new_project_make_leader(make_leader=False)
def test_existing_project_make_leader(self, make_leader=True):
application = NewProjectApplicationFactory()
application.make_leader = make_leader
self._test_project_make_leader(application)
def test_existing_project_make_leader_false(self):
self.test_existing_project_make_leader(make_leader=False)
|
class ProjectApplicationTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_register_account(self):
pass
def _test_project_approval(self, application):
pass
def _test_project_make_leader(self, application):
pass
def test_new_project_make_leader(self, make_leader=True):
pass
def test_new_project_make_leader_false(self):
pass
def test_existing_project_make_leader(self, make_leader=True):
pass
def test_existing_project_make_leader_false(self):
pass
| 10 | 0 | 27 | 3 | 22 | 2 | 1 | 0.1 | 1 | 7 | 7 | 0 | 9 | 0 | 9 | 9 | 255 | 36 | 199 | 25 | 189 | 20 | 130 | 25 | 120 | 2 | 1 | 1 | 11 |
141,906 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/tests/test_applications.py
|
karaage.plugins.kgapplications.tests.test_applications.UserApplicationTestCase
|
class UserApplicationTestCase(TestCase):
def setUp(self):
call_command("loaddata", "test_karaage", **{"verbosity": 0})
def tearDown(self):
set_admin()
def test_register_account(self):
if django.VERSION >= (1, 9):
url_prefix = ""
else:
url_prefix = "http://testserver"
set_no_admin()
with self.assertRaises(Person.DoesNotExist):
Person.objects.get(username="jimbob")
self.assertEqual(len(mail.outbox), 0)
response = self.client.get(reverse("kg_application_new"))
self.assertEqual(response.status_code, 200)
a = response.content.find(b'name="captcha_0" value="') + 24
b = a + 40
hash_ = response.content[a:b].decode("ascii")
captcha_text = CaptchaStore.objects.get(hashkey=hash_).response
# OPEN APPLICATION
form_data = {
"email": "jim.bob@example.com",
"captcha_0": hash_,
"captcha_1": captcha_text,
}
response = self.client.post(reverse("kg_application_new"), form_data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.redirect_chain[0][0], url_prefix + reverse("index"))
token = Application.objects.get().secret_token
self.assertEqual(len(mail.outbox), 1)
self.assertTrue(mail.outbox[0].subject.startswith("TestOrg invitation"))
self.assertEqual(mail.outbox[0].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[0].to[0], "jim.bob@example.com")
# SUBMIT APPLICANT DETAILS
form_data = {
"title": "Mr",
"short_name": "Jim",
"full_name": "Jim Bob",
"position": "Researcher",
"institute": 1,
"department": "Maths",
"telephone": "4444444",
"username": "jimbob",
"next": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "O", "applicant"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0],
url_prefix + reverse("kg_application_unauthenticated", args=[token, "O", "project"]),
)
# SUBMIT PROJECT DETAILS
form_data = {
"application_type": "U",
"project": 1,
"aup": True,
"make_leader": False,
"additional_req": "Meow",
"needs_account": False,
"submit": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "O", "project"]), form_data, follow=True
)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_unauthenticated", args=[token, "L"])
)
self.assertEqual(response.status_code, 200)
applicant = Applicant.objects.get(username="jimbob")
application = applicant.application
self.assertEqual(application.state, ProjectApplication.WAITING_FOR_LEADER)
self.assertEqual(len(mail.outbox), 2)
self.assertTrue(mail.outbox[1].subject.startswith("TestOrg request"))
self.assertEqual(mail.outbox[1].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[1].to[0], "leader@example.com")
# LEADER LOGS IN TO APPROVE
logged_in = self.client.login(username="kgtestuser1", password="aq12ws")
self.assertEqual(logged_in, True)
# LEADER GET DETAILS
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "L"]))
self.assertEqual(response.status_code, 200)
# LEADER GET DECLINE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "L", "cancel"]))
self.assertEqual(response.status_code, 200)
# LEADER GET APPROVE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "L", "approve"]))
self.assertEqual(response.status_code, 200)
# LEADER APPROVE
form_data = {
"make_leader": False,
"additional_req": "Meow",
"needs_account": False,
"approve": True,
}
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "L", "approve"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "K"])
)
application = Application.objects.get(pk=application.id)
self.assertEqual(application.state, Application.WAITING_FOR_ADMIN)
self.assertEqual(len(mail.outbox), 3)
self.client.logout()
# ADMIN LOGS IN TO APPROVE
set_admin()
logged_in = self.client.login(username="kgsuper", password="aq12ws")
self.assertEqual(logged_in, True)
# ADMIN GET DETAILS
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K"]))
self.assertEqual(response.status_code, 200)
# ADMIN GET DECLINE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K", "cancel"]))
self.assertEqual(response.status_code, 200)
# ADMIN GET APPROVE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K", "approve"]))
self.assertEqual(response.status_code, 200)
# ADMIN APPROVE
form_data = {
"make_leader": False,
"additional_req": "Woof",
"needs_account": False,
"approve": True,
}
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "K", "approve"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "P"])
)
application = Application.objects.get(pk=application.id)
self.assertEqual(application.state, ProjectApplication.PASSWORD)
self.assertEqual(len(mail.outbox), 4)
self.client.logout()
set_no_admin()
# APPLICANT GET PASSWORD
response = self.client.get(reverse("kg_application_unauthenticated", args=[token, "P"]))
self.assertEqual(response.status_code, 200)
# APPLICANT SET PASSWORD
form_data = {
"new_password1": "Exaiquouxei0",
"new_password2": "Exaiquouxei0",
"submit": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "P"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_unauthenticated", args=[token, "C"])
)
# APPLICANT GET COMPLETE
response = self.client.get(reverse("kg_application_unauthenticated", args=[token, "C"]))
self.assertEqual(response.status_code, 200)
# APPLICANT SET ARCHIVE
form_data = {
"archive": "string",
}
response = self.client.post(
reverse("kg_application_unauthenticated", args=[token, "C"]), form_data, follow=False
)
# applicant not allowed to do this
self.assertEqual(response.status_code, 400)
self.client.logout()
# ADMIN ARCHIVE
set_admin()
logged_in = self.client.login(username="kgsuper", password="aq12ws")
self.assertEqual(logged_in, True)
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "C"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "A"])
)
self.client.logout()
set_no_admin()
# APPLICANT GET ARCHIVE
response = self.client.get(reverse("kg_application_unauthenticated", args=[token, "A"]))
self.assertEqual(response.status_code, 200)
person = Person.objects.get(username="jimbob")
self.assertEqual(person.title, "Mr")
self.assertEqual(person.short_name, "Jim")
self.assertEqual(person.full_name, "Jim Bob")
self.assertEqual(person.institute.name, "Example")
self.assertEqual(person.email, "jim.bob@example.com")
self.assertEqual(person.telephone, "4444444")
self.assertEqual(person.approved_by.username, "kgsuper")
self.assertEqual(person.account_set.count(), 0)
self.assertIsNotNone(person.date_approved)
|
class UserApplicationTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_register_account(self):
pass
| 4 | 0 | 74 | 9 | 58 | 7 | 1 | 0.11 | 1 | 4 | 4 | 0 | 3 | 0 | 3 | 3 | 225 | 30 | 175 | 16 | 171 | 20 | 109 | 16 | 105 | 2 | 1 | 1 | 4 |
141,907 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/aed.py
|
karaage.plugins.kgapplications.views.aed.StateApplicantEnteringDetails
|
class StateApplicantEnteringDetails(StateWithSteps):
name = "Applicant entering details."
actions = {"cancel", "duplicate", "reopen", "submit"}
def __init__(self, config):
super(StateApplicantEnteringDetails, self).__init__(config)
self.add_step(StateStepIntroduction(), "intro")
if settings.AAF_RAPID_CONNECT_ENABLED:
self.add_step(StateStepAaf(), "AAF")
self.add_step(StateStepApplicant(), "applicant")
self.add_step(StateStepProject(), "project")
def get_actions(self, request, applications, roles):
actions = set(self.actions)
if "is_applicant" not in roles:
if "submit" in actions:
actions.remove("submit")
return actions
def get_next_action(self, request, application, label, roles):
"""Process the get_next_action request at the current step."""
# if user is logged and and not applicant, steal the
# application
if "is_applicant" in roles:
# if we got this far, then we either we are logged in as applicant,
# or we know the secret for this application.
new_person = None
reason = None
details = None
session_jwt = request.session.get("arc_jwt", None)
saml_id = None
if session_jwt is not None:
attributes = session_jwt["https://aaf.edu.au/attributes"]
saml_id = attributes["edupersontargetedid"]
if saml_id is not None:
query = Person.objects.filter(saml_id=saml_id)
if application.existing_person is not None:
query = query.exclude(pk=application.existing_person.pk)
if query.count() > 0:
new_person = Person.objects.get(saml_id=saml_id)
reason = "AAF id is already in use by existing person."
details = (
"It is not possible to continue this application "
+ "as is because the saml identity already exists "
+ "as a registered user."
)
del query
if request.user.is_authenticated:
new_person = request.user
reason = "%s was logged in and accessed the secret URL." % new_person
details = (
"If you want to access this application "
+ "as %s " % application.applicant
+ "without %s stealing it, " % new_person
+ "you will have to ensure %s is " % new_person
+ "logged out first."
)
if new_person is not None:
if application.applicant != new_person:
if "steal" in request.POST:
old_applicant = application.applicant
application.new_applicant = None
application.existing_person = new_person
application.save()
log.change(application.application_ptr, "Stolen application from %s" % old_applicant)
messages.success(request, "Stolen application from %s" % old_applicant)
url = base.get_url(request, application, roles, label)
return HttpResponseRedirect(url)
else:
return render(
template_name="kgapplications/project_aed_steal.html",
context={
"application": application,
"person": new_person,
"reason": reason,
"details": details,
},
request=request,
)
# if the user is the leader, show him the leader specific page.
if ("is_leader" in roles or "is_delegate" in roles) and "is_admin" not in roles and "is_applicant" not in roles:
actions = ["reopen"]
if "reopen" in request.POST:
return "reopen"
return render(
template_name="kgapplications/project_aed_for_leader.html",
context={
"application": application,
"actions": actions,
"roles": roles,
},
request=request,
)
# otherwise do the default behaviour for StateWithSteps
return super(StateApplicantEnteringDetails, self).get_next_action(request, application, label, roles)
|
class StateApplicantEnteringDetails(StateWithSteps):
def __init__(self, config):
pass
def get_actions(self, request, applications, roles):
pass
def get_next_action(self, request, application, label, roles):
'''Process the get_next_action request at the current step.'''
pass
| 4 | 1 | 32 | 2 | 27 | 2 | 6 | 0.08 | 1 | 8 | 6 | 0 | 3 | 0 | 3 | 11 | 102 | 10 | 85 | 17 | 81 | 7 | 57 | 17 | 53 | 12 | 3 | 4 | 17 |
141,908 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/aed.py
|
karaage.plugins.kgapplications.views.aed.StateStepAaf
|
class StateStepAaf(Step):
"""Invitation has been sent to applicant."""
name = "Invitation sent"
def view(self, request, application, label, roles, actions):
"""Django view method."""
status = None
applicant = application.applicant
session_jwt = request.session.get("arc_jwt", None)
# certain actions are supported regardless of what else happens
if "cancel" in request.POST:
return "cancel"
if "prev" in request.POST:
return "prev"
# test for conditions where shibboleth registration not required
if applicant.saml_id is not None:
status = "You have already registered a AAF id."
form = None
done = True
elif application.existing_person is not None:
status = "You are already registered in the system."
form = None
done = True
elif applicant.institute is not None and applicant.institute.saml_entityid is None:
status = "Your institute does not have AAF registered."
form = None
done = True
elif Institute.objects.filter(saml_entityid__isnull=False).count() == 0:
status = "No institutes support AAF here."
form = None
done = True
else:
# shibboleth registration is required
# Do construct the form
form = aaf_rapid_connect.AafInstituteForm(request.POST or None, initial={"institute": applicant.institute})
done = False
status = None
# Was it a POST request?
if request.method == "POST" and "login" in request.POST and form.is_valid():
institute = form.cleaned_data["institute"]
# if institute supports shibboleth, redirect back here via
# shibboleth, otherwise redirect directly back he.
url = aaf_rapid_connect.build_login_url(request, institute.saml_entityid)
response = HttpResponseRedirect(url)
if institute.saml_entityid is not None:
redirect_to = base.get_url(request, application, roles, label)
response.set_cookie("arc_url", redirect_to)
return response
# if we are done, we can proceed to next state
if request.method == "POST":
if "cancel" in request.POST:
return "cancel"
if "prev" in request.POST:
return "prev"
if not done:
if session_jwt:
applicant = _get_applicant_from_token(session_jwt)
if applicant is None:
applicant = application.applicant
else:
application.new_applicant = None
application.existing_person = applicant
application.save()
status, message = aaf_rapid_connect.add_token_data(applicant, session_jwt)
if status != "OK":
log.comment(application.application_ptr, f"Could not use AAF rapid connect: {message}.")
status = f"Could not use AAF rapid connect: {message}. Please contact support."
else:
done = True
else:
status = "Please login to AAF before proceeding."
if request.method == "POST" and done:
for action in actions:
if action in request.POST:
return action
return HttpResponseBadRequest("<h1>Bad Request</h1>")
# render the page
# did we get a AAF session yet?
if session_jwt:
attrs = session_jwt["https://aaf.edu.au/attributes"]
else:
attrs = None
return render(
template_name="kgapplications/project_aed_shibboleth.html",
context={
"form": form,
"done": done,
"status": status,
"actions": actions,
"roles": roles,
"application": application,
"attrs": attrs,
"session_jwt": session_jwt,
},
request=request,
)
|
class StateStepAaf(Step):
'''Invitation has been sent to applicant.'''
def view(self, request, application, label, roles, actions):
'''Django view method.'''
pass
| 2 | 2 | 108 | 16 | 81 | 11 | 20 | 0.14 | 1 | 3 | 3 | 0 | 1 | 0 | 1 | 2 | 113 | 18 | 83 | 15 | 81 | 12 | 62 | 15 | 60 | 20 | 2 | 4 | 20 |
141,909 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/transitions.py
|
karaage.plugins.kgapplications.views.transitions.TransitionApprove
|
class TransitionApprove(base.Transition):
"""A transition after application fully approved."""
actions = {"password_needed", "password_ok", "error"}
def get_next_action(self, request, application, roles):
"""Retrieve the next state."""
# Check for serious errors in submission.
# Should only happen in rare circumstances.
errors = application.check_valid()
if len(errors) > 0:
for error in errors:
messages.error(request, error)
return "error"
application.extend()
# approve application
try:
approved_by = request.user
with transaction.atomic():
created_person, created_account = application.approve(approved_by)
except Exception as e:
logger.exception("Error approving application")
log.comment(application.application_ptr, f"Error approving application: {e}")
messages.error(request, e)
return "error"
else:
# send email
link, is_secret = base.get_email_link(application)
emails.send_approved_email(application, created_person, created_account, link, is_secret)
if created_person or created_account:
return "password_needed"
else:
return "password_ok"
|
class TransitionApprove(base.Transition):
'''A transition after application fully approved.'''
def get_next_action(self, request, application, roles):
'''Retrieve the next state.'''
pass
| 2 | 2 | 31 | 3 | 23 | 5 | 5 | 0.24 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 5 | 36 | 5 | 25 | 9 | 23 | 6 | 24 | 8 | 22 | 5 | 2 | 2 | 5 |
141,910 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/forms.py
|
karaage.plugins.kgsoftware.forms.SoftwareForm
|
class SoftwareForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=None)
name = forms.CharField()
description = forms.CharField(required=False, widget=forms.Textarea())
homepage = forms.URLField(required=False)
tutorial_url = forms.URLField(required=False)
academic_only = forms.BooleanField(required=False)
restricted = forms.BooleanField(required=False, help_text="Will require admin approval")
def __init__(self, *args, **kwargs):
super(SoftwareForm, self).__init__(*args, **kwargs)
self.fields["category"].queryset = SoftwareCategory.objects.all()
class Meta:
model = Software
fields = [
"category",
"name",
"description",
"homepage",
"tutorial_url",
"academic_only",
"restricted",
]
|
class SoftwareForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
pass
class Meta:
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 1 | 1 | 1 | 0 | 1 | 1 | 24 | 2 | 22 | 12 | 19 | 0 | 14 | 12 | 11 | 1 | 1 | 0 | 1 |
141,911 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/applications/tests/test_applications.py
|
karaage.plugins.kgsoftware.applications.tests.test_applications.SoftwareApplicationTestCase
|
class SoftwareApplicationTestCase(TestCase):
def setUp(self):
call_command("loaddata", "test_karaage", **{"verbosity": 0})
def tearDown(self):
set_admin()
def test_register_software(self):
if django.VERSION >= (1, 9):
url_prefix = ""
else:
url_prefix = "http://testserver"
group = Group.objects.create(name="windows")
software = Software.objects.create(
name="windows",
restricted=True,
group=group,
)
SoftwareLicense.objects.create(
software=software,
version="3.11",
text="You give your soal to the author if you wish to access this software.",
)
set_no_admin()
# APPLICANT LOGS IN
logged_in = self.client.login(username="kgtestuser1", password="aq12ws")
self.assertEqual(logged_in, True)
self.assertEqual(len(mail.outbox), 0)
response = self.client.get(reverse("kg_software_detail", args=[software.pk]))
self.assertEqual(response.status_code, 200)
# OPEN APPLICATION
form_data = {}
response = self.client.post(reverse("kg_software_detail", args=[software.pk]), form_data, follow=True)
self.assertEqual(response.status_code, 200)
application = Application.objects.get()
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "O"])
)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, "TestOrg invitation: access software windows")
self.assertEqual(mail.outbox[0].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[0].to[0], "leader@example.com")
# SUBMIT APPLICATION
form_data = {
"submit": True,
}
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "O"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "K"])
)
self.assertEqual(len(mail.outbox), 2)
self.assertEqual(mail.outbox[1].subject, "TestOrg request: access software windows")
self.assertEqual(mail.outbox[1].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[1].to[0], "sam@vpac.org")
# ADMIN LOGS IN TO APPROVE
set_admin()
logged_in = self.client.login(username="kgsuper", password="aq12ws")
self.assertEqual(logged_in, True)
# ADMIN GET DETAILS
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K"]))
self.assertEqual(response.status_code, 200)
# ADMIN GET DECLINE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K", "cancel"]))
self.assertEqual(response.status_code, 200)
# ADMIN GET APPROVE PAGE
response = self.client.get(reverse("kg_application_detail", args=[application.pk, "K", "approve"]))
self.assertEqual(response.status_code, 200)
# ADMIN APPROVE
form_data = {
"make_leader": False,
"additional_req": "Woof",
"needs_account": False,
"approve": True,
}
response = self.client.post(
reverse("kg_application_detail", args=[application.pk, "K", "approve"]), form_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.redirect_chain[0][0], url_prefix + reverse("kg_application_detail", args=[application.pk, "C"])
)
application = Application.objects.get(pk=application.id)
self.assertEqual(application.state, SoftwareApplication.COMPLETED)
self.assertEqual(len(mail.outbox), 3)
self.assertEqual(mail.outbox[2].subject, "TestOrg approved: access software windows")
self.assertEqual(mail.outbox[2].from_email, settings.ACCOUNTS_EMAIL)
self.assertEqual(mail.outbox[2].to[0], "leader@example.com")
self.client.logout()
set_no_admin()
# test group
groups = Group.objects.filter(name="windows", members__username="kgtestuser1")
self.assertEqual(len(groups), 1)
|
class SoftwareApplicationTestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_register_software(self):
pass
| 4 | 0 | 36 | 5 | 28 | 3 | 1 | 0.11 | 1 | 5 | 5 | 0 | 3 | 0 | 3 | 3 | 110 | 17 | 84 | 12 | 80 | 9 | 58 | 12 | 54 | 2 | 1 | 1 | 4 |
141,912 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/applications/__init__.py
|
karaage.plugins.kgsoftware.applications.plugin
|
class plugin(BasePlugin):
name = "karaage.plugins.kgsoftware.applications"
label = "kgsoftware_applications"
depends = (
"karaage.plugins.kgapplications.plugin",
"karaage.plugins.kgsoftware.plugin",
)
|
class plugin(BasePlugin):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 0 | 7 | 4 | 6 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,913 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/applications/models.py
|
karaage.plugins.kgsoftware.applications.models.SoftwareApplication
|
class SoftwareApplication(Application):
type = "software"
software_license = models.ForeignKey(SoftwareLicense, on_delete=models.CASCADE)
objects = ApplicationManager()
class Meta:
db_table = "applications_softwareapplication"
def info(self):
return six.u("access software %s") % self.software_license.software
def check_valid(self):
errors = super(SoftwareApplication, self).check_valid()
if self.existing_person is None:
errors.append("Applicant not already registered person.")
return errors
def approve(self, approved_by):
created_person = super(SoftwareApplication, self).approve(approved_by)
try:
sla = SoftwareLicenseAgreement.objects.get(
person=self.applicant,
license=self.software_license,
)
except SoftwareLicenseAgreement.DoesNotExist:
sla = SoftwareLicenseAgreement()
sla.person = self.applicant
sla.license = self.software_license
sla.date = datetime.datetime.today()
sla.save()
if self.software_license.software.group is not None:
self.software_license.software.group.add_person(self.applicant)
return created_person
|
class SoftwareApplication(Application):
class Meta:
def info(self):
pass
def check_valid(self):
pass
def approve(self, approved_by):
pass
| 5 | 0 | 9 | 1 | 8 | 0 | 2 | 0 | 1 | 3 | 1 | 0 | 3 | 1 | 3 | 18 | 38 | 9 | 29 | 13 | 24 | 0 | 26 | 12 | 21 | 3 | 2 | 1 | 6 |
141,914 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/applications/migrations/0001_initial.py
|
karaage.plugins.kgsoftware.applications.migrations.0001_initial.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0001_initial"),
("kgsoftware", "0002_auto_20141216_1507"),
]
operations = [
migrations.CreateModel(
name="SoftwareApplication",
fields=[
(
"application_ptr",
models.OneToOneField(
parent_link=True,
auto_created=True,
primary_key=True,
serialize=False,
to="kgapplications.Application",
on_delete=models.CASCADE,
),
),
("software_license", models.ForeignKey(to="kgsoftware.SoftwareLicense", on_delete=models.CASCADE)),
],
options={
"db_table": "applications_softwareapplication",
},
bases=("kgapplications.application",),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 29 | 1 | 28 | 3 | 27 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,915 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/transitions.py
|
karaage.plugins.kgapplications.views.transitions.TransitionSubmit
|
class TransitionSubmit(base.Transition):
"""A transition after application submitted."""
actions = {"success", "error"}
def get_next_action(self, request, application, roles):
"""Retrieve the next state."""
# Check for serious errors in submission.
# Should only happen in rare circumstances.
errors = application.check_valid()
if len(errors) > 0:
for error in errors:
messages.error(request, error)
return "error"
# mark as submitted
application.submit()
return "success"
|
class TransitionSubmit(base.Transition):
'''A transition after application submitted.'''
def get_next_action(self, request, application, roles):
'''Retrieve the next state.'''
pass
| 2 | 2 | 15 | 3 | 8 | 4 | 3 | 0.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 20 | 5 | 10 | 5 | 8 | 5 | 10 | 5 | 8 | 3 | 2 | 2 | 3 |
141,916 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/views/transitions.py
|
karaage.plugins.kgapplications.views.transitions.TransitionSplit
|
class TransitionSplit(base.Transition):
"""A transition after application submitted."""
actions = {"existing_project", "new_project", "error"}
def get_next_action(self, request, application, roles):
"""Retrieve the next state."""
# Do we need to wait for leader or delegate approval?
if application.project is None:
return "new_project"
else:
return "existing_project"
|
class TransitionSplit(base.Transition):
'''A transition after application submitted.'''
def get_next_action(self, request, application, roles):
'''Retrieve the next state.'''
pass
| 2 | 2 | 7 | 0 | 5 | 2 | 2 | 0.43 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 12 | 2 | 7 | 3 | 5 | 3 | 6 | 3 | 4 | 2 | 2 | 1 | 2 |
141,917 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgsoftware/forms.py
|
karaage.plugins.kgsoftware.forms.AddPackageForm
|
class AddPackageForm(SoftwareForm):
group_name = forms.RegexField(
"^%s$" % settings.GROUP_VALIDATION_RE,
required=True,
error_messages={"invalid": settings.GROUP_VALIDATION_ERROR_MSG},
)
version = forms.CharField()
module = forms.CharField(required=False)
machines = forms.ModelMultipleChoiceField(queryset=None)
license_version = forms.CharField(required=False)
license_date = forms.DateField(required=False)
license_text = forms.CharField(required=False, widget=forms.Textarea())
def __init__(self, *args, **kwargs):
super(AddPackageForm, self).__init__(*args, **kwargs)
self.fields["machines"].queryset = Machine.active.all()
def clean(self):
data = self.cleaned_data
if "license_version" in data and data["license_version"]:
if (
not data["license_version"]
or "license_date" not in data
or not data["license_date"]
or "license_text" not in data
or not data["license_text"]
):
raise forms.ValidationError(six.u("You must specify all fields in the license section"))
return data
def save(self, commit=True):
assert commit is True
data = self.cleaned_data
software = super(AddPackageForm, self).save(commit=False)
name = self.cleaned_data["group_name"]
software.group, _ = Group.objects.get_or_create(name=name)
software.save()
version = SoftwareVersion(
software=software,
version=data["version"],
module=data["module"],
)
version.save()
version.machines.set(data["machines"])
if data["license_version"]:
SoftwareLicense.objects.create(
software=software,
version=data["license_version"],
date=data["license_date"],
text=data["license_text"],
)
return software
|
class AddPackageForm(SoftwareForm):
def __init__(self, *args, **kwargs):
pass
def clean(self):
pass
def save(self, commit=True):
pass
| 4 | 0 | 15 | 2 | 12 | 0 | 2 | 0 | 1 | 5 | 4 | 0 | 3 | 0 | 3 | 4 | 59 | 10 | 49 | 17 | 45 | 0 | 30 | 17 | 26 | 3 | 2 | 2 | 6 |
141,918 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0005_auto_20180302_1808.py
|
karaage.plugins.kgapplications.migrations.0005_auto_20180302_1808.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0004_auto_20180301_1721"),
]
operations = [
migrations.AlterField(
model_name="application",
name="created_by",
field=models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 18 | 1 | 17 | 3 | 16 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,919 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0006_auto_20190312_0805.py
|
karaage.plugins.kgapplications.migrations.0006_auto_20190312_0805.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0005_auto_20180302_1808"),
]
operations = [
migrations.AlterField(
model_name="applicant",
name="saml_id",
field=models.CharField(blank=True, editable=False, max_length=200, null=True),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 1 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,920 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/plugins/kgapplications/migrations/0003_remove_projectapplication_machine_categories.py
|
karaage.plugins.kgapplications.migrations.0003_remove_projectapplication_machine_categories.Migration
|
class Migration(migrations.Migration):
dependencies = [
("kgapplications", "0002_auto_20161007_1821"),
("karaage", "0004_auto_20160429_0927"),
]
run_before = [
("karaage", "0005_auto_20171215_1831"),
]
operations = [
migrations.RemoveField(
model_name="projectapplication",
name="machine_categories",
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 16 | 2 | 14 | 4 | 13 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
141,921 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/datastores/mam.py
|
karaage.datastores.mam.MamDataStore72
|
class MamDataStore72(MamDataStoreBase):
version = "7.2"
def _get_project_cmd(self, projectname):
cmd = ["glsaccount", "-a", projectname, "--raw"]
return cmd
def _create_user(self, username, default_project_name):
self._call(["gmkuser", "-A", "-a", default_project_name, "-u", username])
def _set_user_default_project(self, username, default_project_name):
self._call(["gchuser", "-a", default_project_name, "-u", username])
def add_account_to_project(self, account, project):
"""Add account to project."""
username = account.username
projectname = project.pid
self._call(["gchaccount", "--add-user", username, "-a", projectname], ignore_errors=[74])
def remove_account_from_project(self, account, project):
"""Remove account from project."""
username = account.username
projectname = project.pid
self._call(["gchaccount", "--del-users", username, "-a", projectname])
def _create_project(self, pid):
self._call(["gmkaccount", "-a", pid, "-u", "MEMBERS"])
def _set_project(self, pid, description, institute):
self._call(["gchaccount", "-d", self._filter_string(description), "-a", pid])
self._call(["gchaccount", "-X", "Organization=%s" % self._filter_string(institute.name), "-a", pid])
def _delete_project(self, pid):
self._call(["grmaccount", "-a", pid])
|
class MamDataStore72(MamDataStoreBase):
def _get_project_cmd(self, projectname):
pass
def _create_user(self, username, default_project_name):
pass
def _set_user_default_project(self, username, default_project_name):
pass
def add_account_to_project(self, account, project):
'''Add account to project.'''
pass
def remove_account_from_project(self, account, project):
'''Remove account from project.'''
pass
def _create_project(self, pid):
pass
def _set_project(self, pid, description, institute):
pass
def _delete_project(self, pid):
pass
| 9 | 2 | 3 | 0 | 3 | 0 | 1 | 0.08 | 1 | 0 | 0 | 0 | 8 | 0 | 8 | 69 | 34 | 8 | 24 | 15 | 15 | 2 | 24 | 15 | 15 | 1 | 3 | 0 | 8 |
141,922 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/datastores/slurm.py
|
karaage.datastores.slurm.SlurmDataStore
|
class SlurmDataStore(base.DataStore):
"""Slurm datastore."""
def __init__(self, config):
super(SlurmDataStore, self).__init__(config)
self._prefix = config.get("PREFIX", ["sudo", "-uslurm"])
self._path = config.get("PATH", "/usr/local/slurm/latest/bin/sacctmgr")
self._null_project = config.get("NULL_PROJECT", "default")
self._add_account_extra = config.get("ADD_ACCOUNT_EXTRA", ["grpcpumins=0"])
@staticmethod
def _filter_string(value):
"""Filter the string so Gold doesn't have heart failure."""
if value is None:
value = ""
# replace whitespace with space
value = value.replace("\n", " ")
value = value.replace("\t", " ")
# CSV seperator
value = value.replace("|", " ")
# remove leading/trailing whitespace
value = value.strip()
# Used for stripping non-ascii characters
value = "".join(c for c in value if 31 < ord(c) < 127)
return value
@staticmethod
def _truncate(value, arg):
"""
Truncates a string after a given number of chars
Argument: Number of chars to _truncate after
"""
length = int(arg)
if value is None:
value = ""
if len(value) > length:
return value[:length] + "..."
else:
return value
def _call(self, command, ignore_errors=None):
"""Call remote command with logging."""
if ignore_errors is None:
ignore_errors = []
cmd = []
cmd.extend(self._prefix)
cmd.extend([self._path, "-iP"])
cmd.extend(command)
command = cmd
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
retcode = process.returncode
logger.debug(f"<-- stdout: {stdout}")
logger.debug(f"<-- stderr: {stderr}")
if retcode in ignore_errors:
logger.debug("<-- Cmd %s returned %d (ignored)" % (command, retcode))
return
if retcode:
logger.error("<-- Cmd %s returned: %d (error)" % (command, retcode))
raise subprocess.CalledProcessError(retcode, command)
logger.debug("<-- Returned %d (good)" % retcode)
return
def _read_output(self, command):
"""Read CSV delimited input from Slurm."""
cmd = []
cmd.extend(self._prefix)
cmd.extend([self._path, "-iP"])
cmd.extend(command)
command = cmd
logger.debug("Cmd %s" % command)
null = open("/dev/null", "w")
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=null)
null.close()
results = []
reader = csv.reader(_input_csv(process.stdout), delimiter=str("|"))
try:
headers = next(reader)
logger.debug("<-- headers %s" % headers)
except StopIteration:
logger.debug("Cmd %s headers not found" % command)
headers = []
for row in reader:
_output_csv(row)
logger.debug("<-- row %s" % row)
this_row = {}
i = 0
for i in range(0, len(headers)):
key = headers[i]
value = row[i]
this_row[key] = value
results.append(this_row)
process.stdout.close()
retcode = process.wait()
if retcode != 0:
logger.error("<-- Cmd %s returned %d (error)" % (command, retcode))
raise subprocess.CalledProcessError(retcode, command)
if len(headers) == 0:
logger.error("Cmd %s didn't return any headers." % command)
raise RuntimeError("Cmd %s didn't return any headers." % command)
logger.debug("<-- Returned: %d (good)" % retcode)
return results
def get_user(self, username):
"""Get the user details from Slurm."""
cmd = ["list", "user", "where", "name=%s" % username]
results = self._read_output(cmd)
if len(results) == 0:
return None
elif len(results) > 1:
logger.error("Command returned multiple results for '%s'." % username)
raise RuntimeError("Command returned multiple results for '%s'." % username)
the_result = results[0]
the_name = the_result["User"]
if username.lower() != the_name.lower():
logger.error("We expected username '%s' but got username '%s'." % (username, the_name))
raise RuntimeError("We expected username '%s' but got username '%s'." % (username, the_name))
return the_result
def get_project(self, projectname):
"""Get the project details from Slurm."""
cmd = ["list", "accounts", "where", "name=%s" % projectname]
results = self._read_output(cmd)
if len(results) == 0:
return None
elif len(results) > 1:
logger.error("Command returned multiple results for '%s'." % projectname)
raise RuntimeError("Command returned multiple results for '%s'." % projectname)
the_result = results[0]
the_project = the_result["Account"]
if projectname.lower() != the_project.lower():
logger.error("We expected projectname '%s' but got projectname '%s'." % (projectname, the_project))
raise RuntimeError("We expected projectname '%s' but got projectname '%s'." % (projectname, the_project))
return the_result
def get_users_in_project(self, projectname):
"""Get list of users in project from Slurm."""
cmd = ["list", "assoc", "where", "account=%s" % projectname]
results = self._read_output(cmd)
user_list = []
for result in results:
if result["User"] != "":
user_list.append(result["User"])
return user_list
def get_projects_in_user(self, username):
"""Get list of projects in user from Slurm."""
cmd = ["list", "assoc", "where", "user=%s" % username]
results = self._read_output(cmd)
project_list = []
for result in results:
project_list.append(result["Account"])
return project_list
def is_user_in_project(self, username, projectname):
cmd = ["list", "assoc", "where", "user=%s" % username, "account=%s" % projectname]
results = self._read_output(cmd)
return len(results) > 0
def _save_account(self, account, username):
"""Called when account is created/updated. With username override."""
# retrieve default project, or use null project if none
default_project_name = self._null_project
if account.default_project is not None:
default_project_name = account.default_project.pid
# account created
# account updated
ds_user = self.get_user(username)
if account.date_deleted is None:
# date_deleted is not set, user should exist
logger.debug("account is active")
if ds_user is None:
# create user if doesn't exist
self._call(
[
"add",
"user",
"accounts=%s" % default_project_name,
"defaultaccount=%s" % default_project_name,
"name=%s" % username,
]
)
else:
# or just set default project
self._call(
["modify", "user", "set", "defaultaccount=%s" % default_project_name, "where", "name=%s" % username]
)
# update user meta information
# add rest of projects user belongs to
slurm_projects = self.get_projects_in_user(username)
slurm_projects = [project.lower() for project in slurm_projects]
slurm_projects = set(slurm_projects)
for project in account.person.projects.all():
if project.pid.lower() not in slurm_projects:
self._call(["add", "user", "name=%s" % username, "accounts=%s" % project.pid])
else:
# date_deleted is not set, user should not exist
logger.debug("account is not active")
self._delete_account(username)
return
def save_account(self, account):
"""Called when account is created/updated."""
self._save_account(account, account.username)
def _delete_account(self, username):
"""Called when account is deleted. With username override."""
# account deleted
ds_user = self.get_user(username)
if ds_user is not None:
self._call(["delete", "user", "name=%s" % username])
return
def delete_account(self, account):
"""Called when account is deleted."""
self._delete_account(account.username)
def set_account_password(self, account, raw_password):
"""Account's password was changed."""
pass
def set_account_username(self, account, old_username, new_username):
"""Account's username was changed."""
self._delete_account(old_username)
self._save_account(account, new_username)
def add_account_to_project(self, account, project):
"""Add account to project."""
username = account.username
projectname = project.pid
if not self.is_user_in_project(username, projectname):
self._call(["add", "user", "accounts=%s" % projectname, "name=%s" % username])
def remove_account_from_project(self, account, project):
"""Remove account from project."""
username = account.username
projectname = project.pid
if self.is_user_in_project(username, projectname):
self._call(["delete", "user", "name=%s" % username, "account=%s" % projectname])
def account_exists(self, username):
"""Does the account exist?"""
ds_user = self.get_user(username)
return ds_user is not None
def get_account_details(self, account):
"""Get the account details"""
result = self.get_user(account.username)
if result is None:
result = {}
return result
def save_group(self, group):
"""Group was saved."""
pass
def delete_group(self, group):
"""Group was deleted."""
pass
def set_group_name(self, group, old_name, new_name):
"""Group was renamed."""
pass
def save_project(self, project):
"""Called when project is saved/updated."""
pid = project.pid
# project created
# project updated
if project.is_active:
# project is not deleted
logger.debug("project is active")
ds_project = self.get_project(pid)
if ds_project is None:
self._call(["add", "account", "name=%s" % pid] + self._add_account_extra)
# update project meta information
name = self._truncate(project.name, 40)
self._call(
["modify", "account", "set", "Description=%s" % self._filter_string(name), "where", "name=%s" % pid]
)
self._call(
[
"modify",
"account",
"set",
"Organization=%s" % self._filter_string(project.institute.name),
"where",
"name=%s" % pid,
]
)
else:
# project is deleted
logger.debug("project is not active")
ds_project = self.get_project(pid)
if ds_project is not None:
self._call(["delete", "account", "name=%s" % pid])
return
def delete_project(self, project):
"""Called when project is deleted."""
pid = project.pid
# project deleted
ds_project = self.get_project(pid)
if ds_project is not None:
self._call(["delete", "account", "name=%s" % pid])
return
def get_project_details(self, project):
"""Get the project details."""
result = self.get_project(project.pid)
if result is None:
result = {}
return result
def set_project_pid(self, project, old_pid, new_pid):
"""Project's pid was changed."""
# FIXME
return
|
class SlurmDataStore(base.DataStore):
'''Slurm datastore.'''
def __init__(self, config):
pass
@staticmethod
def _filter_string(value):
'''Filter the string so Gold doesn't have heart failure.'''
pass
@staticmethod
def _truncate(value, arg):
'''
Truncates a string after a given number of chars
Argument: Number of chars to _truncate after
'''
pass
def _call(self, command, ignore_errors=None):
'''Call remote command with logging.'''
pass
def _read_output(self, command):
'''Read CSV delimited input from Slurm.'''
pass
def get_user(self, username):
'''Get the user details from Slurm.'''
pass
def get_project(self, projectname):
'''Get the project details from Slurm.'''
pass
def get_users_in_project(self, projectname):
'''Get list of users in project from Slurm.'''
pass
def get_projects_in_user(self, username):
'''Get list of projects in user from Slurm.'''
pass
def is_user_in_project(self, username, projectname):
pass
def _save_account(self, account, username):
'''Called when account is created/updated. With username override.'''
pass
def save_account(self, account):
'''Called when account is created/updated.'''
pass
def _delete_account(self, username):
'''Called when account is deleted. With username override.'''
pass
def delete_account(self, account):
'''Called when account is deleted.'''
pass
def set_account_password(self, account, raw_password):
'''Account's password was changed.'''
pass
def set_account_username(self, account, old_username, new_username):
'''Account's username was changed.'''
pass
def add_account_to_project(self, account, project):
'''Add account to project.'''
pass
def remove_account_from_project(self, account, project):
'''Remove account from project.'''
pass
def account_exists(self, username):
'''Does the account exist?'''
pass
def get_account_details(self, account):
'''Get the account details'''
pass
def save_group(self, group):
'''Group was saved.'''
pass
def delete_group(self, group):
'''Group was deleted.'''
pass
def set_group_name(self, group, old_name, new_name):
'''Group was renamed.'''
pass
def save_project(self, project):
'''Called when project is saved/updated.'''
pass
def delete_project(self, project):
'''Called when project is deleted.'''
pass
def get_project_details(self, project):
'''Get the project details.'''
pass
def set_project_pid(self, project, old_pid, new_pid):
'''Project's pid was changed.'''
pass
| 30 | 26 | 12 | 2 | 9 | 2 | 2 | 0.21 | 1 | 9 | 0 | 0 | 25 | 4 | 27 | 51 | 363 | 72 | 241 | 85 | 211 | 50 | 212 | 83 | 184 | 6 | 2 | 3 | 61 |
141,923 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/emails/forms.py
|
karaage.emails.forms.BulkEmailForm
|
class BulkEmailForm(EmailForm):
group = forms.ChoiceField(choices=EMAIL_GROUPS)
institute = AutoCompleteSelectField("institute", required=False, label="Institute")
project = AutoCompleteSelectField("project", required=False, label="Project")
def get_person_query(self):
person_query = Person.active.all()
group = self.cleaned_data["group"]
if group == "leaders":
person_query = person_query.filter(leads__isnull=False)
elif group == "users":
pass
elif group == "cluster_users":
person_query = person_query.filter(account__isnull=False)
else:
person_query = None
institute = self.cleaned_data["institute"]
if institute is not None:
person_query = person_query.filter(institute=institute)
project = self.cleaned_data["project"]
if project is not None:
person_query = person_query.filter(groups__project=project)
return person_query
|
class BulkEmailForm(EmailForm):
def get_person_query(self):
pass
| 2 | 0 | 25 | 7 | 18 | 0 | 6 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 2 | 30 | 8 | 22 | 9 | 20 | 0 | 19 | 9 | 17 | 6 | 2 | 1 | 6 |
141,924 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/emails/forms.py
|
karaage.emails.forms.EmailForm
|
class EmailForm(forms.Form):
subject = forms.CharField(widget=forms.TextInput(attrs={"size": 60}))
body = forms.CharField(widget=forms.Textarea(attrs={"class": "vLargeTextField", "rows": 10, "cols": 40}))
def get_data(self):
return self.cleaned_data["subject"], self.cleaned_data["body"]
|
class EmailForm(forms.Form):
def get_data(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 1 | 0 | 1 |
141,925 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/institutes/forms.py
|
karaage.institutes.forms.InstituteForm
|
class InstituteForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(InstituteForm, self).__init__(*args, **kwargs)
if self.instance.group_id is None:
self.fields["group_name"] = forms.RegexField(
"^%s$" % settings.GROUP_VALIDATION_RE,
required=True,
error_messages={"invalid": settings.GROUP_VALIDATION_ERROR_MSG},
)
def clean_saml_entityid(self):
if self.cleaned_data["saml_entityid"] == "":
return None
return self.cleaned_data["saml_entityid"]
class Meta:
model = Institute
fields = ("name", "project_prefix", "saml_entityid", "saml_scoped_affiliation", "is_active")
def clean_name(self):
name = self.cleaned_data["name"]
try:
Project.objects.get(pid=name)
raise forms.ValidationError(six.u("Institute name already in system"))
except Project.DoesNotExist:
return name
def save(self, commit=True):
institute = super(InstituteForm, self).save(commit=False)
if institute.group_id is None:
name = self.cleaned_data["group_name"]
institute.group, _ = Group.objects.get_or_create(name=name)
if commit:
institute.save()
return institute
|
class InstituteForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
pass
def clean_saml_entityid(self):
pass
class Meta:
def clean_name(self):
pass
def save(self, commit=True):
pass
| 6 | 0 | 7 | 0 | 7 | 0 | 2 | 0 | 1 | 3 | 2 | 0 | 4 | 0 | 4 | 4 | 35 | 4 | 31 | 12 | 25 | 0 | 27 | 12 | 21 | 3 | 1 | 1 | 9 |
141,926 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/institutes/lookups.py
|
karaage.institutes.lookups.InstituteLookup
|
class InstituteLookup(LookupChannel):
model = Institute
def get_query(self, q, request):
"""return a query set searching for the query string q
either implement this method yourself or set the search_field
in the LookupChannel class definition
"""
return Institute.objects.filter(Q(name__icontains=q))
def get_result(self, obj):
"""
result is the simple text that is the completion of what the person
typed
"""
return obj.name
def format_match(self, obj):
"""
(HTML) formatted item for display in the dropdown
"""
return escape(six.u("%s") % obj)
def format_item_display(self, obj):
"""
(HTML) formatted item for displaying item in the selected deck area
"""
return escape(six.u("%s") % obj)
|
class InstituteLookup(LookupChannel):
def get_query(self, q, request):
'''return a query set searching for the query string q
either implement this method yourself or set the search_field
in the LookupChannel class definition
'''
pass
def get_result(self, obj):
'''
result is the simple text that is the completion of what the person
typed
'''
pass
def format_match(self, obj):
'''
(HTML) formatted item for display in the dropdown
'''
pass
def format_item_display(self, obj):
'''
(HTML) formatted item for displaying item in the selected deck area
'''
pass
| 5 | 4 | 6 | 0 | 2 | 4 | 1 | 1.4 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 5 | 28 | 4 | 10 | 6 | 5 | 14 | 10 | 6 | 5 | 1 | 2 | 0 | 4 |
141,927 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/institutes/managers.py
|
karaage.institutes.managers.ActiveInstituteManager
|
class ActiveInstituteManager(models.Manager):
"""
Returns only 'active' institutes.
"""
def get_queryset(self):
query = super(ActiveInstituteManager, self).get_queryset()
return query.filter(is_active=True)
|
class ActiveInstituteManager(models.Manager):
'''
Returns only 'active' institutes.
'''
def get_queryset(self):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.75 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 8 | 1 | 4 | 3 | 2 | 3 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
141,928 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/institutes/models.py
|
karaage.institutes.models.Institute
|
class Institute(TrackingModelMixin, models.Model):
name = models.CharField(max_length=255, unique=True)
project_prefix = models.CharField(max_length=4, validators=[RegexValidator(r"^[a-zA-Z]{4}$")])
delegates = models.ManyToManyField(Person, related_name="delegate_for", blank=True, through="InstituteDelegate")
group = models.ForeignKey(Group, on_delete=models.PROTECT)
saml_scoped_affiliation = models.CharField(max_length=200, null=True, blank=True, unique=True)
saml_entityid = models.CharField(max_length=200, null=True, blank=True, unique=True)
is_active = models.BooleanField(default=True)
objects = models.Manager()
active = ActiveInstituteManager()
class Meta:
ordering = ["name"]
db_table = "institute"
app_label = "karaage"
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
# save the object
super(Institute, self).save(*args, **kwargs)
if created:
log.add(self, "Created")
for field in changed.keys():
log.change(self, "Changed %s to %s" % (field, getattr(self, field)))
# update the datastore
from karaage.datastores import save_institute
save_institute(self)
# has group changed?
if "group_id" in changed:
old_group_pk = changed.get("group_id")
new_group = self.group
if old_group_pk is not None:
old_group = Group.objects.get(pk=old_group_pk)
from karaage.datastores import remove_accounts_from_institute
query = Account.objects.filter(person__groups=old_group)
remove_accounts_from_institute(query, self)
if new_group is not None:
from karaage.datastores import add_accounts_to_institute
query = Account.objects.filter(person__groups=new_group)
add_accounts_to_institute(query, self)
save.alters_data = True
def delete(self, *args, **kwargs):
# Get list of accounts.
# This must happen before we call the super method,
# as this will delete accounts that use this institute.
old_group_pk = self.tracker.changed.get("group_id", self.group_id)
if old_group_pk is not None:
old_group = Group.objects.get(pk=old_group_pk)
query = Account.objects.filter(person__groups=old_group)
query = query.filter(date_deleted__isnull=True)
accounts = list(query)
else:
accounts = []
# delete the object
log.delete(self, "Deleted")
super(Institute, self).delete(*args, **kwargs)
# update datastore associations
for account in accounts:
from karaage.datastores import remove_account_from_institute
remove_account_from_institute(account, self)
# update the datastore
from karaage.datastores import delete_institute
delete_institute(self)
delete.alters_data = True
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("kg_institute_detail", args=[self.id])
def can_view(self, request):
person = request.user
if not person.is_authenticated:
return False
# staff members can view everything
if is_admin(request):
return True
if not self.is_active:
return False
if not person.is_active:
return False
if person.is_locked():
return False
# Institute delegates==person can view institute
if person in self.delegates.all():
return True
return False
|
class Institute(TrackingModelMixin, models.Model):
class Meta:
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
def __str__(self):
pass
def get_absolute_url(self):
pass
def can_view(self, request):
pass
| 7 | 0 | 18 | 4 | 12 | 2 | 4 | 0.14 | 2 | 5 | 3 | 0 | 5 | 0 | 5 | 5 | 114 | 27 | 76 | 36 | 64 | 11 | 74 | 36 | 62 | 7 | 1 | 2 | 19 |
141,929 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/institutes/models.py
|
karaage.institutes.models.InstituteDelegate
|
class InstituteDelegate(TrackingModelMixin, models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
institute = models.ForeignKey(Institute, on_delete=models.CASCADE)
send_email = models.BooleanField()
class Meta:
db_table = "institutedelegate"
app_label = "karaage"
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
super(InstituteDelegate, self).save(*args, **kwargs)
for field in changed.keys():
log.change(self.institute, "Delegate %s: Changed %s to %s" % (self.person, field, getattr(self, field)))
def delete(self, *args, **kwargs):
super(InstituteDelegate, self).delete(*args, **kwargs)
log.delete(self.institute, "Delegate %s: Deleted" % self.person)
|
class InstituteDelegate(TrackingModelMixin, models.Model):
class Meta:
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
| 4 | 0 | 8 | 2 | 6 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 2 | 2 | 25 | 6 | 19 | 11 | 15 | 0 | 18 | 11 | 14 | 3 | 1 | 1 | 4 |
141,930 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/institutes/tables.py
|
karaage.institutes.tables.InstituteTable
|
class InstituteTable(tables.Table):
is_active = tables.Column(order_by="-is_active", verbose_name="active")
name = tables.LinkColumn("kg_institute_detail", args=[A("pk")])
delegates = PeopleColumn(orderable=False)
def render_is_active(self, record):
if not record.is_active:
html = '<span class="no">Deleted</span>'
else:
html = '<span class="yes">Yes</span>'
return mark_safe(html)
class Meta:
model = Institute
fields = ("is_active", "name")
empty_text = "No items"
|
class InstituteTable(tables.Table):
def render_is_active(self, record):
pass
class Meta:
| 3 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 16 | 2 | 14 | 10 | 11 | 0 | 13 | 10 | 10 | 2 | 1 | 1 | 2 |
141,931 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/datastores/mam.py
|
karaage.datastores.mam.MamDataStore71
|
class MamDataStore71(MamDataStoreBase):
version = "7.1"
def _get_project_cmd(self, projectname):
cmd = ["glsproject", "-p", projectname, "--raw"]
return cmd
def _create_user(self, username, default_project_name):
self._call(["gmkuser", "-A", "-p", default_project_name, "-u", username])
def _set_user_default_project(self, username, default_project_name):
self._call(["gchuser", "-p", default_project_name, "-u", username])
def add_account_to_project(self, account, project):
"""Add account to project."""
username = account.username
projectname = project.pid
self._call(["gchproject", "--add-user", username, "-p", projectname], ignore_errors=[74])
def remove_account_from_project(self, account, project):
"""Remove account from project."""
username = account.username
projectname = project.pid
self._call(["gchproject", "--del-users", username, "-p", projectname])
def _create_project(self, pid):
self._call(["gmkproject", "-p", pid, "-u", "MEMBERS"])
def _set_project(self, pid, description, institute):
self._call(["gchproject", "-d", self._filter_string(description), "-p", pid])
self._call(["gchproject", "-X", "Organization=%s" % self._filter_string(institute.name), "-p", pid])
def _delete_project(self, pid):
self._call(["grmproject", "-p", pid])
|
class MamDataStore71(MamDataStoreBase):
def _get_project_cmd(self, projectname):
pass
def _create_user(self, username, default_project_name):
pass
def _set_user_default_project(self, username, default_project_name):
pass
def add_account_to_project(self, account, project):
'''Add account to project.'''
pass
def remove_account_from_project(self, account, project):
'''Remove account from project.'''
pass
def _create_project(self, pid):
pass
def _set_project(self, pid, description, institute):
pass
def _delete_project(self, pid):
pass
| 9 | 2 | 3 | 0 | 3 | 0 | 1 | 0.08 | 1 | 0 | 0 | 0 | 8 | 0 | 8 | 69 | 34 | 8 | 24 | 15 | 15 | 2 | 24 | 15 | 15 | 1 | 3 | 0 | 8 |
141,932 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/logging.py
|
karaage.logging.FileHandler
|
class FileHandler(logging.FileHandler):
def __init__(self, filename, owner=None, **kwargs):
if owner:
if not os.path.exists(filename):
open(filename, "a").close()
uid = pwd.getpwnam(owner[0]).pw_uid
gid = grp.getgrnam(owner[1]).gr_gid
try:
os.chown(filename, uid, gid)
except OSError as ex:
if ex.errno != errno.EPERM:
raise
super(FileHandler, self).__init__(filename=filename, **kwargs)
|
class FileHandler(logging.FileHandler):
def __init__(self, filename, owner=None, **kwargs):
pass
| 2 | 0 | 12 | 0 | 12 | 0 | 5 | 0 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 31 | 13 | 0 | 13 | 5 | 11 | 0 | 13 | 4 | 11 | 5 | 5 | 3 | 5 |
141,933 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/forms.py
|
karaage.machines.forms.AdminAccountForm
|
class AdminAccountForm(forms.ModelForm):
username = forms.CharField(
label=six.u("Requested username"),
max_length=settings.USERNAME_MAX_LENGTH,
help_text=(
(settings.USERNAME_VALIDATION_ERROR_MSG + " and has a max length of %s.") % settings.USERNAME_MAX_LENGTH
),
)
default_project = ajax_select.fields.AutoCompleteSelectField("project", required=True)
shell = forms.ChoiceField(choices=settings.SHELLS)
def __init__(self, person, **kwargs):
self.person = person
super(AdminAccountForm, self).__init__(**kwargs)
self.old_username = self.instance.username
def clean_username(self):
username = self.cleaned_data["username"]
try:
validate_username_for_new_account(self.person, username)
except UsernameException as e:
raise forms.ValidationError(e.args[0])
return username
def clean_default_project(self):
data = self.cleaned_data
if "default_project" not in data:
return data
default_project = data["default_project"]
query = self.person.projects.filter(pk=default_project.pk)
if query.count() == 0:
raise forms.ValidationError(six.u("Person does not belong to default project."))
return default_project
def clean(self):
data = self.cleaned_data
if "username" not in data:
return data
username = data["username"]
if self.old_username is None or self.old_username != username:
try:
check_username_for_new_account(self.person, username)
except UsernameException as e:
raise forms.ValidationError(e.args[0])
return data
def save(self, **kwargs):
if self.instance.pk is None:
self.instance.person = self.person
self.instance.date_created = datetime.date.today()
return super(AdminAccountForm, self).save(**kwargs)
class Meta:
model = Account
fields = ("username", "default_project", "disk_quota", "shell")
|
class AdminAccountForm(forms.ModelForm):
def __init__(self, person, **kwargs):
pass
def clean_username(self):
pass
def clean_default_project(self):
pass
def clean_username(self):
pass
def save(self, **kwargs):
pass
class Meta:
| 7 | 0 | 8 | 1 | 7 | 0 | 2 | 0 | 1 | 3 | 1 | 0 | 5 | 2 | 5 | 5 | 59 | 10 | 49 | 22 | 42 | 0 | 43 | 20 | 36 | 4 | 1 | 2 | 12 |
141,934 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/managers.py
|
karaage.machines.managers.ActiveMachineManager
|
class ActiveMachineManager(MachineManager):
def get_queryset(self):
return super(ActiveMachineManager, self).get_queryset().filter(end_date__isnull=True)
|
class ActiveMachineManager(MachineManager):
def get_queryset(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 2 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
141,935 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/managers.py
|
karaage.machines.managers.MachineManager
|
class MachineManager(BaseUserManager):
def authenticate(self, machine_name, password):
try:
machine = self.get(name=machine_name)
except self.model.DoesNotExist:
return None
if not machine.check_password(password):
return None
return machine
|
class MachineManager(BaseUserManager):
def authenticate(self, machine_name, password):
pass
| 2 | 0 | 8 | 0 | 8 | 0 | 3 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 9 | 0 | 9 | 3 | 7 | 0 | 9 | 3 | 7 | 3 | 1 | 1 | 3 |
141,936 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/models.py
|
karaage.machines.models.Account
|
class Account(TrackingModelMixin, models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
username = models.CharField(max_length=255)
foreign_id = models.CharField(
max_length=255, null=True, unique=True, help_text="The foreign identifier from the datastore."
)
default_project = models.ForeignKey("karaage.Project", null=True, blank=True, on_delete=models.SET_NULL)
date_created = models.DateField()
date_deleted = models.DateField(null=True, blank=True)
disk_quota = models.IntegerField(null=True, blank=True, help_text="In GB")
shell = models.CharField(max_length=50)
login_enabled = models.BooleanField(default=True)
extra_data = models.JSONField(
default=dict, blank=True, help_text="Datastore specific values should be stored in this field."
)
def __init__(self, *args, **kwargs):
super(Account, self).__init__(*args, **kwargs)
self._password = None
class Meta:
ordering = [
"person",
]
db_table = "account"
app_label = "karaage"
def __str__(self):
return "%s" % self.username
def get_absolute_url(self):
return reverse("kg_account_detail", args=[self.pk])
@classmethod
def create(cls, person, default_project):
"""Creates a Account (if needed) and activates person."""
ua = Account.objects.create(
person=person,
username=person.username,
shell=settings.DEFAULT_SHELL,
default_project=default_project,
date_created=datetime.datetime.today(),
)
if default_project is not None:
person.add_group(default_project.group)
return ua
def project_list(self):
return self.person.projects.all()
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
# save the object
super(Account, self).save(*args, **kwargs)
if created:
log.add(self.person, "Account %s: Created" % self)
for field in changed.keys():
if field != "password":
log.change(self.person, "Account %s: Changed %s to %s" % (self, field, getattr(self, field)))
# check if it was renamed
if "username" in changed:
old_username = changed["username"]
if old_username is not None:
new_username = self.username
if self.date_deleted is None:
from karaage.datastores import set_account_username
set_account_username(self, old_username, new_username)
log.change(
self.person, "Account %s: Changed username from %s to %s" % (self, old_username, new_username)
)
# check if deleted status changed
if "date_deleted" in changed:
if self.date_deleted is not None:
# account is deactivated
from karaage.datastores import delete_account
delete_account(self)
log.delete(self.person, "Account %s: Deactivated account" % self)
# deleted
else:
# account is reactivated
log.add(self.person, "Account %s: Activated" % self)
# makes sense to lock non-existant account
if self.date_deleted is not None:
self.login_enabled = False
# update the datastore
if self.date_deleted is None:
from karaage.datastores import save_account
save_account(self)
if self._password is not None:
from karaage.datastores import set_account_password
set_account_password(self, self._password)
log.change(self.person, "Account %s: Changed Password" % self)
self._password = None
save.alters_data = True
def can_view(self, request):
# if user not authenticated, no access
if not request.user.is_authenticated:
return False
# ensure person making request isn't deleted.
if not request.user.is_active:
return False
# ensure person making request isn't locked.
if request.user.is_locked():
return False
# if user is admin, full access
if is_admin(request):
return True
# ensure this account is not locked
if self.is_locked():
return False
# ensure this account is not deleted
if self.date_deleted is not None:
return False
# ensure person owning account isn't locked.
if self.person.is_locked():
return False
# ensure person owning account isn't deleted.
if not self.person.is_active:
return False
return True
def can_edit(self, request):
# if we can't view this account, we can't edit it either
if not self.can_view(request):
return False
if not is_admin(request):
# if not admin, ensure we are the person being altered
if self.person != request.user:
return False
return True
def delete(self, **kwargs):
# delete the object
log.delete(self.person, "Account %s: Deleted" % self)
super(Account, self).delete(**kwargs)
if self.date_deleted is None:
# delete the datastore
from karaage.datastores import delete_account
delete_account(self)
delete.alters_data = True
def deactivate(self):
if self.date_deleted is not None:
raise RuntimeError("Account is deactivated")
# save the object
self.date_deleted = timezone.now()
self.login_enabled = False
self.save()
# self.save() will delete the datastore for us.
deactivate.alters_data = True
def change_shell(self, shell):
self.shell = shell
self.save()
# self.save() will update the datastore for us.
change_shell.alters_data = True
def set_password(self, password):
if self.date_deleted is not None:
raise RuntimeError("Account is deactivated")
self._password = password
set_password.alters_data = True
def get_disk_quota(self):
# FIXME: should this become deprecated?
return self.disk_quota
def login_shell(self):
return self.shell
def lock(self):
if self.date_deleted is not None:
raise RuntimeError("Account is deactivated")
self.login_enabled = False
self.save()
lock.alters_data = True
def unlock(self):
if self.date_deleted is not None:
raise RuntimeError("Account is deactivated")
self.login_enabled = True
self.save()
unlock.alters_data = True
def is_locked(self):
return not self.login_enabled
|
class Account(TrackingModelMixin, models.Model):
def __init__(self, *args, **kwargs):
pass
class Meta:
def __str__(self):
pass
def get_absolute_url(self):
pass
@classmethod
def create(cls, person, default_project):
'''Creates a Account (if needed) and activates person.'''
pass
def project_list(self):
pass
def save(self, *args, **kwargs):
pass
def can_view(self, request):
pass
def can_edit(self, request):
pass
def delete(self, **kwargs):
pass
def deactivate(self):
pass
def change_shell(self, shell):
pass
def set_password(self, password):
pass
def get_disk_quota(self):
pass
def login_shell(self):
pass
def lock(self):
pass
def unlock(self):
pass
def is_locked(self):
pass
| 20 | 1 | 10 | 1 | 7 | 1 | 3 | 0.17 | 2 | 4 | 1 | 0 | 16 | 1 | 17 | 17 | 222 | 49 | 148 | 44 | 123 | 25 | 131 | 43 | 107 | 13 | 1 | 3 | 46 |
141,937 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/models.py
|
karaage.machines.models.Machine
|
class Machine(TrackingModelMixin, AbstractBaseUser):
name = models.CharField(max_length=50, unique=True)
no_cpus = models.IntegerField()
no_nodes = models.IntegerField()
type = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField(null=True, blank=True)
pbs_server_host = models.CharField(max_length=50, null=True, blank=True)
mem_per_core = models.IntegerField(help_text="In GB", null=True, blank=True)
objects = MachineManager()
active = ActiveMachineManager()
scaling_factor = models.IntegerField(default=1)
USERNAME_FIELD = "name"
def save(self, *args, **kwargs):
created = self.pk is None
if created:
changed = {field: None for field in self.tracker.tracked_fields}
else:
changed = copy.deepcopy(self.tracker.changed)
# save the object
super(Machine, self).save(*args, **kwargs)
if created:
log.add(self, "Created")
for field in changed.keys():
if field == "password":
log.change(self, "Changed %s" % field)
else:
log.change(self, "Changed %s to %s" % (field, getattr(self, field)))
def delete(self, *args, **kwargs):
# delete the object
log.delete(self, "Deleted")
super(Machine, self).delete(*args, **kwargs)
class Meta:
db_table = "machine"
app_label = "karaage"
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("kg_machine_detail", args=[self.id])
|
class Machine(TrackingModelMixin, AbstractBaseUser):
def save(self, *args, **kwargs):
pass
def delete(self, *args, **kwargs):
pass
class Meta:
def __str__(self):
pass
def get_absolute_url(self):
pass
| 6 | 0 | 6 | 1 | 5 | 1 | 2 | 0.05 | 2 | 2 | 1 | 0 | 4 | 0 | 4 | 4 | 47 | 8 | 37 | 22 | 31 | 2 | 35 | 22 | 29 | 5 | 1 | 2 | 8 |
141,938 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/tables.py
|
karaage.machines.tables.AccountTable
|
class AccountTable(tables.Table):
active = tables.Column(empty_values=(), order_by=("date_deleted", "-login_enabled"))
person = tables.LinkColumn("kg_person_detail", args=[A("person__username")])
username = tables.LinkColumn("kg_account_detail", args=[A("pk")], verbose_name="Account")
default_project = tables.LinkColumn("kg_project_detail", args=[A("default_project__id")])
def render_active(self, record):
if record.date_deleted is not None:
html = '<span class="no">Deleted</span>'
elif not record.login_enabled:
html = '<span class="locked">Locked</span>'
else:
html = '<span class="yes">Yes</span>'
return mark_safe(html)
class Meta:
model = Account
fields = ("active", "username", "person", "default_project", "date_created", "date_deleted")
|
class AccountTable(tables.Table):
def render_active(self, record):
pass
class Meta:
| 3 | 0 | 8 | 0 | 8 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 18 | 2 | 16 | 10 | 13 | 0 | 14 | 10 | 11 | 3 | 1 | 1 | 3 |
141,939 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/tables.py
|
karaage.machines.tables.MachineTable
|
class MachineTable(tables.Table):
name = tables.LinkColumn("kg_machine_detail", args=[A("pk")])
status = tables.Column(empty_values=(), order_by=("end_date", "start_date"))
def render_status(self, record):
if record.end_date is not None:
return "Decommissioned %s" % record.end_date
else:
return "Active since %s" % record.start_date
class Meta:
model = Machine
fields = ("name",)
empty_text = "No items"
|
class MachineTable(tables.Table):
def render_status(self, record):
pass
class Meta:
| 3 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 14 | 2 | 12 | 8 | 9 | 0 | 11 | 8 | 8 | 2 | 1 | 1 | 2 |
141,940 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/management/commands/changepassword.py
|
karaage.management.commands.changepassword.Command
|
class Command(BaseCommand):
help = "Change a person's password for Karaage."
def add_arguments(self, parser):
parser.add_argument("username", nargs="?", type=str)
def _get_pass(self, prompt="Password: "):
p = getpass.getpass(prompt=prompt)
if not p:
raise CommandError("aborted")
return p
def handle(self, *args, **options):
if len(args) > 1:
raise CommandError("need exactly one or zero arguments for username")
if options["username"] is not None:
username = options["username"]
else:
username = getpass.getuser()
try:
person = Person.objects.get(username=username)
except Person.DoesNotExist:
raise CommandError("person '%s' does not exist" % username)
self.stdout.write("Changing password for person '%s'\n" % person)
max_tries = 3
count = 0
p1, p2 = 1, 2 # To make them initially mismatch.
while p1 != p2 and count < max_tries:
p1 = self._get_pass()
p2 = self._get_pass("Password (again): ")
if p1 != p2:
self.stdout.write("Passwords do not match. Please try again.\n")
count = count + 1
if count == max_tries:
raise CommandError("Aborting password change for user '%s' after %s attempts" % (username, count))
person.set_password(p1)
person.save()
return "Password changed successfully for user '%s'" % person
|
class Command(BaseCommand):
def add_arguments(self, parser):
pass
def _get_pass(self, prompt="Password: "):
pass
def handle(self, *args, **options):
pass
| 4 | 0 | 13 | 2 | 11 | 0 | 3 | 0.03 | 1 | 2 | 1 | 0 | 3 | 0 | 3 | 3 | 45 | 10 | 35 | 11 | 31 | 1 | 34 | 11 | 30 | 7 | 1 | 2 | 10 |
141,941 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/management/commands/daily_cleanup.py
|
karaage.management.commands.daily_cleanup.Command
|
class Command(BaseCommand):
help = "Karaage Daily cleanup"
def handle(self, **options):
from karaage.projects.signals import daily_cleanup as project_daily_cleanup
management.call_command("lock_expired")
project_daily_cleanup()
daily_cleanup.send(sender=self.__class__)
|
class Command(BaseCommand):
def handle(self, **options):
pass
| 2 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 2 | 7 | 4 | 4 | 0 | 7 | 4 | 4 | 1 | 1 | 0 | 1 |
141,942 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/middleware/threadlocals.py
|
karaage.middleware.threadlocals.ThreadLocals
|
class ThreadLocals(MiddlewareMixin):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
# We need to retrieve the actual value of the user here.
# Otherwise it might be too late when we need it.
# See commit cf8e22f95894b8922de771ca52946a3966fe6c90.
user = auth.get_user(request)
request.user = user
_thread_locals.user = user
|
class ThreadLocals(MiddlewareMixin):
'''Middleware that gets various objects from the
request object and saves them in thread local storage.'''
def process_request(self, request):
pass
| 2 | 1 | 7 | 0 | 4 | 3 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 11 | 1 | 5 | 3 | 3 | 5 | 5 | 3 | 3 | 1 | 1 | 0 | 1 |
141,943 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/machines/forms.py
|
karaage.machines.forms.AddProjectForm
|
class AddProjectForm(forms.Form):
project = ajax_select.fields.AutoCompleteSelectField("project", required=True, label="Add to existing project")
|
class AddProjectForm(forms.Form):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
141,944 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/migrations/0001_initial.py
|
karaage.migrations.0001_initial.Migration
|
class Migration(migrations.Migration):
dependencies = [
("contenttypes", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Person",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("password", models.CharField(max_length=128, verbose_name="password")),
("last_login", models.DateTimeField(default=django.utils.timezone.now, verbose_name="last login")),
("username", models.CharField(unique=True, max_length=255)),
("email", models.EmailField(max_length=75, null=True, db_index=True)),
("short_name", models.CharField(max_length=30)),
("full_name", models.CharField(max_length=60)),
("is_active", models.BooleanField(default=True)),
("is_admin", models.BooleanField(default=False)),
("saml_id", models.CharField(max_length=200, unique=True, null=True, editable=False, blank=True)),
("position", models.CharField(max_length=200, null=True, blank=True)),
("telephone", models.CharField(max_length=200, null=True, blank=True)),
("mobile", models.CharField(max_length=200, null=True, blank=True)),
("department", models.CharField(max_length=200, null=True, blank=True)),
("supervisor", models.CharField(max_length=100, null=True, blank=True)),
(
"title",
models.CharField(
blank=True,
max_length=10,
null=True,
choices=[
("", ""),
("Mr", "Mr"),
("Mrs", "Mrs"),
("Miss", "Miss"),
("Ms", "Ms"),
("Dr", "Dr"),
("Prof", "Prof"),
("A/Prof", "A/Prof"),
],
),
),
("address", models.CharField(max_length=200, null=True, blank=True)),
("city", models.CharField(max_length=100, null=True, blank=True)),
("postcode", models.CharField(max_length=8, null=True, blank=True)),
(
"state",
models.CharField(
blank=True,
max_length=4,
null=True,
choices=[
("", "--------"),
("ACT", "ACT"),
("NSW", "New South Wales"),
("NT", "Northern Territory"),
("QLD", "Queensland"),
("SA", "South Australia"),
("TAS", "Tasmania"),
("VIC", "Victoria"),
("WA", "Western Australia"),
],
),
),
(
"country",
models.CharField(
blank=True,
max_length=2,
null=True,
choices=[
("AU", "Australia"),
("NZ", "New Zealand"),
("GB", "United Kingdom"),
("DE", "Germany"),
("US", "United States"),
("", "--------------------------------------"),
("AD", "Andorra"),
("AE", "United Arab Emirates"),
("AF", "Afghanistan"),
("AG", "Antigua and Barbuda"),
("AI", "Anguilla"),
("AL", "Albania"),
("AM", "Armenia"),
("AN", "Netherlands Antilles"),
("AO", "Angola"),
("AQ", "Antarctica"),
("AR", "Argentina"),
("AS", "American Samoa"),
("AT", "Austria"),
("AW", "Aruba"),
("AX", "Aland Islands"),
("AZ", "Azerbaijan"),
("BA", "Bosnia and Herzegovina"),
("BB", "Barbados"),
("BD", "Bangladesh"),
("BE", "Belgium"),
("BF", "Burkina Faso"),
("BG", "Bulgaria"),
("BH", "Bahrain"),
("BI", "Burundi"),
("BJ", "Benin"),
("BM", "Bermuda"),
("BN", "Brunei Darussalam"),
("BO", "Bolivia"),
("BR", "Brazil"),
("BS", "Bahamas"),
("BT", "Bhutan"),
("BV", "Bouvet Island"),
("BW", "Botswana"),
("BY", "Belarus"),
("BZ", "Belize"),
("CA", "Canada"),
("CC", "Cocos (Keeling) Islands"),
("CD", "Congo"),
("CF", "Central African Republic"),
("CG", "Congo"),
("CH", "Switzerland"),
("CI", "Cote d'Ivoire"),
("CK", "Cook Islands"),
("CL", "Chile"),
("CM", "Cameroon"),
("CN", "China"),
("CO", "Colombia"),
("CR", "Costa Rica"),
("CU", "Cuba"),
("CV", "Cape Verde"),
("CX", "Christmas Island"),
("CY", "Cyprus"),
("CZ", "Czech Republic"),
("DJ", "Djibouti"),
("DK", "Denmark"),
("DM", "Dominica"),
("DO", "Dominican Republic"),
("DZ", "Algeria"),
("EC", "Ecuador"),
("EE", "Estonia"),
("EG", "Egypt"),
("EH", "Western Sahara"),
("ER", "Eritrea"),
("ES", "Spain"),
("ET", "Ethiopia"),
("FI", "Finland"),
("FJ", "Fiji"),
("FK", "Falkland Islands"),
("FM", "Micronesia"),
("FO", "Faroe Islands"),
("FR", "France"),
("GA", "Gabon"),
("GD", "Grenada"),
("GE", "Georgia"),
("GF", "French Guiana"),
("GG", "Guernsey"),
("GH", "Ghana"),
("GI", "Gibraltar"),
("GL", "Greenland"),
("GM", "Gambia"),
("GN", "Guinea"),
("GP", "Guadeloupe"),
("GQ", "Equatorial Guinea"),
("GR", "Greece"),
("GS", "South Georgia and the South Sandwich Islands"),
("GT", "Guatemala"),
("GU", "Guam"),
("GW", "Guinea-Bissau"),
("GY", "Guyana"),
("HK", "Hong Kong"),
("HM", "Heard Island and McDonald Islands"),
("HN", "Honduras"),
("HR", "Croatia"),
("HT", "Haiti"),
("HU", "Hungary"),
("ID", "Indonesia"),
("IE", "Ireland"),
("IL", "Israel"),
("IM", "Isle of Man"),
("IN", "India"),
("IO", "British Indian Ocean Territory"),
("IQ", "Iraq"),
("IR", "Iran"),
("IS", "Iceland"),
("IT", "Italy"),
("JE", "Jersey"),
("JM", "Jamaica"),
("JO", "Jordan"),
("JP", "Japan"),
("KE", "Kenya"),
("KG", "Kyrgyzstan"),
("KH", "Cambodia"),
("KI", "Kiribati"),
("KM", "Comoros"),
("KN", "Saint Kitts and Nevis"),
("KP", "Korea"),
("KR", "Korea"),
("KW", "Kuwait"),
("KY", "Cayman Islands"),
("KZ", "Kazakhstan"),
("LA", "Lao People's Democratic Republic"),
("LB", "Lebanon"),
("LC", "Saint Lucia"),
("LI", "Liechtenstein"),
("LK", "Sri Lanka"),
("LR", "Liberia"),
("LS", "Lesotho"),
("LT", "Lithuania"),
("LU", "Luxembourg"),
("LV", "Latvia"),
("LY", "Libyan Arab Jamahiriya"),
("MA", "Morocco"),
("MC", "Monaco"),
("MD", "Moldova"),
("ME", "Montenegro"),
("MG", "Madagascar"),
("MH", "Marshall Islands"),
("MK", "Macedonia"),
("ML", "Mali"),
("MM", "Myanmar"),
("MN", "Mongolia"),
("MO", "Macao"),
("MP", "Northern Mariana Islands"),
("MQ", "Martinique"),
("MR", "Mauritania"),
("MS", "Montserrat"),
("MT", "Malta"),
("MU", "Mauritius"),
("MV", "Maldives"),
("MW", "Malawi"),
("MX", "Mexico"),
("MY", "Malaysia"),
("MZ", "Mozambique"),
("NA", "Namibia"),
("NC", "New Caledonia"),
("NE", "Niger"),
("NF", "Norfolk Island"),
("NG", "Nigeria"),
("NI", "Nicaragua"),
("NL", "Netherlands"),
("NO", "Norway"),
("NP", "Nepal"),
("NR", "Nauru"),
("NU", "Niue"),
("OM", "Oman"),
("PA", "Panama"),
("PE", "Peru"),
("PF", "French Polynesia"),
("PG", "Papua New Guinea"),
("PH", "Philippines"),
("PK", "Pakistan"),
("PL", "Poland"),
("PM", "Saint Pierre and Miquelon"),
("PN", "Pitcairn"),
("PR", "Puerto Rico"),
("PS", "Palestinian Territory"),
("PT", "Portugal"),
("PW", "Palau"),
("PY", "Paraguay"),
("QA", "Qatar"),
("RE", "Reunion"),
("RO", "Romania"),
("RS", "Serbia"),
("RU", "Russian Federation"),
("RW", "Rwanda"),
("SA", "Saudi Arabia"),
("SB", "Solomon Islands"),
("SC", "Seychelles"),
("SD", "Sudan"),
("SE", "Sweden"),
("SG", "Singapore"),
("SH", "Saint Helena"),
("SI", "Slovenia"),
("SJ", "Svalbard and Jan Mayen"),
("SK", "Slovakia"),
("SL", "Sierra Leone"),
("SM", "San Marino"),
("SN", "Senegal"),
("SO", "Somalia"),
("SR", "Suriname"),
("ST", "Sao Tome and Principe"),
("SV", "El Salvador"),
("SY", "Syrian Arab Republic"),
("SZ", "Swaziland"),
("TC", "Turks and Caicos Islands"),
("TD", "Chad"),
("TF", "French Southern Territories"),
("TG", "Togo"),
("TH", "Thailand"),
("TJ", "Tajikistan"),
("TK", "Tokelau"),
("TL", "Timor-Leste"),
("TM", "Turkmenistan"),
("TN", "Tunisia"),
("TO", "Tonga"),
("TR", "Turkey"),
("TT", "Trinidad and Tobago"),
("TV", "Tuvalu"),
("TW", "Taiwan"),
("TZ", "Tanzania"),
("UA", "Ukraine"),
("UG", "Uganda"),
("UM", "United States Minor Outlying Islands"),
("UY", "Uruguay"),
("UZ", "Uzbekistan"),
("VA", "Vatican City"),
("VC", "Saint Vincent and the Grenadines"),
("VE", "Venezuela"),
("VG", "Virgin Islands (British)"),
("VI", "Virgin Islands (US)"),
("VN", "Viet Nam"),
("VU", "Vanuatu"),
("WF", "Wallis and Futuna"),
("WS", "Samoa"),
("YE", "Yemen"),
("YT", "Mayotte"),
("ZA", "South Africa"),
("ZM", "Zambia"),
("ZW", "Zimbabwe"),
],
),
),
("website", models.URLField(null=True, blank=True)),
("fax", models.CharField(max_length=50, null=True, blank=True)),
("comment", models.TextField(null=True, blank=True)),
("date_approved", models.DateField(null=True, blank=True)),
("date_deleted", models.DateField(null=True, blank=True)),
("last_usage", models.DateField(null=True, blank=True)),
("expires", models.DateField(null=True, blank=True)),
("is_systemuser", models.BooleanField(default=False)),
("login_enabled", models.BooleanField(default=True)),
("legacy_ldap_password", models.CharField(max_length=128, null=True, blank=True)),
(
"approved_by",
models.ForeignKey(
related_name="user_approver",
blank=True,
to="karaage.Person",
null=True,
on_delete=models.CASCADE,
),
),
(
"deleted_by",
models.ForeignKey(
related_name="user_deletor",
blank=True,
to="karaage.Person",
null=True,
on_delete=models.CASCADE,
),
),
],
options={
"ordering": ["full_name", "short_name"],
"db_table": "person",
"verbose_name_plural": "people",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="Account",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("username", models.CharField(max_length=255)),
(
"foreign_id",
models.CharField(
help_text="The foreign identifier from the datastore.", max_length=255, unique=True, null=True
),
),
("date_created", models.DateField()),
("date_deleted", models.DateField(null=True, blank=True)),
("disk_quota", models.IntegerField(help_text="In GB", null=True, blank=True)),
("shell", models.CharField(max_length=50)),
("login_enabled", models.BooleanField(default=True)),
(
"extra_data",
models.JSONField(
blank=True, default=dict, help_text="Datastore specific values should be stored in this field."
),
),
],
options={
"ordering": ["person"],
"db_table": "account",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="Group",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("name", models.CharField(unique=True, max_length=255)),
(
"foreign_id",
models.CharField(
help_text="The foreign identifier from the datastore.", max_length=255, unique=True, null=True
),
),
("description", models.TextField(null=True, blank=True)),
(
"extra_data",
models.JSONField(
blank=True, default=dict, help_text="Datastore specific values should be stored in this field."
),
),
("members", models.ManyToManyField(related_name="groups", to="karaage.Person")),
],
options={
"ordering": ["name"],
"db_table": "people_group",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="Institute",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("name", models.CharField(unique=True, max_length=255)),
("saml_entityid", models.CharField(max_length=200, unique=True, null=True, blank=True)),
("is_active", models.BooleanField(default=True)),
],
options={
"ordering": ["name"],
"db_table": "institute",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="InstituteDelegate",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("send_email", models.BooleanField()),
("institute", models.ForeignKey(to="karaage.Institute", on_delete=models.CASCADE)),
("person", models.ForeignKey(to="karaage.Person", on_delete=models.CASCADE)),
],
options={
"db_table": "institutedelegate",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="InstituteQuota",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("quota", models.DecimalField(max_digits=5, decimal_places=2)),
("cap", models.IntegerField(null=True, blank=True)),
("disk_quota", models.IntegerField(null=True, blank=True)),
("institute", models.ForeignKey(to="karaage.Institute", on_delete=models.CASCADE)),
],
options={
"db_table": "institute_quota",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="LogEntry",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("action_time", models.DateTimeField(auto_now_add=True, verbose_name="action time")),
("object_id", models.TextField(null=True, verbose_name="object id", blank=True)),
("object_repr", models.CharField(max_length=200, verbose_name="object repr")),
("action_flag", models.PositiveSmallIntegerField(verbose_name="action flag")),
("change_message", models.TextField(verbose_name="change message", blank=True)),
(
"content_type",
models.ForeignKey(blank=True, to="contenttypes.ContentType", null=True, on_delete=models.CASCADE),
),
("user", models.ForeignKey(to="karaage.Person", null=True, on_delete=models.CASCADE)),
],
options={
"ordering": ("-action_time", "-pk"),
"db_table": "admin_log",
"verbose_name": "log entry",
"verbose_name_plural": "log entries",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="Machine",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("password", models.CharField(max_length=128, verbose_name="password")),
("last_login", models.DateTimeField(default=django.utils.timezone.now, verbose_name="last login")),
("name", models.CharField(unique=True, max_length=50)),
("no_cpus", models.IntegerField()),
("no_nodes", models.IntegerField()),
("type", models.CharField(max_length=100)),
("start_date", models.DateField()),
("end_date", models.DateField(null=True, blank=True)),
("pbs_server_host", models.CharField(max_length=50, null=True, blank=True)),
("mem_per_core", models.IntegerField(help_text="In GB", null=True, blank=True)),
("scaling_factor", models.IntegerField(default=1)),
],
options={
"db_table": "machine",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="MachineCategory",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("name", models.CharField(unique=True, max_length=100)),
(
"datastore",
models.CharField(
help_text="Modifying this value on existing "
"categories will affect accounts created under the old datastore",
max_length=255,
choices=[("dummy", "dummy"), ("ldap", "ldap")],
),
),
],
options={
"db_table": "machine_category",
"verbose_name_plural": "machine categories",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="Project",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("pid", models.CharField(unique=True, max_length=255)),
("name", models.CharField(max_length=200)),
("description", models.TextField(null=True, blank=True)),
("is_approved", models.BooleanField(default=False)),
("start_date", models.DateField(default=datetime.datetime.today)),
("end_date", models.DateField(null=True, blank=True)),
("additional_req", models.TextField(null=True, blank=True)),
("is_active", models.BooleanField(default=False)),
("date_approved", models.DateField(null=True, editable=False, blank=True)),
("date_deleted", models.DateField(null=True, editable=False, blank=True)),
("last_usage", models.DateField(null=True, editable=False, blank=True)),
(
"approved_by",
models.ForeignKey(
related_name="project_approver",
blank=True,
editable=False,
to="karaage.Person",
null=True,
on_delete=models.CASCADE,
),
),
(
"deleted_by",
models.ForeignKey(
related_name="project_deletor",
blank=True,
editable=False,
to="karaage.Person",
null=True,
on_delete=models.CASCADE,
),
),
("group", models.ForeignKey(to="karaage.Group", on_delete=models.CASCADE)),
("institute", models.ForeignKey(to="karaage.Institute", on_delete=models.CASCADE)),
("leaders", models.ManyToManyField(related_name="leads", to="karaage.Person")),
],
options={
"ordering": ["pid"],
"db_table": "project",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="ProjectQuota",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("cap", models.IntegerField(null=True, blank=True)),
("machine_category", models.ForeignKey(to="karaage.MachineCategory", on_delete=models.CASCADE)),
("project", models.ForeignKey(to="karaage.Project", on_delete=models.CASCADE)),
],
options={
"db_table": "project_quota",
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name="projectquota",
unique_together=set([("project", "machine_category")]),
),
migrations.AddField(
model_name="machine",
name="category",
field=models.ForeignKey(to="karaage.MachineCategory", on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name="institutequota",
name="machine_category",
field=models.ForeignKey(to="karaage.MachineCategory", on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AlterUniqueTogether(
name="institutequota",
unique_together=set([("institute", "machine_category")]),
),
migrations.AddField(
model_name="institute",
name="delegates",
field=models.ManyToManyField(
related_name="delegate_for",
null=True,
through="karaage.InstituteDelegate",
to="karaage.Person",
blank=True,
),
preserve_default=True,
),
migrations.AddField(
model_name="institute",
name="group",
field=models.ForeignKey(to="karaage.Group", on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name="account",
name="default_project",
field=models.ForeignKey(blank=True, to="karaage.Project", null=True, on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name="account",
name="machine_category",
field=models.ForeignKey(to="karaage.MachineCategory", on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name="account",
name="person",
field=models.ForeignKey(to="karaage.Person", on_delete=models.CASCADE),
preserve_default=True,
),
migrations.AddField(
model_name="person",
name="institute",
field=models.ForeignKey(to="karaage.Institute", on_delete=models.CASCADE),
preserve_default=True,
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 641 | 1 | 640 | 3 | 639 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
141,945 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/datastores/ldap_schemas.py
|
karaage.datastores.ldap_schemas.OpenldapGroup
|
class OpenldapGroup(BaseGroup):
"""An OpenLDAP specific group."""
@classmethod
def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject:
python_data = BaseGroup.on_load(python_data, database)
python_data = helpers.load_group(python_data, OpenldapAccount)
return python_data
@classmethod
def on_save(cls, changes: Changeset, database: Database) -> Changeset:
changes = BaseGroup.on_save(changes, database)
changes = dhelpers.save_group(changes, OpenldapGroup, database)
return changes
|
class OpenldapGroup(BaseGroup):
'''An OpenLDAP specific group.'''
@classmethod
def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject:
pass
@classmethod
def on_save(cls, changes: Changeset, database: Database) -> Changeset:
pass
| 5 | 1 | 4 | 0 | 4 | 0 | 1 | 0.09 | 1 | 1 | 1 | 0 | 0 | 0 | 2 | 9 | 14 | 2 | 11 | 5 | 6 | 1 | 9 | 3 | 6 | 1 | 2 | 0 | 2 |
141,946 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/karaage/datastores/ldap_schemas.py
|
karaage.datastores.ldap_schemas.Ds389Group
|
class Ds389Group(BaseGroup):
"""A DS389 specific group."""
@classmethod
def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject:
python_data = BaseGroup.on_load(python_data, database)
python_data = helpers.load_group(python_data, Ds389Account)
return python_data
@classmethod
def on_save(cls, changes: Changeset, database: Database) -> Changeset:
changes = BaseGroup.on_save(changes, database)
changes = dhelpers.save_group(changes, Ds389Group, database)
return changes
|
class Ds389Group(BaseGroup):
'''A DS389 specific group.'''
@classmethod
def on_load(cls, python_data: LdapObject, database: Database) -> LdapObject:
pass
@classmethod
def on_save(cls, changes: Changeset, database: Database) -> Changeset:
pass
| 5 | 1 | 4 | 0 | 4 | 0 | 1 | 0.09 | 1 | 1 | 1 | 0 | 0 | 0 | 2 | 9 | 14 | 2 | 11 | 5 | 6 | 1 | 9 | 3 | 6 | 1 | 2 | 0 | 2 |
141,947 |
Karaage-Cluster/karaage
|
Karaage-Cluster_karaage/docs/ext/djangodocs.py
|
djangodocs.KaraageHTMLTranslator
|
class KaraageHTMLTranslator(HTMLTranslator):
"""
Karaage-specific reST to HTML tweaks.
"""
# Don't use border=1, which docutils does by default.
def visit_table(self, node):
self.context.append(self.compact_p)
self.compact_p = True
self._table_row_index = 0 # Needed by Sphinx
self.body.append(self.starttag(node, 'table', CLASS='docutils'))
def depart_table(self, node):
self.compact_p = self.context.pop()
self.body.append('</table>\n')
def visit_desc_parameterlist(self, node):
self.body.append('(') # by default sphinx puts <big> around the "("
self.first_param = 1
self.optional_param_level = 0
self.param_separator = node.child_text_separator
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children)
def depart_desc_parameterlist(self, node):
self.body.append(')')
#
# Turn the "new in version" stuff (versionadded/versionchanged) into a
# better callout -- the Sphinx default is just a little span,
# which is a bit less obvious that I'd like.
#
# FIXME: these messages are all hardcoded in English. We need to change
# that to accommodate other language docs, but I can't work out how to make
# that work.
#
version_text = {
'versionchanged': 'Changed in Karaage %s',
'versionadded': 'New in Karaage %s',
}
def visit_versionmodified(self, node):
self.body.append(
self.starttag(node, 'div', CLASS=node['type'])
)
version_text = self.version_text.get(node['type'])
if version_text:
title = "%s%s" % (
version_text % node['version'],
":" if node else "."
)
self.body.append('<span class="title">%s</span> ' % title)
def depart_versionmodified(self, node):
self.body.append("</div>\n")
# Give each section a unique ID -- nice for custom CSS hooks
def visit_section(self, node):
old_ids = node.get('ids', [])
node['ids'] = ['s-' + i for i in old_ids]
node['ids'].extend(old_ids)
super().visit_section(node)
node['ids'] = old_ids
|
class KaraageHTMLTranslator(HTMLTranslator):
'''
Karaage-specific reST to HTML tweaks.
'''
def visit_table(self, node):
pass
def depart_table(self, node):
pass
def visit_desc_parameterlist(self, node):
pass
def depart_desc_parameterlist(self, node):
pass
def visit_versionmodified(self, node):
pass
def depart_versionmodified(self, node):
pass
def visit_section(self, node):
pass
| 8 | 1 | 5 | 0 | 5 | 0 | 1 | 0.4 | 1 | 1 | 0 | 0 | 7 | 6 | 7 | 7 | 62 | 8 | 40 | 18 | 32 | 16 | 32 | 18 | 24 | 3 | 1 | 1 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.