index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
72,126 | Skaty/orbital | refs/heads/develop | /profiles/admin.py | from django.contrib import admin
# Register your models here.
from profiles.models import Preferences
@admin.register(Preferences)
class PreferencesModelAdmin(admin.ModelAdmin):
model = Preferences | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,127 | Skaty/orbital | refs/heads/develop | /targets/migrations/0003_goal_milestone.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-28 16:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('targets', '0002_auto_20160628_2336'),
]
operations = [
migrations.AddField(
model_name='goal',
name='milestone',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='targets.Milestone'),
),
]
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,128 | Skaty/orbital | refs/heads/develop | /projects/api/views.py | from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from projects.models import *
from .serializers import *
class ProjectViewSet(viewsets.ViewSet):
def list(self, request):
queryset = request.user.project_set.all()
serializer = ProjectSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = Project.objects.all()
project = get_object_or_404(queryset, pk=pk)
if not project.facilitators.filter(pk=request.user.pk).exists():
raise PermissionDenied('You are not a facilitator for this project!')
serializer = ProjectSerializer(project)
return Response(serializer.data)
class ProjectGroupViewSet(viewsets.ViewSet):
def retrieve(self, request, pk=None):
queryset = ProjectGroup.objects.all()
group = get_object_or_404(queryset, pk=pk)
if not (group.project.facilitators.filter(pk=request.user.pk).exists()
or group.members.filter(pk=request.user.pk).exists()):
raise PermissionDenied('You are not a facilitator for this project!')
serializer = ProjectGroupSerializer(group)
return Response(serializer.data) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,129 | Skaty/orbital | refs/heads/develop | /projects/tests/test_models.py | from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from projects.models import Project, ProjectGroup
class ProjectTestCase(TestCase):
def test_create_project(self):
"""
Tests if a project can be created.
Coverage:
- Creation of Project model instance
- Persistence of Project model instance in DB
"""
mock_facilitator = User.objects.create_user('facilitator')
parameters = {
'name': 'Test Project'
}
project = Project.objects.create(**parameters)
retrieved_project = Project.objects.get(pk=project.pk)
project.facilitators.add(mock_facilitator)
for key, value in parameters.items():
self.assertEqual(value, getattr(retrieved_project, key),
"{key} attribute of instance is {value} in DB".format(key=key, value=value))
self.assertIn(retrieved_project, mock_facilitator.project_set.all(),
"Assert the existence of a reverse relationship from User to Project")
def test_is_active_method(self):
"""
Tests the behaviour of the is_active model method.
Coverage:
- Checks if is_active has been declared
- Output of is_active is as expected
"""
parameters = {
'name': 'Test Project',
'ends_on': timezone.now() - timedelta(days=1),
}
expired_project = Project.objects.create(**parameters)
self.assertFalse(expired_project.is_active(),
"An expired/ended project is inactive")
parameters['ends_on'] = timezone.now() + timedelta(days=1)
active_project = Project.objects.create(**parameters)
self.assertTrue(active_project.is_active(),
"A project with ending date > now is active")
def test_string_representation(self):
"""
Tests the string representation of Project model instance
Coverage:
- String representation of Project model instance
"""
parameters = {
'name': 'Test Project 123',
}
project = Project.objects.create(**parameters)
self.assertEqual(project.name, str(project),
"String representation of name is equal to the instance's name attribute")
class ProjectGroupTestCase(TestCase):
def test_create_group(self):
"""
Tests if a group can be created.
Coverage:
- Creation of ProjectGroup model instance
- Persistence of ProjectGroup model instance in DB
"""
mock_member = User.objects.create_user('group_member')
mock_project = Project.objects.create(name="Test")
parameters = {
'name': 'Test Group',
'project': mock_project,
}
project_group = ProjectGroup.objects.create(**parameters)
retrieved_project_group = ProjectGroup.objects.get(pk=project_group.pk)
project_group.members.add(mock_member)
for key, value in parameters.items():
self.assertEqual(value, getattr(retrieved_project_group, key),
"{key} attribute of instance {value} in DB".format(key=key, value=value))
self.assertIn(retrieved_project_group, mock_project.projectgroup_set.all(),
"Assert the existence of a reverse relationship from Project to ProjectGroup")
self.assertIn(retrieved_project_group, mock_member.projectgroup_set.all(),
"Assert the existence of a reverse relationship from User to ProjectGroup")
def test_string_representation(self):
"""
Tests the string representation of ProjectGroup model instance
Coverage:
- String representation of ProjectGroup model instance
"""
parameters = {
'name': 'Test Group',
}
project_group = Project.objects.create(**parameters)
self.assertEqual(project_group.name, str(project_group),
"String representation of name is equal to the instance's name attribute")
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,130 | Skaty/orbital | refs/heads/develop | /projects/tests/__init__.py | from projects.tests.test_models import * | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,131 | Skaty/orbital | refs/heads/develop | /targets/migrations/0002_auto_20160628_2336.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-28 15:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('targets', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='goal',
name='completed_on',
field=models.DateTimeField(blank=True, default=None, null=True),
),
migrations.AddField(
model_name='milestone',
name='completed_on',
field=models.DateTimeField(blank=True, default=None, null=True),
),
migrations.AddField(
model_name='target',
name='completed_on',
field=models.DateTimeField(blank=True, default=None, null=True),
),
]
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,132 | Skaty/orbital | refs/heads/develop | /miscellaneous/signals.py | from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from profiles.models import Preferences
@receiver(post_save, sender=User, dispatch_uid="user_post_save")
def target_assignment_post_save(sender, **kwargs):
user = kwargs['instance']
if kwargs['created']:
preferences = Preferences(user=user)
preferences.save() | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,133 | Skaty/orbital | refs/heads/develop | /targets/api/urls.py | from rest_framework import routers
from targets.api.views import *
router = routers.DefaultRouter()
router.register(r'targets', TargetViewSet, base_name='targets')
router.register(r'milestones', MilestoneViewSet, base_name='milestones')
router.register(r'goals', GoalViewSet, base_name='goals')
urlpatterns = router.urls | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,134 | Skaty/orbital | refs/heads/develop | /targets/signals.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from targets.models import TargetAssignment
@receiver(post_save, sender=TargetAssignment, dispatch_uid="target_assignment_post_save")
def target_assignment_post_save(sender, **kwargs):
is_completed_by_all = kwargs['instance'].target.targetassignment_set.filter(marked_completed_on=None).count() == 0
print(is_completed_by_all)
if is_completed_by_all:
target = kwargs['instance'].target
target.completed_on = kwargs['instance'].marked_completed_on
target.save() | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,135 | Skaty/orbital | refs/heads/develop | /targets/api/serializers.py | from rest_framework import serializers
from targets.models import *
class TargetSerializer(serializers.ModelSerializer):
completed_by = serializers.SerializerMethodField()
def get_completed_by(self, obj):
return obj.targetassignment_set.filter(marked_completed_on__isnull=False).values_list('assignee', flat=True)
class Meta:
model = Target
fields = ('id', 'name', 'created_on', 'completed_on', 'deadline', 'group', 'milestone', 'assigned_to', 'completed_by')
class MilestoneSerializer(serializers.ModelSerializer):
class Meta:
model = Milestone
fields = ('id', 'name', 'created_on', 'completed_on', 'deadline', 'project')
class GoalSerializer(serializers.ModelSerializer):
class Meta:
model = Goal
fields = ('id', 'name', 'created_on', 'completed_on', 'deadline', 'project') | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,136 | Skaty/orbital | refs/heads/develop | /projection/backends.py | from social.backends.open_id import OpenIdAuth
class NUSOpenId(OpenIdAuth):
"""NUS OpenID authentication"""
URL = 'http://openid.nus.edu.sg'
name = 'nus'
USERNAME_KEY = 'nickname'
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,137 | Skaty/orbital | refs/heads/develop | /profiles/views.py | from django.contrib.auth import models
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse_lazy
from django import forms
from django.utils.decorators import method_decorator
from django.views.generic import DetailView
from django.views.generic.base import TemplateView
from django.views.generic.edit import UpdateView, FormView
from profiles.models import Preferences
class ProfileDetailView(DetailView):
model = models.User
template_name = 'profiles/profile_detail.html'
class PasswordChangeForm(forms.Form):
password = forms.CharField(widget=forms.PasswordInput, required=True)
confirm_password = forms.CharField(widget=forms.PasswordInput, required=True)
def clean(self):
cleaned_data = super(PasswordChangeForm, self).clean()
password = cleaned_data.get('password')
confirm = cleaned_data.get('confirm_password')
if password != confirm:
raise forms.ValidationError(
'Passwords do not match!'
)
class TimezonePreferenceForm(forms.ModelForm):
class Meta:
model = Preferences
fields = ['timezone']
class ProfileChangeForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name']
@method_decorator(login_required, name='dispatch')
class PreferencesDisplay(TemplateView):
template_name = 'profiles/preferences_form.html'
def get_context_data(self, **kwargs):
pref_instance, create = Preferences.objects.get_or_create(user=self.request.user)
forms = [
{
'title': 'Update Preferences',
'form': TimezonePreferenceForm(instance=pref_instance),
'url': reverse_lazy('profiles:preferences-update')
},
{
'title': 'Profile',
'form': ProfileChangeForm(instance=self.request.user),
'url': reverse_lazy('profiles:profile-update')
}
]
if self.request.user.has_usable_password():
forms += [
{
'title': 'Change Password',
'form': PasswordChangeForm(),
'url': reverse_lazy('profiles:password-update')
}
]
kwargs['forms'] = forms
return super(PreferencesDisplay, self).get_context_data(**kwargs)
@method_decorator(login_required, name='dispatch')
class PasswordUpdateView(FormView):
form_class = PasswordChangeForm
success_url = reverse_lazy('homepage')
template_name = 'profiles/single_form.html'
def get_context_data(self, **kwargs):
kwargs['formtitle'] = 'Change Password'
return super(PasswordUpdateView, self).get_context_data(**kwargs)
def form_valid(self, form):
user = self.request.user
user.set_password(form.cleaned_data['password'])
user.save()
return super(PasswordUpdateView, self).form_valid(form)
@method_decorator(login_required, name='dispatch')
class PreferencesUpdateView(FormView):
form_class = TimezonePreferenceForm
success_url = reverse_lazy('projects:project-list')
template_name = 'profiles/single_form.html'
def get_context_data(self, **kwargs):
kwargs['formtitle'] = 'Update Preferences'
return super(PreferencesUpdateView, self).get_context_data(**kwargs)
def form_valid(self, form):
form.instance.user = self.request.user
self.object = form.save()
return super(PreferencesUpdateView, self).form_valid(form)
@method_decorator(login_required, name='dispatch')
class ProfileUpdateView(UpdateView):
form_class = ProfileChangeForm
success_url = reverse_lazy('projects:project-list')
template_name = 'profiles/single_form.html'
def get_object(self, queryset=None):
return self.request.user
def get_context_data(self, **kwargs):
kwargs['formtitle'] = 'Profile'
return super(ProfileUpdateView, self).get_context_data(**kwargs) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,138 | Skaty/orbital | refs/heads/develop | /projection/settings.py | """
Django settings for projection project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import bleach
from django.contrib.messages import constants as message_constants
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3_v8)xa7+_9-m=1=b5(^+_nslvzmaox3tefx)w1vv3eu!eh%vc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_nose',
'postman',
'projects.apps.ProjectsConfig',
'targets.apps.TargetsConfig',
'miscellaneous.apps.MiscellaneousConfig',
'social.apps.django_app.default',
'profiles.apps.ProfilesConfig',
'rest_framework',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'projection.middleware.TimezoneMiddleware',
]
AUTHENTICATION_BACKENDS = (
'projection.backends.NUSOpenId',
'django.contrib.auth.backends.ModelBackend',
)
ROOT_URLCONF = 'projection.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.dirname(os.path.realpath(__file__)) + "/templates", ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
],
},
},
]
WSGI_APPLICATION = 'projection.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
if os.getenv('PROJECTION_APP_ENV', 'debug') == 'production':
DATABASES = {
'default': dj_database_url.config(conn_max_age=600)
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
if os.getenv('PROJECTION_APP_ENV', 'debug') == 'production':
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# Test Runner Configuration
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# Redirects
LOGIN_URL = '/auth/login/'
LOGIN_REDIRECT_URL = '/'
# Messaging
MESSAGE_TAGS = {
message_constants.ERROR: 'danger'
}
# Python Social Auth
SOCIAL_AUTH_URL_NAMESPACE = 'sso'
# Timezones
DEFAULT_TZ = 'Asia/Singapore'
# REST API
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
# Bleach
BLEACH_ALLOWED_TAGS = bleach.ALLOWED_TAGS + [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'img',
'p',
'sup',
'sub',
'code',
]
EXTRA_ALLOWED = {
'img': ['src', 'alt', 'width', 'height'],
'p': ['style'],
}
BLEACH_ALLOWED_ATTRIBUTES = {**bleach.ALLOWED_ATTRIBUTES, **EXTRA_ALLOWED}
# django-postman
POSTMAN_DISALLOW_ANONYMOUS = True
POSTMAN_AUTO_MODERATE_AS = True
POSTMAN_DISABLE_USER_EMAILING = True
POSTMAN_NOTIFIER_APP = None
POSTMAN_MAILER_APP = None | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,139 | Skaty/orbital | refs/heads/develop | /targets/api/views.py | from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from targets.models import *
from .serializers import *
class TargetViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Target.objects.filter(group__members=request.user)
serializer = TargetSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = Target.objects.all()
target = get_object_or_404(queryset, pk=pk)
if not request.user.projectgroup_set.filter(target=target).exists():
raise PermissionDenied('You are not a group member of the group with this target!')
serializer = TargetSerializer(target)
return Response(serializer.data)
class MilestoneViewSet(viewsets.ViewSet):
def retrieve(self, request, pk=None):
queryset = Milestone.objects.all()
milestone = get_object_or_404(queryset, pk=pk)
if not milestone.project.facilitators.filter(pk=request.user.pk).exists():
raise PermissionDenied('You are not a facilitator for this project!')
serializer = MilestoneSerializer(milestone)
return Response(serializer.data)
class GoalViewSet(viewsets.ViewSet):
def retrieve(self, request, pk=None):
queryset = Goal.objects.all()
goal = get_object_or_404(queryset, pk=pk)
if not (request.user.project_set.filter(goal=goal).exists() or request.user.projectgroup_set.filter(project__goal=goal).exists()):
raise PermissionDenied('You are not a facilitator for this project!')
serializer = MilestoneSerializer(goal)
return Response(serializer.data) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,140 | Skaty/orbital | refs/heads/develop | /targets/models.py | from django.conf import settings
from django.db import models
from django.utils import timezone
class AbstractTarget(models.Model):
"""
AbstractTarget - an abstract model with fields that are common amongst
all types of targets
"""
name = models.CharField(max_length=255)
description = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)
completed_on = models.DateTimeField(default=None, null=True, blank=True)
deadline = models.DateTimeField(null=True, blank=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL)
def is_due(self):
if not self.deadline:
return False
return self.deadline < timezone.now()
def has_permission(self, user):
return user == self.created_by
class Meta:
abstract = True
class Target(AbstractTarget):
"""
Target represents a Goal for a particular ProjectGroup.
Unlike a Goal, a ProjectGroup can have multiple Targets
"""
group = models.ForeignKey('projects.ProjectGroup', on_delete=models.CASCADE)
milestone = models.ForeignKey('targets.Milestone', default=None, null=True, blank=True, on_delete=models.SET_NULL)
assigned_to = models.ManyToManyField(settings.AUTH_USER_MODEL, through='TargetAssignment',
related_name="assigned_targets")
def __str__(self):
return self.name
class TargetAssignment(models.Model):
"""
Representation of an Assignment of Target to a User.
Contains metadata regarding the assignment - such as whether the Target has been marked completed by the user
"""
assignee = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
target = models.ForeignKey(Target, on_delete=models.CASCADE)
marked_completed_on = models.DateTimeField(default=None, null=True, blank=True)
def __str__(self):
return '{target} metadata for {user}'.format(target=self.target, user=self.assignee)
class Milestone(AbstractTarget):
"""
Representation of a Milestone - a 'project-wide' goal.
Kinda like Orbital's Milestone system :(
Unlike Goals, there can be multiple Milestones per project
"""
project = models.ForeignKey('projects.Project', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Goal(AbstractTarget):
"""
Representation of a Goal - a singular, ultimate target
for a Project. All ProjectGroups will be assigned to this goal
"""
project = models.OneToOneField('projects.Project', on_delete=models.CASCADE)
def __str__(self):
return self.name | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,141 | Skaty/orbital | refs/heads/develop | /profiles/urls.py | from django.conf.urls import url, include
from profiles.views import ProfileDetailView, PreferencesUpdateView, PasswordUpdateView, PreferencesDisplay, \
ProfileUpdateView
urlpatterns = [
url(r'^(?P<pk>[0-9]+)/$', ProfileDetailView.as_view(), name='profile-detail'),
url(r'^update/', include([
url(r'^$', PreferencesDisplay.as_view(), name='preferences-display'),
url(r'^password/$', PasswordUpdateView.as_view(), name='password-update'),
url(r'^preferences/$', PreferencesUpdateView.as_view(), name='preferences-update'),
url(r'^profile/$', ProfileUpdateView.as_view(), name='profile-update'),
]))
] | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,174 | PointyShinyBurning/tuttle | refs/heads/master | /tests/functional_tests/test_invalidate_command.py | # -*- coding: utf-8 -*-
import sys
from subprocess import Popen, PIPE
from os.path import abspath, join, dirname, isfile
from re import search, DOTALL
from unittest.case import SkipTest
from tests.functional_tests import isolate, run_tuttle_file
from cStringIO import StringIO
from tuttlelib.commands import invalidate_resources
class TestCommands():
def tuttle_invalide(self, project=None, urls=[]):
if project is not None:
with open('tuttlefile', "w") as f:
f.write(project)
oldout, olderr = sys.stdout, sys.stderr
out = StringIO()
try:
sys.stdout, sys.stderr = out, out
rcode = invalidate_resources('tuttlefile', urls)
finally:
sys.stdout, sys.stderr = oldout, olderr
return rcode, out.getvalue()
@isolate(['A'])
def test_command_invalidate(self):
""" Should display a message if there is no tuttlefile in the current directory"""
project = """file://B <- file://A
echo A creates B
echo A creates B > B
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
assert isfile('B')
rcode, output = self.tuttle_invalide(urls=['file://B'])
assert rcode == 0, output
assert output.find('* file://B') >= 0, output
assert not isfile('B'), output
@isolate(['A'])
def test_command_invalidate_with_dependencies(self):
""" Should display a message if there is no tuttlefile in the current directory"""
project = """file://B <- file://A
echo A creates B
echo A creates B > B
file://C <- file://B
echo A creates C
echo A creates C > C
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
assert isfile('B')
assert isfile('C')
rcode, output = self.tuttle_invalide(urls=['file://B'])
assert rcode == 0, output
assert output.find('* file://B') >= 0, output
assert output.find('* file://C') >= 0, output
assert not isfile('B'), output
assert not isfile('C'), output
@isolate(['A'])
def test_duration(self):
""" Should display a message if there is no tuttlefile in the current directory"""
project = """file://B <- file://A
echo A creates B
python -c "import time; time.sleep(1)"
echo A creates B > B
file://C <- file://B
echo A creates C
python -c "import time; time.sleep(2)"
echo A creates C > C
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
assert isfile('B')
assert isfile('C')
rcode, output = self.tuttle_invalide(urls=['file://B'])
assert rcode == 0, output
assert output.find('* file://B') >= 0, output
assert output.find('* file://C') >= 0, output
assert output.find(' seconds') >= 0, output
assert output.find('\n0 seconds') == -1, output
assert not isfile('B'), output
assert not isfile('C'), output
@isolate
def test_invalidate_no_tuttle_file(self):
""" Should display a message when launching invalidate and there is tuttlefile in the current directory"""
proc = Popen(['tuttle', 'invalidate', 'file://B'], stdout=PIPE)
output = proc.stdout.read()
rcode = proc.wait()
assert rcode == 2, output
assert output.find('No tuttlefile') >= 0, output
@isolate
def test_invalidate_nothing_have_run(self):
""" Should display a message when launching invalidate and tuttle hasn't been run before :
nothing to invalidate """
project = """file://B <- file://A
echo A creates B
echo A creates B > B
"""
rcode, output = self.tuttle_invalide(project=project)
assert rcode == 2, output
assert output.find("Tuttle has not run yet ! It has produced nothing, "
"so there is nothing to invalidate.") >= 0, output
@isolate(['A'])
def test_try_invalidate_bad_project(self):
""" Should display a message if the tuttlefile is incorrect"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
bad_project = """file://B <- file://A bad
echo A produces B
echo A produces B > B
"""
rcode, output = self.tuttle_invalide(project=bad_project, urls=['file://B'])
assert rcode == 2, output
assert output.find('Invalidation has failed because tuttlefile is has errors') >= 0, output
@isolate(['A'])
def test_invalidate_no_urls(self):
""" Should remove everything that is not in the last version of the tuttlefile """
project = """file://B <- file://A
echo A produces B
echo A produces B > B
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
new_project = """file://B <- file://A
echo A produces B
echo A produces B > B
"""
rcode, output = self.tuttle_invalide(project=new_project)
assert rcode == 0, output
assert output.find('* file://C') >= 0, output
assert output.find('no longer created') >= 0, output
@isolate(['A'])
def test_invalid_url_should_fail(self):
""" Should display an error if the url passed in parameter is not valid or unknown scheme """
project = """file://B <- file://A
echo A produces B
echo A produces B > B
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
rcode, output = self.tuttle_invalide(urls=['error://B'])
assert rcode == 2, output
assert output.find("'error://B'") >= 0, output
@isolate(['A'])
def test_unknown_resource_should_be_ignored(self):
""" Should display a message if there is no tuttlefile in the current directory"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
rcode, output = self.tuttle_invalide(urls=['file://C'])
assert rcode == 0, output
assert output.find("Ignoring file://C") >= 0, output
@isolate(['A'])
def test_not_produced_resource_should_be_ignored(self):
""" Should display a message if there is no tuttlefile in the current directory"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0
project = """file://B <- file://A
echo A produces B
echo A produces B > B
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = self.tuttle_invalide(project=project, urls=['file://C'])
assert rcode == 0, output
assert output.find("Ignoring file://C : this resource has not been produced yet") >= 0, output
@isolate(['A'])
def test_new_primary_resources_should_not_be_invalidated(self):
""" A primary resource that was produced with previous workflow shouldn't invalidate dependencies
if it hasn't changed"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = run_tuttle_file(project)
print output
assert rcode == 0, output
project = """
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = self.tuttle_invalide(project=project)
assert rcode == 0, output
assert output.find("Report has been updated to reflect") >= 0, output
@isolate(['A'])
def test_modified_new_primary_resources_should_invalidate_dependencies(self):
""" If a resource has become a primary resource, but signature has not changed
that was produced with previous workflow shouldn't invalidate dependencies
if it hasn't changed"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = run_tuttle_file(project)
print output
assert rcode == 0, output
with open('B', "w") as f:
f.write("Another B")
project = """
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = self.tuttle_invalide(project=project)
assert rcode == 0, output
assert output.find("file://C") >= 0, output
@isolate(['A'])
def test_not_modified_new_primary_resources_should_not_invalidate_dependencies(self):
""" If a resource has become a primary resource, but signature has not changed
that was produced with previous workflow shouldn't invalidate dependencies
if it hasn't changed"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = run_tuttle_file(project)
print output
assert rcode == 0, output
project = """
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = self.tuttle_invalide(project=project)
assert rcode == 0, output
assert output.find("Report has been updated to reflect") >= 0, output
@isolate(['A'])
def test_workflow_must_be_run_after_resource_invalidation(self):
""" After invalidation of a resource, tuttle run should re-produce this resource """
project = """file://B <- file://A
echo A produces B
echo A produces B > B
file://C <- file://B
echo B produces C
echo B produces C > C
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
rcode, output = self.tuttle_invalide(urls=["file://C"])
assert rcode == 0, output
assert output.find("file://C") >= 0, output
rcode, output = run_tuttle_file(project)
assert output.find("Nothing to do") == -1, output
assert output.find("B produces C") >= 0, output
@isolate(['A'])
def test_workflow_must_be_run_after_resource_invalidation_in_cascade(self):
""" After invalidation of a resource, tuttle run should re-produce this resource and the dependencies"""
project = """file://B <- file://A
echo A produces B
echo A produces B > B
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
rcode, output = self.tuttle_invalide(urls=["file://A"])
assert rcode == 0, output
assert output.find("Ignoring file://A") >= 0, output
@isolate(['A'])
def test_process_in_error_should_be_invalidated(self):
""" If a process failed, its dependencies should be invalidated """
project = """file://B <- file://A
echo A produces B
echo A produces B > B
an error
"""
rcode, output = run_tuttle_file(project)
print output
assert rcode == 2, output
assert isfile('B')
rcode, output = self.tuttle_invalide(project=project)
assert rcode == 0, output
assert output.find("file://B") >= 0, output
assert not isfile('B'), output
@isolate(['A'])
def test_a_failing_process_without_output_should_be_invalidated(self):
""" When a process fail, Tuttle should exit with status code 2, even if the process has no outputs"""
project = """file://B <- file://A
echo A produces B
echo B > B
<- file://B
error
echo This should not be written
echo C > C
"""
rcode, output = run_tuttle_file(project)
assert rcode == 2
assert isfile('B')
assert not isfile('C')
report_path = join('.tuttle', 'report.html')
assert isfile(report_path)
report = open(report_path).read()
title_match_failure = search(r'<h1>.*Failure.*</h1>', report, DOTALL)
assert title_match_failure, report
rcode, output = self.tuttle_invalide()
assert rcode == 0
report = open(report_path).read()
title_match_failure = search(r'<h1>.*Failure.*</h1>', report, DOTALL)
assert not title_match_failure, title_match_failure.group()
@isolate(['A', 'B'])
def test_dont_invalidate_outputless_process(self):
""" Don't invalidate a successful process without outputs(from bug) """
first = """file://C <- file://A
echo A produces C > C
<- file://B
echo Action after B is created
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
rcode, output = self.tuttle_invalide()
assert rcode == 0, output
rcode, output = run_tuttle_file(first)
assert rcode == 0
assert output.find("Nothing to do") >= 0, output
assert output.find("Action") == -1, output
@isolate(['A'])
def test_changes_in_the_graph_without_removing_resource(self):
""" If the graph changes without removing resource tuttle should display a message
event if the removed resource is used elsewhere (from bug) """
#raise SkipTest("Failing for the moment")
first = """ <- file://A
echo Action after A is created.
file://B <- file://A
echo B > B
file://C <- file://B
echo C > C
"""
rcode, output = run_tuttle_file(first)
print output
assert rcode == 0, output
second = """ <- file://A
echo Action after A is created.
file://C <- file://B
echo C > C
"""
rcode, output = self.tuttle_invalide(project=second)
assert rcode == 0, output
assert output.find("Report has been updated to reflect") >= 0, output
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,175 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/extensions/python.py | # -*- coding: utf8 -*-
from os import path, chmod, stat, mkdir
from stat import S_IXUSR, S_IXGRP, S_IXOTH
from subprocess import Popen, PIPE
from tuttlelib.error import TuttleError
from tuttlelib.processors import run_and_log
class PythonProcessor:
""" A processor to run python2 code
"""
name = 'python'
header = u"""# -*- coding: utf8 -*-
from os import getcwd as __get_current_dir__
from sys import path as __python__path__
__python__path__.append(__get_current_dir__())
"""
def generate_executable(self, process, reserved_path):
""" Create an executable file
:param directory: string
:return: the path to the file
"""
mkdir(reserved_path)
script_name = path.abspath(path.join(reserved_path, "{}.py".format(process.id)))
with open(script_name, "w+") as f:
f.write(self.header.encode("utf8"))
f.write(process._code.encode('utf8'))
return script_name
def run(self, process, reserved_path, log_stdout, log_stderr):
script = self.generate_executable(process, reserved_path)
run_and_log(["python", script], log_stdout, log_stderr)
def static_check(self, process):
pass
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,176 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/commands.py | from tuttlelib.error import TuttleError
from tuttlelib.invalidation import prep_for_invalidation
from tuttlelib.project_parser import ProjectParser
from tuttlelib.workflow import Workflow
from tuttlelib.workflow_builder import WorkflowBuilder
from tuttlelib.workflow_runner import WorkflowRuner
def load_project(tuttlefile):
print("load_project Ok")
pp = ProjectParser()
workflow = pp.parse_and_check_file(tuttlefile)
return workflow
def print_missing_input(missing):
error_msg = "Missing the following resources to launch the workflow :\n"
for mis in missing:
error_msg += "* {}\n".format(mis.url)
print(error_msg)
def print_failing_process(failing_process):
msg = "Workflow already failed on process '{}'. Fix the process and run tuttle again.".format(failing_process.id)
msg += "\n\nIf failure has been caused by an external factor like a connection breakdown, " \
'use "tuttle invalidate" to reset execution then "tuttle run" again.'
print(msg)
def print_failures(failure_processes):
print("\nSummary : {} processe(s) have failed:".format(len(failure_processes)))
for process in failure_processes:
header = "== Process : {} ==".format(process.id)
print(header)
print(process.error_message)
def print_success():
print("====")
print("Done")
def print_nothing_to_do():
print("Nothing to do")
def print_updated():
print("Report has been updated to reflect tuttlefile")
def parse_invalidate_and_run(tuttlefile, threshold=-1, nb_workers=-1, keep_going=False):
print("parse_invalidate_and_run Ok")
try:
workflow = load_project(tuttlefile)
except TuttleError as e:
print(e)
return 2
print("load_project Ok")
workflow.discover_resources()
missing = workflow.primary_inputs_not_available()
if missing:
print_missing_input(missing)
return 2
print("Workflow.load Ok")
previous_workflow = Workflow.load()
inv_collector = prep_for_invalidation(workflow, previous_workflow, [])
print("prep_for_invalidation Ok")
failing_process = workflow.pick_a_failing_process()
if failing_process:
# check before invalidate
print_failing_process(failing_process)
return 2
if inv_collector.warn_and_abort_on_threshold(threshold):
return 2
# We have to remove resources, even if there is no previous workflow,
# because of resources that may not have been produced by tuttle
inv_collector.remove_resources(workflow)
inv_collector.reset_execution_info()
inv_collector.straighten_out_availability(workflow)
workflow.create_reports()
workflow.dump()
print("invalidation Ok")
wr = WorkflowRuner(nb_workers)
success_processes, failure_processes = wr.run_parallel_workflow(workflow, keep_going)
if failure_processes:
print_failures(failure_processes)
return 2
if success_processes:
print_success()
elif inv_collector.something_to_invalidate():
print_updated()
else:
print_nothing_to_do()
return 0
def get_resources(urls):
result = []
pb = WorkflowBuilder()
for url in urls:
resource = pb.build_resource(url)
if resource is None:
print("Tuttle cannot understand '{}' as a valid resource url".format(url))
return False
result.append(resource)
return result
def filter_invalidable_urls(workflow, urls):
""" Returns a list of url that can be invalidated and warns about illegal urls"""
to_invalidate = []
for url in urls:
resource = workflow.find_resource(url)
if not resource:
msg = "Ignoring {} : this resource does not belong to the workflow.".format(url)
print(msg)
elif not workflow.resource_available(url):
msg = "Ignoring {} : this resource has not been produced yet.".format(url)
print(msg)
elif resource.is_primary():
msg = "Ignoring {} : primary resources can't be invalidated.".format(url)
print(msg)
else:
to_invalidate.append(url)
return to_invalidate
def invalidate_resources(tuttlefile, urls, threshold=-1):
resources = get_resources(urls)
if resources is False:
return 2
previous_workflow = Workflow.load()
if previous_workflow is None:
print("Tuttle has not run yet ! It has produced nothing, so there is nothing to invalidate.")
return 2
try:
workflow = load_project(tuttlefile)
# TODO : add preprocessors to invalidation
except TuttleError as e:
print("Invalidation has failed because tuttlefile is has errors (a valid project is needed for "
"clean invalidation) :")
print(e)
return 2
workflow.discover_resources()
to_invalidate = filter_invalidable_urls(workflow, urls)
inv_collector = prep_for_invalidation(workflow, previous_workflow, to_invalidate)
if inv_collector.resources_to_invalidate():
if inv_collector.warn_and_abort_on_threshold(threshold):
return 2
# availability has already been cleared in rep_for_inv
inv_collector.remove_resources(workflow)
inv_collector.reset_execution_info()
inv_collector.straighten_out_availability(workflow)
reseted_failures = workflow.reset_failures()
if inv_collector.resources_to_invalidate() or reseted_failures:
workflow.dump()
workflow.create_reports()
if not inv_collector.resources_to_invalidate():
if reseted_failures or inv_collector.something_to_invalidate():
print_updated()
else:
print_nothing_to_do()
return 0
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,177 | PointyShinyBurning/tuttle | refs/heads/master | /tests/test_run_parallel.py | # -*- coding: utf-8 -*-
from os.path import isfile, abspath, exists
from tests.test_project_parser import ProjectParser
from tests.functional_tests import run_tuttle_file, isolate
from tuttlelib.resources import FileResource
from tuttlelib.workflow_runner import WorkflowRuner
from tuttlelib.workflow import Workflow
from time import time, sleep
class BuggyProcessor:
# This class mus remain outside another class because it is serialized
name = 'buggy_processor'
def static_check(self, process):
pass
def run(self, process, reserved_path, log_stdout, log_stderr):
raise Exception("Unexpected error in processor")
class BuggySignatureResource(FileResource):
# This class mus remain outside another class because it is serialized
scheme = 'buggy'
def _get_path(self):
return abspath(self.url[len("buggy://"):])
def signature(self):
raise Exception("Unexpected error in signature()")
class BuggyExistsResource(FileResource):
# This class mus remain outside another class because it is serialized
scheme = 'buggy'
def _get_path(self):
return abspath(self.url[len("buggy://"):])
def exists(self):
if exists(self._get_path()):
raise Exception("Unexpected error in exists()")
else:
return False
def run_first_process(one_process_workflow, extra_processor = None, extra_resource = None):
""" utility method to run the first process of a workflow and assert on process result """
pp = ProjectParser()
if extra_processor:
# we can inject a new processor to test exceptions
pp.wb._processors[extra_processor.name] = extra_processor
if extra_resource:
# we can inject a new resource to test exceptions
pp.wb._resources_definition[extra_resource.scheme] = extra_resource
pp.set_project(one_process_workflow)
workflow = pp.parse_extend_and_check_project()
process = workflow._processes[0]
wr = WorkflowRuner(2)
wr.init_workers()
try:
WorkflowRuner.prepare_and_assign_paths(process)
wr._lt.follow_process(process.log_stdout, process.log_stderr, process.id)
with wr._lt.trace_in_background():
wr.start_process_in_background(process) # The function we're testing !
timeout = time() + 0.5
while time() < timeout and not wr._completed_processes:
sleep(0.1)
assert time() < timeout, "Process should have stoped now"
finally:
wr.terminate_workers_and_clean_subprocesses()
return process
class TestRunParallel():
def test_workers(self):
"""Test the flow of using workers"""
wr = WorkflowRuner(4)
try:
wr.init_workers()
assert wr.workers_available() == 4
wr.acquire_worker()
assert wr.workers_available() == 3
wr.acquire_worker()
assert wr.active_workers()
wr.acquire_worker()
assert wr.active_workers()
wr.acquire_worker()
assert not wr.active_workers()
wr.release_worker()
assert wr.active_workers()
wr.release_worker()
assert wr.workers_available() == 2
wr.terminate_workers_and_clean_subprocesses()
except:
wr.terminate_workers_and_clean_subprocesses()
def test_background_process(self):
""" Starting a process in background should end up with the process beeing
added to the list of completed processes"""
first = """file://B <- file://A
sleep 1
echo A produces B > B
"""
pp = ProjectParser()
pp.set_project(first)
workflow = pp.parse_extend_and_check_project()
process = workflow._processes[0]
wr = WorkflowRuner(3)
wr.init_workers()
try:
wr.start_process_in_background(process)
assert wr.active_workers()
timeout = time() + 1.5
while time() < timeout and not wr._completed_processes:
sleep(0.1)
assert time() < timeout, "Process should have stoped now"
finally:
wr.terminate_workers_and_clean_subprocesses()
@isolate(['A'])
def test_error_before_all_processes_complete(self):
""" When a process stops in error, all running processes whould be stopped right now and declared in error """
first = """file://B <- file://A
sleep 1
echo A produces B > B
error
file://C <- file://A
sleep 2
echo A produces C > C
"""
rcode, output = run_tuttle_file(first, nb_workers=2)
assert rcode == 2
assert isfile('B')
assert not isfile('C')
w = Workflow.load()
p = w.find_process_that_creates("file://C")
assert not p.success, "Process that creates C should be in error in the dump"
def test_error_message_from_background_process(self):
""" When the process fails, its success attribute should be false, and there should be an error message"""
one_process_workflow = """file://B <- file://A
error
echo A produces B > B
"""
process = run_first_process(one_process_workflow)
assert process.error_message.find("Process ended with error code") >= 0, process.error_message
@isolate(['A'])
def test_outputs_not_created(self):
""" When the outputs have not been created by a process, there should be an error message"""
one_process_workflow = """file://B <- file://A
echo A does not produce B
"""
process = run_first_process(one_process_workflow)
assert process.success is False, process.error_message
assert process.error_message.find("these resources should have been created") >= 0, process.error_message
assert process.error_message.find("* file://B") >= 0, process.error_message
@isolate(['A'])
def test_unexpected_error_in_processor(self):
""" Tuttle should be protected against unexpected exceptions from the processor """
one_process_workflow = """file://B <- file://A ! buggy_processor
echo A does not produce B
"""
process = run_first_process(one_process_workflow, BuggyProcessor())
assert process.success is False, process.error_message
assert process.error_message.find('An unexpected error have happen in tuttle processor '
'buggy_processor :') >= 0, process.error_message
assert process.error_message.find('Traceback (most recent call last):') >= 0, process.error_message
assert process.error_message.find('raise Exception("Unexpected error in processor")') >= 0, process.error_message
assert process.error_message.find('will not complete.') >= 0, process.error_message
@isolate(['A'])
def test_unexpected_error_in_signature(self):
""" Tuttle should be protected against unexpected exceptions from resource.signature() """
# TODO
one_process_workflow = """buggy://B <- file://A
echo A produces B > B
"""
process = run_first_process(one_process_workflow, extra_resource=BuggySignatureResource)
assert process.success is False, process.error_message
assert process.error_message.find('An unexpected error have happen in tuttle while retrieving signature' \
) >= 0, process.error_message
assert process.error_message.find('Traceback (most recent call last):') >= 0, process.error_message
assert process.error_message.find('raise Exception("Unexpected error in signature()")') >= 0, process.error_message
assert process.error_message.find('Process cannot be considered complete.') >= 0, process.error_message
@isolate(['A'])
def test_unexpected_error_in_exists(self):
""" Tuttle should be protected against unexpected exceptions from resource.exists() """
# TODO
one_process_workflow = """buggy://B <- file://A
echo A produces B > B
"""
process = run_first_process(one_process_workflow, extra_resource=BuggyExistsResource)
assert process.success is False, process.error_message
assert process.error_message.find('An unexpected error have happen in tuttle while checking existence of '
'output resources' ) >= 0, process.error_message
assert process.error_message.find('Traceback (most recent call last):') >= 0, process.error_message
assert process.error_message.find('raise Exception("Unexpected error in exists()")') >= 0, process.error_message
assert process.error_message.find('Process cannot be considered complete.') >= 0, process.error_message
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,178 | PointyShinyBurning/tuttle | refs/heads/master | /tests/functional_tests/test_errors/test_keep_going.py | # -*- coding: utf-8 -*-
import glob
from os.path import isfile
from tests.functional_tests import isolate, run_tuttle_file
from tuttlelib.project_parser import ProjectParser
from tuttlelib.workflow_runner import WorkflowRuner
class TestKeepGoing:
@isolate(['A'])
def test_keep_going(self):
""" If tuttle is run with option keep_going, it should run all it can and not stop at first error"""
# As in Gnu Make
project = """file://B <- file://A
Obvious error
file://C <- file://B
echo B produces C > C
file://D <- file://A
echo A produces D
echo A produces D > D
file://E <- file://A
Another error
"""
rcode, output = run_tuttle_file(project, nb_workers=1, keep_going=True)
assert rcode == 2
assert output.find("::stderr") >= 0, output
assert output.find("Obvious") >= 0, output
assert output.find("Another") >= 0, output
assert output.find("Process ended with error code 1") >= 0, output
pos_have_failed = output.find("have failed")
assert pos_have_failed >= 0, output
assert output.find("tuttlefile_1", pos_have_failed) >= 0, output
assert output.find("tuttlefile_11", pos_have_failed) >= 0, output
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,179 | PointyShinyBurning/tuttle | refs/heads/master | /tests/functional_tests/test_threshold.py | # -*- coding: utf-8 -*-
from subprocess import Popen, PIPE
from os.path import isfile, dirname, abspath, join
from os import path
from tests.functional_tests import isolate, run_tuttle_file
class TestThreshold:
@isolate(['A'])
def test_abort_if_lost_exceeds_threshold(self):
""" Should disply a message and abort if processing time lost by invalidation is above the threshold """
first = """file://B <- file://A
echo A produces B
echo B > B
file://C <- file://B
echo B produces C
python -c "import time; time.sleep(2)"
echo C > C
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
assert isfile('C')
second = """file://B <- file://A
echo B has changed
echo B has changed > B
file://C <- file://B
echo B produces C
python -c "import time; time.sleep(2)"
echo C > C
"""
rcode, output = run_tuttle_file(second, threshold=1)
assert rcode == 2, output
assert output.find("Aborting") >= 0, output
@isolate(['A'])
def test_not_abort_if_lost_not_exceeds_threshold(self):
""" Should disply a message and abort if processing time lost by invalidation is above the threshold """
first = """file://B <- file://A
echo A produces B
echo B > B
file://C <- file://B
echo B produces C
echo C > C
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
assert isfile('C')
second = """file://B <- file://A
echo B has changed
echo B has changed > B
file://C <- file://B
echo B produces C
echo C > C
"""
rcode, output = run_tuttle_file(second, threshold=1)
assert rcode == 0, output
assert output.find("Aborting") == -1, output
@isolate(['A'])
def test_not_abort_if_threshold_is_0(self):
""" Should abort if threshold whatever lost time is"""
first = """file://B <- file://A
echo A produces B
echo B > B
file://C <- file://B
echo B produces C
echo C > C
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
assert isfile('B')
assert isfile('C')
second = """file://B <- file://A
echo B has changed
echo B has changed > B
file://C <- file://B
echo B produces C
echo C > C
"""
rcode, output = run_tuttle_file(second, threshold=0)
assert rcode == 2, output
assert output.find("Aborting") >= 0, output
assert isfile('B')
assert isfile('C')
@isolate(['A'])
def test_threshold_in_command_line_run(self):
""" The threshold -t parameter should be available from the command line"""
first = """file://B <- file://A
echo A produces B
python -c "import time; time.sleep(1)"
echo B > B
file://C <- file://B
echo B produces C
echo C > C
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
assert isfile('B')
second = """file://B <- file://A
echo B has changed
echo B has changed > B
"""
with open('tuttlefile', "w") as f:
f.write(second)
proc = Popen(['tuttle', 'run', '-t', '1'], stdout=PIPE)
output = proc.stdout.read()
rcode = proc.wait()
assert rcode == 2, output
assert output.find('Aborting') >= 0, output
assert isfile('B'), output
@isolate(['A'])
def test_ignore_default_threshold(self):
""" Threshold should be ignored if not provided or left to default value"""
first = """file://B <- file://A
echo A produces B
python -c "import time; time.sleep(2)"
echo B > B
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
assert isfile('B')
second = """file://B <- file://A
echo B has changed
echo B has changed > B
"""
with open('tuttefile', "w") as f:
f.write(second)
proc = Popen(['tuttle', 'run'], stdout=PIPE)
output = proc.stdout.read()
rcode = proc.wait()
assert rcode == 0, output
assert output.find('Aborting') == -1, output
@isolate(['A'])
def test_threshold_in_command_line_invalidate(self):
""" The threshold -t parameter should be available from the invalidate command"""
first = """file://B <- file://A
echo A produces B
python -c "import time; time.sleep(2)"
echo B > B
"""
rcode, output = run_tuttle_file(first)
assert rcode == 0, output
assert isfile('B')
proc = Popen(['tuttle', 'invalidate', '-t', '1', 'file://B'], stdout=PIPE)
output = proc.stdout.read()
rcode = proc.wait()
assert rcode == 2, output
assert output.find('Aborting') >= 0, output
assert isfile('B'), output
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,180 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/report/html_repport.py | # -*- coding: utf8 -*-
from jinja2 import Template
from os import path, error
from shutil import copytree
from time import strftime, localtime
from tuttlelib.report.dot_repport import dot
from os.path import dirname, join, relpath, abspath, split
import sys
def data_path(*path_parts):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = join(dirname(sys.executable), "report")
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = dirname(__file__)
return join(datadir, *path_parts)
def nice_size(size):
if size < 1000:
return "{} B".format(size)
elif size < 1000 * 1000:
return "{} KB".format(size / 1024)
elif size < 1000 * 1000 * 1000:
return "{} MB".format(size / (1024 * 1024))
elif size < 1000 * 1000 * 1000 * 1000:
return "{} GB".format(size / (1024 * 1024 * 1024))
def nice_file_size(filename):
if not filename:
return ""
try:
file_size = path.getsize(filename)
if file_size == 0:
return "empty"
return nice_size(file_size)
except error:
return ""
def format_resource(resource, workflow):
sig = workflow.signature(resource.url)
return {
'url': resource.url,
'signature': sig,
}
def workflow_status(workflow):
for process in workflow.iter_processes():
if process.start and not process.end:
return "NOT_FINISHED"
if process.success is False:
return "FAILURE"
if not process.start:
return "NOT_FINISHED"
return "SUCCESS"
def path2url(path, ref_path):
if path is None:
return
abs_path = abspath(path)
rel_path = relpath(abs_path, ref_path)
parts = split(rel_path)
return '/'.join(parts)
def format_process(process, workflow, report_dir):
duration = ""
start = ""
end = ""
if process.start:
start = strftime("%a, %d %b %Y %H:%M:%S", localtime(process.start))
if process.end:
end = strftime("%a, %d %b %Y %H:%M:%S", localtime(process.end))
duration = process.end - process.start
return {
'id': process.id,
'processor': process.processor.name,
'start': start,
'end': end,
'duration': duration,
'log_stdout': path2url(process.log_stdout, report_dir),
'log_stdout_size': nice_file_size(process.log_stdout),
'log_stderr': path2url(process.log_stderr, report_dir),
'log_stderr_size': nice_file_size(process.log_stderr),
'outputs': (format_resource(resource, workflow) for resource in process.iter_outputs()),
'inputs': (format_resource(resource, workflow) for resource in process.iter_inputs()),
'code': process.code,
'success': process.success,
'error_message': process.error_message,
}
def ensure_assets(dest_dir):
assets_dir = path.join(dest_dir, 'html_report_assets')
if not path.isdir(assets_dir):
copytree(data_path('html_report_assets', ''), assets_dir)
def create_html_report(workflow, filename):
""" Write an html file describing the workflow
:param workflow:
:param filename: path to the html fil to be generated
:return: None
"""
file_dir = path.dirname(filename)
ensure_assets(file_dir)
tpl_filename = data_path("report_template.html")
with open(tpl_filename, 'rb') as ftpl:
t = Template(ftpl.read().decode('utf8'))
processes = [format_process(p, workflow, abspath(file_dir)) for p in workflow.iter_processes()]
preprocesses = [format_process(p, workflow, abspath(file_dir)) for p in workflow.iter_preprocesses()]
with open(filename, 'wb') as fout:
content = t.render(processes=processes, preprocesses=preprocesses, dot_src=dot(workflow), status=workflow_status(workflow))
fout.write(content.encode('utf8)'))
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,181 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/report/dot_repport.py | # -*- coding: utf8 -*-
DOT_HEADER = """digraph workflow {
Node [style="rounded,filled", shape=box, fillcolor=none]
"""
def color_from_process(process):
color = "none"
if process.start:
if not process.end:
# Running
color = "skyblue"
elif process.success:
# success
color = "green"
else:
color = "red"
return color
# TODO nick names for resources should be uniq
def nick_from_url(url):
parts = url.split("/")
return parts.pop()
def dot_id(url):
import urllib
return urllib.quote(url)
def process_node_id(id):
p_node = '"p_{}"'.format(id)
return p_node
def dot(workflow):
# TODO :
# * Add a legend
# * Show missing resources in a different color
result = DOT_HEADER
for process in workflow.iter_processes():
color = color_from_process(process)
p_node = process_node_id(process.id)
if color != "none":
fontcolor = color
else:
fontcolor = "black"
result += ' {} [label="{}", URL="#{}", color={}, fontcolor={}, width=0, height=0] ' \
';\n'.format(p_node, process.id, process.id, color, fontcolor)
for res_input in process.iter_inputs():
nick = nick_from_url(res_input.url)
resource_id = dot_id(res_input.url)
result += ' "{}" -> {} [arrowhead="none"] \n'.format(resource_id, p_node)
if res_input.is_primary():
result += ' "{}" [fillcolor=beige, label="{}"] ;\n'.format(resource_id, nick)
for res_output in process.iter_outputs():
nick = nick_from_url(res_output.url)
resource_id = dot_id(res_output.url)
result += ' {} -> "{}" \n'.format(p_node, resource_id)
result += ' "{}" [fillcolor={}, label="{}"] ;\n'.format(resource_id, color, nick)
result += '}'
return result
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,182 | PointyShinyBurning/tuttle | refs/heads/master | /tests/test_extensions/test_net_extension.py | # -*- coding: utf8 -*-
import re
from os.path import isfile, join
from tests.functional_tests import isolate, run_tuttle_file
from tuttlelib.error import TuttleError
from tuttlelib.project_parser import ProjectParser
from tuttlelib.extensions.net import HTTPResource
from BaseHTTPServer import BaseHTTPRequestHandler
from SocketServer import TCPServer
from tuttlelib.workflow_runner import WorkflowRuner
class MockHTTPHandler(BaseHTTPRequestHandler):
""" This class is used to mock some HTTP behaviours :
* Etag
* Last-Modified
* Neither
Useful both for running tests offline and for not depending on some external change
"""
def do_GET(self):
if self.path == "/resource_with_etag":
self.send_response(200, "OK")
self.send_header('Etag', 'my_etag')
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This resource provides an Etag")
if self.path == "/resource_with_last_modified":
self.send_response(200, "OK")
self.send_header('Last-Modified', 'Tue, 30 Jun 1981 03:14:59 GMT')
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This resource provides a Last-Modified")
if self.path == "/resource_without_version":
self.send_response(200, "OK")
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This resource has no version information")
class TestHttpResource():
httpd = None
p = None
@classmethod
def run_server(cls):
cls.httpd = TCPServer(("", 8042), MockHTTPHandler)
cls.httpd.serve_forever()
@classmethod
def setUpClass(cls):
""" Run a web server in background to mock some specific HTTP behaviours
"""
from threading import Thread
cls.p = Thread(target=cls.run_server)
cls.p.start()
@classmethod
def tearDownClass(cls):
""" Stop the http server in background
"""
cls.httpd.shutdown()
cls.p.join()
def test_real_resource_exists(self):
"""A real resource should exist"""
# TODO : change this when tuttle has its site... If it can handle the load...
# Or by a local http server
res = HTTPResource("http://www.google.com/")
assert res.exists()
def test_fictive_resource_not_exists(self):
"""A fictive resource should not exist"""
res = HTTPResource("http://www.example.com/tuttle")
assert not res.exists()
def test_http_resource_in_workflow(self):
"""An HTTP resource should be allowed in a workflow"""
pp = ProjectParser()
project = "file://result <- http://www.google.com/"
pp.set_project(project)
workflow = pp.parse_project()
assert len(workflow._processes) == 1
inputs = [res for res in workflow._processes[0].iter_inputs()]
assert len(inputs) == 1
# TODO : should we follow resources in case of http redirection ?
def test_resource_etag_signature(self):
""" An HTTPResource with an Etag should use it as signature """
res = HTTPResource("http://www.example.com/")
sig = res.signature()
assert sig.find('Etag:') >= 0, sig
assert sig.find('359670651') >= 0, sig
def test_resource_last_modified_signature(self):
""" An HTTPResource with an Last-Modified should use it as signature in case it doesn't have Etag"""
# res = HTTPResource("http://www.wikipedia.org/")
res = HTTPResource("http://localhost:8042/resource_with_last_modified")
sig = res.signature()
assert sig == 'Last-Modified: Tue, 30 Jun 1981 03:14:59 GMT', sig
def test_ressource_signature_without_etag_nor_last_modified(self):
""" An HTTPResource signature should be a hash of the beginning of the file if we can't rely on headers """
res = HTTPResource("http://localhost:8042/resource_without_version")
sig = res.signature()
assert sig == 'sha1-32K: 7ab4a6c6ca8bbcb3de82530797a0e455070e18fa', sig
class TestHttpsResource:
def test_real_resource_exists(self):
"""A real resource should exist"""
res = HTTPResource("https://www.google.com/")
assert res.exists()
def test_fictive_resource_not_exists(self):
"""A fictive resource should not exist"""
res = HTTPResource("https://www.example.com/tuttle")
assert not res.exists()
def test_http_resource_in_workflow(self):
"""An HTTPS resource should be allowed in a workflow"""
pp = ProjectParser()
project = "file://result <- https://www.google.com/"
pp.set_project(project)
workflow = pp.parse_project()
assert len(workflow._processes) == 1
inputs = [res for res in workflow._processes[0].iter_inputs()]
assert len(inputs) == 1
class TestDownloadProcessor:
@isolate
def test_standard_download(self):
"""Should download a simple url"""
project = " file://google.html <- http://www.google.com/ ! download"
pp = ProjectParser()
pp.set_project(project)
workflow = pp.parse_extend_and_check_project()
workflow.static_check_processes()
workflow.discover_resources()
wr = WorkflowRuner(3)
wr.run_parallel_workflow(workflow)
assert isfile("google.html")
content = open("google.html").read()
assert content.find("<title>Google</title>") >= 0
logs = open(join(".tuttle", "processes", "logs", "__1_stdout.txt"), "r").read()
assert re.search("\n\.+\n", logs) is not None
assert isfile(join(".tuttle", "processes", "logs", "__1_err.txt"))
@isolate
def test_long_download(self):
""" Progress dots should appear in the logs in a long download"""
project = " file://jquery.js <- http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js ! download"
pp = ProjectParser()
pp.set_project(project)
workflow = pp.parse_extend_and_check_project()
workflow.static_check_processes()
workflow.discover_resources()
wr = WorkflowRuner(3)
wr.run_parallel_workflow(workflow)
assert isfile("jquery.js"), "jquery.js is missing"
logs = open(join(".tuttle", "processes", "logs", "__1_stdout.txt"), "r").read()
assert logs.find("...") >= 0
@isolate
def test_pre_check(self):
"""Should fail if not http:// <- file:// """
project = " http://www.google.com/ <- ! download"
pp = ProjectParser()
pp.set_project(project)
try:
workflow = pp.parse_extend_and_check_project()
assert False, "An exception should be raised"
except TuttleError:
assert True
# @isolate
# def test_download_fails(self):
# """Should raise an exception if download fails"""
# project = " file://tuttle.html <- http://www.example.com/tuttle ! download"
# pp = ProjectParser()
# pp.set_project(project)
# # Don't check project or execution of the workflow will not be allowed because input resource is missing
# workflow = pp.parse_project()
# print workflow._processes
# print [res.url for res in workflow._processes[0].inputs]
# workflow.prepare_execution()
# workflow.run()
# assert isfile("tuttle.html")
@isolate
def test_pre_check_before_running(self):
""" Pre check should happen for each process before run the whole workflow """
project = """file://A <-
obvious failure
file://google.html <- file://A ! download
"""
rcode, output = run_tuttle_file(project)
assert rcode == 2
assert output.find("Download processor") >= 0, output
@isolate
def test_pre_check_before_invalidation(self):
"""Pre check should happen before invalidation"""
project1 = """file://A <-
echo A > A
"""
rcode, output = run_tuttle_file(project1)
assert isfile('A')
project2 = """file://A <-
echo different > A
file://google.html <- file://A ! download
"""
rcode, output = run_tuttle_file(project2)
assert rcode == 2
assert output.find("* file://B") == -1
assert output.find("Download processor") >= 0, output
@isolate
def test_download_https(self):
"""https download should work"""
project = "file://google.html <- https://www.google.com/ ! download"
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
assert isfile("google.html")
content = open("google.html").read()
assert content.find("<title>Google</title>") >= 0
logs = open(join(".tuttle", "processes", "logs", "tuttlefile_1_stdout.txt"), "r").read()
assert re.search("\n\.+\n", logs) is not None
assert isfile(join(".tuttle", "processes", "logs", "tuttlefile_1_err.txt"))
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,183 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/invalidation.py | # -*- coding: utf8 -*-
from itertools import chain
NOT_PRODUCED_BY_TUTTLE = "The existing resource has not been produced by tuttle"
USER_REQUEST = "User request"
PROCESS_HAS_FAILED = "The resource has been produced by a failing process"
NO_LONGER_CREATED = "Resource no longer created by the newer process"
NOT_SAME_INPUTS = "Resource was created with different inputs"
PROCESS_HAS_CHANGED = "Process code has changed"
PROCESSOR_HAS_CHANGED = "Processor has changed"
MUST_CREATE_RESOURCE = "The former primary resource has to be created by tuttle" # Is it a subscase of NOT_PRODUCED_BY_TUTTLE ?
RESOURCE_NOT_CREATED_BY_TUTTLE = "The existing resource has not been created by tuttle"
RESOURCE_HAS_CHANGED = "Primary resource has changed"
INCOHERENT_OUTPUTS = "Other outputs produced by the same process are missing"
DEPENDENCY_CHANGED = "Resource depends on {} that have changed"
BROTHER_INVALID = "Resource is created along with {} that is invalid"
BROTHER_MISSING = "Resource is created along with {} that is missing"
class InvalidCollector:
""" This class class collects the resources to invalidate and their reason, in order to display them to the user
and remove them all at once.
Resources can come from several workflows (eg the current and the previous one)
"""
def __init__(self, previous_workflow):
self._resources_and_reasons = []
self._resources_urls = set()
self._processes = []
self._previous_processes = []
self._previous_workflow = previous_workflow
def iter_urls(self):
for url in self._resources_urls:
yield url
def resource_invalid(self, url):
return url in self._resources_urls
def resources_to_invalidate(self):
return self._resources_urls
def something_to_invalidate(self):
return self._resources_urls or self._previous_processes or self._processes
def duration(self):
all_processes = (process for process in chain(self._previous_processes, self._processes))
duration_sum = sum( (process.end - process.start for process in all_processes if process.end is not None) )
return int(duration_sum)
def warn_and_abort_on_threshold(self, threshold):
aborted = False
if self._resources_and_reasons: # BETTER TEST NEEDED HERE
inv_duration = self.duration()
print("The following resources are not valid any more and will be removed :")
for resource, reason in self._resources_and_reasons:
print("* {} - {}".format(resource.url, reason))
if -1 < threshold <= inv_duration:
msg = "You were about to loose {} seconds of processing time (which exceeds the {} seconds " \
"threshold). \nAborting... ".format(inv_duration, threshold)
print(msg)
aborted = True
else:
print("{} seconds of processing will be lost".format(inv_duration))
return aborted
def remove_resources(self, workflow):
for resource, reason in self._resources_and_reasons:
# if resource is from the workflow, we know its availability
# but we have to check existence if it comes from the previous workflow
if (workflow.contains_resource(resource) and workflow.resource_available(resource.url)) \
or resource.exists():
try:
resource.remove()
except Exception as e:
msg = 'Warning : Removing resource {} has failed. Even if the resource is still available, ' \
'it should not be considered valid.'.format(resource.url)
print(msg)
def reset_execution_info(self):
for process in self._processes:
process.reset_execution_info()
def collect_resource(self, resource, reason):
if resource.url not in self._resources_urls:
self._resources_and_reasons.append((resource, reason))
self._resources_urls.add(resource.url)
def collect_prev_process_and_not_primary_outputs(self, new_workflow, prev_process, reason):
for resource in prev_process.iter_outputs():
new_resource = new_workflow.find_resource(resource.url)
if not (new_resource and new_resource.is_primary()):
self.collect_resource(resource, reason)
# Should we check for availability ?
self._previous_processes.append(prev_process)
def collect_process_and_available_outputs(self, workflow, process, reason):
for resource in process.iter_outputs():
if workflow.resource_available(resource.url):
self.collect_resource(resource, reason)
self._processes.append(process)
def ensure_successful_process_validity(self, workflow, process, invalidate_urls):
for input_resource in process.iter_inputs():
if input_resource.is_primary():
if self._previous_workflow:
if self._previous_workflow.signature(input_resource.url) != workflow.signature(input_resource.url):
self.collect_process_and_available_outputs(workflow, process, RESOURCE_HAS_CHANGED)
# All outputs have been invalidated, no need to dig further
return
elif self.resource_invalid(input_resource.url):
reason = DEPENDENCY_CHANGED.format(input_resource.url)
self.collect_process_and_available_outputs(workflow, process, reason)
# All outputs have been invalidated, no need to dig further
return
for output_resource in process.iter_outputs():
if output_resource.url in invalidate_urls:
self.collect_resource(output_resource, USER_REQUEST)
reason = BROTHER_INVALID.format(output_resource.url)
self.collect_process_and_available_outputs(workflow, process, reason)
# All outputs have been invalidated, no need to dig further
return
elif not workflow.resource_available(output_resource.url):
reason = BROTHER_MISSING.format(output_resource.url)
self.collect_process_and_available_outputs(workflow, process, reason)
# All outputs have been invalidated, no need to dig further
return
# Could check for integrity here
def ensure_process_validity(self, workflow, process, invalidate_urls):
if not process.start:
# Process hasn't run yet. So it can't produce valid outputs
for resource in process.iter_outputs():
if workflow.resource_available(resource.url):
self.collect_resource(resource, RESOURCE_NOT_CREATED_BY_TUTTLE)
else:
if process.success is False:
# Process has failed. So it can't have produced valid outputs
for resource in process.iter_outputs():
if workflow.resource_available(resource.url):
self.collect_resource(resource, PROCESS_HAS_FAILED)
# NB : we don't collect the process itself, in order to be able to check for failing processes
else:
# If process is in success, we need to look deeper to check if everything is coherent
self.ensure_successful_process_validity(workflow, process, invalidate_urls)
def insure_dependency_coherence(self, workflow, invalidate_urls):
for process in workflow.iter_processes_on_dependency_order():
self.ensure_process_validity(workflow, process, invalidate_urls)
def retrieve_common_processes_form_previous(self, workflow):
if not self._previous_workflow:
return
for prev_process in self._previous_workflow.iter_processes():
if prev_process.start:
# Don't need to retreive from a process that hasn't run yet
process = workflow.similar_process(prev_process)
if not process:
self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, NO_LONGER_CREATED)
else:
if process.code != prev_process.code:
self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, PROCESS_HAS_CHANGED)
elif process.processor.name != prev_process.processor.name:
self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, PROCESSOR_HAS_CHANGED)
elif process.input_urls() != prev_process.input_urls():
self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, NOT_SAME_INPUTS)
# elif process.output_urls() != prev_process.output_url():
# invalid_collector.collect_process_and_outputs(workflow, prev_process, NOT_SAME_OUPUTS)
# Should we ? Only if check-integrity
else:
# Both process are the same
process.retrieve_execution_info(prev_process)
def straighten_out_availability(self, workflow):
if self._previous_workflow:
workflow.retrieve_signatures_new(self._previous_workflow)
workflow.clear_availability(self.iter_urls())
workflow.fill_missing_availability()
def prep_for_invalidation(workflow, prev_workflow, invalidate_urls):
inv_collector = InvalidCollector(prev_workflow)
inv_collector.retrieve_common_processes_form_previous(workflow)
# workflow contains execution info based on what happened in previous
inv_collector.insure_dependency_coherence(workflow, invalidate_urls)
return inv_collector
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,184 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/workflow_runner.py | # -*- coding: utf8 -*-
"""
Utility methods for use in running workflows.
This module is responsible for the inner structure of the .tuttle directory
"""
def test_run_process_without_exception(process):
print("run_process_without_exception Ok")
return
from glob import glob
from multiprocessing import Pool, cpu_count
import multiprocessing
from shutil import rmtree
from os import remove, makedirs, getcwd
from os.path import join, isdir, isfile
from traceback import format_exception
from tuttlelib.error import TuttleError
from tuttlelib.utils import EnvVar
from tuttlelib.log_follower import LogsFollower
from time import sleep, time
import sys
import logging
import psutil
LOGGER = logging.getLogger(__name__)
def print_process_header(process, logger):
pid = multiprocessing.current_process().pid
msg = "{}\nRunning process {} (pid={})".format("=" * 60, process.id, pid)
logger.info(msg)
def resources2list(resources):
res = "\n".join(("* {}".format(resource.url) for resource in resources))
return res
def output_signatures(process):
result = {resource.url : str(resource.signature()) for resource in process.iter_outputs()}
return result
# This is a free method, because it will be serialized and passed
# to another process, so it must not be linked to objects nor
# capture closures
def run_process_without_exception(process):
multiprocessing.current_process().name = process.id
print("After process name Ok")
try:
print_process_header(process, LOGGER)
print("After print_process_header Ok")
process._processor.run(process, process._reserved_path, process.log_stdout, process.log_stderr)
except TuttleError as e:
return False, str(e), None
except Exception:
exc_info = sys.exc_info()
stacktrace = "".join(format_exception(*exc_info))
error_msg = "An unexpected error have happen in tuttle processor {} : \n" \
"{}\n" \
"Process {} will not complete.".format(process._processor.name, stacktrace, process.id)
return False, error_msg, None
try:
missing_outputs = process.missing_outputs()
except Exception:
exc_info = sys.exc_info()
stacktrace = "".join(format_exception(*exc_info))
error_msg = "An unexpected error have happen in tuttle while checking existence of output resources " \
"after process {} has run: \n" \
"{}\n" \
"Process cannot be considered complete.".format(process.id, stacktrace)
return False, error_msg, None
if missing_outputs:
msg = "After execution of process {} : these resources " \
"should have been created : \n{} ".format(process.id, resources2list(missing_outputs))
return False, msg, None
try:
signatures = output_signatures(process)
except Exception:
exc_info = sys.exc_info()
stacktrace = "".join(format_exception(*exc_info))
error_msg = "An unexpected error have happen in tuttle while retrieving signature after process {} has run: " \
"\n{}\n" \
"Process cannot be considered complete.".format(process.id, stacktrace)
return False, error_msg, None
return True, None, signatures
def tuttle_dir(*args):
return join('.tuttle', *args)
class WorkflowRuner:
_processes_dir = tuttle_dir('processes')
_logs_dir = tuttle_dir('processes', 'logs')
_extensions_dir = tuttle_dir('extensions')
@staticmethod
def tuttle_dir(*args):
return join('.tuttle', *args)
@staticmethod
def resources2list(resources):
res = "\n".join(("* {}".format(resource.url) for resource in resources))
return res
def __init__(self, nb_workers):
self._lt = LogsFollower()
self._logger = WorkflowRuner.get_logger()
self._pool = None
if nb_workers == -1:
self._nb_workers = int( (cpu_count() + 1) / 2)
else :
self._nb_workers = nb_workers
self._free_workers = None
self._completed_processes = []
def start_process_in_background(self, process):
print("start_process_in_background Ok")
sleep(1)
print("Slept 1s ok")
self.acquire_worker()
def process_run_callback(result):
success, error_msg, signatures = result
process.set_end(success, error_msg)
self.release_worker()
self._completed_processes.append((process, signatures))
process.set_start()
resp = self._pool.apply_async(run_process_without_exception, [process], callback = process_run_callback)
#print resp.wait(5)
#raise Exception("Stop")
def run_parallel_workflow(self, workflow, keep_going=False):
""" Runs a workflow by running every process in the right order
:return: success_processes, failure_processes :
list of processes ended with success, list of processes ended with failure
"""
print("run_parallel_workflow Ok")
sleep(1)
print("Slept 1s ok")
sys.stdin.flush()
# TODO create tuttle dirs only once
WorkflowRuner.create_tuttle_dirs()
for process in workflow.iter_processes():
WorkflowRuner.prepare_and_assign_paths(process)
self._lt.follow_process(process.log_stdout, process.log_stderr, process.id)
print("Added logs to follow ok")
sys.stdin.flush()
failure_processes, success_processes = [], []
print("Before starting to trace in bg ok")
sys.stdin.flush()
sleep(1)
print("Slept 1s ok")
sys.stdin.flush()
with self._lt.trace_in_background():
print("After starting to trace in bg ok")
sys.stdin.flush()
sleep(1)
print("Slept 1s ok")
sys.stdin.flush()
self.init_workers()
print("After workers are initialized in bg ok")
sys.stdin.flush()
sleep(1)
print("Slept 1s ok")
sys.stdin.flush()
runnables = workflow.runnable_processes()
failures = False
while (keep_going or not failures) and (self.active_workers() or self._completed_processes or runnables):
print("keep_going = {}".format(keep_going))
print("failures = {}".format(failures))
print("self.active_workers() = {}".format(self.active_workers()))
print("self._completed_processes = {}".format(self._completed_processes))
print("runnables = {}".format(runnables))
print("self.workers_available() = {}".format(self.workers_available()))
started_a_process = False
while self.workers_available() and runnables:
# No error
process = runnables.pop()
print("Before start_process_in_background ok")
sys.stdin.flush()
self.start_process_in_background(process)
#raise Exception("Stop")
print("After start_process_in_background ok")
sys.stdin.flush()
started_a_process = True
handled_completed_process = False
while self._completed_processes:
completed_process, signatures = self._completed_processes.pop()
if completed_process.success:
success_processes.append(completed_process)
workflow.update_signatures(signatures)
new_runnables = workflow.discover_runnable_processes(completed_process)
runnables.update(new_runnables)
else:
failure_processes.append(completed_process)
failures = True
handled_completed_process = True
if handled_completed_process:
workflow.dump()
workflow.create_reports()
if not (handled_completed_process or started_a_process):
sleep(1)
print("Slept 1s instead of 0.1 ok")
sys.stdin.flush()
self.terminate_workers_and_clean_subprocesses()
if failure_processes:
WorkflowRuner.mark_unfinished_processes_as_failure(workflow)
return success_processes, failure_processes
def init_workers(self):
self._pool = Pool(self._nb_workers)
self._free_workers = self._nb_workers
def terminate_workers_and_clean_subprocesses(self):
direct_procs = set(psutil.Process().children())
all_procs = set(psutil.Process().children(recursive=True))
sub_procs = all_procs - direct_procs
# Terminate cleanly direct procs instanciated by multiprocess
self._pool.terminate()
self._pool.join()
# Then terminate subprocesses that have not been terminated
for p in sub_procs:
p.terminate()
gone, still_alive = psutil.wait_procs(sub_procs, timeout=2)
for p in still_alive:
p.kill()
def acquire_worker(self):
assert self._free_workers > 0
self._free_workers -= 1
def release_worker(self):
self._free_workers += 1
def workers_available(self):
return self._free_workers
def active_workers(self):
return self._free_workers != self._nb_workers
@staticmethod
def mark_unfinished_processes_as_failure(workflow):
for process in workflow.iter_processes():
if process.start and not process.end:
error_msg = "This process was canceled because another process has failed"
process.set_end(False, error_msg)
workflow.dump()
workflow.create_reports()
@staticmethod
def prepare_and_assign_paths(process):
log_stdout = join(WorkflowRuner._logs_dir, "{}_stdout.txt".format(process.id))
log_stderr = join(WorkflowRuner._logs_dir, "{}_err.txt".format(process.id))
# It would be a good idea to clean up all directories before
# running the whole workflow
# For the moment we clean here : before folowing the logs
if isfile(log_stdout):
remove(log_stdout)
if isfile(log_stderr):
remove(log_stderr)
reserved_path = join(WorkflowRuner._processes_dir, process.id)
if isdir(reserved_path):
rmtree(reserved_path)
elif isfile(reserved_path):
remove(reserved_path)
process.assign_paths(reserved_path, log_stdout, log_stderr)
@staticmethod
def create_tuttle_dirs():
if not isdir(WorkflowRuner._processes_dir):
makedirs(WorkflowRuner._processes_dir)
if not isdir(WorkflowRuner._logs_dir):
makedirs(WorkflowRuner._logs_dir)
@staticmethod
def empty_extension_dir():
if not isdir(WorkflowRuner._extensions_dir):
makedirs(WorkflowRuner._extensions_dir)
else:
rmtree(WorkflowRuner._extensions_dir)
makedirs(WorkflowRuner._extensions_dir)
@staticmethod
def print_preprocess_header(process, logger):
logger.info("-" * 60)
logger.info("Preprocess : {}".format(process.id))
logger.info("-" * 60)
@staticmethod
def print_preprocesses_header():
print("=" * 60)
print("Running preprocesses for this workflow")
print("=" * 60)
@staticmethod
def print_preprocesses_footer():
print("=" * 60)
print("End of preprocesses... Running the workflow")
print("=" * 60)
@staticmethod
def list_extensions():
path = join(WorkflowRuner._extensions_dir, '*')
return glob(path)
@staticmethod
def get_logger():
logger = logging.getLogger(__name__)
formater = logging.Formatter("%(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formater)
handler.setLevel(logging.INFO)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
class TuttleEnv(EnvVar):
"""
Adds the 'TUTTLE_ENV' environment variable so subprocesses can find the .tuttle directory.
"""
def __init__(self):
directory = join(getcwd(), '.tuttle')
super(TuttleEnv, self).__init__('TUTTLE_ENV', directory)
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,185 | PointyShinyBurning/tuttle | refs/heads/master | /tuttlelib/entry_points.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
from os.path import abspath, exists, dirname, join
#if getattr(sys, 'frozen', False):
# # frozen
# tuttle_module = join(dirname(abspath(sys.executable)), '..', 'tuttlelib')
#else:
# # unfrozen
# tuttle_module = join(dirname(abspath(__file__)), '..', 'tuttlelib')
#sys.path.insert(0,tuttle_module)
from argparse import ArgumentParser, ArgumentTypeError
from tuttlelib.commands import parse_invalidate_and_run, invalidate_resources
from tuttlelib.utils import CurrentDir
from tuttlelib.version import version
from tuttlelib.extend_workflow import extend_workflow, ExtendError, extract_variables
def check_minus_1_or_positive(value):
ivalue = int(value)
if ivalue == 0 or ivalue < -1:
raise ArgumentTypeError("%s is an invalid positive int value or -1" % value)
return ivalue
def tuttle_main():
print("tuttle_main Ok")
parser = ArgumentParser(
description="Runs a workflow - version {}".format(version)
)
parent_parser = ArgumentParser(
add_help=False
)
parent_parser.add_argument('-f', '--file',
default='tuttlefile',
dest='tuttlefile',
help='Path to the tuttlefile : project file describing the workflow')
parent_parser.add_argument('-w', '--workspace',
default='.',
dest='workspace',
help='Directory where the workspace lies. Default is the current directory')
parent_parser.add_argument('-t', '--threshold',
default='-1',
type=int,
dest='threshold',
help='Threshold for invalidation : \n'
'0 - prevents any invalidation \n'
'N - prevents invalidation if lost processing time >= N\n'
'-1 (default) - no verification')
subparsers = parser.add_subparsers(help='commands help', dest='command')
parser_run = subparsers.add_parser('run', parents=[parent_parser],
help='Run the missing part of workflow')
parser_run.add_argument('-j', '--jobs',
help='Number of workers (to run processes in parallel)\n'
'-1 = half of the number of cpus\n',
default=1,
type=check_minus_1_or_positive)
parser_run.add_argument('-k', '--keep-going',
help='Number of workers (to run processes in parallel)\n'
'Default -1 = half of the number of cpus',
default=False,
dest='keep_going',
action="store_true")
parser_invalidate = subparsers.add_parser('invalidate', parents=[parent_parser],
help='Remove some resources already computed and all their dependencies')
parser_invalidate.add_argument('resources', help='url of the resources to invalidate', nargs="*")
params = parser.parse_args(sys.argv[1:])
print("args Ok")
tuttlefile_path = abspath(params.tuttlefile)
if not exists(tuttlefile_path):
print "No tuttlefile"
sys.exit(2)
with CurrentDir(params.workspace):
if params.command == 'run':
return parse_invalidate_and_run(tuttlefile_path, params.threshold, params.jobs, params.keep_going)
elif params.command == 'invalidate':
return invalidate_resources(tuttlefile_path, params.resources, params.threshold)
def format_variable(name, value):
if isinstance(value, list):
res = "{}[]={}".format(name, " ".join(value))
else:
res = "{}={}".format(name, value)
return res
def tuttle_extend_workflow_main():
parser = ArgumentParser(
description="Extends a workflow by adding a templated tuttle project. Must be run from a preprocessor in a "
"tuttle project - version {}".format(version)
)
parser.add_argument("-v", "--verbose", action="store_true",
help="Display template and variables")
parser.add_argument("template", help="template file")
parser.add_argument('variables', help='variables to insert into the template int the form my_var="my value"',
nargs="*")
parser.add_argument('-n', '--name',
default='extension',
dest='name',
help='Name of the extended workflow')
params = parser.parse_args()
try:
vars_dic = extract_variables(params.variables)
extend_workflow(params.template, name=params.name, **vars_dic)
if params.verbose:
print("Injecting into template {} :".format(params.template))
for key, value in vars_dic.iteritems():
print(" * {}".format(format_variable(key, value)))
except ExtendError as e:
print e.message
exit(1)
| {"/tuttlelib/commands.py": ["/tuttlelib/invalidation.py", "/tuttlelib/workflow_runner.py"], "/tests/test_run_parallel.py": ["/tuttlelib/workflow_runner.py"], "/tests/functional_tests/test_errors/test_keep_going.py": ["/tuttlelib/workflow_runner.py"], "/tuttlelib/report/html_repport.py": ["/tuttlelib/report/dot_repport.py"], "/tests/test_extensions/test_net_extension.py": ["/tuttlelib/workflow_runner.py"]} |
72,214 | rskarp/cs251proj9 | refs/heads/master | /analysis.py | # Riley Karp
# analysis.py
# 4/14/2017
import numpy as np
import scipy.stats
import scipy.cluster
import data
import PCAData
import random
import sys
import math
def saveClusters( d, codes, filename ):
'''Takes in a data object, list of cluster ids, and a filename, and saves the
data to a file with the cluster ids as the last column.
'''
d.addColumn( 'Categories', 'numeric', codes )
d.write( filename, d.get_raw_headers() )
if 'Categories' in d.get_raw_headers():
print True
else:
print False
def kmeans_numpy( d, headers, k, whiten = True ):
'''Takes in a Data object, a set of headers, and the number of clusters to create
Computes and returns the codebook, codes, and representation error.
'''
A = d.get_data( headers )
W = scipy.cluster.vq.whiten(A)
codebook , bookerror = scipy.cluster.vq.kmeans( W, k )
codes , error = scipy.cluster.vq.vq( W , codebook )
return codebook, codes, error
def kmeans_init( data, k, labels = None ):
'''Takes in a numpy matrix of data and the number of clusters to calculate
the initial cluster means. Returns a matrix of K rows of initial cluster means.
'''
#get cluster labels
if labels == None:
idx = []
for i in range( k ):
id = random.randint(0,k)
if id not in idx:
idx.append( id )
#calculate means
means = []
for i in idx:
m = data[int(i),0:].tolist()[0]
means.append( m )
means = np.matrix( means )
else:
idx = labels
means = np.matrix(np.zeros( [ k,data.shape[1] ] ))
indexes = np.array(labels.T)[0]
for i in range(k):
means[i,:] = np.mean( data[indexes==i,:],axis=0 )
return means #numpy matrix with K rows
def kmeans_classify( data, means ):
'''Takes in data and cluster means. Returns matrices of closest cluster ids
and distances to closest cluster for each data point
'''
dist = np.matrix(np.zeros( [ data.shape[0],means.shape[0] ] ))
for m in range( means.shape[0] ): #loop through rows of means
d = np.sum(np.square(data - means[m,:]),axis=1)
dist[:,m] = d
ids = np.argmin( dist,axis=1 )
dist = np.sqrt(np.min( dist, axis=1 ))
return ids, dist #matrix of id values , distances
def kmeans_algorithm(A, means):
# set up some useful constants
MIN_CHANGE = 1e-7
MAX_ITERATIONS = 100
D = means.shape[1]
K = means.shape[0]
N = A.shape[0]
# iterate no more than MAX_ITERATIONS
for i in range(MAX_ITERATIONS):
# calculate the codes
codes, errors = kmeans_classify( A, means )
# calculate the new means
newmeans = np.zeros_like( means )
counts = np.zeros( (K, 1) )
indexes = np.array(codes.T)[0]
for j in range(K):
newmeans[j,:] = np.mean( A[indexes==j,:],axis=0 )
# finish calculating the means, taking into account possible zero counts
# for j in range(K):
# if counts[j,0] > 0.0:
# newmeans[j,:] /= counts[j, 0]
# else:
# newmeans[j,:] = A[random.randint(0,A.shape[0]-1),:]
# test if the change is small enough
diff = np.sum(np.square(means - newmeans))
means = newmeans
if diff < MIN_CHANGE:
break
# call classify with the final means
codes, errors = kmeans_classify( A, means )
# return the means, codes, and errors
return (means, codes, errors)
def kmeans(d, headers, K, whiten=True, categories=None ):
'''Takes in a Data object, a set of headers, and the number of clusters to create
Computes and returns the codebook, codes and representation errors.
If given an Nx1 matrix of categories, it uses the category labels
to calculate the initial cluster means.
'''
A = d.get_data( headers )
if whiten:
W = scipy.cluster.vq.whiten( A )
else:
W = A
codebook = kmeans_init( W, K, categories )
codebook, codes, errors = kmeans_algorithm( W, codebook )
return codebook, codes, errors
def pca( d, headers, normalized = True ):
#takes in a data object, list of column headers, and optional normalized boolean.
#returns a PCAData object with the original headers, projected data, eigen values,
#eigen vectors, and data means.
#data
if normalized:
A = normalize_columns_separately( headers,d )
else:
A = d.get_data(headers)
#means
m = A.mean(axis=0)
#difference matrix
D = A-m
#transformation matrix
U,S,V = np.linalg.svd( D, full_matrices=False )
#eigen values
evals = np.matrix( (S*S)/(A.shape[0]-1) )
#eigen vectors
evecs = V
#projected data
pdata = D*V.T
#PCAData object
return PCAData.PCAData( headers, pdata, evals, evecs, m )
def linear_regression( d, ind, dep ):
#takes a data set, list of independent headers, and dependent header
#returns fit, sse, r2, t, and p of the multiple linear regression
y = d.get_data( [dep] )
A = d.get_data( ind )
ones = []
for i in range( A.shape[0] ):
ones.append( 1 )
ones = np.matrix( ones ).T
A = np.hstack( [A,ones] )
AAinv = np.linalg.inv( np.dot(A.T,A) )
x = np.linalg.lstsq( A,y )
b = x[0]
N = y.shape[0] #rows of y
C = b.shape[0] #rows of b
df_e = N-C #degrees of freedom of error
df_r = C-1 #degrees of freedom of model fit
error = y - np.dot( A,b )
sse = np.dot( error.T,error) / df_e #1x1 matrix
stderr = np.sqrt( np.diagonal( sse[0,0]*AAinv ) ) #Cx1 matrix
t = b.T/stderr #t-statistic
p = 2*( 1 - scipy.stats.t.cdf(abs(t),df_e) ) #prob of random relationship
r2 = 1 - error.var() / y.var()
return { 'b':b, 'sse':sse[0][0], 'r2':r2, 't':t[0], 'p':p[0] }
def data_range( headers,d ):
#returns a list of lists containing the min and max values of each column
ranges = []
data = d.get_data(headers)
for i in range( d.get_num_columns() ):
col = data[0:,i:i+1]
if col.size > 0:
ranges.append( [ col.min(),col.max() ] )
return ranges
def mean( headers,d ):
#returns a list containing the mean value for each column
means = []
data = d.get_data(headers)
for i in range( d.get_num_columns() ):
if data[0:,i:i+1].size > 0:
means.append( data[0:,i:i+1].mean() )
return means
def stdev( headers,d ):
#returns a list containing the standard deviation for each column
stdev = []
data = d.get_data(headers)
for i in range( d.get_num_columns() ):
if data[0:,i:i+1].size > 0:
stdev.append( data[0:,i:i+1].std() )
return stdev
def median( headers,d ):
#returns a list containing the median value for each column
meds = []
data = d.get_data(headers)
for i in range( d.get_num_columns() ):
if data[0:,i:i+1].size > 0:
meds.append( np.median( data[0:,i:i+1].A ) )
return meds
def normalize_columns_separately( headers,d ):
#normalizes each column so the min maps to 0 and the max maps to 1
data = d.get_data(headers)
norm = np.matrix([], dtype = float)
norm.shape = ( d.get_raw_num_rows(), 0 ) #reshape so we can add cols using hstack
for i in range( d.get_num_columns() ):
col = data[0:,i:i+1]
if col.size > 0:
col = col - col.min()
if col.max() != 0:
col = col/col.max()
norm = np.hstack( [norm, col] )
return norm
def normalize_columns_together( headers,d ):
#normalizes all the data so the min maps to 0 and the max maps to 1
data = d.get_data(headers)
if data.size > 0:
norm = data - data.min()
if data.max() != 0:
norm = norm/data.max()
return norm
def testLinReg():
#prints linReg data in terminal for the 3 test CSV files
for file in [ 'data-clean.csv','data-good.csv','data-noisy.csv' ]:
d = data.Data( file )
print '-----------------------------------------------------'
print '\t' , file
print '-----------------------------------------------------'
linReg = linear_regression( d, ['X0','X1'], 'Y' )
print 'm0: ' , float(linReg['b'][0])
print 'm1: ' , float(linReg['b'][1])
print 'b: ' , float(linReg['b'][2])
print 'sse: ' , float(linReg['sse'])
print 'r2: ' , linReg['r2']
print 't ' , linReg['t'].tolist()[0]
print 'p: ' , linReg['p']
def myLinReg():
#prints linReg data in terminal for nfldata.csv
d = data.Data( 'nfldata.csv' )
print '-----------------------------------------------------'
print '\tnfldata.csv'
print '-----------------------------------------------------'
ind = ['Make Playoffs','Win Division','1st Round Bye']
linReg = linear_regression( d, ind, 'Win Super Bowl' )
print 'm0: ' , float(linReg['b'][0])
print 'm1: ' , float(linReg['b'][1])
print 'm2: ' , float(linReg['b'][2])
print 'b: ' , float(linReg['b'][3])
print 'sse: ' , float(linReg['sse'])
print 'r2: ' , linReg['r2']
print 't ' , linReg['t'].tolist()[0]
print 'p: ' , linReg['p']
def acLinReg():
#prints linReg data in terminal for AustraliaCoast.csv
d = data.Data( 'AustraliaCoast.csv' )
print '-----------------------------------------------------'
print '\tAustraliaCoast.csv'
print '-----------------------------------------------------'
ind = ['minairtemp','maxairtemp','minsst','maxsst']
linReg = linear_regression( d, ind, 'Latitude' )
print 'm0: ' , float(linReg['b'][0])
print 'm1: ' , float(linReg['b'][1])
print 'm2: ' , float(linReg['b'][2])
print 'b: ' , float(linReg['b'][3])
print 'sse: ' , float(linReg['sse'])
print 'r2: ' , linReg['r2']
print 't ' , linReg['t'].tolist()[0]
print 'p: ' , linReg['p']
# if __name__ == '__main__':
# testLinReg()
# myLinReg()
acLinReg()
| {"/PCAData.py": ["/data.py"]} |
72,215 | rskarp/cs251proj9 | refs/heads/master | /classify.py | # Riley Karp
# classify.py
# 5/12/17
import sys
import data
import classifiers
def main(argv):
#usage
if len(argv) < 4:
print 'Usage: python %s <training data file> <test data file> <nb or knn> <optional training category file> <optional test category file>' % (argv[0])
exit(-1)
#store classifier type
classifier = argv[3]
if classifier != 'nb' and classifier != 'knn':
print 'Usage: python %s <training data file> <test data file> <nb or knn> <optional training category file> <optional test category file>' % (argv[0])
exit(-1)
print '\nReading data files'
#read the training and test sets
dtrain = data.Data(argv[1])
dtest = data.Data(argv[2])
#get the categories and the training data train and the test data test
if len(argv) > 5:
traincatdata = data.Data(argv[4])
testcatdata = data.Data(argv[5])
traincats = traincatdata.get_data( [traincatdata.get_headers()[0]] )
testcats = testcatdata.get_data( [testcatdata.get_headers()[0]] )
train = dtrain.get_data( dtrain.get_headers() )
test = dtest.get_data( dtest.get_headers() )
headers = dtest.get_headers()
else:
#assume the categories are the last column
traincats = dtrain.get_data( [dtrain.get_headers()[-1]] )
testcats = dtest.get_data( [dtest.get_headers()[-1]] )
train = dtrain.get_data( dtrain.get_headers()[:-1] )
test = dtest.get_data( dtest.get_headers()[:-1] )
headers = dtest.get_headers()[:-1]
#create classifier using training set
if classifier == 'knn':
#get k
k = raw_input('How many nearest neighbors? (default=3) Type number then press enter: ')
if k == '':
k = 3
else:
k = abs( int(k) )
#make new KNN classifier
knntrain = classifiers.KNN()
print '\nTraining the classifier'
# build the classifier from training set
knntrain.build( train, traincats, k )
print '\nClassifying training data'
# classify training set print confusion matrix
trainCat, trainLab = knntrain.classify( train )
print '\nBuilding training confusion matrix'
traincmat = knntrain.confusion_matrix( traincats, trainCat )
print knntrain.confusion_matrix_str( traincmat )
print '\nClassifying testing data'
# classify test set and print confusion matrix
testCat, testLab = knntrain.classify( test )
print '\nBuilding testing confusion matrix'
testcmat = knntrain.confusion_matrix( testcats, testCat )
print knntrain.confusion_matrix_str( testcmat )
#write test data set and categories to CSV file
filename = raw_input('Type filename for test data, then press enter: ')
print '\nSaving test data'
dtest.addColumn( 'Categories', 'numeric', testCat.T.tolist()[0] )
headers.append( 'Categories' )
dtest.write( filename, headers )
else: # classifier is nb
#make new naive bayes classifier
nbtrain = classifiers.NaiveBayes()
print '\nTraining the classifier'
# build the classifier from training set
nbtrain.build( train, traincats )
print '\nClassifying training data'
# classify training set print confusion matrix
trainCat, trainLab = nbtrain.classify( train )
print '\nBuilding training confusion matrix'
traincmat = nbtrain.confusion_matrix( traincats, trainCat )
print nbtrain.confusion_matrix_str( traincmat )
print '\nClassifying testing data'
# classify test set and print confusion matrix
testCat, testLab = nbtrain.classify( test )
print '\nBuilding testing confusion matrix'
testcmat = nbtrain.confusion_matrix( testcats, testCat )
print nbtrain.confusion_matrix_str( testcmat )
#write test data set and categories to CSV file
filename = raw_input('Type filename for test data, then press enter: ')
print '\nSaving test data'
dtest.addColumn( 'Categories', 'numeric', testCat.T.tolist()[0] )
headers.append( 'Categories' )
dtest.write( filename, headers )
if __name__ == "__main__":
main(sys.argv) | {"/PCAData.py": ["/data.py"]} |
72,216 | rskarp/cs251proj9 | refs/heads/master | /display.py | # Skeleton Tk interface example
# Written by Bruce Maxwell
# Modified by Stephanie Taylor
#
# CS 251
# Spring 2015
# Personalized by Riley Karp
# display.py
# 4/4/2017
import Tkinter as tk
import tkFont as tkf
import tkFileDialog
import math
import random
import view
import data as d
import analysis as a
import numpy as np
import scipy.stats
import tkMessageBox
# create a class to build and manage the display
class DisplayApp:
def __init__(self, width, height):
#create fields for bioluminescence data
self.circadian = False
self.bio = None
self.cellState = None
#create fields for classifying categories
self.categories = False
#create fields for cluster analysis
self.clusterIDX = []
self.clusterColors = False
self.clusterData = None
#create fields for PCA analysis
self.pcad = {}
self.plotPCA = None
self.pca = False
#create fileds for linear regression data
self.linReg = []
self.linRegEnds = None
self.slope = None
self.intercept = None
self.rval = None
self.pval = None
self.stderr = None
self.ranges = None
self.linRegEq = []
self.ind = None #linReg
self.dep = None #linReg
#create Data object and fields
self.data = None
self.points = None
self.zAxis = False
self.colors = False
self.sizes = False
self.r = []
self.headers = []
self.axisLabels = []
self.stats = []
# create View parameters object
self.view = view.View()
# create fields for axes
self.axes = np.matrix( [[0,0,0,1],[1,0,0,1],
[0,0,0,1],[0,1,0,1],
[0,0,0,1],[0,0,1,1]], dtype=float )
self.xLine = self.yLine = self.zLine = None
self.x = self.y = self.z = None
self.axisLines = [ self.xLine, self.yLine, self.zLine ]
#create interaction constant fields for translation, rotation, and scaling
self.ks = 1 #scaling
self.kt = 1 #rotation
self.kr = 1 #translation
# create a tk object, which is the root window
self.root = tk.Tk()
# width and height of the window
self.initDx = width
self.initDy = height
# set up the geometry for the window
self.root.geometry( "%dx%d+50+30" % (self.initDx, self.initDy) )
# set the title of the window
self.root.title("D.A.V.I.S")
# set the maximum size of the window for resizing
self.root.maxsize( 1600, 900 )
# setup the menus
self.buildMenus()
# build the controls
self.buildControls()
# build the Canvas
self.buildCanvas()
# build the axes
self.buildAxes()
# bring the window to the front
self.root.lift()
# - do idle events here to get actual canvas size
self.root.update_idletasks()
# now we can ask the size of the canvas
print self.canvas.winfo_geometry()
# set up the key bindings
self.setBindings()
# set up the application state
self.objects = [] # list of data objects that will be drawn in the canvas
self.data = None # will hold the raw data someday.
self.baseClick = None # used to keep track of mouse movement
self.baseClick2 = None
self.origExtent = None
self.origView = None
self.points = None
def buildAxes(self):
#builds the x,y,and z axes lines and labels on the canvas
vtm = self.view.build()
pts = ( vtm * self.axes.T ).T
self.xLine = self.canvas.create_line( pts[0,0], pts[0,1], pts[1,0], pts[1,1] )
self.yLine = self.canvas.create_line( pts[2,0], pts[2,1], pts[3,0], pts[3,1] )
self.zLine = self.canvas.create_line( pts[4,0], pts[4,1], pts[5,0], pts[5,1] )
self.x = self.canvas.create_text( pts[1,0], pts[1,1], text = 'X' )
self.y = self.canvas.create_text( pts[3,0], pts[3,1], text = 'Y' )
self.z = self.canvas.create_text( pts[5,0], pts[5,1], text = 'Z' )
def updateAxes(self):
#updates the x,y,and z axes lines and labels on the canvas
vtm = self.view.build()
pts = ( vtm * self.axes.T ).T
#update lines
self.canvas.coords(self.xLine, pts[0,0], pts[0,1], pts[1,0], pts[1,1] )
self.canvas.coords(self.yLine, pts[2,0], pts[2,1], pts[3,0], pts[3,1] )
self.canvas.coords(self.zLine, pts[4,0], pts[4,1], pts[5,0], pts[5,1] )
#update labels
self.canvas.coords(self.x, pts[1,0], pts[1,1])
self.canvas.coords(self.y, pts[3,0], pts[3,1])
self.canvas.coords(self.z, pts[5,0], pts[5,1])
def buildMenus(self):
# create a new menu
menu = tk.Menu(self.root)
# set the root menu to our new menu
self.root.config(menu = menu)
# create a variable to hold the individual menus
menulist = []
# create a file menu
filemenu = tk.Menu( menu )
menu.add_cascade( label = "File", menu = filemenu )
menulist.append(filemenu)
# create a command menu
cmdmenu = tk.Menu( menu )
menu.add_cascade( label = "Command", menu = cmdmenu )
menulist.append(cmdmenu)
# menu text for the elements
# the first sublist is the set of items for the file menu
# the second sublist is the set of items for the option menu
menutext = [ [ '-', '-', 'Quit \xE2\x8C\x98-Q', 'Open \xE2\x8C\x98-O'],
[ 'Linear Regression \xE2\x8C\x98-L',
'Multiple Linear Regression \xE2\x8C\x98-M',
'Principal Component Analysis \xE2\x8C\x98-P',
'Cluster Analysis \xE2\x8C\x98-C' ] ]
# menu callback functions (note that some are left blank,
# so that you can add functions there if you want).
# the first sublist is the set of callback functions for the file menu
# the second sublist is the set of callback functions for the option menu
menucmd = [ [None, None, self.handleQuit, self.handleOpen],
[ self.handleLinearRegression, self.handleMultLinReg, self.handlePCA,
self.handleClustering ] ]
# build the menu elements and callbacks
for i in range( len( menulist ) ):
for j in range( len( menutext[i]) ):
if menutext[i][j] != '-':
menulist[i].add_command( label = menutext[i][j], command=menucmd[i][j] )
else:
menulist[i].add_separator()
def buildCanvas(self):
# create the canvas object
self.canvas = tk.Canvas( self.root, width=self.initDx, height=self.initDy )
self.canvas.pack( expand=tk.YES, fill=tk.BOTH )
return
def buildControls(self):
# build a frame and put controls in it
### Control ###
# make a control frame on the right
rightcntlframe = tk.Frame(self.root)
rightcntlframe.pack(side=tk.RIGHT, padx=2, pady=2, fill=tk.Y)
# make a separator frame
sep = tk.Frame( self.root, height=self.initDy, width=2, bd=1, relief=tk.SUNKEN )
sep.pack( side=tk.RIGHT, padx = 2, pady = 1, fill=tk.Y)
# use a label to set the size of the right panel
label = tk.Label( rightcntlframe, text="Control Panel", width=20 )
label.pack( side=tk.TOP, pady=10 )
# make a stats frame on the right
self.statframe = tk.Frame(self.root)
self.statframe.pack(side=tk.RIGHT, padx=2, pady=2, fill=tk.Y)
# make a separator frame
sep2 = tk.Frame( self.root, height=self.initDy, width=2, bd=1, relief=tk.SUNKEN )
sep2.pack( side=tk.RIGHT, padx = 2, pady = 1, fill=tk.Y)
# use a label to set the size of the right panel
label = tk.Label( self.statframe, text="Stats", width=15 )
label.pack( side=tk.TOP, pady=0.1 )
#create buttons
button1 = tk.Button( rightcntlframe, text = 'Plot Data', command = self.handlePlotData )
save = tk.Button( rightcntlframe, text = 'Save Linear Regression', command = self.saveLinReg )
pca = tk.Button( rightcntlframe, text = 'Manage PCA', command = self.handlePCA )
cluster = tk.Button( rightcntlframe, text = 'Cluster Analysis', command = self.handleClustering )
saveCluster = tk.Button( rightcntlframe, text = 'Save Clusters', command = self.saveClusters )
#make sliders for interaction constants
self.trans = tk.Scale( rightcntlframe, from_ = 0.1, to = 5.0, command = self.setKT,
orient=tk.HORIZONTAL, label = 'Translation Speed',
length = 125, resolution = 0.1 )
self.rot = tk.Scale( rightcntlframe, from_ = 0.1, to = 5.0, command = self.setKR,
orient=tk.HORIZONTAL, label = 'Rotation Speed',
length = 125, resolution = 0.1 )
self.scale = tk.Scale( rightcntlframe, from_ = 0.1, to = 5.0, command = self.setKS,
orient=tk.HORIZONTAL, label = 'Scaling Speed',
length = 125, resolution = 0.1 )
#make slider and ListBox for bioluminescence data
self.bio = tk.Scale( rightcntlframe, from_ = 1, to = 144, command = self.updateBio,
orient=tk.HORIZONTAL, label = 'Bioluminescence Hour',
length = 200, resolution = 1 )
self.cellState = tk.Listbox(rightcntlframe, selectmode=tk.SINGLE, exportselection=0, height=3)
for item in ['Base','Toxin','Washed']:
self.cellState.insert( 'end', item )
label = tk.Label( rightcntlframe, text="Choose cell environemnt", width=20 )
#add objects to screen
self.trans.pack( side = tk.TOP, pady=5 )
self.rot.pack( side = tk.TOP, pady=5 )
self.scale.pack( side = tk.TOP, pady=5 )
button1.pack( side = tk.TOP, pady=5 )
save.pack( side = tk.TOP, pady=5 )
pca.pack( side = tk.TOP, pady=5 )
cluster.pack( side = tk.TOP, pady=5 )
saveCluster.pack( side = tk.TOP, pady=5 )
label.pack( side = tk.TOP, pady=5 )
self.cellState.pack( side = tk.TOP, pady=5 )
self.bio.pack( side = tk.TOP, pady=5 )
#set sliders to start at 1
self.trans.set(1)
self.rot.set(1)
self.scale.set(1)
self.bio.set(1)
self.cellState.selection_set(0)
return
def updateBio(self,event):
'''updates the color of the bioluminescence points based on relative value to other
points. Bioluminescence data from column given by Listbox selection and slider
in control panel.
'''
if ( len( self.objects ) == 0 ) or ( self.circadian == False ):
return
hour = str( self.bio.get() )
cell = self.cellState.get( self.cellState.curselection()[0] )
if cell == 'Base':
head = 'B' + hour
elif cell == 'Toxin':
head = 'T' + hour
else: # cell is Washed
if int(hour) > 142:
hour = '142'
head = 'W' + hour
colors = a.normalize_columns_separately([head],self.data)
#create list of colors
c = []
for i in range( self.data.get_raw_num_rows() ):
r = 255 * colors[i,0]
g = 255 * colors[i,0]
b = 255 * (1-colors[i,0])
s = "#%02X%02X%02X" % (int(r), int(g), int(b))
c.append(s)
#updates colors of all the data points
for i in range( len(self.objects) ):
color = c[i]
self.canvas.itemconfig( self.objects[i], fill = color )
def addAxisLabels(self):
#adds axis labels to side frame
labels = []
i = j = 0
for axis in [ 'X: '+self.axisLabels[0], 'Y: '+self.axisLabels[1],
'Z: '+self.axisLabels[2], 'Color: '+self.axisLabels[3],
'Size: '+self.axisLabels[4] ]:
label = tk.Label( self.statframe, text= axis, width=20 )
label.pack( side=tk.TOP, pady=0.1 )
labels.append(label)
if self.axisLabels[j] != 'None':
for s in [ ['Mean: ', round( self.axisLabels[5][i],2 )],
['Standard Deviation: ', round( self.axisLabels[6][i],2 )],
['Median: ', round( self.axisLabels[7][i],2 )],
['Min: ', round( self.axisLabels[8][i][0],2 )],
['Max: ', round( self.axisLabels[8][i][1],2 )] ]:
statText = s[0]+ str(s[1])
stat = tk.Label( self.statframe, text= statText, width=20 )
stat.pack( side=tk.TOP, pady=0.1 )
labels.append(stat)
else:
i += 1
j += 1
self.axisLabels = labels
def addAxisStats(self):
#calculates means, stdevs, medians, and ranges and adds them to self.axisLabels
mean = a.mean(self.headers,self.data)
stdev = a.stdev(self.headers,self.data)
median = a.median(self.headers,self.data)
range = a.data_range(self.headers,self.data)
self.axisLabels.append(mean[:])
self.axisLabels.append(stdev[:])
self.axisLabels.append(median[:])
self.axisLabels.append(range[:])
def setBindings(self):
# bind mouse motions to the canvas
self.canvas.bind( '<Button-1>', self.handleMouseButton1 )
self.canvas.bind( '<Control-Button-1>', self.handleMouseButton2 )
self.canvas.bind( '<Button-2>', self.handleMouseButton2 )
self.canvas.bind( '<Button-3>', self.handleMouseButton3 )
self.canvas.bind( '<B1-Motion>', self.handleMouseButton1Motion )
self.canvas.bind( '<B2-Motion>', self.handleMouseButton2Motion )
self.canvas.bind( '<B3-Motion>', self.handleMouseButton3Motion )
self.canvas.bind( '<Control-B1-Motion>', self.handleMouseButton2Motion )
# bind command sequences to the root window
self.root.bind( '<Command-q>', self.handleQuit )
self.root.bind( '<Command-o>', self.handleOpen )
self.root.bind( '<Command-r>', self.reset )
self.root.bind( '<Command-z>', self.xzPlane )
self.root.bind( '<Command-x>', self.xyPlane )
self.root.bind( '<Command-y>', self.yzPlane )
self.root.bind( '<Command-l>', self.handleLinearRegression )
self.root.bind( '<Command-s>', self.saveLinReg )
self.root.bind( '<Command-m>', self.handleMultLinReg )
self.root.bind( '<Command-p>', self.handlePCA )
self.root.bind( '<Command-c>', self.handleClustering )
def setKT(self,event=None):
#sets translation interaction constant to current slider value
self.kt = self.trans.get()
def setKR(self,event=None):
#sets rotation interaction constant to current slider value
self.kr = self.rot.get()
def setKS(self,event=None):
#sets scaling interaction constant to current slider value
self.ks = self.scale.get()
def xzPlane(self,event=None):
#puts the view into the xz plane
self.view.vpn = np.matrix( [0,1,0], dtype=float)
self.view.vup = np.matrix( [-1,0,0], dtype=float)
self.view.u = np.matrix( [0,0,1], dtype=float)
self.updateAxes()
self.updatePoints()
self.updateFits()
def xyPlane(self,event=None):
#puts the view into the xy plane
self.view.vpn = np.matrix( [0,0,-1], dtype=float)
self.view.vup = np.matrix( [0,1,0], dtype=float)
self.view.u = np.matrix( [1,0,0], dtype=float)
self.updateAxes()
self.updatePoints()
self.updateFits()
def yzPlane(self,event=None):
#puts the view into the yz plane
self.view.vpn = np.matrix( [-1,0,0], dtype=float)
self.view.vup = np.matrix( [0,1,0], dtype=float)
self.view.u = np.matrix( [0,0,-1], dtype=float)
self.updateAxes()
self.updatePoints()
self.updateFits()
def handleQuit(self, event=None):
#ends program and closes window
print 'Terminating'
self.root.destroy()
def handleClustering( self, event=None):
#allows user to select data and number of clusters to plot, then plots clusters
#calculated by kmeans clustering
if self.data == None:
self.handleOpen()
if self.pca:
self.clusterData = self.plotPCA
else:
self.clusterData = self.data
self.clearAxes()
clusters = SelectClusterHeaders( self.root, self.clusterData, 'Select Cluster Headers' )
headers = clusters.result[0]
k = clusters.result[1]
color = clusters.result[2]
if color == 'Discrete':
self.clusterColors = True
#calculate clusters with kmeans
codebook,codes,error = a.kmeans_numpy( self.clusterData, headers, k )
#assign codes to self.clusterIDX list
self.clusterIDX = codes
#choose axes to plot
axes = self.chooseClusterPlots()
#draw clusters
self.buildClusters( axes, k )
def chooseClusterPlots( self ):
#returns a list of the headers for the axes to plot
axes = SelectClusterAxes(self.root, self.clusterData, 'Select Axes')
headers = [ axes.result['x'], axes.result['y'], axes.result['z'],
axes.result['size'] ]
self.headers = headers[:]
#set z, colors, and sizes variables
if axes.result['z'] != 'None':
self.zAxis = True
if axes.result['size'] != 'None':
self.sizes = True
#remove axes whose value is 'None'
x = 0
for i in range( len(self.headers) ):
if self.headers[i] == 'None':
x += 1
for j in range(x):
self.headers.remove('None')
return self.headers
def buildClusters( self, headers, k ):
#draws the data points in colored clusters
self.clearData()
self.points = a.normalize_columns_separately(headers,self.clusterData)
#create column of ones for homogeneous coordinates
ones = []
for i in range( self.data.get_raw_num_rows() ):
ones.append( 1 )
ones = np.matrix( ones ).T
#z data values
if self.zAxis:
end = self.points[0:,3:]
self.points = self.points[0:,0:3]
else:
end = self.points[0:,2:]
self.points = self.points[0:,0:2]
#sizes
if self.sizes:
sizes = end
print 'sizes'
#add column of zeros if only 2 axes selected
#create column of zeros
zeros = []
for i in range( self.data.get_raw_num_rows() ):
zeros.append( 0 )
zeros = np.matrix( zeros ).T
if self.points.shape[1] == 2:
self.points = np.hstack( [self.points, zeros] )
#add column of ones to matrix
self.points = np.hstack( [self.points, ones] )
#transform data
vtm = self.view.build()
pts = (vtm * self.points.T).T
colors = [ 'red','blue','green','yellow', 'cyan', 'black', 'blue violet', 'pink', 'lavender', 'brown' ]
if k > 10 :
for i in range( k-10 ):
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
colors.append( (r,g,b) )
normcIDX = self.clusterIDX/float( max( self.clusterIDX ) )
#create data points
for i in range( self.clusterData.get_raw_num_rows() ):
if self.sizes:
self.r.append( ( 5 * math.sqrt(sizes[i,0]) ) + 1 )
r = self.r[i]
else:
r = 2
if self.clusterColors:
color = colors[ self.clusterIDX[i] ]
else:
red = 255 * normcIDX[i]
g = 255 * normcIDX[i]
b = 255 * (1-normcIDX[i])
color = "#%02X%02X%02X" % (int(red), int(g), int(b))
x = pts[i,0]
y = pts[i,1]
pt = self.canvas.create_oval( x+r, y+r, x-r, y-r, fill=color, outline='' )
self.objects.append(pt)
self.clearLinReg()
self.updateFits()
return
def handlePCA(self, event=None):
if self.data == None:
self.handleOpen()
pca = SelectPCA( self.root, self.data, self.pcad, 'Select PCA' ).result
self.pcad = pca['pcad']
if pca['plotPCA'] != None:
self.plotPCA = pca['plotPCA']
self.clearAxes()
axes = self.choosePCAAxes()
self.buildPCAPoints( axes )
def choosePCAAxes(self):
#returns a list of the headers for the axes
axes = SelectPCAAxes(self.root, self.plotPCA, 'Select Axes')
headers = [ axes.result['x'], axes.result['y'], axes.result['z'],
axes.result['color'], axes.result['size'] ]
self.headers = headers[:]
#set colors, and sizes variables
if axes.result['color'] != 'None':
self.colors = True
if axes.result['size'] != 'None':
self.sizes = True
#remove axes whose value is 'None'
x = 0
for i in range( len(self.headers) ):
if self.headers[i] == 'None':
x += 1
for j in range(x):
self.headers.remove('None')
return self.headers
def buildPCAPoints(self,axes):
self.clearData()
self.pca = True
points = a.normalize_columns_separately( self.plotPCA.get_headers(),self.plotPCA )
self.points = points[0:,0:len(axes)]
#create column of ones for homogeneous coordinates
ones = []
for i in range( self.plotPCA.get_raw_num_rows() ):
ones.append( 1 )
ones = np.matrix( ones ).T
#z data values
end = self.points[0:,3:]
self.points = self.points[0:,0:3]
#colors and sizes
if self.colors and self.sizes:
colors = end[0:,0]
sizes = end[0:,1]
print 'colors and sizes'
elif self.colors:
colors = end
print 'colors'
elif self.sizes:
sizes = end
print 'sizes'
#set values of colors (gradient from blue to yellow)
if self.colors:
c = []
for i in range( self.plotPCA.get_raw_num_rows() ):
r = 255 * colors[i,0]
g = 255 * colors[i,0]
b = 255 * (1-colors[i,0])
s = "#%02X%02X%02X" % (int(r), int(g), int(b))
c.append(s)
#add column of ones to matrix
self.points = np.hstack( [self.points, ones] )
#transform data
vtm = self.view.build()
pts = (vtm * self.points.T).T
#create data points
for i in range( self.plotPCA.get_raw_num_rows() ):
if self.colors:
color = c[i]
else:
color = 'black'
if self.sizes:
self.r.append( ( 5 * math.sqrt(sizes[i,0]) ) + 1 )
r = self.r[i]
else:
r = 2
x = pts[i,0]
y = pts[i,1]
pt = self.canvas.create_oval( x+r, y+r, x-r, y-r, fill=color, outline='' )
self.objects.append(pt)
self.clearLinReg()
self.updateFits()
def handleMouseButton1(self, event):
#stores where the mouse button 1 was clicked
self.baseClick = (event.x, event.y)
def handleMouseButton1Motion(self, event):
#translates the data around the screen when mouse button 1 is clicked & dragged
# calculate the differential motion
diff = ( event.x - self.baseClick[0], event.y - self.baseClick[1] )
self.baseClick = (event.x, event.y)
#calculate new vrp
dx = diff[0]/self.view.screen[0]
dy = diff[1]/self.view.screen[1]
delta0 = self.kt * dx * self.view.extent[0]
delta1 = self.kt * dy * self.view.extent[1]
self.view.vrp += (delta0*self.view.u) + (delta1*self.view.vup)
self.updateAxes()
self.updatePoints()
self.updateFits()
def handleMouseButton2(self, event):
#stores the click position and original View
self.baseClick2 = (event.x, event.y)
self.origView = self.view.clone()
def handleMouseButton2Motion(self, event):
#rotates the axes when the right mouse button is clicked and dragged
diff = ( event.x - self.baseClick2[0], event.y - self.baseClick2[1] )
delta0 = self.kr * math.pi * diff[0]/200
delta1 = self.kr * math.pi * diff[1]/200
self.view = self.view.clone()
self.view.rotateVRC( delta0,delta1 )
self.updateAxes()
self.updatePoints()
self.updateFits()
def handleMouseButton3(self, event):
#stores the mouse button 3 click location and original extents
self.baseClick = (event.x, event.y)
self.origExtent = self.view.clone().extent
def handleMouseButton3Motion(self, event):
#scales the data as mouse is moved vertically while button 3 is held
#convert distance to scale factor
dy = 1 + self.ks*(event.y - self.baseClick[1])/self.view.screen[1]
scale = max( min(3.0,dy),0.1 )
#apply scale factor
self.view.extent = ( scale*self.origExtent[0], scale*self.origExtent[1], scale*self.origExtent[2] )
self.updateAxes()
self.updatePoints()
self.updateFits()
def reset(self,event=None):
#resets the view to the original view
self.view.reset()
self.updateAxes()
self.updatePoints()
self.updateFits()
def saveClusters( self ):
'''Saves a data file with a column of cluster categories at the end
'''
if self.clusterData != None:
filename = EnterFileName(self.root, 'Cluster Filename' )
a.saveClusters( self.clusterData, self.clusterIDX, filename.result )
def clearLinReg(self):
#resets fields for linReg data to their default values
if self.linReg != []:
for l in self.linReg:
self.canvas.delete(l)
self.linReg = []
if self.linRegEq != []:
for l in self.linRegEq:
self.canvas.delete(l)
self.linRegEq = []
self.linRegEnds = None
self.slope = None
self.intercept = None
self.rval = None
self.pval = None
self.stderr = None
self.ranges = None
def saveLinReg(self,event=None):
#saves the current linear regression data to a txt file
if self.linReg == []:
tkMessageBox.showwarning( 'Failed to Save',
'There is no linear regression data to save. Press \xE2\x8C\x98-L to run a linear regression' )
return
f = EnterFileName( self.root,'Enter File Name' )
filename = f.result + '.txt'
file = open( filename, 'w' )
string = 'Independent Variable: ' + str(self.ind) + \
'\nDependent Variable: ' + str(self.dep) + \
'\nSlope: ' + str(round( self.slope,3 )) + \
'\nIntercept: ' + str(round( self.intercept,3 )) + \
'\nR-Squared: ' + str(round( self.rval*self.rval, 3 )) + \
'\nStandard Error: ' + str(round( self.stderr,3 )) + \
'\nX minimum , maximum: ' + str(self.ranges[0][0]) + ' , ' + str(self.ranges[0][1]) + \
'\nY minimum , maximum: ' + str(self.ranges[1][0]) + ' , ' + str(self.ranges[1][1])
file.write( string )
def handleLinearRegression(self,event=None):
#creates linear regression line from variables specified by user in dialog box
if self.data == None:
self.handleOpen()
vars = SelectVariables(self.root, self.data, 'Select Variables')
self.clearData()
self.clearAxes()
self.clearLinReg()
self.reset()
self.updateAxes()
self.buildLinearRegression( vars.result )
def buildLinearRegression(self,vars):
#creates matrix of data points
self.ind = vars[0]
self.dep = vars[1]
self.points = a.normalize_columns_separately(vars,self.data)
zeros = np.matrix( np.zeros( (self.data.get_raw_num_rows(), 1) ), dtype = float )
ones = np.matrix( np.ones( (self.data.get_raw_num_rows(), 1) ), dtype = float )
self.points = np.hstack( [self.points,zeros,ones] )
#transforms data
vtm = self.view.build()
pts = (vtm * self.points.T).T
#draws 2D plot
for i in range( self.data.get_raw_num_rows() ):
x = pts[i,0]
y = pts[i,1]
pt = self.canvas.create_oval( x+1, y+1, x-1, y-1, fill='black', outline='' )
self.objects.append(pt)
#stores regression data
d = self.data.get_data( vars )
x = d[0:,0:1].T.tolist()[0]
y = d[0:,1:2].T.tolist()[0]
self.slope, self.intercept, self.rval, self.pval, self.stderr = \
scipy.stats.linregress( x,y )
self.ranges = a.data_range( vars, self.data )
#determines endpoints
xmin = self.ranges[0][0]
xmax = self.ranges[0][1]
ymin = self.ranges[1][0]
ymax = self.ranges[1][1]
#normalize end points here
x1 = 0.0
x2 = 1.0
y1 = ( ( xmin * self.slope + self.intercept ) - ymin )/( ymax - ymin )
y2 = ( ( xmax * self.slope + self.intercept ) - ymin )/( ymax - ymin )
self.linRegEnds = np.matrix( [ [x1,y1,0.0,1.0],
[x2,y2,0.0,1.0] ] )
#multiply endpoints by vtm
ends = (vtm * self.linRegEnds.T).T
#draw line
line = self.canvas.create_line( ends[0,0], ends[0,1], ends[1,0], ends[1,1],
fill = 'red' )
self.linReg.append( line )
#display slope, intercept, and rval
eqString = 'y = ' + str( round(self.slope,3) ) + 'x + ' + str( round(self.intercept,3) )
eqString += '\nR^2: ' + str( round(self.rval*self.rval,3) )
eq = self.canvas.create_text( 3*len(eqString), self.initDy-20, text=eqString,
fill = 'red' )
self.linRegEq.append( eq )
def updateFits(self):
#updates the linReg line on the canvas
if self.linRegEnds == None:
return
vtm = self.view.build()
ends = ( vtm * self.linRegEnds.T ).T
for l in self.linReg:
self.canvas.coords(l, ends[0,0], ends[0,1], ends[1,0], ends[1,1] )
def handleMultLinReg(self,event=None):
if self.data == None:
self.handleOpen()
self.clearAxes()
self.reset()
self.updateAxes()
vars = SelectMultiVars( self.root, self.data, 'Select Variables' )
ind = vars.independent
dep = vars.dependent
if len(ind) > 1:
self.zAxis = dep[0]
headers = ind + dep
self.buildPoints(headers)
self.displayMultLinReg(ind,dep)
def displayMultLinReg(self,ind,dep):
#display b, sse, r^2, t, and p vals in window
linReg = a.linear_regression( self.data, ind, dep[0] )
eqString = ''
b = linReg['b']
for i in range( len(b) - 1 ):
eqString += 'm' + str(i) + ': ' + str( round(float(b[i]),3) ) + ' , '
eqString += ' b: ' + str( round(float(b[-1]),3) ) + ' , sse: ' + \
str(round(float(linReg['sse']),3))
tvals = []
for t in linReg['t'].tolist()[0]:
tvals.append( round(float(t),3) )
pvals = []
for p in linReg['p']:
pvals.append( round(float(p),3) )
eqString += '\nR-Squared: ' + str( round(linReg['r2'],3) ) + ' , t: ' + \
str( tvals ) + ' , p: ' + str( pvals )
eq = self.canvas.create_text( 3*len(eqString), self.initDy-20, text=eqString,
fill = 'red' )
self.linRegEq.append( eq )
def clearAxes(self):
#resets all fields for plotting different dimensions
self.zAxis = False
self.colors = False
self.sizes = False
self.clusterColors = False
self.pca = False
self.categories = False
self.r = []
self.headers = []
if self.axisLabels != []:
for l in self.axisLabels:
l.destroy()
self.axisLabels = []
def handleOpen(self,event=None):
#opens and reads the file selected in the file dialog
self.circadian = False
fn = tkFileDialog.askopenfilename( parent=self.root, title='Choose a data file',
initialdir='.' )
self.data = d.Data( fn )
if fn[-18:] =='circadian_data.csv':
self.circadian = True
def handlePlotData(self):
#plots data based on user's axes selections
if self.data == None:
self.handleOpen()
self.clearAxes()
axes = self.handleChooseAxes()
self.buildPoints( axes )
def handleChooseAxes(self):
#returns a list of the headers for the axes
axes = SelectAxes(self.root, self.data, 'Select Axes')
headers = [ axes.result['x'], axes.result['y'], axes.result['z'],
axes.result['color'], axes.result['size'] ]
self.axisLabels = headers
self.headers = headers[:]
#set z, colors, and sizes variables
if axes.result['z'] != 'None':
self.zAxis = True
if axes.result['color'] != 'None':
self.colors = True
if axes.result['size'] != 'None':
self.sizes = True
#remove axes whose value is 'None'
x = 0
for i in range( len(self.headers) ):
if self.headers[i] == 'None':
x += 1
for j in range(x):
self.headers.remove('None')
self.addAxisStats()
self.addAxisLabels()
return self.headers
def buildPoints(self, headers ):
#creates and draws the data points from the data in the given column headers
self.clearData()
#normalize data
self.points = a.normalize_columns_separately(headers,self.data)
#create column of ones for homogeneous coordinates
ones = []
for i in range( self.data.get_raw_num_rows() ):
ones.append( 1 )
ones = np.matrix( ones ).T
#z data values
if self.zAxis:
end = self.points[0:,3:]
self.points = self.points[0:,0:3]
else:
end = self.points[0:,2:]
self.points = self.points[0:,0:2]
#colors and sizes
if self.colors and self.sizes:
colors = end[0:,0]
sizes = end[0:,1]
print 'colors and sizes'
elif self.colors:
colors = end
print 'colors'
elif self.sizes:
sizes = end
print 'sizes'
#check if the data has been classified into categories
if 'Categories' in self.data.get_raw_headers():
self.categories = True
if self.categories:
self.colors = False
c = []
unique, map = np.unique( self.data.get_data( ['Categories'] ).T.tolist()[0], return_inverse=True )
print 'unique clustuers: ' , len(unique)
for i in range(len(unique)):
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
color = "#%02X%02X%02X" % (r, g, b)
c.append( color )
#set values of colors (gradient from blue to yellow)
if self.colors:
c = []
for i in range( self.data.get_raw_num_rows() ):
r = 255 * colors[i,0]
g = 255 * colors[i,0]
b = 255 * (1-colors[i,0])
s = "#%02X%02X%02X" % (int(r), int(g), int(b))
c.append(s)
#add column of zeros if only 2 axes selected
#create column of zeros
zeros = []
for i in range( self.data.get_raw_num_rows() ):
zeros.append( 0 )
zeros = np.matrix( zeros ).T
if self.points.shape[1] == 2:
self.points = np.hstack( [self.points, zeros] )
#add column of ones to matrix
self.points = np.hstack( [self.points, ones] )
#transform data
vtm = self.view.build()
pts = (vtm * self.points.T).T
#create data points
for i in range( self.data.get_raw_num_rows() ):
if self.colors:
color = c[i]
elif self.categories:
color = c[ map[i] ]
else:
color = 'black'
if self.sizes:
self.r.append( ( 5 * math.sqrt(sizes[i,0]) ) + 1 )
r = self.r[i]
else:
r = 2
x = pts[i,0]
y = pts[i,1]
pt = self.canvas.create_oval( x+r, y+r, x-r, y-r, fill=color, outline='' )
self.objects.append(pt)
self.clearLinReg()
self.updateFits()
def updatePoints(self):
#updates all the data points
if len( self.objects ) == 0:
return
vtm = self.view.build()
pts = (vtm * self.points.T).T
for i in range( len(self.objects) ):
if self.sizes:
r = self.r[i]
else:
r = 2
x = pts[i,0]
y = pts[i,1]
self.canvas.coords( self.objects[i], x+r, y+r, x-r, y-r )
def clearData( self, event=None ):
#Clears all the data points on the canvas
for obj in self.objects:
self.canvas.delete(obj)
self.objects = []
def main(self):
#runs the data point creation application
print 'Entering main loop'
self.root.mainloop()
class Dialog(tk.Toplevel):
#outline class for a dialog box
def __init__(self, parent, title = None):
#creates dialog box object
tk.Toplevel.__init__(self, parent)
self.transient(parent)
if title:
self.title(title)
self.parent = parent
self.result = None
body = tk.Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=5, pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus = self
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
# construction hooks
def body(self, master):
# create dialog body. return widget that should have
# initial focus. this method should be overridden
pass
def buttonbox(self):
# add standard button box. override if you don't want the
# standard buttons
box = tk.Frame(self)
w = tk.Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side=tk.LEFT, padx=5, pady=5)
w = tk.Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=tk.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
# standard button semantics
def ok(self, event=None):
#specifies what happens when ok is clicked
if not self.validate():
self.initial_focus.focus_set() # put focus back
return
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()
def cancel(self, event=None):
# put focus back to the parent window
self.parent.focus_set()
self.destroy()
# command hooks
def validate(self):
#check data
return 1 # override
def apply(self):
pass # override
class SelectPCA(Dialog):
'''class that creates a dialog box where the user can select a PCA analysis to view,
add, remove, save, or plot. '''
def __init__(self, parent, d, pcad, title = None):
#sets up dialog box
self.data = d
self.pcad = pcad
self.parent = parent
self.p = False
Dialog.__init__(self,parent)
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose PCA") #instructions
#creates ListBox to choose multiple headers
self.options = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=8)
#adds options to the ListBoxes
for item in self.pcad.keys():
self.options.insert('end',item)
#adds the items to the grid
label.pack()
self.options.pack()
if self.pcad == {}:
self.add()
#sets selection to first item
self.options.selection_set(0)
def buttonbox(self):
# add standard button box. override if you don't want the
# standard buttons
box = tk.Frame(self)
w = tk.Button(box, text="Add", width=10, command=self.add)
w.pack(side=tk.LEFT, padx=5, pady=5)
w = tk.Button(box, text="Remove", width=10, command=self.remove)
w.pack(side=tk.LEFT,padx=5,pady=5)
w = tk.Button(box, text="Plot", width=10, command=self.plot)
w.pack(side=tk.LEFT,padx=5,pady=5)
w = tk.Button(box, text="View", width=10, command=self.view)
w.pack(side=tk.LEFT,padx=5,pady=5)
w = tk.Button(box, text="Save", width=10, command=self.save)
w.pack(side=tk.LEFT,padx=5,pady=5)
w = tk.Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side=tk.LEFT,padx=5,pady=5)
w = tk.Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=tk.LEFT,padx=5,pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
def add(self):
headers = SelectPCAHeaders(self.parent,self.data,'Select Column Headers').result
newPCA = a.pca( self.data,headers )
pcaName = EnterPCAName(self.parent,'Enter PCA Name').result
self.pcad[ pcaName ] = newPCA
self.options.insert( 'end',pcaName )
def remove(self):
#removes the selected item from the listbox
remItem = self.options.get( self.options.curselection() )
self.pcad.pop(remItem)
self.options.delete(0,'end')
for item in self.pcad:
self.options.insert('end',item)
def plot(self):
#sets the plot field to True, and then closes the Dialog box
self.p = True
self.ok()
def view(self):
#displays the values of the selected PCA
curPCA = self.options.get( self.options.curselection() )
ViewPCA( self.parent, self.pcad[curPCA], curPCA )
def save(self):
#saves the selected PCA to a .csv file of the specified name
curPCA = self.options.get( self.options.curselection() )
pcaName = EnterFileName(self.parent,'Enter File Name').result
self.pcad[curPCA].write( pcaName )
def apply(self):
#assigns a dictionary of the new pcad list and the currently selected pca to
#self.result
if self.p == True:
pca = self.options.get( self.options.curselection() )
plotPCA = self.pcad[pca]
else:
plotPCA = None
self.result = {'pcad':self.pcad,'plotPCA':plotPCA}
class ViewPCA(Dialog):
'''class that creates a dialog box where the user can view information of the selected
PCA analysis '''
def __init__(self, parent, pca, title = None):
#sets up dialog box
self.pca = pca
Dialog.__init__(self,parent)
def body(self,master):
#displays all the PCA information in the dialog box
total = 0
sum = 0
for i in range( self.pca.get_eigenvalues().size ):
total += self.pca.get_eigenvalues()[0,i]
for i in range( self.pca.get_eigenvectors().shape[0] + 1 ):
for j in range( len(self.pca.get_data_headers()) + 3 ):
if i == 0:
if j == 0:
string = 'E-vec'
elif j == 1:
string = 'E-val'
elif j == 2:
string = 'Cummulative'
else:
string = self.pca.get_data_headers()[j-3]
else:
if j == 0: #E-vec labels column
string = self.pca.get_raw_headers()[i-1]
elif j == 1: #E-val column
string = str( round(self.pca.get_eigenvalues()[0,i-1],4) )
elif j == 2: #cumulative column
sum += self.pca.get_eigenvalues()[0,i-1]
string = str( round( (sum/total),4 ) )
else: #data columns
string = str( round( self.pca.get_eigenvectors()[i-1,j-3],4) )
label = tk.Label( master, text=string )
label.grid(row=i,column=j)
class SelectPCAHeaders(Dialog):
'''class that creates a dialog box where the user can specify column headers to
be used in PCA analysis '''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.headers = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose columns to use for PCA") #instructions
#creates ListBox to choose multiple headers
self.headers = tk.Listbox(master, selectmode=tk.MULTIPLE, exportselection=0, height=8)
#adds options to the ListBoxes
for item in self.data.get_headers():
self.headers.insert('end',item)
#sets selection to first item
self.headers.selection_set(0)
#adds the items to the grid
label.pack()
self.headers.pack()
def buttonbox(self):
# add standard button box. override if you don't want the
# standard buttons
box = tk.Frame(self)
w = tk.Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side=tk.LEFT, padx=5, pady=5)
w = tk.Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=tk.LEFT, padx=5, pady=5)
w = tk.Button(box, text="Select All", width=10, command=self.select)
w.pack(side=tk.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
def select(self):
#selects all options in the listbox
self.headers.selection_set(0, len( self.data.get_headers() )-1 )
def apply(self):
#assign axes variables to the ListBox selections
headIdx = self.headers.curselection()
#assigns a list of headers to self.result
self.result = []
for h in headIdx:
self.result.append( self.headers.get( h ) )
class SelectClusterHeaders(Dialog):
'''class that creates a dialog box where the user can specify column headers to
be used in cluster analysis and number of clusters'''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.headers = None
self.k = None
self.color = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose column headers to use for clustering") #instructions
labelc = tk.Label(master, text="Cluster Colors: ")
#creates ListBox to choose multiple headers
self.headers = tk.Listbox(master, selectmode=tk.MULTIPLE, exportselection=0, height=8)
#adds options to the ListBoxes
for item in self.data.get_headers():
self.headers.insert('end',item)
#sets selection to first item
self.headers.selection_set(0)
#adds the items to the grid
label.pack()
self.headers.pack()
label = tk.Label(master, text="Choose number of clusters") #instructions
label.pack()
maxK = len( self.data.get_headers() )
self.k = tk.Scale( master, from_ = 1, to = maxK,
orient=tk.HORIZONTAL,
length = 225, resolution = 1 )
self.k.pack()
self.k.set(1)
labelc.pack()
self.color = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=2)
for item in ['Discrete','Blue/Yellow Gradient']:
self.color.insert( 'end', item )
self.color.pack()
self.color.selection_set(0)
def buttonbox(self):
# add standard button box. override if you don't want the
# standard buttons
box = tk.Frame(self)
w = tk.Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side=tk.LEFT, padx=5, pady=5)
w = tk.Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=tk.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
self.bind("<Button-2>", self.select)
box.pack()
def select(self, event):
#selects all options in the listbox
ends = self.headers.curselection()[-2:]
self.headers.select_clear(0,len( self.data.get_headers() )-1 )
self.headers.selection_set(ends[0], ends[1] )
def apply(self):
#assign axes variables to the ListBox selections
headIdx = self.headers.curselection()
k = self.k.get()
#assigns a list of headers to self.result
heads = []
for h in headIdx:
heads.append( self.headers.get( h ) )
self.color = self.color.get( self.color.curselection()[0] )
self.result = [heads,k,self.color]
class SelectClusterAxes(Dialog):
'''class that creates a dialog box where the user can specify data to plot on x,y,z,
and size axes'''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.x = None
self.y = None
self.z = None
self.size = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose Axes") #instructions
labelx = tk.Label(master, text="x: ")
labely = tk.Label(master, text="y: ")
labelz = tk.Label(master, text="z: ")
sz = tk.Label(master, text="Size: ")
#adds labels to grid
label.grid(row=0,columnspan=2, sticky='W')
labelx.grid(row=1,sticky='W')
labely.grid(row=2,sticky='W')
labelz.grid(row=3,sticky='W')
sz.grid(row=4,sticky='W')
#creates ListBoxes for the x, y, z, color, and size axes
self.x = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.y = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.z = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.size = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
#adds 'None' as first option in the z and size lists
for item in [self.z, self.size]:
item.insert('end','None')
#adds options to all the ListBoxes
for item in self.data.get_headers():
self.x.insert('end',item)
self.y.insert('end',item)
self.z.insert('end',item)
self.size.insert( 'end', item )
#adds the ListBoxes to the grid
self.x.grid(row=1, column=1)
self.y.grid(row=2, column=1)
self.z.grid(row=3, column=1)
self.size.grid(row=4, column=1)
#sets default values to first
for item in [self.x, self.y, self.z, self.size]:
item.selection_set(0)
def apply(self):
#assign axes variables to the ListBox selections
self.x = self.x.get( self.x.curselection()[0] )
self.y = self.y.get( self.y.curselection()[0] )
self.z = self.z.get( self.z.curselection()[0] )
self.size = self.size.get( self.size.curselection()[0] )
#assigns a dictionary of the axes to self.result
self.result = { 'x':self.x,'y':self.y, 'z':self.z, 'size':self.size }
class SelectPCAAxes(Dialog):
'''class that creates a dialog box where the user can specify x, y, z, shape, and color
axes to be plotted'''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.x = None
self.y = None
self.z = None
self.color = None
self.size = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose Axes") #instructions
labelx = tk.Label(master, text="x: ")
labely = tk.Label(master, text="y: ")
labelz = tk.Label(master, text="z: ")
col = tk.Label(master, text="Color: ")
sz = tk.Label(master, text="Size: ")
#adds labels to grid
label.grid(row=0,columnspan=2, sticky='W')
labelx.grid(row=1,sticky='W')
labely.grid(row=2,sticky='W')
labelz.grid(row=3,sticky='W')
col.grid(row=4,sticky='W')
sz.grid(row=5,sticky='W')
#creates ListBoxes for the x, y, z, color, and size axes
self.x = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.y = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.z = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.color = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.size = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
#adds 'None' as first option in the z, color, and size lists
for item in [self.color, self.size]:
item.insert('end','None')
#adds options to all the ListBoxes
for item in self.data.raw_headers:
self.x.insert('end',item)
self.y.insert('end',item)
self.z.insert('end',item)
self.color.insert( 'end', item )
self.size.insert( 'end', item )
#adds the ListBoxes to the grid
self.x.grid(row=1, column=1)
self.y.grid(row=2, column=1)
self.z.grid(row=3, column=1)
self.color.grid(row=4, column=1)
self.size.grid(row=5, column=1)
#sets default values to first
for item in [self.x, self.color, self.size]:
item.selection_set(0)
self.y.selection_set(1)
self.z.selection_set(2)
def apply(self):
#assign axes variables to the ListBox selections
self.x = self.x.get( self.x.curselection()[0] )
self.y = self.y.get( self.y.curselection()[0] )
self.z = self.z.get( self.z.curselection()[0] )
self.color = self.color.get( self.color.curselection()[0] )
self.size = self.size.get( self.size.curselection()[0] )
#assigns a dictionary of the axes to self.result
self.result = { 'x':self.x,'y':self.y, 'z':self.z, 'color':self.color, 'size':self.size }
class EnterPCAName(Dialog):
'''class that creates a dialog box where the user can specify the name of the PCA
Analysis that it can be found as. '''
def __init__(self, parent, title = None):
#sets up dialog box
Dialog.__init__(self,parent)
self.name = None
self.v = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Type your desired PCA analysis name.") #instructions
labelName = tk.Label(master, text="Analysis name: ")
#adds labels to grid
label.grid(row=0,columnspan=2, sticky='W')
labelName.grid(row=1,sticky='W')
#creates input textbox
self.v = tk.StringVar()
self.name = tk.Entry(master, textvariable = self.v)
#adds the Entry textbox to the grid
self.name.grid(row=1, column=1)
self.v.set( 'TypeAnalysisNameHere' )
def apply(self):
#assigns a dictionary of the axes to self.result
self.result = self.v.get()
class EnterFileName(Dialog):
'''class that creates a dialog box where the user can specify the name of the text
file that the linear regression data will be saved to. '''
def __init__(self, parent, title = None):
#sets up dialog box
Dialog.__init__(self,parent)
self.name = None
self.v = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Type your desired output file name.") #instructions
labelName = tk.Label(master, text="Output file name: ")
#adds labels to grid
label.grid(row=0,columnspan=2, sticky='W')
labelName.grid(row=1,sticky='W')
#creates input textbox
self.v = tk.StringVar()
self.name = tk.Entry(master, textvariable = self.v)
#adds the Entry textbox to the grid
self.name.grid(row=1, column=1)
self.v.set( 'TypeFileNameHere' )
def apply(self):
#assigns a dictionary of the axes to self.result
self.result = self.v.get()
class SelectMultiVars(Dialog):
'''class that creates a dialog box where the user can specify independent and dependent
variables to find the linear regression data for. '''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.vars = None
self.dep = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose Independent Variables") #instructions
dep = tk.Label(master, text="Choose Dependent Variable")
#creates ListBoxe to choose multiple variables
self.vars = tk.Listbox(master, selectmode=tk.MULTIPLE, exportselection=0, height=8)
self.dep = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=8)
#adds options to the ListBoxes
for item in self.data.get_headers():
self.vars.insert('end',item)
self.dep.insert('end',item)
#adds the items to the grid
label.pack()
self.vars.pack()
dep.pack()
self.dep.pack()
#sets default values to first elements
self.vars.selection_set(0)
self.dep.selection_set(0)
def apply(self):
#assign axes variables to the ListBox selections
varsIdx = self.vars.curselection()
#assigns a dictionary of the axes to self.result
self.independent = []
for h in varsIdx:
self.independent.append( self.vars.get( h ) )
self.dependent = [self.dep.get( self.dep.curselection()[0] )]
class SelectVariables(Dialog):
'''class that creates a dialog box where the user can specify x, y ,z color, and
size axes to plot. '''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.x = None
self.y = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose Variables") #instructions
labelx = tk.Label(master, text="Independent (x): ")
labely = tk.Label(master, text="Dependent (y): ")
#adds labels to grid
label.grid(row=0,columnspan=2, sticky='W')
labelx.grid(row=1,sticky='W')
labely.grid(row=2,sticky='W')
#creates ListBoxes for the x, y, z, color, and size axes
self.x = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=5)
self.y = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=5)
#adds options to all the ListBoxes
for item in self.data.get_headers():
self.x.insert('end',item)
self.y.insert('end',item)
#adds the ListBoxes to the grid
self.x.grid(row=1, column=1)
self.y.grid(row=2, column=1)
#sets default values to first element
self.x.selection_set(0)
self.y.selection_set(0)
def apply(self):
#assign axes variables to the ListBox selections
self.x = self.x.get( self.x.curselection()[0] )
self.y = self.y.get( self.y.curselection()[0] )
#assigns a dictionary of the axes to self.result
self.result = [ self.x, self.y ]
class SelectAxes(Dialog):
'''class that creates a dialog box where the user can specify x and y random
distributions, number of data points to be drawn, and shape of the data points'''
def __init__(self, parent, d, title = None):
#sets up dialog box
self.data = d
Dialog.__init__(self,parent)
self.x = None
self.y = None
self.z = None
self.color = None
self.size = None
def body(self,master):
#creates all the elements of the dialog box
label = tk.Label(master, text="Choose Axes") #instructions
labelx = tk.Label(master, text="x: ")
labely = tk.Label(master, text="y: ")
labelz = tk.Label(master, text="z: ")
col = tk.Label(master, text="Color: ")
sz = tk.Label(master, text="Size: ")
#adds labels to grid
label.grid(row=0,columnspan=2, sticky='W')
labelx.grid(row=1,sticky='W')
labely.grid(row=2,sticky='W')
labelz.grid(row=3,sticky='W')
col.grid(row=4,sticky='W')
sz.grid(row=5,sticky='W')
#creates ListBoxes for the x, y, z, color, and size axes
self.x = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.y = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.z = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.color = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
self.size = tk.Listbox(master, selectmode=tk.SINGLE, exportselection=0, height=4)
#adds 'None' as first option in the z, color, and size lists
for item in [self.z, self.color, self.size]:
item.insert('end','None')
#adds options to all the ListBoxes
for item in self.data.get_headers():
self.x.insert('end',item)
self.y.insert('end',item)
self.z.insert('end',item)
self.color.insert( 'end', item )
self.size.insert( 'end', item )
#adds the ListBoxes to the grid
self.x.grid(row=1, column=1)
self.y.grid(row=2, column=1)
self.z.grid(row=3, column=1)
self.color.grid(row=4, column=1)
self.size.grid(row=5, column=1)
#sets default values to first
for item in [self.x, self.y, self.z, self.color, self.size]:
item.selection_set(0)
def apply(self):
#assign axes variables to the ListBox selections
self.x = self.x.get( self.x.curselection()[0] )
self.y = self.y.get( self.y.curselection()[0] )
self.z = self.z.get( self.z.curselection()[0] )
self.color = self.color.get( self.color.curselection()[0] )
self.size = self.size.get( self.size.curselection()[0] )
#assigns a dictionary of the axes to self.result
self.result = { 'x':self.x,'y':self.y, 'z':self.z, 'color':self.color, 'size':self.size }
if __name__ == "__main__":
dapp = DisplayApp(1200, 675)
dapp.main()
| {"/PCAData.py": ["/data.py"]} |
72,217 | rskarp/cs251proj9 | refs/heads/master | /data.py | # Riley Karp
# data.py
# 2/20/2017
import sys
import csv
import numpy as np
#class that can read a csv data file and provide information about it
class Data:
def __init__(self, filename = None):
#creates a Data object by initializing the fields and reading the given csv file
#create and initialize fields
self.raw_headers = []
self.raw_types = []
self.raw_data = []
self.header2raw = {}
self.matrix_data = np.matrix([])
self.header2matrix = {}
self.matrix2header = {} #allows headers to be listed in order in self.get_headers()
if filename != None:
self.read(filename)
def read(self, filename):
#reads the given csv file and adds headers, types, and data to their respective fields
file = open( filename, 'rU' )
rows = csv.reader( file )
#append data to raw_data list field
for row in rows:
self.raw_data.append(row)
file.close()
#strip data to get rid of random spaces
for row in self.raw_data:
for j in range( len(row) ):
row[j] = row[j].strip()
#add headers and types to their respective fields
self.raw_headers = self.raw_data.pop(0)
self.raw_types = self.raw_data.pop(0)
#add values to header2raw dictionary & strip header strings
for item in self.raw_headers:
self.header2raw[ item ] = self.raw_headers.index(item)
#add numeric values to matrix_data and header2matrix dictionary
idx = 0
data = []
for i in range( len(self.raw_types) ):
if self.raw_types[i] == 'numeric':
#add headers and indexes to dictionary
header = self.raw_headers[i]
self.header2matrix[header] = idx
self.matrix2header[idx] = header
#add data to matrix_data
data.append([]) #makes new empty row
for r in range( self.get_raw_num_rows() ):
data[idx].append( self.raw_data[r][i] )
idx += 1
#put data into numpy matrix
self.matrix_data = np.matrix( data , dtype = float).T
def write( self, filename, headers = [] ):
#writes the data of the specified headers to a file of the given name
if len(headers) > 0:
d = self.get_data( headers )
file = filename + '.csv'
f = open( file, 'wb' )
writer = csv.writer( f, delimiter=',', quoting=csv.QUOTE_MINIMAL )
writer.writerow(headers)
types = []
for h in headers:
types.append( self.get_raw_types()[ self.header2raw[h] ] )
writer.writerow(types)
for i in range( d.shape[0] ):
row = []
for j in range( len(headers) ):
if headers[j] in self.header2raw.keys():
row.append( self.get_raw_value( i, headers[j] ) )
elif headers[j] in self.header2matrix.keys():
row.append( round( d[i,j],3 ) )
if row != []:
writer.writerow( row )
f.close()
def get_headers(self):
#returns a list of the headers of columns with numeric data
headers = []
for i in range( len(self.matrix2header) ):
headers.append( self.matrix2header[i] )
return headers
def get_num_columns(self):
#returns the number of columns with numeric data
return len(self.header2matrix)
def get_row(self, rIdx):
#returns the specified row of numeric data
if rIdx >= 0 and rIdx < self.get_raw_num_rows():
return self.matrix_data.tolist()[rIdx]
def get_value(self, rIdx, cString):
#returns the value of numeric data at the given row,col location
if rIdx >= 0 and rIdx < self.get_raw_num_rows() and cString in self.header2matrix:
return self.matrix_data[ rIdx, self.header2matrix[cString] ]
def get_data(self, headers):
#returns a matrix of numeric data from the columns with the specified list of headers
d = np.matrix([]) #empty matrix
d.shape = ( self.get_raw_num_rows(), 0 ) #reshape matrix so we can use hstack
for h in headers:
if h in self.header2matrix.keys():
cIdx = self.header2matrix[h]
col = self.matrix_data[ 0:, cIdx:cIdx+1 ]
d = np.hstack( [d,col] )
return d
def addColumn(self, header, type, points):
#adds a column of data with the given header, type, and list of data points
if len(points) == self.get_raw_num_rows():
self.header2raw[header] = self.get_raw_num_columns()
self.raw_headers.append(header)
self.raw_types.append(type)
for i in range( len(points) ):
self.raw_data[i].append(points[i])
if type == 'numeric':
self.header2matrix[header] = self.get_num_columns()
col = np.matrix( points ).T
self.matrix_data = np.hstack( [self.matrix_data, col] )
def get_raw_headers(self):
#returns a reference to the list of all the headers
return self.raw_headers
def get_raw_types(self):
#returns a reference to the list of data types in each column
return self.raw_types
def get_raw_num_columns(self):
#returns the total number of columns of data
return len(self.raw_headers)
def get_raw_num_rows(self):
#returns the total number of rows of data
return len(self.raw_data)
def get_raw_row(self, idx):
#returns the specified row of raw data
if idx >=0 and idx < self.get_raw_num_rows():
return self.raw_data[idx]
def get_raw_value(self, rIdx, cString):
#returns the value at the specified row,col location
if rIdx >=0 and rIdx < self.get_raw_num_rows():
return self.raw_data[ rIdx ][ self.header2raw[cString] ]
def toString(self):
#prints the contents of the Data object by rows and columns
string = ''
for item in [self.get_raw_headers(), self.get_raw_types()]:
for idx in range( self.get_raw_num_columns() ):
string += item[idx] + '\t'
string += '\n'
for row in self.raw_data:
for idx in range( len(row) ):
string += row[idx] + '\t'
string += '\n'
print string
def main(filename):
#tests all the methods of the Data class
d = Data( filename )
print '\t Testing Raw Methods'
print 'd.get_raw_headers: ' , d.get_raw_headers()
print 'd.get_raw_types: ' , d.get_raw_types()
print 'd.get_raw_num_columns: ' , d.get_raw_num_columns()
print 'd.get_raw_row(0): ' , d.get_raw_row(0)
# print 'raw_data: ' , d.raw_data
# print 'header2raw:' , d.header2raw
# d.toString()
headers = ['hi', 'headers', 'in', 'spaces', 'bye']
print '\n \t Testing Numeric Methods'
print 'd.get_headers: ' , d.get_headers()
print 'd.get_num_columns: ' , d.get_num_columns()
print 'd.get_row(0): ' , d.get_row(0)
print 'd.get_value( 1, "bad" ): ' , d.get_value( 1, 'bad' )
print 'd.get_data( headers ): \n' , d.get_data( headers )
print '\n \t Testing Analysis Methods'
print 'range: ' , a.data_range(headers,d)
print 'median: ' , a.median(headers,d)
print 'mean: ' , a.mean(headers,d)
print 'stdev: ' , a.stdev(headers,d)
print 'normalize_columns_separately: \n' , a.normalize_columns_separately(headers,d)
print 'normalize_columns_together: \n' , a.normalize_columns_together(headers,d)
print '\n \t Testing addColumn'
print 'd.get_raw_headers: ' , d.get_raw_headers()
print 'd.get_raw_types: ' , d.get_raw_types()
print 'd.raw_data: ' , d.raw_data
print 'd.get_data( headers ): \n' , d.get_data( headers )
print '\t adding column'
d.addColumn( 'newCol', 'numeric', [3,1,4] )
headers.append( 'newCol' )
print 'd.get_raw_headers: ' , d.get_raw_headers()
print 'd.get_raw_types: ' , d.get_raw_types()
print 'd.raw_data: ' , d.raw_data
print 'd.get_data( headers ): \n' , d.get_data( headers )
def testWrite(filename):
d = Data(filename)
headers = d.get_raw_headers()[0:5]
d.write( 'testWrite',headers )
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: python %s <csv_filename>" % sys.argv[0]
print " where <csv_filename> specifies a csv file"
exit()
# main( sys.argv[1] )
testWrite( sys.argv[1] ) | {"/PCAData.py": ["/data.py"]} |
72,218 | rskarp/cs251proj9 | refs/heads/master | /PCAData.py | # Riley Karp
# data.py
# 2/20/2017
import sys
import csv
import numpy as np
import data
#class that can read a csv data file and provide information about it
class PCAData( data.Data ):
def __init__(self, origHeaders, projData, evals, evecs, origMeans ):
#creates a PCAData object by initializing the fields of the Data object
data.Data.__init__(self)
#create and initialize fields
self.evecs = evecs
self.evals = evals
self.means = origMeans
self.headers = origHeaders
self.matrix_data = projData
#old fields
self.raw_headers = [] # e0,e1,etc...
self.raw_types = [] # all numeric
self.raw_data = projData.tolist()
self.header2raw = {} # raw_headers
self.header2matrix = {} # origHeaders
for i in range( len(self.headers) ):
self.raw_headers.append( 'e' + str(i) )
self.header2raw[ 'e' + str(i) ] = i
self.raw_types.append( 'numeric' )
self.header2matrix[ self.headers[i] ] = i
self.matrix2header[ i ] = self.headers[i]
def write( self, filename ):
#writes all the PCA information to the specified file
file = filename + '.csv'
f = open( file, 'wb' )
writer = csv.writer( f, delimiter=',', quoting=csv.QUOTE_MINIMAL )
heads = ['E-vec','E-val','Cumulative']
for h in self.get_headers():
heads.append( h )
types = ['enum','string','percent']
for i in range( len(self.get_raw_headers()) ):
types.append( 'numeric' )
writer.writerow(heads)
writer.writerow(types)
total = 0
sum = 0
for i in range( self.get_eigenvalues().size ):
total += self.get_eigenvalues()[0,i]
for i in range( self.get_eigenvectors().shape[1] ):
sum += self.get_eigenvalues()[0,i]
cum = round( (sum/total) , 4 )
row = [ 'e'+str(i), round( self.get_eigenvalues()[0,i] , 4 ), cum ]
for j in range( self.get_eigenvectors().shape[0] ):
row.append( round( self.get_eigenvectors()[i,j],4) )
writer.writerow(row)
f.close()
# def write( self, filename ):
# #second write method. writes all the PCA information to the specified file
# file = filename + '.csv'
# f = open( file, 'wb' )
# writer = csv.writer( f, delimiter=',', quoting=csv.QUOTE_MINIMAL )
#
# types = []
# heads = []
# for i in range( self.matrix_data.shape[1] ):
# heads.append( 'e'+str(i) )
# types.append( 'numeric' )
#
# writer.writerow(heads)
# writer.writerow(types)
#
# print self.get_eigenvectors().shape
# print self.matrix_data.shape
# for i in range( self.matrix_data.shape[1] ):
# row = self.matrix_data[i,:].tolist()[0]
# writer.writerow(row)
#
# f.close()
def get_eigenvalues(self):
#returns a copy of the eigenvalues as a single-row numpy matrix
return self.evals
def get_eigenvectors(self):
#returns a copy of the eigenvectors as a numpy matrix with the eigenvectors as rows
return self.evecs
def get_data_means(self):
#returns the means for each column in the original data as a single row numpy matrix
return self.means
def get_data_headers(self):
#returns a copy of the list of the headers from the original data used to generate the projected data
return self.headers | {"/PCAData.py": ["/data.py"]} |
72,219 | rskarp/cs251proj9 | refs/heads/master | /view.py | #Riley Karp
#view.py
#02/27/2017
import numpy as np
import math
class View:
def __init__(self):
#sets up the View
self.reset()
def reset(self):
#resets the view parameters to their original values
self.vrp = np.matrix([0.5,0.5,1.0])
self.vpn = np.matrix([0.0,0.0,-1.0])
self.vup = np.matrix([0.0,1.0,0.0])
self.u = np.matrix([-1.0,0.0,0.0])
self.extent = [1.0,1.0,1.0]
self.screen = [400.0,400.0]
self.offset = [20.0,20.0]
def build(self):
#move VRP to origin
vtm = np.identity(4,float)
t1 = np.matrix( [[1,0,0,-self.vrp[0,0]],
[0,1,0,-self.vrp[0,1]],
[0,0,1,-self.vrp[0,2]],
[0,0,0,1]],dtype=float )
vtm = t1*vtm
#calculate tu, tvup, and tvpn
tu = np.cross( self.vup,self.vpn )
tvup = np.cross( self.vpn,tu )
tvpn = self.vpn
#normalize tu, tvup, tvpn to unit length
for v in [tu,tvup,tvpn]:
self.normalize(v)
self.u = tu
self.vup = tvup
self.vpn = tvpn
#align view reference axes
r1 = np.matrix( [[ tu[0,0], tu[0,1], tu[0,2], 0.0 ],
[ tvup[0,0], tvup[0,1], tvup[0,2], 0.0 ],
[tvpn[0,0], tvpn[0,1], tvpn[0,2], 0.0 ],
[ 0.0, 0.0, 0.0, 1.0 ]], dtype=float )
vtm = r1*vtm
#translate lower left corner of view space to origin
t2 = np.matrix( [[ 1,0,0,0.5*self.extent[0] ],
[ 0,1,0,0.5*self.extent[1] ],
[ 0,0,1,0 ],
[ 0,0,0,1 ]], dtype=float )
vtm = t2*vtm
#scale the screen
s1 = np.matrix( [[ -self.screen[0]/self.extent[0],0,0,0 ],
[ 0,-self.screen[1]/self.extent[1],0,0 ],
[ 0,0,1.0/self.extent[2],0 ],
[ 0,0,0,1 ]], dtype=float )
vtm = s1*vtm
#translate lower left corner to origin & add view offset
t3 = np.matrix( [[ 1,0,0,self.screen[0]+self.offset[0] ],
[ 0,1,0,self.screen[1]+self.offset[1] ],
[ 0,0,1,0 ],
[ 0,0,0,1 ]], dtype=float )
vtm = t3*vtm
return vtm
def normalize(self,v):
#normalizes the given vector
length = math.sqrt(v[0,0]*v[0,0] + v[0,1]*v[0,1] + v[0,2]*v[0,2])
if length != 0:
v[0,0] = v[0,0]/length
v[0,1] = v[0,1]/length
v[0,2] = v[0,2]/length
def clone(self):
#creates and returns a clone of the current view object
newView = View()
newView.vrp = self.vrp
newView.vpn = self.vpn
newView.vup = self.vup
newView.u = self.u
newView.extent = self.extent
newView.screen = self.screen
newView.offset = self.offset
return newView
def rotateVRC(self,VUPangle,Uangle):
#rotates the center of the view volume around the the VUP and U axes based on
#the given angles
cor = self.vrp + self.vpn*self.extent[2]*0.5
t1 = np.matrix( [[1,0,0,-cor[0,0]],
[0,1,0,-cor[0,1]],
[0,0,1,-cor[0,2]],
[0,0,0,1]], dtype=float )
Rxyz = np.matrix( [ [self.u[0,0],self.u[0,1],self.u[0,2],0],
[self.vup[0,0],self.vup[0,1],self.vup[0,2],0],
[self.vpn[0,0],self.vpn[0,1],self.vpn[0,2],0],
[0,0,0,1] ], dtype=float )
cosVUP = math.cos( math.radians(VUPangle) )
sinVUP = math.sin( math.radians(VUPangle) )
cosU = math.cos( math.radians(Uangle) )
sinU = math.sin( math.radians(Uangle) )
r1 = np.matrix( [[cosVUP,0,sinVUP,0],
[0,1,0,0],
[-sinVUP,0,cosVUP,0],
[0,0,0,1]], dtype=float )
r2 = np.matrix( [[1,0,0,0],
[0,cosU,-sinU,0],
[0,sinU,cosU,0],
[0,0,0,1]], dtype=float )
t2 = np.matrix( [[1,0,0,cor[0,0]],
[0,1,0,cor[0,1]],
[0,0,1,cor[0,2]],
[0,0,0,1]], dtype=float )
tvrc = np.matrix( [ [self.vrp[0,0],self.vrp[0,1],self.vrp[0,2],1],
[self.u[0,0],self.u[0,1],self.u[0,2],0],
[self.vup[0,0],self.vup[0,1],self.vup[0,2],0],
[self.vpn[0,0],self.vpn[0,1],self.vpn[0,2],0] ], dtype=float )
tvrc = (t2*Rxyz.T*r2*r1*Rxyz*t1*tvrc.T).T
#copy values from tvrc back to VPR, U, VUP, and VPN
self.vrp = np.matrix( tvrc.tolist()[0][0:-1], dtype=float )
self.u = np.matrix( tvrc.tolist()[1][0:-1], dtype=float )
self.vup = np.matrix( tvrc.tolist()[2][0:-1], dtype=float )
self.vpn = np.matrix( tvrc.tolist()[3][0:-1], dtype=float )
#normalize U, VUP, and VPN
for v in [self.u,self.vup,self.vpn]:
self.normalize(v)
def main():
v = View()
print v.build()
if __name__ == '__main__':
main()
| {"/PCAData.py": ["/data.py"]} |
72,220 | rskarp/cs251proj9 | refs/heads/master | /classifiers.py | # Template by Bruce Maxwell
# Spring 2015
# CS 251 Project 8
#
# Classifier class and child definitions
# Riley Karp
# classifiers.py
# 5/12/17
import sys
import data
import analysis as an
import numpy as np
import scipy.cluster
class Classifier:
def __init__(self, type):
'''The parent Classifier class stores only a single field: the type of
the classifier. A string makes the most sense.
'''
self._type = type
def type(self, newtype = None):
'''Set or get the type with this function'''
if newtype != None:
self._type = newtype
return self._type
def confusion_matrix( self, truecats, classcats ):
'''Takes in two Nx1 matrices of zero-index numeric categories and
computes the confusion matrix. The rows represent true
categories, and the columns represent the classifier output.
'''
trueunique, truemap = np.unique( np.array( truecats ), return_inverse= True )
numCats = len( trueunique )
cmat = np.matrix( np.zeros( [ numCats,numCats ] ) )
for i in range( classcats.shape[0] ):
cmat[ truemap[i], classcats[i,0] ] += 1
cmat = np.concatenate( (np.matrix( trueunique ).T,cmat),axis=1 )
return cmat
def confusion_matrix_str( self, cmtx ):
'''Takes in a confusion matrix and returns a string suitable for printing.'''
labels = cmtx[:,0]
s = '\nConfusion Matrix:\n'
for i in range( cmtx.shape[1] ):
for j in range( cmtx.shape[1] ):
if i == 0:
if j == 0:
s += 'Actual->'
else:
s += '\t' + str( int( labels[j-1,0] ) )
else:
s += '\t' + str( int( cmtx[i-1,j] ) )
s += '\n'
return s
def __str__(self):
'''Converts a classifier object to a string. Prints out the type.'''
return str(self._type)
class NaiveBayes(Classifier):
'''NaiveBayes implements a simple NaiveBayes classifier using a
Gaussian distribution as the pdf.
'''
def __init__(self, dataObj=None, headers=[], categories=None):
'''Takes in a Data object with N points, a set of F headers, and a
matrix of categories, one category label for each data point.'''
# call the parent init with the type
Classifier.__init__(self, 'Naive Bayes Classifier')
self.headers = headers #headers used for classification
self.C = None #number of classes
self.F = None #number of features
self.class_labels = None #original class labels
# unique data for the Naive Bayes: means, variances, scales
self.class_means = None
self.class_vars = None
self.class_scales = None
if dataObj != None:
A = dataObj.getData(headers)
self.build( A,categories )
def build( self, A, categories ):
'''Builds the classifier give the data points in A and the categories'''
# figure out how many categories there are and get the mapping (np.unique)
unique, mapping = np.unique( np.array( categories.T ), return_inverse= True )
self.C = len( unique )
self.F = A.shape[1]
self.class_labels = unique
# create the matrices for the means, vars, and scales
# the output matrices will be categories (C) x features (F)
self.class_means = np.matrix( np.empty([self.C,self.F]) )
self.class_vars = np.matrix( np.empty([self.C,self.F]) )
self.class_scales = np.matrix( np.empty([self.C,self.F]) )
# compute the means/vars/scales for each class
for i in range( self.C ):
for j in range( self.F ):
self.class_means[i,:] = np.mean( A[mapping==i,:],axis=0 )
vars = np.var( A[mapping==i,:],axis=0 )
self.class_vars[i,:] = vars
if vars.all() != 0:
self.class_scales[i,:] = 1/np.sqrt( 2*np.pi*vars )
else:
self.class_scales[i,:] = 0
return
def classify( self, A, return_likelihoods=False ):
'''Classify each row of A into one category. Return a matrix of
category IDs in the range [0..C-1], and an array of class
labels using the original label values. If return_likelihoods
is True, it also returns the NxC likelihood matrix.
'''
# error check to see if A has the same number of columns as
# the class means
if A.shape[1] != self.class_means.shape[1]:
print 'Error: different number of data columns and means.'
return
# make a matrix that is N x C to store the probability of each
# class for each data point
P = np.matrix( np.empty([A.shape[0],self.C]) )
# calculate the probabilities by looping over the classes
for i in range( self.C ):
P[:,i] = np.prod( np.multiply(self.class_scales[i,:],
np.exp( np.multiply(-1.0,
np.divide( np.square(A - self.class_means[i,:]),
np.multiply(2, self.class_vars[i,:]) )) )), axis = 1 )
# calculate the most likely class for each data point
cats = np.argmax( P, axis=1 ) # take the argmax of P along axis 1
# use the class ID as a lookup to generate the original labels
labels = self.class_labels[cats]
if return_likelihoods:
return cats, labels, P
return cats, labels
def __str__(self):
'''Make a pretty string that prints out the classifier information.'''
s = "\nNaive Bayes Classifier\n"
for i in range(self.C):
s += 'Class %d --------------------\n' % (i)
s += 'Mean : ' + str(self.class_means[i,:]) + "\n"
s += 'Var : ' + str(self.class_vars[i,:]) + "\n"
s += 'Scales: ' + str(self.class_scales[i,:]) + "\n"
s += "\n"
return s
def write(self, filename):
'''Writes the Bayes classifier to a file.'''
# extension
return
def read(self, filename):
'''Reads in the Bayes classifier from the file'''
# extension
return
class KNN(Classifier):
def __init__(self, dataObj=None, headers=[], categories=None, K=None):
'''Take in a Data object with N points, a set of F headers, and a
matrix of categories, with one category label for each data point.'''
# call the parent init with the type
Classifier.__init__(self, 'KNN Classifier')
# store the headers used for classification
self.headers = headers
# number of classes and number of features
self.C = None
self.F = None
# original class labels
self.class_labels = None
# unique data for the KNN classifier: list of exemplars (matrices)
self.exemplars = []
if dataObj != None:
self.build( dataObj.get_data( headers ), categories, K )
def build( self, A, categories, K = None ):
'''Builds the classifier give the data points in A and the categories'''
# figure out how many categories there are and get the mapping (np.unique)
unique, mapping = np.unique( np.array( categories.T ), return_inverse= True )
self.C = len( unique )
self.F = A.shape[1]
self.class_labels = unique
for i in range( self.C ):
if K == None:
self.exemplars.append( A[mapping==i,:] )
else:
# codebook = an.kmeans_init( A[mapping==i,:],K )
codebook, distortion = scipy.cluster.vq.kmeans( A[mapping==i,:],K )
self.exemplars.append( codebook )
return
def classify(self, A, K=3, return_distances=False):
'''Classify each row of A into one category. Return a matrix of
category IDs in the range [0..C-1], and an array of class
labels using the original label values. If return_distances is
True, it also returns the NxC distance matrix.
The parameter K specifies how many neighbors to use in the
distance computation. The default is three.'''
# error check to see if A has the same number of columns as the class means
if A.shape[1] != self.exemplars[0].shape[1]:
print 'Error: different number of data columns and means.'
return
# make a matrix that is N x C to store the distance to each class for each data point
N = A.shape[0]
D = np.matrix( np.empty( [N,self.C] ) )
for i in range( self.C ):
# make a temporary matrix that is N x M where M is the number of examplars (rows in exemplars[i])
temp = np.matrix( np.empty( [ N,self.exemplars[i].shape[0] ] ) )
# calculate the distance from each point in A to each point in exemplar matrix i (for loop)
for j in range( self.exemplars[i].shape[0] ):
temp[:,j] = np.sqrt( np.sum(np.square(A - self.exemplars[i][j,:]),axis=1 ) )
# sort the distances by row
temp = np.sort( temp, axis=1 )
# sum the first K columns
D[:,i] = np.sum( temp[:,:K],axis=1 )
# this is the distance to the first class
# calculate the most likely class for each data point
cats = np.argmin( D,axis=1 ) # take the argmin of D along axis 1
# use the class ID as a lookup to generate the original labels
labels = self.class_labels[cats]
if return_distances:
return cats, labels, D
return cats, labels
def __str__(self):
'''Make a pretty string that prints out the classifier information.'''
s = "\nKNN Classifier\n"
for i in range(self.C):
s += 'Class %d --------------------\n' % (i)
s += 'Number of Exemplars: %d\n' % (self.exemplars[i].shape[0])
s += 'Mean of Exemplars :' + str(np.mean(self.exemplars[i], axis=0)) + "\n"
s += "\n"
return s
def write(self, filename):
'''Writes the KNN classifier to a file.'''
# extension
return
def read(self, filename):
'''Reads in the KNN classifier from the file'''
# extension
return
| {"/PCAData.py": ["/data.py"]} |
72,221 | IlkinR/vacancies-counter | refs/heads/main | /services.py | import asyncio
from bs4 import BeautifulSoup
import aiohttp
HEAD_HUNTER_URL = 'https://api.hh.ru/vacancies'
FLEX_JOBS_URL = 'https://www.flexjobs.com/search?search=&search={query}'
INDEED_URL = 'https://www.indeed.com/jobs?q={query}&l=&ts=1621597199451&rq=1&rsIdx=0&fromage=last&newcount=38396'
SUPER_JOB_URL = 'https://ru.jobsora.com/работа-{query}'
async def get_soup(url: str):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response = await response.text()
soup = BeautifulSoup(response, 'lxml')
return soup
class FlexJobCounter:
SEARCH_URL_JOINER = '+'
FLEX_JOBS_URL = 'https://www.flexjobs.com/search?search=&search={query}'
VACANCIES_TAG_ATTRS = {'style': 'margin:0;font-size:14px;'}
@classmethod
def _get_search_url(cls, searched_job) -> str:
words = searched_job.split()
search_query = cls.SEARCH_URL_JOINER.join(words)
return cls.FLEX_JOBS_URL.format(query=search_query)
@classmethod
def _extract_vacancies(cls, soup) -> str:
vacancies_tag = soup.find('h4', attrs=cls.VACANCIES_TAG_ATTRS)
vacancies = vacancies_tag.text
vacancies_slice = slice(
vacancies.index('of') + 2,
vacancies.index('for') - 3
)
return vacancies[vacancies_slice].strip()
def __init__(self, searched_job: str) -> None:
self.search_url = FlexJobCounter._get_search_url(searched_job)
async def count_vacancies(self) -> str:
soup = await get_soup(self.search_url)
return FlexJobCounter._extract_vacancies(soup)
class IndeedCounter:
SEARCH_URL_JOINER = '+'
INDEED_URL = 'https://www.indeed.com/jobs?q={query}&l=&ts=1621597199451&rq=1&rsIdx=0&fromage=last&newcount=38396'
VACANCIES_TAG_PATH = 'div#searchCountPages'
@classmethod
def _get_search_url(cls, searched_job: str) -> str:
words = searched_job.split()
search_query = cls.SEARCH_URL_JOINER.join(words)
return cls.INDEED_URL.format(query=search_query)
@classmethod
def _extract_vacancies(cls, soup) -> str:
vacancies_tag = soup.select(cls.VACANCIES_TAG_PATH)[0]
vacancies = vacancies_tag.text
start, end = vacancies.index('of'), vacancies.index('jobs')
return vacancies[start + 2: end].strip()
def __init__(self, searched_job: str) -> None:
self.search_url = IndeedCounter._get_search_url(searched_job)
async def count_vacancies(self) -> str:
soup = await get_soup(self.search_url)
return IndeedCounter._extract_vacancies(soup)
__all__ = ['FlexJobCounter', 'IndeedCounter']
| {"/main.py": ["/services.py"]} |
72,222 | IlkinR/vacancies-counter | refs/heads/main | /main.py | from fastapi import FastAPI
from services import FlexJobCounter, IndeedCounter
api = FastAPI()
@api.get('/flexjobs/{query}')
async def flexjobs(query: str):
counter = FlexJobCounter(searched_job=query)
vacancies = await counter.count_vacancies()
return {'job': query, 'items': vacancies, 'source': 'flexjobs'}
@api.get('/indeed/{query}')
async def indeed(query: str):
counter = IndeedCounter(searched_job=query)
vacancies = await counter.count_vacancies()
return {'job': query, 'items': vacancies, 'source': 'indeed'}
| {"/main.py": ["/services.py"]} |
72,238 | jekolonardo/evian | refs/heads/master | /evian/course/admin.py | from django.contrib import admin
from .models import Course, CourseIndex, CourseIndexType, ClassTaker, ClassInstructor, Class, Attendance
# Register your models here.
admin.site.register(Course)
admin.site.register(CourseIndex)
admin.site.register(CourseIndexType)
admin.site.register(ClassTaker)
admin.site.register(ClassInstructor)
admin.site.register(Class)
admin.site.register(Attendance) | {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,239 | jekolonardo/evian | refs/heads/master | /evian/login/tests.py | from django.test import TestCase
from .models import User, UserLogin
import json
# Create your tests here.
def createUser(matric="U1620136D", name="Jeko Lonardo", domain="student", img="test.jpg"):
return User.objects.create(matric_no=matric, name=name, domain=domain, face_image=img)
def createUserLogin(user, username="jeko002",password="jeko002"):
return UserLogin.objects.create(username=username, password=password, user=user)
class UserLoginViewTests(TestCase):
def test_success_login(self):
createUserLogin(user=createUser())
response = self.client.post("/login/",json.dumps({'username':'jeko002','password':'jeko002'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
def test_wrong_username_login(self):
createUserLogin(user=createUser())
response = self.client.post("/login/",json.dumps({'username':'jeko001','password':'jeko002'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_wrong_password_login(self):
createUserLogin(user=createUser())
response = self.client.post("/login/",json.dumps({'username':'jeko002','password':'jeko001'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,240 | jekolonardo/evian | refs/heads/master | /evian/course/management/commands/generate_class_session.py | from django.core.management.base import BaseCommand, CommandError
from course.models import Course, CourseIndex, CourseIndexType, ClassTaker, Class, Attendance
from login.models import User
import datetime
class Command(BaseCommand):
today = datetime.datetime.now()
today_date = today.date()+datetime.timedelta(days=1)
today_time = today.time()
help = "generate new class sessions for "+datetime.datetime.strftime(today_date, "%d-%m-%y")
def handle(self, *args, **options):
print("Generating classes")
date = datetime.datetime.now().date()
self.generate_class(date)
def generate_class(self, date):
day = date.weekday()
course_index_type_list = CourseIndexType.objects.filter(day = day)
for c in course_index_type_list:
date_time = datetime.datetime.combine(date, c.time)
try:
class_session = Class.objects.get(course_index_type = c, datetime = date_time)
except Class.DoesNotExist:
class_session = Class(course_index_type = c, datetime = date_time)
class_session.save()
class_taker_list = ClassTaker.objects.filter(course_index = c.course_index)
for ct in class_taker_list:
attendance = Attendance(class_session = class_session, student = ct.student, status="absent")
attendance.save()
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,241 | jekolonardo/evian | refs/heads/master | /evian/login/models.py | from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings
import os
from functools import partial
DOMAIN = [('student','student'), ('staff','staff')]
FACE_DIR = 'face_images/'
SIGN_DIR = "sign_images/"
def _update_filename(instance, filename, path):
ext = filename.split('.')[-1]
filename = '{}.{}'.format(instance.matric_no, ext)
return os.path.join(path, filename)
def upload_to(path):
return partial(_update_filename, path=path)
# Create your models here.
class User(models.Model):
matric_no = models.CharField(max_length=20)
name = models.CharField(max_length=200)
domain = models.CharField(max_length=20, choices = DOMAIN)
face_image = models.ImageField(upload_to=upload_to(FACE_DIR))
sign_image = models.ImageField(upload_to=upload_to(SIGN_DIR), blank=True)
def __str__(self):
return self.matric_no
@receiver(models.signals.post_delete, sender=User)
def auto_delete_file_on_delete(sender, instance, **kwargs):
"""
Deletes file from filesystem
when corresponding `MediaFile` object is deleted.
"""
if instance.face_image:
if os.path.isfile(instance.face_image.path):
os.remove(instance.face_image.path)
if instance.sign_image:
if os.path.isfile(instance.sign_image.path):
os.remove(instance.sign_image.path)
@receiver(pre_save, sender=User)
def file_update(sender, **kwargs):
upload_folder_instance = kwargs['instance']
if FACE_DIR not in upload_folder_instance.face_image.name:
filename = upload_folder_instance.face_image.name
# print(f"face image is {filename}")
path = _update_filename(instance = upload_folder_instance, filename = filename, path = FACE_DIR)
path = os.path.join(settings.MEDIA_ROOT, path)
try:
os.remove(path)
except:
pass
if SIGN_DIR not in upload_folder_instance.sign_image.name:
filename = upload_folder_instance.sign_image.name
# print(f"sign image is {filename}")
path = _update_filename(instance = upload_folder_instance, filename = filename, path = SIGN_DIR)
path = os.path.join(settings.MEDIA_ROOT, path)
try:
os.remove(path)
except:
pass
class UserLogin(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
username = models.CharField(max_length = 20)
password = models.CharField(max_length = 100)
def __str__(self):
return f'{self.user.matric_no}-{self.username}'
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,242 | jekolonardo/evian | refs/heads/master | /evian/course/models.py | from django.db import models
from login.models import User
DAYS=[
(0,'Monday'),
(1,'Tuesday'),
(2,'Wednesday'),
(3,'Thursday'),
(4,'Friday'),
(5,'Saturday'),
(6,'Sunday')
]
CLASS_TYPE = [
('lecture','Lecture'),
('tutorial','Tutorial'),
('lab','Lab')
]
STATUS = [
('present','Present'),
('absent','Absent'),
('mc','MC')
]
# Create your models here.
class Course(models.Model):
course_code = models.CharField(max_length=10)
course_name = models.CharField(max_length=100)
def __str__(self):
return self.course_code
class CourseIndex(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
index = models.CharField(max_length=10)
group = models.CharField(max_length=10)
def __str__(self):
return f'{str(self.course)}-{self.index}'
class Meta:
verbose_name_plural = "Course Indexes"
class CourseIndexType(models.Model):
course_index = models.ForeignKey(CourseIndex, on_delete=models.CASCADE)
class_type = models.CharField(max_length=10, choices=CLASS_TYPE)
day = models.IntegerField(choices=DAYS)
time = models.TimeField('class time')
duration = models.DurationField()
def __str__(self):
return f'{str(self.course_index)}-{self.class_type}'
class Class(models.Model):
course_index_type = models.ForeignKey(CourseIndexType, on_delete=models.CASCADE)
datetime = models.DateTimeField('class datetime')
def __str__(self):
return f'{str(self.course_index_type)}-{self.datetime.date()}-{self.datetime.time()}'
class Meta:
verbose_name_plural = "Classes"
class ClassTaker(models.Model):
course_index = models.ForeignKey(CourseIndex, on_delete=models.CASCADE)
student = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
# matric_no = models.CharField(max_length=20)
def __str__(self):
return f'{str(self.course_index)}-{str(self.student)}'
class ClassInstructor(models.Model):
course_index = models.ForeignKey(CourseIndex, on_delete=models.CASCADE)
staff = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
def __str__(self):
return f'{str(self.course_index)}-{str(self.staff)}'
class Attendance(models.Model):
class_session = models.ForeignKey(Class, on_delete=models.CASCADE)
student = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
status = models.CharField(max_length=10, choices=STATUS)
attendance_time = models.TimeField('attendance time', null=True, blank=True)
signature = models.TextField(blank=True, default='')
def __str__(self):
return f'{str(self.class_session)}-{str(self.student)}'
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,243 | jekolonardo/evian | refs/heads/master | /evian/facial/tests.py | from django.test import TestCase
from login.models import User, UserLogin
from course.models import Course, CourseIndex, CourseIndexType, ClassTaker, ClassInstructor, Attendance, Class
import json
import datetime
import base64
# Create your tests here.
def createUser(matric="U1620136D", name="Jeko Lonardo", domain="student", img="test.jpg"):
return User.objects.create(matric_no=matric, name=name, domain=domain, face_image=img)
def createUserLogin(user, username="jeko002",password="jeko002"):
return UserLogin.objects.create(username=username, password=password, user=user)
def createCourse(code="CZ3002", name="Software Engineering"):
return Course.objects.create(course_code=code, course_name=name)
def createCourseIndex(course, index="12345", group="CS1"):
return CourseIndex.objects.create(course=course, index=index, group=group)
def createCourseIndexType(course_index, class_type="lab", day=3, time="10:30", duration=2):
time = datetime.datetime.strptime(time,"%H:%M").time()
duration = datetime.timedelta(hours=duration)
return CourseIndexType.objects.create(course_index=course_index, class_type=class_type, day=day, time=time, duration=duration)
def createClass(course_index_type, time="10:30"):
tdelta = (3 - datetime.datetime.today().weekday()) % 7
today_date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
time = datetime.datetime.strptime(time,"%H:%M").time()
dt = datetime.datetime.combine(today_date, time)
return Class.objects.create(course_index_type=course_index_type, datetime=dt)
def createClassTaker(course_index, student):
return ClassTaker.objects.create(course_index=course_index, student=student)
def createClassInstructor(course_index, staff):
return ClassInstructor.objects.create(course_index=course_index, staff=staff)
def createAttendance(class_session, student, status="present", attendance_time="10:40"):
if not attendance_time:
return Attendance.objects.create(class_session=class_session, student=student, status=status)
attendance_time = datetime.datetime.strptime(attendance_time,"%H:%M").time()
return Attendance.objects.create(class_session=class_session, student=student, status=status, attendance_time=attendance_time)
class FacialViewTests(TestCase):
def test_facial_tolerance_5_success_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-valid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':1,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "success")
self.assertEqual(json_data["info"], "lt5")
def test_facial_tolerance_5_multi_success_view(self):
student1 = createUser()
student2 = createUser(matric="U1620137D", name="Jeko Lonardo 2", domain="student", img="test.jpg")
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student1)
createUserLogin(user=student2, username="jeko003", password="jeko003")
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student1)
createClassTaker(course_index=course_index, student=student2)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student1)
createAttendance(class_session=class_session, student=student2)
with open("test-valid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':1,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "warning")
self.assertEqual(json_data["info"], "lt5")
self.assertEqual(json_data["message"], "Multiple students recognized")
def test_facial_tolerance_5_fail_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-invalid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':1,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["message"], "Authentication failed!")
def test_facial_tolerance_5_no_face_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-no-face.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':1,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["message"], "Authentication failed! No face detected")
def test_facial_tolerance_5_multi_faces_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-multi-faces.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':1,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["message"], "Authentication failed! Multiple faces detected")
def test_facial_tolerance_6_success_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-valid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':4,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "success")
self.assertEqual(json_data["info"], "lt6")
def test_facial_tolerance_6_multi_success_view(self):
student1 = createUser()
student2 = createUser(matric="U1620137D", name="Jeko Lonardo 2", domain="student", img="test.jpg")
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student1)
createUserLogin(user=student2, username="jeko003", password="jeko003")
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student1)
createClassTaker(course_index=course_index, student=student2)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student1)
createAttendance(class_session=class_session, student=student2)
with open("test-valid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':4,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "warning")
self.assertEqual(json_data["info"], "lt6")
self.assertEqual(json_data["message"], "Multiple students recognized")
def test_facial_tolerance_6_fail_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-invalid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':4,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["message"], "Authentication failed!")
def test_facial_tolerance_6_no_face_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-no-face.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':4,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["message"], "Authentication failed! No face detected")
def test_facial_tolerance_6_multi_faces_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-multi-faces.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':4,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["message"], "Authentication failed! Multiple faces detected")
def test_facial_invalid_count_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("test-valid.jpg", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':7,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["info"], "error-count")
def test_facial_invalid_image_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
encoded_string = ""
response = self.client.post("/facial/",json.dumps({'count':1,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["info"], "error-image")
def test_facial_sign_success_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("sign.png", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':6,'matric':'U1620136D','image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "success")
def test_facial_sign_invalid_image_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
encoded_string = ""
response = self.client.post("/facial/",json.dumps({'count':6,'matric':'U1620136D','image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["info"], "error-image")
def test_facial_sign_no_matric_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
with open("sign.png", "rb") as img_file:
encoded_string = base64.b64encode(img_file.read())
encoded_string = encoded_string.decode("utf-8")
encoded_string = "data:image/jpeg;base64,"+encoded_string
response = self.client.post("/facial/",json.dumps({'count':6,'image':encoded_string}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], "error")
self.assertEqual(json_data["info"], "error-matric")
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,244 | jekolonardo/evian | refs/heads/master | /evian/course/views.py | import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.utils.duration import _get_duration_components
from login.models import User, UserLogin
from .models import Course, CourseIndex, CourseIndexType, ClassTaker, ClassInstructor, Attendance, Class
import datetime
# Create your views here.
class AttendanceView(View):
def post(self, request):
body = json.loads(request.body)
username = body.get('username')
domain = body.get('domain')
course = body.get('course')
print(username,domain,course)
try:
user = UserLogin.objects.get(username=username)
user = user.user
except UserLogin.DoesNotExist:
user = None
state = False
data_list = []
if (user and domain == "student" and domain == user.domain):
state = True
class_taker_list = ClassTaker.objects.filter(student=user)
course_index_list = []
for c in class_taker_list:
course_index = c.course_index
if (course_index.course.course_name == course):
course_index_list.append(course_index)
course_index_type_list = []
for c in course_index_list:
course_index_type = CourseIndexType.objects.filter(course_index = c)
for ci in course_index_type:
course_index_type_list.append(ci)
class_list = []
for c in course_index_type_list:
class_session = Class.objects.filter(course_index_type = c)
for cs in class_session:
class_list.append(cs)
attendance_list = []
for c in class_list:
print (c,user)
attendance = Attendance.objects.get(class_session = c, student = user)
attendance_list.append(attendance)
attendance_list = sorted(attendance_list, key=lambda r:r.class_session.datetime, reverse=True)
for attendance in attendance_list:
status = attendance.status
time = attendance.attendance_time
if (time):
time = time.strftime("%H:%M")
else:
time = "__:__"
class_session = attendance.class_session
date = class_session.datetime.strftime("%d-%m-%y")
course_index_type = class_session.course_index_type
class_type = course_index_type.class_type
_, hours, minutes, _, _ = _get_duration_components(course_index_type.duration)
if (minutes == 0):
duration = f"{hours} hour(s)"
elif (hours == 0):
duration = f"{minutes} minute(s)"
else:
duration = f"{hours} hour(s) {minutes} minute(s)"
course_index = course_index_type.course_index.index
data_list.append({
'index':course_index,
'type':class_type,
'date':date,
'time':time,
'duration':duration,
'status':status
})
data = {'state':state,
'attendance':data_list
}
print (data)
return JsonResponse(data)
class CourseStatsView(View):
def post(self, request):
body = json.loads(request.body)
username = body.get('username')
domain = body.get('domain')
course = body.get('course')
print(username,domain,course)
try:
user = UserLogin.objects.get(username=username)
user = user.user
except UserLogin.DoesNotExist:
user = None
state = False
data_tut_list = []
data_lab_list = []
if (user and domain == "staff" and domain == user.domain):
state = True
class_instructor_list = ClassInstructor.objects.filter(staff=user)
course_index_list = []
for c in class_instructor_list:
course_index = c.course_index
if (course_index.course.course_name == course):
course_index_list.append(course_index)
course_index_type_list = []
for c in course_index_list:
course_index_type = CourseIndexType.objects.filter(course_index = c)
for ci in course_index_type:
course_index_type_list.append(ci)
class_list = []
for c in course_index_type_list:
class_session = Class.objects.filter(course_index_type = c)
for cs in class_session:
class_list.append(cs)
class_list = sorted(class_list, key=lambda r:r.datetime, reverse=True)
for c in class_list:
date = c.datetime.date().strftime("%d-%m-%y")
time = c.datetime.time().strftime("%H%M")
index = c.course_index_type.course_index.index
attendance_list = Attendance.objects.filter(class_session = c)
present = 0
for a in attendance_list:
if (a.status == "present"):
present += 1
total = len(attendance_list)
rate = f"{present}/{total}"
class_type = c.course_index_type.class_type
course_code = c.course_index_type.course_index.course.course_code
if class_type == "lab":
data_lab_list.append({
'course_code':course_code,
'index':index,
'rate':rate,
'date':date,
'time':time
})
elif class_type == "tutorial":
data_tut_list.append({
'course_code':course_code,
'index':index,
'rate':rate,
'date':date,
'time':time
})
data = {'state':state,
'tut':data_tut_list,
'lab':data_lab_list
}
print (data)
return JsonResponse(data)
class SessionAttendanceView(View):
def post(self, request):
body = json.loads(request.body)
index = body.get('index')
date_str = body.get('date')
print(index, date_str)
try:
course_index = CourseIndex.objects.get(index = index)
except CourseIndex.DoesNotExist:
course_index = None
state = False
data_list = []
if (course_index):
state = True
date = datetime.datetime.strptime(date_str, "%d-%m-%y")
day = date.weekday()
try:
course_index_type = CourseIndexType.objects.get(course_index = course_index, day = day)
class_session = Class.objects.get(course_index_type = course_index_type, datetime__date = date)
attendance_list = Attendance.objects.filter(class_session = class_session)
for a in attendance_list:
student = a.student
name = student.name
matric = student.matric_no
status = a.status
time = date_str
signature = a.signature
data_list.append({
'name':name,
'matric':matric,
'status':status,
'index':index,
'time':time,
'signature':signature
})
except (CourseIndexType.DoesNotExist, Class.DoesNotExist, Attendance.DoesNotExist) as e:
state = False
data = {'state':state,
'student':data_list
}
print (data)
return JsonResponse(data)
class OverwriteView(View):
def post(self, request):
body = json.loads(request.body)
matric_no = body.get('matric')
status = body.get('status')
index = body.get('index')
time = body.get('time')
print(matric_no, status, index, time)
course_name = ""
try:
course_index = CourseIndex.objects.get(index = index)
course_name = course_index.course.course_name
except CourseIndex.DoesNotExist:
course_index = None
state = False
if (status != "present" and status != "mc" and status != "absent"):
data = {'state':state, 'course':course_name}
print (data)
return JsonResponse(data)
if (course_index):
date = datetime.datetime.strptime(time, "%d-%m-%y").date()
try:
student = User.objects.get(matric_no = matric_no)
course_index_type = CourseIndexType.objects.filter(course_index = course_index)
class_session = None
for c in course_index_type:
try:
class_session = Class.objects.get(course_index_type = c, datetime__date = date)
break
except Class.DoesNotExist:
pass
try:
attendance = Attendance.objects.get(class_session = class_session, student = student)
attendance.status = status
attendance.save()
state = True
except Attendance.DoesNotExist:
pass
except User.DoesNotExist:
pass
data = {'state':state, 'course':course_name}
print (data)
return JsonResponse(data)
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,245 | jekolonardo/evian | refs/heads/master | /evian/facial/apps.py | from django.apps import AppConfig
class FacialConfig(AppConfig):
name = 'facial'
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,246 | jekolonardo/evian | refs/heads/master | /evian/evian/cron.py | from django_cron import CronJobBase, Schedule
from course.models import Course, CourseIndex, CourseIndexType, ClassTaker, Class, Attendance
from login.models import User
import datetime
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 1
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = "evian.my_cron_job"
def do(self):
# print("test")
tdelta = (3 - datetime.datetime.today().weekday()) % 7
today_date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
# today_date = datetime.datetime.now().date()
day = today_date.weekday()
course_index_type_list = CourseIndexType.objects.filter(day = day)
for c in course_index_type_list:
date_time = datetime.datetime.combine(today_date, c.time)
try:
class_session = Class.objects.get(course_index_type = c, datetime = date_time)
except Class.DoesNotExist:
class_session = Class(course_index_type = c, datetime = date_time)
class_session.save()
class_taker_list = ClassTaker.objects.filter(course_index = c.course_index)
for ct in class_taker_list:
attendance = Attendance(class_session = class_session, student = ct.student, status="absent")
attendance.save()
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,247 | jekolonardo/evian | refs/heads/master | /evian/course/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2019-10-07 15:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Course',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course_code', models.CharField(max_length=10)),
('course_name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='CourseIndex',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('index', models.CharField(max_length=10)),
('group', models.CharField(max_length=10)),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course')),
],
),
migrations.CreateModel(
name='CourseIndexType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('class_type', models.CharField(choices=[('lecture', 'Lecture'), ('tutorial', 'Tutorial'), ('lab', 'Lab')], max_length=10)),
('day', models.IntegerField(choices=[(0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday')])),
('time', models.TimeField(verbose_name='class time')),
('duration', models.DurationField()),
('index', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.CourseIndex')),
],
),
migrations.CreateModel(
name='ClassTaker',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('matric_no', models.CharField(max_length=20)),
('index', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.CourseIndex')),
],
),
migrations.CreateModel(
name='ClassInstructor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('matric_no', models.CharField(max_length=20)),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course')),
],
),
migrations.CreateModel(
name='Class',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('datetime', models.DateTimeField(verbose_name='class datetime')),
('index_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.CourseIndexType')),
],
),
migrations.CreateModel(
name='Attendance',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('matric_no', models.CharField(max_length=20)),
('status', models.CharField(choices=[('present', 'Present'), ('absent', 'Absent'), ('mc', 'MC')], max_length=10)),
('attendance_time', models.TimeField(verbose_name='attendance_time')),
('class_session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Class')),
],
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,248 | jekolonardo/evian | refs/heads/master | /evian/facial/views.py | import json
import base64
import datetime
from io import BytesIO
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from login.models import User
from course.models import Course, CourseIndex, CourseIndexType, Class, Attendance
from django.conf import settings
from face_recognition import api
import numpy as np
# Create your views here.
class FacialView(View):
def updateAttendance(self, matric, sign=""):
student = User.objects.get(matric_no = matric)
course = Course.objects.get(course_code = "CZ3002")
course_index = CourseIndex.objects.get(index = "12345")
course_index_type = CourseIndexType.objects.get(course_index = course_index, class_type="lab")
today = datetime.datetime.now()
tdelta = (3 - datetime.datetime.today().weekday()) % 7
today_date = today.date() + datetime.timedelta(days=tdelta)
# today_date = today.date()
time = course_index_type.time
today_time = today.time()
class_session = Class.objects.get(course_index_type = course_index_type, datetime__date = today_date)
attendance = Attendance.objects.get(class_session = class_session, student = student)
print(attendance)
attendance.status = "present"
attendance.attendance_time = today_time
attendance.signature = sign
attendance.save()
def getAttendanceData(self):
# student = User.objects.get(matric_no = "U1620133D")
course = Course.objects.get(course_code = "CZ3002")
course_index = CourseIndex.objects.get(index = "12345")
course_index_type = CourseIndexType.objects.get(course_index = course_index, class_type="lab")
today = datetime.datetime.now()
tdelta = (3 - datetime.datetime.today().weekday()) % 7
today_date = today.date() + datetime.timedelta(days=tdelta)
# today_date = today.date()
time = course_index_type.time
today_time = today.time()
class_session = Class.objects.get(course_index_type = course_index_type, datetime__date = today_date)
attendance = Attendance.objects.filter(class_session = class_session)
student_list = []
for a in attendance:
student_list.append(a.student)
pic_list = []
for s in student_list:
pic_list.append(s.face_image)
p_encs = []
for p in pic_list:
p_dir = settings.MEDIA_ROOT+"/"+str(p)
p_image = api.load_image_file(p_dir)
p_enc = api.face_encodings(p_image)[0]
p_encs.append(p_enc)
return student_list, pic_list, p_encs
def post(self, request):
body = json.loads(request.body)
count = body.get('count')
print (count)
# print(image)
# print(type(image))
if count == 1 or count == 2 or count == 3:
image = body.get('image')
# print(image)
try:
image = image[23:]
except:
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
print (type(image))
# print(image)
# Get Image and store in unknown.jpg
try:
imgdata = BytesIO(base64.b64decode(image))
except:
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
print(type(imgdata))
# filename = 'unknown.jpg' # I assume you have a way of picking unique filenames
# with open(filename, 'wb') as f:
# f.write(base64.b64decode(image))
# Get list of students, and list of face encodings
student_list, pic_list, p_encs = self.getAttendanceData()
# print (p_encs)
# Get encoding of captured image
try:
unknown = api.load_image_file(imgdata)
except:
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
unknown_enc = api.face_encodings(unknown)
if (len(unknown_enc) == 1):
unknown_enc = unknown_enc[0]
face_distance = api.face_distance(p_encs, unknown_enc)
face_distance = face_distance.tolist()
print(face_distance)
elif (len(unknown_enc) > 1):
data = {'state': 'error',
'message': 'Authentication failed! Multiple faces detected', 'mode': 'img'}
return JsonResponse(data)
else:
data = {'state': 'error',
'message': 'Authentication failed! No face detected', 'mode': 'img'}
return JsonResponse(data)
# Face recognition with tolerance of 0.5
lt5 = {}
cnt_lt5 = 0
for f in face_distance:
if f <= 0.5: # Edit value here
lt5[student_list[face_distance.index(f)].matric_no] = 1
cnt_lt5 += 1
else:
lt5[student_list[face_distance.index(f)].matric_no] = 0
print(lt5)
print(cnt_lt5)
if (cnt_lt5 == 1):
matric_no = list(lt5.keys())[list(lt5.values()).index(1)]
message = matric_no + " Authentication success!"
data = {'state': 'success', 'info': 'lt5',
'message': message, 'mode': 'img'}
self.updateAttendance(matric_no)
return JsonResponse(data)
elif (cnt_lt5 > 1):
s = []
for matric, state in lt5.items():
if state == 1:
s.append(matric)
data = {'state': 'warning', 'info': 'lt5',
'message': 'Multiple students recognized', 'mode': 'img', 'students':s}
return JsonResponse(data)
else:
data = {'state': 'error',
'message': 'Authentication failed!', 'mode': 'img'}
return JsonResponse(data)
# print(attendance)
# attendance.status = "present"
# attendance.attendance_time = today_time
# attendance.save()
elif count == 4:
image = body.get('image')
# print (image)
try:
image = image[23:]
except:
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
print (type(image))
# Get Image and store in unknown.jpg
try:
imgdata = BytesIO(base64.b64decode(image))
except:
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
print(type(imgdata))
# filename = 'unknown.jpg' # I assume you have a way of picking unique filenames
# with open(filename, 'wb') as f:
# f.write(imgdata)
# Get list of students, and list of face encodings
student_list, pic_list, p_encs = self.getAttendanceData()
# print (p_encs)
# Get encoding of captured image
try:
unknown = api.load_image_file(imgdata)
except:
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
unknown_enc = api.face_encodings(unknown)
if (len(unknown_enc) == 1):
unknown_enc = unknown_enc[0]
face_distance = api.face_distance(p_encs, unknown_enc)
face_distance = face_distance.tolist()
print(face_distance)
elif (len(unknown_enc) > 1):
data = {'state': 'error',
'message': 'Authentication failed! Multiple faces detected', 'mode': 'img'}
return JsonResponse(data)
else:
data = {'state': 'error',
'message': 'Authentication failed! No face detected', 'mode': 'img'}
return JsonResponse(data)
# Face recognition with tolerance of 0.6
lt6 = {}
cnt_lt6 = 0
for f in face_distance:
if f <= 0.6:
lt6[student_list[face_distance.index(f)].matric_no] = 1
cnt_lt6 += 1
else:
lt6[student_list[face_distance.index(f)].matric_no] = 0
print(lt6)
print(cnt_lt6)
if (cnt_lt6 == 1):
matric_no = list(lt6.keys())[list(lt6.values()).index(1)]
message = matric_no + " detected. Please sign"
data = {'state': 'success', 'info': 'lt6',
'message': message, 'mode': 'sign', 'matric':matric_no}
return JsonResponse(data)
elif (cnt_lt6 > 1):
s = []
for matric, state in lt6.items():
if state == 1:
s.append(matric)
data = {'state': 'warning', 'info': 'lt6',
'message': 'Multiple students recognized', 'mode': 'img', 'students':s}
return JsonResponse(data)
else:
data = {'state': 'error',
'message': 'Authentication failed!', 'mode': 'img'}
return JsonResponse(data)
elif count == 5:
matric = body.get('matric')
if (not matric):
data = {'state': 'error', 'info':'error-matric',
'message': 'Matric not provided!', 'mode': 'img'}
return JsonResponse(data)
message = matric + " detected. Please sign"
print(matric)
data = {'state': 'info',
'message': message, 'mode': 'sign', 'matric':matric}
elif count == 6:
matric = body.get('matric')
if (not matric):
data = {'state': 'error', 'info':'error-matric',
'message': 'Matric not provided!', 'mode': 'img'}
return JsonResponse(data)
message = matric + " Authentication success!"
print(matric)
data = {'state': 'success',
'message': message, 'mode': 'img'}
image = body.get('image')
image = image[22:]
if (not image):
data = {'state': 'error', 'info':'error-image',
'message': 'Image Upload Error! Please try again.', 'mode': 'img'}
return JsonResponse(data)
# imgdata = base64.b64decode(image)
print (type(image))
self.updateAttendance(matric, image)
else:
data = {'state': 'error', 'info': 'error-count',
'message': "Invalid State", 'mode': 'img'}
return JsonResponse(data)
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,249 | jekolonardo/evian | refs/heads/master | /evian/login/migrations/0002_auto_20191007_1549.py | # Generated by Django 2.2.1 on 2019-10-07 07:49
from django.db import migrations, models
import functools
import login.models
class Migration(migrations.Migration):
dependencies = [
('login', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='face_image',
field=models.ImageField(upload_to=functools.partial(login.models._update_filename, *(), **{'path': 'face_images/'})),
),
migrations.AlterField(
model_name='user',
name='sign_image',
field=models.ImageField(upload_to=functools.partial(login.models._update_filename, *(), **{'path': 'sign_images/'})),
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,250 | jekolonardo/evian | refs/heads/master | /evian/login/migrations/0005_auto_20191008_1206.py | # Generated by Django 2.2.1 on 2019-10-08 04:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('login', '0004_userlogin'),
]
operations = [
migrations.RenameField(
model_name='userlogin',
old_name='matric_no',
new_name='user',
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,251 | jekolonardo/evian | refs/heads/master | /evian/login/views.py | import json
import base64
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.conf import settings
from .models import User, UserLogin
from course.models import Course, CourseIndex, ClassTaker, ClassInstructor
# Create your views here.
class LoginView(View):
def post(self, request):
body = json.loads(request.body)
username = body.get('username')
password = body.get('password')
print(username,password)
try:
user = UserLogin.objects.get(username=username, password=password)
except UserLogin.DoesNotExist:
user = None
domain = None
state = False
encoded_string = ""
course_list = []
if (user):
state = True
user = user.user
face_dir = settings.MEDIA_ROOT+"\\"+str(user.face_image)
with open(face_dir, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
encoded_string = encoded_string.decode("utf-8")
domain = user.domain
matric_no = user.matric_no
if (domain == "student"):
classes = ClassTaker.objects.filter(student=user)
elif (domain == "staff"):
classes = ClassInstructor.objects.filter(staff=user)
for c in classes:
course_index = c.course_index
course = course_index.course
course_code = course.course_code
course_name = course.course_name
group = course_index.group
course_list.append({
'code':course_code,
'name':course_name,
'group':group
})
data = {'state':state,
'domain':domain,
'image':encoded_string,
'course':course_list}
print (data)
return JsonResponse(data)
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,252 | jekolonardo/evian | refs/heads/master | /evian/login/migrations/0004_userlogin.py | # Generated by Django 2.2.1 on 2019-10-07 08:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('login', '0003_auto_20191007_1645'),
]
operations = [
migrations.CreateModel(
name='UserLogin',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=20)),
('password', models.CharField(max_length=100)),
('matric_no', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='login.User')),
],
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,253 | jekolonardo/evian | refs/heads/master | /evian/course/migrations/0003_auto_20191008_1206.py | # Generated by Django 2.2.1 on 2019-10-08 04:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('login', '0005_auto_20191008_1206'),
('course', '0002_auto_20191008_1121'),
]
operations = [
migrations.CreateModel(
name='CourseInstructor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course')),
('staff', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='login.User')),
],
),
migrations.AlterModelOptions(
name='courseindex',
options={'verbose_name_plural': 'Course Indexes'},
),
migrations.RenameField(
model_name='class',
old_name='index_type',
new_name='course_index_type',
),
migrations.RenameField(
model_name='classtaker',
old_name='index',
new_name='course_index',
),
migrations.RenameField(
model_name='courseindextype',
old_name='index',
new_name='course_index',
),
migrations.RemoveField(
model_name='attendance',
name='matric_no',
),
migrations.AddField(
model_name='attendance',
name='student',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='login.User'),
),
migrations.AlterField(
model_name='classtaker',
name='student',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='login.User'),
),
migrations.DeleteModel(
name='ClassInstructor',
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,254 | jekolonardo/evian | refs/heads/master | /evian/course/tests.py | from django.test import TestCase
from login.models import User, UserLogin
from .models import Course, CourseIndex, CourseIndexType, ClassTaker, ClassInstructor, Attendance, Class
import json
import datetime
# Create your tests here.
def createUser(matric="U1620136D", name="Jeko Lonardo", domain="student", img="test.jpg"):
return User.objects.create(matric_no=matric, name=name, domain=domain, face_image=img)
def createUserLogin(user, username="jeko002",password="jeko002"):
return UserLogin.objects.create(username=username, password=password, user=user)
def createCourse(code="CZ2006", name="Software Engineering"):
return Course.objects.create(course_code=code, course_name=name)
def createCourseIndex(course, index="54321", group="CS1"):
return CourseIndex.objects.create(course=course, index=index, group=group)
def createCourseIndexType(course_index, class_type="lab", day=3, time="10:30", duration=2):
time = datetime.datetime.strptime(time,"%H:%M").time()
duration = datetime.timedelta(hours=duration)
return CourseIndexType.objects.create(course_index=course_index, class_type=class_type, day=day, time=time, duration=duration)
def createClass(course_index_type, time="10:30"):
tdelta = (3 - datetime.datetime.today().weekday()) % 7
today_date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
time = datetime.datetime.strptime(time,"%H:%M").time()
dt = datetime.datetime.combine(today_date, time)
return Class.objects.create(course_index_type=course_index_type, datetime=dt)
def createClassTaker(course_index, student):
return ClassTaker.objects.create(course_index=course_index, student=student)
def createClassInstructor(course_index, staff):
return ClassInstructor.objects.create(course_index=course_index, staff=staff)
def createAttendance(class_session, student, status="present", attendance_time="10:40"):
if not attendance_time:
return Attendance.objects.create(class_session=class_session, student=student, status=status)
attendance_time = datetime.datetime.strptime(attendance_time,"%H:%M").time()
return Attendance.objects.create(class_session=class_session, student=student, status=status, attendance_time=attendance_time)
class AttendanceViewTests(TestCase):
def test_attendance_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/attendance/",json.dumps({'username':'jeko002','domain':'student','course':'Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
self.assertEqual(len(json_data["attendance"]), 1)
def test_attendance_wrong_username_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/attendance/",json.dumps({'username':'jeko003','domain':'student','course':'Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_attendance_wrong_domain_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/attendance/",json.dumps({'username':'jeko002','domain':'staff','course':'Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_attendance_no_course_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/attendance/",json.dumps({'username':'jeko002','domain':'student','course':'Advanced Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
self.assertEqual(len(json_data["attendance"]), 0)
class CourseStatsViewTests(TestCase):
def test_course_stats_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/course-stats/",json.dumps({'username':'chris002','domain':'staff','course':'Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
self.assertEqual(len(json_data["lab"]), 1)
def test_course_stats_wrong_username_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/course-stats/",json.dumps({'username':'chris003','domain':'staff','course':'Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_course_stats_wrong_domain_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/course-stats/",json.dumps({'username':'chris002','domain':'student','course':'Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_course_stats_no_course_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
response = self.client.post("/course-stats/",json.dumps({'username':'chris002','domain':'staff','course':'Advanced Software Engineering'}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
self.assertEqual(len(json_data["lab"]), 0)
self.assertEqual(len(json_data["tut"]), 0)
class SessionAttendanceViewTests(TestCase):
def test_session_attendance_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
tdelta = (3 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/session-attendance/",json.dumps({'index':'54321', 'date':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
def test_session_attendance_wrong_index_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
tdelta = (3 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/session-attendance/",json.dumps({'index':'54322', 'date':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_session_attendance_wrong_date_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student)
tdelta = (2 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/session-attendance/",json.dumps({'index':'54321', 'date':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
class OverwriteViewTests(TestCase):
def test_overwrite_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student, status="absent", attendance_time="")
tdelta = (3 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/overwrite/",json.dumps({'matric':'U1620136D', 'status':'mc', 'index' : '54321', 'time':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], True)
def test_overwrite_wrong_matric_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student, status="absent", attendance_time="")
tdelta = (3 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/overwrite/",json.dumps({'matric':'U1620137D', 'status':'mc', 'index' : '54321', 'time':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_overwrite_wrong_status_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student, status="absent", attendance_time="")
tdelta = (3 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/overwrite/",json.dumps({'matric':'U1620136D', 'status':'late', 'index' : '54321', 'time':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_overwrite_wrong_index_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student, status="absent", attendance_time="")
tdelta = (3 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/overwrite/",json.dumps({'matric':'U1620136D', 'status':'mc', 'index' : '54322', 'time':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
def test_overwrite_wrong_time_view(self):
student = createUser()
staff = createUser(matric="S1620136D", name="Chris", domain="staff", img="test.jpg")
createUserLogin(user=student)
createUserLogin(user=staff, username="chris002", password="chris002")
course = createCourse()
course_index = createCourseIndex(course=course)
course_index_type = createCourseIndexType(course_index=course_index)
class_session = createClass(course_index_type=course_index_type)
createClassTaker(course_index=course_index, student=student)
createClassInstructor(course_index=course_index, staff=staff)
createAttendance(class_session=class_session, student=student, status="absent", attendance_time="")
tdelta = (2 - datetime.datetime.today().weekday()) % 7
date = datetime.datetime.now().date() + datetime.timedelta(days=tdelta)
date = datetime.datetime.strftime(date, "%d-%m-%y")
response = self.client.post("/overwrite/",json.dumps({'matric':'U1620136D', 'status':'mc', 'index' : '54321', 'time':date}),'json')
self.assertEqual(response.status_code, 200)
json_data = json.loads(response.content)
self.assertEqual(json_data["state"], False)
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,255 | jekolonardo/evian | refs/heads/master | /evian/course/migrations/0004_auto_20191009_1046.py | # Generated by Django 2.2.1 on 2019-10-09 02:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('login', '0005_auto_20191008_1206'),
('course', '0003_auto_20191008_1206'),
]
operations = [
migrations.CreateModel(
name='ClassInstructor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course_index', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.CourseIndex')),
('staff', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='login.User')),
],
),
migrations.DeleteModel(
name='CourseInstructor',
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,256 | jekolonardo/evian | refs/heads/master | /evian/course/migrations/0005_auto_20191009_1229.py | # Generated by Django 2.2.1 on 2019-10-09 12:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course', '0004_auto_20191009_1046'),
]
operations = [
migrations.AlterModelOptions(
name='class',
options={'verbose_name_plural': 'Classes'},
),
migrations.AlterField(
model_name='attendance',
name='attendance_time',
field=models.TimeField(blank=True, null=True, verbose_name='attendance time'),
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,257 | jekolonardo/evian | refs/heads/master | /evian/login/migrations/0003_auto_20191007_1645.py | # Generated by Django 2.2.1 on 2019-10-07 08:45
from django.db import migrations, models
import functools
import login.models
class Migration(migrations.Migration):
dependencies = [
('login', '0002_auto_20191007_1549'),
]
operations = [
migrations.AlterField(
model_name='user',
name='sign_image',
field=models.ImageField(blank=True, upload_to=functools.partial(login.models._update_filename, *(), **{'path': 'sign_images/'})),
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,258 | jekolonardo/evian | refs/heads/master | /evian/login/admin.py | from django.contrib import admin
from .models import User, UserLogin
# Register your models here.
admin.site.register(User)
admin.site.register(UserLogin) | {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,259 | jekolonardo/evian | refs/heads/master | /evian/course/migrations/0002_auto_20191008_1121.py | # Generated by Django 2.2.1 on 2019-10-08 03:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('login', '0004_userlogin'),
('course', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='classtaker',
name='matric_no',
),
migrations.AddField(
model_name='classtaker',
name='student',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='login.User'),
),
]
| {"/evian/course/admin.py": ["/evian/course/models.py"], "/evian/login/tests.py": ["/evian/login/models.py"], "/evian/course/views.py": ["/evian/course/models.py"], "/evian/login/views.py": ["/evian/login/models.py"], "/evian/course/tests.py": ["/evian/course/models.py"], "/evian/login/admin.py": ["/evian/login/models.py"]} |
72,316 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/post_revision.py | '''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/post-revisions/
'''
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,317 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/category.py |
'''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/posts/
'''
import json
import logging
import requests
from .wordpress_entity import WPEntity, WPRequest, context_values
#from .post import PostRequest
from ..import exc
from ..cache import WPORMCacheObjectNotFoundError
logger = logging.getLogger(__name__.split(".")[0]) # package name
order_values = ["asc", "desc"]
orderby_values = ["id", "include", "name", "slug", "term_group", "description", "count"]
class Category(WPEntity):
def __init__(self, id=None, session=None, api=None):
super().__init__(api=api)
# cache related objects
self._posts = None
def __repr__(self):
return "<WP {0} object at {1} name='{2}'>".format(self.__class__.__name__, hex(id(self)), self.s.name)
@property
def schema_fields(self):
if self._schema_fields is None:
# These are the default WordPress fields for the "category" object.
self._schema_fields = ["id", "count", "description", "link", "name", "slug", "taxonomy", "parent", "meta"]
return self._schema_fields
@property
def post_fields(self):
'''
Arguments for Category POST requests.
'''
if self._post_fields is None:
self._post_fields = ["description", "name", "slug", "parent", "meta"]
return self._post_fields
def posts(self):
'''
Return a list of posts (type: Post) that have this category.
'''
# maybe not cache this...?
if self._posts is None:
pr = self.api.PostRequest()
pr.categories.append(self)
self._posts = pr.get()
return self._posts
class CategoryRequest(WPRequest):
'''
A class that encapsulates requests for WordPress categories.
'''
def __init__(self, api=None):
super().__init__(api=api)
self.id = None # WordPress ID
self.url = self.api.base_url + "categories"
# parameters that undergo validation, i.e. need custom setter
#
self._hide_empty = None
self._per_page = None
@property
def parameter_names(self):
if self._parameter_names is None:
self._parameter_names = ["context", "page", "per_page", "search", "exclude", "include",
"order", "orderby", "hide_empty", "parent", "post", "slug"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
for param in self.parameter_names:
if getattr(self, param, None):
self.parameters[param] = getattr(self, param)
def get(self, class_object=Category, count=False, embed=True, links=True):
'''
Returns a list of 'Category' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
#if self.id:
# self.url += "/{}".format(self.id)
self.populate_request_parameters()
try:
self.get_response(wpid=self.id)
logger.debug("URL='{}'".format(self.request.url))
except requests.exceptions.HTTPError:
logger.debug("Post response code: {}".format(self.response.status_code))
if self.response.status_code == 400: # bad request
logger.debug("URL={}".format(self.response.url))
raise exc.BadRequest("400: Bad request. Error: \n{0}".format(json.dumps(self.response.json(), indent=4)))
elif self.response.status_code == 404: # not found
return None
elif self.response.status_code == 500: #
raise Exception("500: Internal Server Error. Error: \n{0}".format(self.response.json()))
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
#return len(pages_data)
categories_data = self.response.json()
if isinstance(categories_data, dict):
# only one object was returned, make it a list
categories_data = [categories_data]
categories = list()
for d in categories_data:
# Before we continue, do we have this Category in the cache already?
try:
logger.debug(d)
category = self.api.wordpress_object_cache.get(class_object.__name__, key=d["id"]) # default = Category()
except WPORMCacheObjectNotFoundError:
category = class_object.__new__(class_object) # default = Category()
category.__init__(api=self.api)
category.json = json.dumps(d)
category.update_schema_from_dictionary(d)
if "_embedded" in d:
logger.debug("TODO: implement _embedded content for Category object")
# perform postprocessing for custom fields
category.postprocess_response()
# add to cache
self.api.wordpress_object_cache.set(value=category, keys=(category.s.id, category.s.slug))
finally:
categories.append(category)
return categories
@property
def context(self):
if self._context is None:
self._context = None
return self._context
@context.setter
def context(self, value):
if value is None:
self._context = None
return
else:
try:
value = value.lower()
if value in ["view", "embed", "edit"]:
self._context = value
return
except:
pass
raise ValueError ("'context' may only be one of ['view', 'embed', 'edit']")
@property
def order(self):
return self._order;
#return self.api_params.get('order', None)
@order.setter
def order(self, value):
if value is None:
self._order = None
else:
if isinstance(value, str):
value = value.lower()
if value not in order_values:
raise ValueError('The "order" parameter must be one '+\
'of these values: {}'.format(order_values))
else:
#self.api_params['order'] = value
self._order = value
else:
raise ValueError('The "order" parameter must be one of '+\
'these values: {} (or None).'.format(order_values))
return self._order
@property
def orderby(self):
return self.api_params.get('orderby', None)
@orderby.setter
def orderby(self, value):
if value is None:
self._orderby = None
else:
if isinstance(value, str):
value = value.lower()
if value not in orderby_values:
raise ValueError('The "orderby" parameter must be one '+\
'of these values: {}'.format(orderby_values))
else:
#self.api_params['orderby'] = value
self._orderby = value
else:
raise ValueError('The "orderby" parameter must be one of these '+\
'values: {} (or None).'.format(orderby_values))
return self._orderby
@property
def hide_empty(self):
return self._hide_empty
@hide_empty.setter
def hide_empty(self, value):
if isinstance(value, bool) or value is None:
self._hide_empty = value
else:
raise ValueError("The property 'hide_empty' must be a Boolean value "+\
"('{0}' provided).".format(type(value)))
@property
def per_page(self):
return self._per_page
@per_page.setter
def per_page(self, value):
if value is None:
if "per_page" in self.parameters:
del self.parameters["per_page"]
elif isinstance(value, str):
try:
value = int(value)
except ValueError:
raise ValueError("The 'per_page' parameter should be a number.")
elif isinstance(value, int):
if value < 0:
raise ValueError("The 'per_page' parameter should greater than zero.")
else:
self._per_page = value
else:
raise ValueError("The 'per_page' parameter should be a number.")
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,318 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/post_status.py | '''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/post-statuses/
'''
import json
import logging
import requests
from .wordpress_entity import WPEntity, WPRequest
from .. import exc
logger = logging.getLogger(__name__.split(".")[0]) # package name
class PostStatus(WPEntity):
def __init__(self, id=None, session=None, api=None):
super().__init__(api=api)
def __repr__(self):
if len(self.s.name) < 11:
truncated_name = self.s.name
else:
truncated_name = self.s.name[0:10] + "..."
return "<WP {0} object at {1}, id={2}, title='{3}'>".format(self.__class__.__name__,
hex(id(self)), self.s.id, truncated_name)
@property
def schema_fields(self):
if self._schema_fields is None:
self._schema_fields = ["name", "private", "protected", "public", "queryable", "show_in_list", "slug"]
return self._schema_fields
@property
def post_fields(self):
raise Exception("There is no WordPress API to create 'PostStatus' objects.")
class PostStatusRequest(WPRequest):
'''
A class that encapsulates requests for WordPress post statuses.
'''
def __init__(self, api=None, categories=None, slugs=None):
super().__init__(api=api)
self.id = None # WordPress ID
self.url = self.api.base_url + "statuses"
# values read from the response header
self.total = None
self.total_pages = None
# parameters that undergo validation, i.e. need custom setter
pass
@property
def parameter_names(self):
'''
PostStatus request parameters.
'''
if self._parameter_names is None:
self._parameter_names = ["context"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
def get(self, class_object=PostStatus, count=False, embed=True, links=True):
'''
Returns a list of 'PostStatus' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
populate_request_parameters() # populates 'self.parameters'
try:
self.get_response()
logger.debug("URL='{}'".format(self.request.url))
except requests.exceptions.HTTPError:
logger.debug("PostStatus response code: {}".format(self.response.status_code))
if self.response.status_code == 400: # bad request
logger.debug("URL={}".format(self.response.url))
raise exc.BadRequest("400: Bad request. Error: \n{0}".format(json.dumps(self.response.json(), indent=4)))
elif self.response.status_code == 404: # not found
return None
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
# return len(posts_data)
if isinstance(poststatus_data, dict):
# only one object was returned; make it a list
poststatus_data = [poststatus_data]
post_statuses = list()
for d in poststatus_data:
# TODO: check cache? This is not an object that has an ID
post_status = class_object.__new__(class_object) # default = PostStatus()
post_status.__init__(api=self.api)
post_status.json = json.dumps(d)
# perform postprocessing for custom fields
post_status.postprocess_response()
raise NotImplementedError("Not yet finished.")
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,319 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/page.py |
'''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/pages/
'''
import json
import logging
import requests
from datetime import datetime
from .wordpress_entity import WPEntity, WPRequest, context_values
from .user import User
from .. import exc
from ..cache import WPORMCacheObjectNotFoundError
logger = logging.getLogger(__name__.split(".")[0]) # package name
order_values = ["asc", "desc"]
orderby_values = ["author", "date", "id", "include", "modified", "parent",
"relevance", "slug", "title", "menu_order"]
class Page(WPEntity):
def __init__(self, id=None, session=None, api=None):
super().__init__(api=api)
# related objects to cache
self._author = None
self._featured_media = None
def __repr__(self):
if len(self.s.title) < 11:
truncated_title = self.s.title
else:
truncated_title = self.s.title[0:10] + "..."
return "<WP {0} object at {1}, id={2}, title='{3}'>".format(self.__class__.__name__,
hex(id(self)), self.s.id, truncated_title)
@property
def schema_fields(self):
if self._schema_fields is None:
self._schema_fields = ["date", "date_gmt", "guid", "id", "link", "modified", "modified_gmt",
"slug", "status", "type", "password", "parent", "title", "content", "author",
"excerpt", "featured_media", "comment_status", "ping_status", "menu_order",
"meta", "template"]
return self._schema_fields
@property
def post_fields(self):
'''
Arguments for POST requests.
'''
if self._post_fields is None:
# Note that 'date' is excluded from the specification in favor of exclusive use of 'date_gmt'.
self._post_fields = ["date_gmt", "slug", "status", "password", "parent", "title", "content",
"author", "excerpt", "featured_media", "comment_status", "ping_status",
"menu_order", "meta", "template"]
return self._post_fields
@property
def featured_media(self):
'''
Returns the 'Media' object that is the "featured media" for this page.
'''
if self._featured_media is None:
found_media = self.api.media(id=self.s.featured_media)
self._featured_media = found_media
# mr = self.api.MediaRequest()
# mr.id = self.s.featured_media
# media_list = mr.get()
# if len(media_list) == 1:
# self._featured_media = media_list[0]
# else:
# self._featured_media = None
return self._featured_media
@property
def author(self):
'''
Returns the author of this page, class: 'User'.
'''
if self._author is None:
ur = self.api.UserRequest()
ur.id = self.s.author # ID for the author of the object
user_list = ur.get()
if len(user_list) == 1:
self._author = user_list[0]
else:
raise exc.UserNotFound("User ID '{0}' not found.".format(self.author))
return self._author
class PageRequest(WPRequest):
'''
A class that encapsulates requests for WordPress pages.
'''
def __init__(self, api=None, categories=None, slugs=None):
super().__init__(api=api)
self.id = None # WordPress ID
self.url = self.api.base_url + "pages"
# values read from the response header
self.total = None
self.total_pages = None
# parameters that undergo validation, i.e. need custom setter
#self._author = None
self._after = None
self._before = None
self._order = None
self._orderby = None
self._page = None
self._per_page = None
self._status = list()
self._author_ids = list()
self._parent_ids = list()
self._parent_exclude_ids = list()
self._slugs = list()
if slugs:
self.slugs = slugs
@property
def parameter_names(self):
'''
Page request parameters.
'''
if self._parameter_names is None:
self._parameter_names = ["context", "page", "per_page", "search", "after", "author",
"author_exclude", "before", "exclude", "include", "menu_order", "offset",
"order", "orderby", "parent", "parent_exclude", "slug", "status"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
if self.page:
self.parameters["page"] = self.page
if self.per_page:
self.parameters["per_page"] = self.per_page
if self.search:
self.parameters["search"] = self.search
if self.after:
self.parameters["after"] = self._after.isoformat()
if len(self.author) > 0:
# takes a list of author IDs
self.parameters["author"] = ",".join(self.author)
if len(self.status) > 0:
self.parameters["status"] = ",".join(self.status)
if self.slug:
self.parameters["slug"] = self.slug
if len(self.parent) > 0:
self.parameters["parent"] = ",".join(self.parent)
if len(self.parent_exclude) > 0:
self.parameters["parent_exclude"] = ",".join(self.parent_exclude)
if self.order:
self.parameters["order"] = self.order
if self.menu_order:
self.parameters["menu_order"] = self.menu_order
def get(self, class_object=Page, count=False, embed=True, links=True):
'''
Returns a list of 'Page' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
#if self.id:
# self.url += "/{}".format(self.id)
self.populate_request_parameters() # populates 'self.parameters'
try:
self.get_response(wpid=self.id)
logger.debug("URL='{}'".format(self.request.url))
except requests.exceptions.HTTPError:
logger.debug("page response code: {}".format(self.response.status_code))
if self.response.status_code == 400: # bad request
logger.debug("URL={}".format(self.response.url))
raise exc.BadRequest("400: Bad request. Error: \n{0}".format(json.dumps(self.response.json(), indent=4)))
elif self.response.status_code == 404: # not found
return None
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
#return len(pages_data)
pages_data = self.response.json()
if isinstance(pages_data, dict):
# only one object was returned; make it a list
pages_data = [pages_data]
pages = list()
for d in pages_data:
# Before we continue, do we have this page in the cache already?
try:
page = self.api.wordpress_object_cache.get(class_name=class_object.__name__, key=d["id"])
except WPORMCacheObjectNotFoundError:
# create new object
page = class_object.__new__(class_object) # default = Page()
page.__init__(api=self.api)
page.json = json.dumps(d)
page.update_schema_from_dictionary(d)
if "_embedded" in d:
logger.debug("TODO: implement _embedded content for Page object")
# perform postprocessing for custom fields
page.postprocess_response()
# add to cache
self.api.wordpress_object_cache.set(value=page, keys=(page.s.id, page.s.slug))
finally:
pages.append(page)
return pages
@property
def context(self):
if self._context is None:
self._context = None
return self._context
@context.setter
def context(self, value):
if value is None:
self.parameters.pop("context", None)
self._context = None
return
else:
try:
value = value.lower()
if value in ["view", "embed", "edit"]:
self._context = value
return
except:
pass
raise ValueError ("'context' may only be one of ['view', 'embed', 'edit']")
@property
def page(self):
'''
Current page of the collection.
'''
return self._page
@page.setter
def page(self, value):
#
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._page = value
elif isinstance(value, str):
try:
self._page = int(value)
except ValueError:
raise ValueError("The 'Page' parameter must be an integer, was given '{0}'".format(value))
@property
def per_page(self):
'''
Maximum number of items to be returned in result set.
'''
return self._per_page
@per_page.setter
def per_page(self, value):
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._per_page = value
elif isinstance(value, str):
try:
self._per_page = int(value)
except ValueError:
raise ValueError("The 'per_page' parameter must be an integer, was given '{0}'".format(value))
@property
def author(self):
#return self._author
#return self.parameters.get("author", None)
return self._author_ids
@author.setter
def author(self, value):
'''
Set author parameter for this request; stores WordPress user ID.
'''
author_id = None
if value is None:
self.parameters.pop("author", None) # remove key
return
#self.g = None
elif isinstance(value, User):
# a single user was given, replace any existing list with this one
self._author_ids = list()
author_id = value.s.id
elif isinstance(value, int):
# a single id was given, replace any existing list with this one
self._author_ids = list()
author_id = value # assuming WordPress ID
#self.parameters["author"] = value
#self._author = value
elif isinstance(value, str):
# is this string value the WordPress user ID?
try:
author_id = int(value)
except ValueError:
# nope, see if it's the username and get the User object
try:
user = self.api.user(username=value)
author_id = user.s.id
except exc.NoEntityFound:
raise ValueError("Could not determine a user from the value: {0} (type {1})".format(value, type(value)))
else:
raise ValueError("Unexpected value type passed to 'author' (type: '{1}')".format(type(value)))
assert author_id is not None, "could not determine author_id from value {0}".format(value)
#self.parameters["author"].append(str(author_id))
self._author_ids.append(author_id)
@property
def after(self):
'''
WordPress parameter to return pages after this date.
'''
return self._after
@after.setter
def after(self, value):
'''
Set the WordPress parameter to return pages after this date.
'''
# The stored format is a datetime object, even though WordPress requires
# it to be ISO-8601.
#
if value is None:
self.parameters.pop("after", None)
self._after = None
elif isinstance(value, datetime):
self._after = value
else:
raise ValueError("Th 'after' property only accepts `datetime` objects.")
@property
def before(self):
'''
WordPress parameter to return pages before this date.
'''
return self._after
@after.setter
def before(self, value):
'''
Set the WordPress parameter to return pages before this date.
'''
# The stored format is a datetime object, even though WordPress requires
# it to be ISO-8601.
#
if value is None:
self.parameters.pop("before", None)
self._before = None
elif isinstance(value, datetime):
self._before = value
else:
raise ValueError("The 'before' property only accepts `datetime` objects.")
@property
def order(self):
return self._order;
#return self.api_params.get('order', None)
@order.setter
def order(self, value):
if value is None:
self.parameters.pop("order", None)
self._order = None
else:
if isinstance(value, str):
value = value.lower()
if value not in order_values:
raise ValueError('The "order" parameter must be one '+\
'of these values: {}'.format(order_values))
else:
#self.api_params['order'] = value
self._order = value
else:
raise ValueError('The "order" parameter must be one of '+\
'these values: {} (or None).'.format(order_values))
return self._order
@property
def orderby(self):
return self.api_params.get('orderby', None)
@orderby.setter
def orderby(self, value):
if value is None:
self.parameters.pop("orderby", None)
self._orderby = None
else:
if isinstance(value, str):
value = value.lower()
if value not in orderby_values:
raise ValueError('The "orderby" parameter must be one '+\
'of these values: {}'.format(orderby_values))
else:
#self.api_params['orderby'] = value
self._orderby = value
else:
raise ValueError('The "orderby" parameter must be one of these '+\
'values: {} (or None).'.format(orderby_values))
return self._orderby
@property
def status(self):
return self._status
@status.setter
def status(self, value):
'''
Note that 'status' may contain one or more values.
Ref: https://developer.wordpress.org/rest-api/reference/pages/#arguments
'''
if value is None:
self.parameters.pop("status", None)
self._status = list() # set default value
return
try:
value = value.lower()
if value in ["draft", "pending", "private", "publish", "future"]:
# may be one or more values; store as a list
if self._status:
self._status.append(value)
else:
self._status = [value]
return
except:
pass
raise ValueError("'status' must be one of ['draft', 'pending', 'private', 'publish', 'future'] ('{0}' given)".format(value))
@property
def parent(self):
return self._parent_ids
@parent.setter
def parent(self, values):
'''
This method validates the parent passed to this request.
It accepts parent ID (integer or string) or the slug value.
'''
if values is None:
self.parameters.pop("parent", None)
self._parent_ids = list()
return
elif not isinstance(values, list):
raise ValueError("Parents must be provided as a list (or append to the existing list, or None).")
for p in values:
par_id = None
if isinstance(p, int):
# self._category_ids.append(str(c))
par_id = p
elif isinstance(p, str):
try:
# is this a category ID value?
par_id = int(p)
#self._category_ids.append(str(int(c)))
except ValueError:
# not a category ID value, try by slug?
try:
parent = self.api.category(slug=p)
par_id = parent.s.id
#self._category_ids.append(category.s.id)
except exc.NoEntityFound:
logger.debug("Asked to find a parent with the slug '{0}' but not found.".format(slug))
# Categories are stored as string ID values.
#
self._parent_ids.append(str(par_id))
@property
def parent_exclude(self):
return self._parent_exclude_ids
@parent_exclude.setter
def parent_exclude(self, values):
'''
This method validates the parent_exclude passed to this request.
It accepts category ID (integer or string) or the slug value.
'''
if values is None:
self.parameters.pop("parent_exclude", None)
self._parent_exclude_ids = list()
return
elif not isinstance(values, list):
raise ValueError("parent_exclude must be provided as a list (or append to the existing list, or None).")
for p in values:
par_id = None
if isinstance(p, int):
# self._category_exclude_ids.append(str(c))
par_id = p
elif isinstance(p, str):
try:
# is this a category ID value?
par_id = int(p)
#self._category_exclude_ids.append(str(int(c)))
except ValueError:
# not a category ID value, try by slug?
try:
category = self.api.parent(slug=p)
par_id = parent.s.id
#self._category_exclude_ids.append(category.s.id)
except exc.NoEntityFound:
logger.debug("Asked to find a parent with the slug '{0}' but not found.".format(slug))
# Categories are stored as string ID values.
#
self._parent_exclude_ids.append(str(par_id))
@property
def slugs(self):
'''
The list of page slugs to retrieve.
'''
return self._slugs
@slugs.setter
def slugs(self, values):
if values is None:
self.parameters.pop("slugs", None)
self._slugs = list()
return
elif not isinstance(values, list):
raise ValueError("Slugs must be provided as a list (or append to the existing list).")
for s in values:
if isinstance(s, str):
self._slugs.append(s)
else:
raise ValueError("Unexpected type for property list 'slugs'; expected str, got '{0}'".format(type(s)))
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,320 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/cache.py |
class WPORMCacheObjectNotFoundError(Exception):
pass
class WPORMCache:
def __init__(self):
self.initialize()
def initialize(self):
'''
Internal method to set up the cache from scratch.
'''
self.cache = dict()
def get(self, class_name=None, key=None):
'''
Method to retrieve wordpress-orm entity from cache; key can be WordPress 'id' or slug.
Keys that are not strings are coerced to type 'str' (i.e. an id of 4 or "4" is equivalent).
class_name : class name as string
'''
if key is not None and isinstance(key, str) is False:
key = str(key)
if class_name not in self.cache:
self.cache[class_name] = dict()
try:
return self.cache[class_name][key] #.get(key, None) # return 'None' if key is not found
except KeyError:
raise WPORMCacheObjectNotFoundError("Object of class '{0}' with key='{1}' not found".format(class_name, key))
def set(self, value=None, keys=list()):
'''
Method to set values in the cache. Typically keys is a tuple or list containing the WordPress id and slug.
Keys that are not strings are coerced to type 'str' (i.e. an id of 4 or "4" is equivalent).
'''
# if key is not None and isinstance(key, str) is False:
# key = str(key)
class_name = type(value).__name__
if class_name not in self.cache:
self.cache[class_name] = dict()
for key in [k for k in keys if k is not None]: # safeguard against any key value that might be None
if isinstance(key, str) is False:
key = str(key)
self.cache[class_name][key] = value
def clear(self):
'''
Clear all items from the cache.
'''
self.initialize()
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,321 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/tests/test_users.py |
from ..entities.user import User, UserRequest
def test_user_query(wp_api):
'''
Basic test to see that users can be queried.
'''
uq = wp_api.UserRequest()
users = uq.get()
assert uq.response.status_code == 200, "Could not connect to: '{0}'".format(wp_api.base_url)
assert len(users) > 0, "No users found in the WordPress installation."
assert isinstance(users[0], User), "The object returned from the UserRequest was not a User class as expected."
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,322 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/wordpress_entity.py |
import inspect
import logging
from abc import ABCMeta, abstractmethod, abstractproperty
import requests
logger = logging.getLogger(__name__.split(".")[0]) # package name
context_values = ["view", "embed", "edit"]
class WPSchema():
'''
Object representing the schema for each WordPress entity.
'''
#
# Properties are defined based on the field names, see below.
#
pass
class WPEntity(metaclass=ABCMeta):
'''
Abstract superclass for all entities of the WordPress API.
'''
def __init__(self, api=None):
if api is None:
raise Exception("Use the 'wordpress_orm.API.{0}()' method to create a new '{0}' object (or set the 'api' parameter).".format(self.__class__.__name__))
self.api = api # holds the connection information
self.json = None # holds the raw JSON returned from the API
self.s = WPSchema() # an empty object to use to hold custom properties
self._schema_fields = None # a list of the fields in the schema
self._post_fields = None # a list of the fields used in POST queries
# define the schema properties for the WPSchema object
for field in self.schema_fields:
setattr(self.s, field, None)
# POST fields are also implemented as schema properties
for field in self.post_fields:
setattr(self.s, field, None)
@abstractproperty
def schema_fields(self):
'''
This method returns a list of schema properties for this entity, e.g. ["id", "date", "slug", ...]
'''
pass
@abstractproperty
def post_fields(self):
'''
This method returns a list of properties for creating (POSTing) a new entity to WordPress, e.g. ["date", "slug", ...]
'''
pass
def add_schema_field(self, new_field):
'''
Method to allow extending schema fields.
'''
assert isinstance(new_field, str)
new_field = new_field.lower()
if new_field not in self._schema_fields:
self._schema_fields.append(new_field)
def postprocess_response(self, data=None):
'''
Hook to allow custom subclasses to process responses.
Usually will access self.json to get the full JSON record that created this entity.
'''
pass
def post(self, url=None, parameters=None, data=None):
'''
Implementation of HTTP POST comment for WordPress entities.
'''
if self.api.session is None:
self.post_response = requests.post(url=url, data=data, params=parameters, auth=self.api.auth())
else:
# use existing session
self.post_response = self.api.session.post(url=url, data=data, params=parameters, auth=self.api.auth())
self.post_response.raise_for_status()
def preprocess_additional_post_fields(self, data=None, parameters=None):
'''
Hook for subclasses to allow for custom processing of POST request data (before the request is made).
'''
pass
def update_schema_from_dictionary(self, d, process_links=False):
'''
Replaces schema values with those found in provided dictionary whose keys match the field names.
This is useful to parse the JSON dictionary returned by the WordPress API or embedded content
(see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding).
d : dictionary of data, key=schema field, value=data
process_links : parse the values under the "_links" key, if present
'''
if d is None or not isinstance(d, dict):
raise ValueError("The method 'update_schema_from_dictionary' expects a dictionary.")
fields = self.schema_fields
for key in fields:
if key in d:
if isinstance(d[key], dict) and "rendered" in d[key]:
# for some fields, we want the "rendered" value - any cases where we don't??
setattr(self.s, key, d[key]["rendered"])
else:
setattr(self.s, key, d[key])
if key not in fields:
logger.debug("WARNING: encountered field ('{0}') in dictionary that is not in the list of schema fields for '{1}' (fields: {2}).".format(key, self.__class__.__name__, fields))
if process_links:
# TODO: handle _links if present
raise NotImplementedError("Processing '_links' has not yet been implemented.")
class WPRequest(metaclass=ABCMeta):
'''
Abstract superclass for WordPress requests.
'''
def __init__(self, api=None):
if api is None:
raise Exception("Create this object ('{0}') from the API object, not directly.".format(self.__class__.__name__))
# WordPress headers ('X-WP-*')
self.total = None # X-WP-Total
self.total_pages = None # X-WP-TotalPages
self.nonce = None # X-WP-Nonce
self.api = api
self.url = None
self.parameters = dict()
self.context = None # parameter found on all entities
self.response = None
self._parameter_names = None
for arg in self.parameter_names:
setattr(self, arg, None)
#self.context = "view" # default value
# @property
# def context(self):
# # 'view' is default value in API
# return self.arguments.get("context", "view")
@abstractproperty
def parameter_names(self):
pass
def get(self, class_object=None, count=False, embed=True, links=True):
'''
Base implementation of the HTTP GET request to fetch WordPress entities.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
if embed is True:
self.parameters["_embed"] = "true"
if links is True:
self.parameters["_links"] = "true"
if count:
request_context = "embed" # only counting results, this is a shorter response
else:
request_context = "view" # default value
# if the user set the
def process_response_headers(self):
'''
Handle any customization of parsing response headers, processes X-WP-* headers by default.
'''
# read response headers
# ---------------------
# Pagination, ref: https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/
#
# X-WP-Total : total number of records in the collection
# X-WP-TotalPages : total number of pages encompassing all available records
#
if 'X-WP-Total' in self.response.headers:
self.total = int(self.response.headers['X-WP-Total'])
if 'X-WP-TotalPages' in self.response.headers:
self.total_pages = int(self.response.headers['X-WP-TotalPages'])
if 'X-WP-Nonce' in self.response.headers:
self.nonce = self.response.headers['X-WP-Nonce']
def get_response(self, wpid=None):
'''
wpid : specify this if a specific WordPress object (of given ID) is being requested
'''
if self.response is None:
if wpid is None:
url = self.url
else:
url = "{0}/{1}".format(self.url, wpid)
if self.api.session is None:
#logger.debug("creating new request")
# no exiting request, create a new one
self.response = requests.get(url=url, params=self.parameters, auth=self.api.auth())
else:
# use existing session
self.response = self.api.session.get(url=url, params=self.parameters, auth=self.api.auth())
self.response.raise_for_status()
#return self.response
@property
def request(self):
if self.response:
return self.response.request
else:
return None
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,323 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/post.py |
'''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/posts/
'''
import json
import logging
import requests
import dateutil.parser
from datetime import datetime
from .wordpress_entity import WPEntity, WPRequest, context_values
from .user import User
from .category import Category
from .media import Media
from .. import exc
from ..cache import WPORMCacheObjectNotFoundError
logger = logging.getLogger(__name__.split(".")[0]) # package name
order_values = ["asc", "desc"]
orderby_values = ["author", "date", "id", "include", "modified", "parent",
"relevance", "slug", "title"]
class Post(WPEntity):
def __init__(self, id=None, session=None, api=None):
super().__init__(api=api)
# related objects to cache
self._author = None
self._featured_media = None
self._comments = None
self._categories = None
self._date_gmt = None # datetime object
def __repr__(self):
if self.s.title is None:
truncated_title = "<NO TITLE SET>"
elif len(self.s.title) < 11:
truncated_title = "'{}'".format(self.s.title)
else:
truncated_title = "'{}...'".format(self.s.title[0:10])
return "<WP {0} object at {1}, id={2}, title={3}>".format(self.__class__.__name__,
hex(id(self)), self.s.id, truncated_title)
@property
def schema_fields(self):
if self._schema_fields is None:
self._schema_fields = ["date", "date_gmt", "guid", "id", "link", "modified", "modified_gmt",
"slug", "status", "type", "password", "title", "content", "author",
"excerpt", "featured_media", "comment_status", "ping_status", "format",
"meta", "sticky", "template", "categories", "tags"]
return self._schema_fields
@property
def post_fields(self):
'''
Arguments for POST requests.
'''
if self._post_fields is None:
# Note that 'date' is excluded from the specification in favor of exclusive use of 'date_gmt'.
self._post_fields = ["date_gmt", "slug", "status", "password",
"title", "content", "author", "excerpt", "featured_media",
"comment_status", "ping_status", "format", "meta", "sticky",
"template", "categories", "tags"]
return self._post_fields
@property
def post(self):
'''
Create a new Post.
'''
url = self.api.base_url + "{}".format("posts")
logger.debug("URL = {}".format(url))
# Build a list of parameters based on the properties of the provided Post object.
post_parameters = dict()
post_data = dict()
# date
# (Don't use the 'date' parameter as this is in the site's timezone, which we don't know.
# Also note that WordPress doesn't properly support ISO8601,
# see: https://core.trac.wordpress.org/ticket/41032)
# date_gmt
if self.s.date_gmt is None:
post_parameters["date_gmt"] = datetime.now().isoformat()
else:
post_parameters["date_gmt"] = self.s.date_gmt.isoformat()
#slug
if self.s.slug is not None:
post_parameters["slug"] = self.s.slug
#status
if self.s.status is not None:
post_parameters["status"] = self.s.status
#password
if self.s.password is not None:
post_parameters["password"] = self.s.password
#title
if self.s.title is not None:
post_parameters["title"] = self.s.title
#content
if self.s.content is not None:
post_parameters["content"] = self.s.content
#author
if any([self.author, self.s.author]):
if self.author is not None:
post_parameters["author"] = self.author.s.id
else:
post_parameters["author"] = self.s.author
#excerpt
if self.s.excerpt is not None:
post_parameters["excerpt"] = self.s.excerpt
#featured_media
if any([self.featured_media, self.s.featured_media]):
if self.featured_media is not None:
post_parameters["featured_media"] = self.featured_media.s.id
else:
post_parameters["featured_media"] = self.s.featured_media
#comment_status
if self.s.comment_status is not None:
post_parameters["comment_status"] = self.s.comment_status
#ping_status
pass
#format
if self.s.format is not None:
post_parameters["format"] = self.s.format
#meta
pass
#sticky
if self.s.sticky is not None:
if self.s.sticky == True:
post_parameters["sticky"] = "1"
else:
post_parameters["sticky"] = "0"
#template
pass
#categories
pass
#tags
pass
#self.preprocess_additional_post_fields(data=post_data, parameters=post_parameters)
logger.debug(post_parameters)
try:
super().post(url=url, data=post_parameters, parameters=post_parameters)
except requests.exceptions.HTTPError:
logger.debug("Post response code: {}".format(self.post_response.status_code))
if self.post_response.status_code == 400: # bad request
logger.debug("URL={}".format(self.post_response.url))
raise exc.BadRequest("400: Bad request. Error: \n{0}".format(json.dumps(self.post_response.json(), indent=4)))
@property
def featured_media(self):
'''
Returns the 'Media' object that is the "featured media" for this post.
'''
if self._featured_media is None and self.s.featured_media is not None:
media_id = self.s.featured_media
if media_id == 0:
# no featured media for this post entry (this is what WordPress returns)
self._featured_media = None
else:
self._featured_media = self.api.media(id=media_id)
return self._featured_media
@featured_media.setter
def featured_media(self, new_media):
'''
Set the "featured media" object to this post.
'''
if isinstance(new_media, Media) or new_media is None:
self._featured_media = new_media
else:
raise ValueError("The featured media of a Post must be an object of class 'Media' ('{0}' provided).".format(type(new_media).__name__))
@property
def date(self):
'''
Raises an exception to warn not to use the 'date' property; use 'date_gmt' instead.
'''
raise Exception("Although 'date' is a valid property, we don't have access to the WordPress server's time zone. " +
"Please use the 'date_gmt' property instead (see: https://core.trac.wordpress.org/ticket/41032).")
@date.setter
def date(self, new_date):
'''
Raises an exception to warn not to use the 'date' property; use 'date_gmt' instead.
'''
raise Exception("The 'date' property depends on knowing the server's time zone, which we don't. " +
"Please use the 'date_gmt' property instead (see: https://core.trac.wordpress.org/ticket/41032).")
@property
def date_gmt(self):
'''
The date associated with the post in GMT as a datetime object.
'''
if self._date_gmt is None and self.s.date_gmt is not None:
# format of this field is ISO 8610 (e.g. "2018-07-17T17:33:36")
self._date_gmt = dateutil.parser.parse(self.s.date_gmt) # returns datetime object
return self._date_gmt
@date_gmt.setter
def date_gmt(self, new_date):
'''
Set the date associated with the post in GMT, takes a datetime.datetime object or a string in ISO 8601 format.
'''
if new_date is None:
self._date_gmt = None
return
if isinstance(new_date, datetime):
self._date_gmt = new_date
elif isinstance(new_date, str):
try:
self._date_gmt = dateutil.parser.parse(new_date)
except ValueError:
raise ValueError("The found 'date_gmt' string from the schema could not be converted to a datetime object.".format(new_date))
else:
raise ValueError("'date_gmt' must be set to either a datetime.datetime object or else an ISO 8601 string.")
@property
def status(self):
'''
The status of the post, one of ["publish", "future", "draft", "pending", "private"].
'''
return self.s.status
@status.setter
def status(self, new_status):
'''
Set the status for this post, must be one of ["publish", "future", "draft", "pending", "private"].
'''
if new_status is None:
self.s.status = None
else:
new_status = new_status.lower()
if new_status in ["publish", "future", "draft", "pending", "private"]:
self.s.status = new_status
else:
raise ValueError('Post status must be one of ["publish", "future", "draft", "pending", "private"].')
@property
def author(self):
'''
Returns the author of this post, class: 'User'.
'''
if self._author is None and self.s.author is not None:
try:
self._author = self.api.user(id=self.s.author) # ID for the author of the object
# TODO does this put the object in the cache?
except exc.NoEntityFound:
raise exc.UserNotFound("User ID '{0}' not found.".format(self.author))
# ur = self.api.UserRequest()
# ur.id = self.s.author # ID for the author of the object
# user_list = ur.get()
# if len(user_list) == 1:
# self._author = user_list[0]
# else:
# raise exc.UserNotFound("User ID '{0}' not found.".format(self.author))
return self._author
@author.setter
def author(self, author):
'''
Set the related author object (class User).
'''
# TODO: could potentially accept an interger ID value.
if isinstance(author, User) or author is None:
self._author = author
else:
raise ValueError("The author of a Post must be an object of class 'User' ('{0}' provided).".format(type(new_media).__name__))
@property
def comment_status(self):
'''
Whether or not comments are open on the object, one of ["open", "closed"].
'''
return self.comment_status
@comment_status.setter
def comment_status(self, new_status):
'''
Set the status for this post, must be one of ["publish", "future", "draft", "pending", "private"].
'''
if new_status is None:
self.new_status = None
else:
new_status = new_status.lower()
if new_status in ["open", "closed"]:
self.comment_status = new_status
else:
raise ValueError('Comment status must be one of ["open", "closed"].')
@property
def ping_status(self):
'''
Whether or not this post can be pinged., one of ["open", "closed"].
'''
return self.ping_status
@ping_status.setter
def ping_status(self, new_status):
'''
Whether or not this post can be pinged., must be one of ["open", "closed"].
'''
if new_status is None:
self.new_status = None
else:
new_status = new_status.lower()
if new_status in ["open", "closed"]:
self.ping_status = new_status
else:
raise ValueError('Ping status must be one of ["open", "closed"].')
@property
def format(self):
'''
The format of the post, one of ["standard", "aside", "chat", "gallery", "link", "image", "quote", "status", "video", "audio"].
'''
return self.ping_status
@format.setter
def format(self, new_value):
'''
The format of the post, one of ["standard", "aside", "chat", "gallery", "link", "image", "quote", "status", "video", "audio"].
'''
if new_value is None:
self.format = None
else:
new_value = new_value.lower()
if new_value in ["open", "closed"]:
self.format = format
else:
raise ValueError('Format must be one of ["open", "closed"].')
@property
def comments(self):
'''
Returns the comments associated with this post.
'''
if self._comments is None:
self._comments = self.api.CommentRequest(post=self).get()
return self._comments
@property
def categories(self):
'''
Returns a list of categories (as Category objects) associated with this post.
'''
if self._categories is None and self.s.categories is not None:
self._categories = list()
for category_id in self.s.categories:
try:
self._categories.append(self.api.category(id=category_id))
except exc.NoEntityFound:
logger.debug("Expected to find category ID={0} from post (ID={1}), but no category found.".format(category_id, self.s.id))
return self._categories
@property
def category_names(self):
if self.categories is not None:
return [x.s.name for x in self.categories]
else:
return list()
class PostRequest(WPRequest):
'''
A class that encapsulates requests for WordPress posts.
'''
def __init__(self, api=None, categories=None, slugs=None):
super().__init__(api=api)
self.id = None # WordPress ID
self._post_fields = None
self.url = self.api.base_url + "posts"
# values read from the response header
self.total = None
self.total_pages = None
# parameters that undergo validation, i.e. need custom setter
self._after = None
self._before = None
self._offset = None
self._order = None
self._orderby = None
self._page = None
self._per_page = None
self._sticky = None
self._status = list()
self._author_ids = list()
self._author_exclude = list()
self._includes = list()
self._excludes = list()
self._slugs = list()
self._category_ids = list()
self._categories_exclude_ids = list()
self._tags = list() # list of IDs of tags
self._tags_exclude = list() # list of IDs of tags
if categories:
self.categories = categories
if slugs:
self.slugs = slugs
@property
def parameter_names(self):
'''
Post request parameters.
'''
if self._parameter_names is None:
self._parameter_names = ["context", "page", "per_page", "search", "after", "author",
"author_exclude", "before", "exclude", "include", "offset",
"order", "orderby", "slug", "status", "categories",
"categories_exclude", "tags", "tags_exclude", "sticky"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
if self.page:
self.parameters["page"] = self.page
if self.per_page:
self.parameters["per_page"] = self.per_page
if self.search:
self.parameters["search"] = self.search
if self.after:
self.parameters["after"] = self.after.isoformat()
if len(self.author) > 0:
# takes a list of author IDs
self.parameters["author"] = ",".join(self.author)
# author_exclude : Ensure result set excludes posts assigned to specific authors.
if len(self.author_exclude) > 0:
self.parameters["author_exclude"] = ",".join(self.author_exclude)
# before : Limit response to posts published before a given ISO8601 compliant date.
if self.before is not None:
self.parameters["before"] = self.before.isoformat()
# exclude : Ensure result set excludes specific IDs.
if len(self.exclude) > 0:
self.parameters["exclude"] = ",".join(self.exclude)
# include : Limit result set to specific IDs.
if len(self.include) > 0:
self.parameters["include"] = ",".join(self.include)
# offset : Offset the result set by a specific number of items.
if self.offset:
self.parameters["offset"] = self.offset
# order : Order sort attribute ascending or descending. Default: desc, one of: asc, desc
if self.order:
self.parameters["order"] = self.order
# orderby : Sort collection by object attribute, default "date"
# one of: author, date, id, include, modified, parent, relevance, slug, title
if self.orderby:
self.parameters["orderby"] = self.orderby
# slug : Limit result set to posts with one or more specific slugs.
if self.slug:
self.parameters["slug"] = self.slug
# status : Limit result set to posts assigned one or more statuses. (default: publish)
if len(self.status) > 0:
self.parameters["status"] = ",".join(self.status)
# categories : Limit result set to all items that have the specified term assigned in the categories taxonomy.
if len(self.categories) > 0:
self.parameters["categories"] = ",".join(self.categories)
# categories_exclude : Limit result set to all items except those that have the specified term assigned in the categories taxonomy.
if len(self.categories_exclude) > 0:
self.parameters["categories_exclude"] = ",".join(self.categories_exclude)
# tags : Limit result set to all items that have the specified term assigned in the tags taxonomy.
if len(self.tags) > 0:
self.parameters["tags"] = ",".join(self.tags)
# tags_exclude : Limit result set to all items except those that have the specified term assigned in the tags taxonomy.
if len(self.tags_exclude) > 0:
self.parameters["tags_exclude"] = ",".join(self.tags_exclude)
# sticky : Limit result set to items that are sticky.
if self.sticky:
self.parameters["sticky"] = "1"
def get(self, class_object=Post, count=False, embed=True, links=True):
'''
Returns a list of 'Post' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
#if self.id:
# self.url += "/{}".format(self.id)
if embed is True:
self.parameters["_embed"] = "true"
self.populate_request_parameters()
try:
self.get_response()
logger.debug("URL='{}'".format(self.request.url))
except requests.exceptions.HTTPError:
logger.debug("Post response code: {}".format(self.response.status_code))
if self.response.status_code == 400: # bad request
logger.debug("URL={}".format(self.response.url))
raise exc.BadRequest("400: Bad request. Error: \n{0}".format(json.dumps(self.response.json(), indent=4)))
elif self.response.status_code == 404: # not found
return None
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
# if count:
# return len(posts_data)
posts_data = self.response.json()
if isinstance(posts_data, dict):
# only one object was returned; make it a list
posts_data = [posts_data]
posts = list()
for d in posts_data:
# Before we continue, do we have this Post in the cache already?
try:
post = self.api.wordpress_object_cache.get(class_name=class_object.__name__, key=d["id"])
except WPORMCacheObjectNotFoundError:
post = class_object.__new__(class_object) # default = Post()
post.__init__(api=self.api)
post.json = json.dumps(d)
post.update_schema_from_dictionary(d)
# Check for embedded content
if "_embedded" in d:
embedded = d["_embedded"]
for key in embedded:
# These are related objects, provided by the API in full.
# See if the objects are in the cache first, and if not, create them.
if key == "author":
# value is a list of objects (dictionaries), only expecting one
author_obj = embedded[key][0]
try:
author = self.api.wordpress_object_cache.get(class_name=User.__name__, key=author_obj["id"])
except WPORMCacheObjectNotFoundError:
author = User(api=self.api)
author.update_schema_from_dictionary(author_obj)
self.api.wordpress_object_cache.set(value=author, keys=(author.s.id, author.s.slug))
post.author = author
elif key == "wp:featuredmedia":
# value is a list of objects (dictionaries), only expecting one
media_obj = embedded[key][0]
try:
media = self.api.wordpress_object_cache.get(class_name=Media.__name__, key=media_obj["id"])
except WPORMCacheObjectNotFoundError:
media = Media(api=self.api)
media.update_schema_from_dictionary(media_obj)
self.api.wordpress_object_cache.set(value=media, keys=(media.s.id, media.s.slug))
post.featured_media = media
elif key == "wp:term":
# value is list of lists,
# first list is a list of metadata objects (can potentially be different kinds, or is this strictly 'category'?)
# (this is not documented)
# see: https://www.sitepoint.com/wordpress-term-meta/
for term_list in embedded[key]:
if len(term_list) == 0:
continue
for category_obj in term_list:
if "taxonomy" in category_obj and category_obj["taxonomy"] in ["category", "post_tag", "nav_menu", "link_category", "post_format"]:
try:
category = self.api.wordpress_object_cache.get(class_name=Category.__name__,
key=category_obj["id"])
except WPORMCacheObjectNotFoundError:
category = Category(api=self.api)
category.update_schema_from_dictionary(category_obj)
self.api.wordpress_object_cache.set(value=category, keys=(category.s.id, category.s.slug))
post.categories.append(category)
else:
logger.warning("Unknown taxonomy encountered in _embedded data of Post (or something else entirely): {0}".format(json.dumps(term_list)))
else:
logger.debug("Note: Unhandled embedded content in {0}, key='{1}'".format(self.__class__.__name__, key))
# perform postprocessing for custom fields
post.postprocess_response()
# add to cache
self.api.wordpress_object_cache.set(value=post, keys=(post.s.id, post.s.slug))
finally:
posts.append(post)
return posts
@property
def context(self):
if self._context is None:
self._context = None
return self._context
@context.setter
def context(self, value):
if value is None:
self.parameters.pop("context", None)
self._context = None
return
else:
try:
value = value.lower()
if value in ["view", "embed", "edit"]:
self._context = value
return
except:
pass
raise ValueError ("'context' may only be one of ['view', 'embed', 'edit']")
@property
def page(self):
'''
Current page of the collection.
'''
return self._page
@page.setter
def page(self, value):
#
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._page = value
elif isinstance(value, str):
try:
self._page = int(value)
except ValueError:
raise ValueError("The 'page' parameter must be an integer, was given '{0}'".format(value))
@property
def per_page(self):
'''
Maximum number of items to be returned in result set.
'''
return self._per_page
@per_page.setter
def per_page(self, value):
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._per_page = value
elif isinstance(value, str):
try:
self._per_page = int(value)
except ValueError:
raise ValueError("The 'per_page' parameter must be an integer, was given '{0}'".format(value))
@property
def after(self):
'''
WordPress parameter to return posts after this date.
'''
return self._after
@after.setter
def after(self, value):
'''
Set the WordPress parameter to return posts after this date.
'''
# The stored format is a datetime object, even though WordPress requires
# it to be ISO-8601.
#
if value is None:
self.parameters.pop("after", None)
self._after = None
elif isinstance(value, datetime):
self._after = value
else:
raise ValueError("Th 'after' property only accepts `datetime` objects.")
@property
def author(self):
return self._author_ids
@author.setter
def author(self, value):
'''
Set author parameter for this request; stores WordPress user ID.
'''
author_id = None
if value is None:
self.parameters.pop("author", None) # remove key
return
#self.g = None
elif isinstance(value, User):
# a single user was given, replace any existing list with this one
self._author_ids = list()
author_id = value.s.id
elif isinstance(value, int):
# a single id was given, replace any existing list with this one
self._author_ids = list()
author_id = value # assuming WordPress ID
#self.parameters["author"] = value
#self._author = value
elif isinstance(value, str):
# is this string value the WordPress user ID?
try:
author_id = int(value)
except ValueError:
# nope, see if it's the username and get the User object
try:
user = self.api.user(username=value)
author_id = user.s.id
except exc.NoEntityFound:
raise ValueError("Could not determine a user from the value: {0} (type {1})".format(value, type(value)))
else:
raise ValueError("Unexpected value type passed to 'author' (type: '{1}')".format(type(value)))
assert author_id is not None, "could not determine author_id from value {0}".format(value)
#self.parameters["author"].append(str(author_id))
self._author_ids.append(author_id)
@property
def author_exclude(self):
return self._author_exclude
@author_exclude.setter
def author_exclude(self, value):
'''
Set author to exclude from this query; stores WordPress user ID.
'''
author_id = None
# plan: define author_id, append to "self._author_ids" list below
if value is None:
self.parameters.pop("author_exclude", None) # remove key
return
#self.g = None
elif isinstance(value, User):
# a single user was given, replace any existing list with this one
self._author_exclude = list()
author_id = value.s.id
elif isinstance(value, int):
# a single id was given, replace any existing list with this one
self._author_exclude = list()
author_id = value # assuming WordPress ID
#self.parameters["author"] = value
#self._author = value
elif isinstance(value, str):
# is this string value the WordPress user ID?
try:
author_id = int(value)
except ValueError:
# nope, see if it's the username and get the User object
try:
user = self.api.user(username=value)
author_id = user.s.id
except exc.NoEntityFound:
raise ValueError("Could not determine a user from the value: '{0}' (type '{1}')".format(value, type(value)))
else:
raise ValueError("Unexpected value type passed to 'author_exclude' (type: '{1}')".format(type(value)))
assert author_id is not None, "Could not determine author_id from value '{0}'.".format(value)
self._author_exclude.append(author_id)
@property
def before(self):
'''
WordPress parameter to return posts before this date.
'''
return self._before
@after.setter
def before(self, value):
'''
Set the WordPress parameter to return posts before this date.
'''
# The stored format is a datetime object, even though WordPress requires
# it to be ISO-8601.
#
if value is None:
self.parameters.pop("before", None)
self._before = None
elif isinstance(value, datetime):
self._before = value
else:
raise ValueError("The 'before' property only accepts `datetime` objects.")
@property
def exclude(self):
return self._excludes
@exclude.setter
def exclude(self, values):
'''
List of WordPress IDs to exclude from a search.
'''
if values is None:
self.parameters.pop("exclude", None)
self._excludes = list()
return
elif not isinstance(values, list):
raise ValueError("'excludes' must be provided as a list (or append to the existing list).")
for exclude_id in values:
if isinstance(exclude_id, int):
self._excludes.append(str(exclude_id))
elif isinstance(exclude_id, str):
try:
self._includes.append(str(int(exclude_id)))
except ValueError:
raise ValueError("The WordPress ID (an integer, '{0}' given) must be provided to limit result to specific users.".format(exclude_id))
@property
def include(self):
return self._includes
@include.setter
def include(self, values):
'''
Limit result set to specified WordPress user IDs, provided as a list.
'''
if values is None:
self.parameters.pop("include", None)
self._includes = list()
return
elif not isinstance(values, list):
raise ValueError("Includes must be provided as a list (or append to the existing list).")
for include_id in values:
if isinstance(include_id, int):
self._includes.append(str(include_id))
elif isinstance(include_id, str):
try:
self._includes.append(str(int(include_id)))
except ValueError:
raise ValueError("The WordPress ID (an integer, '{0}' given) must be provided to limit result to specific users.".format(include_id))
@property
def offset(self):
return self._offset
@offset.setter
def offset(self, value):
'''
Set value to offset the result set by the specified number of items.
'''
if value is None:
self.parameters.pop("offset", None)
self._offset = None
elif isinstance(value, int):
self._offset = value
elif isinstance(value, str):
try:
self._offset = str(int(str))
except ValueError:
raise ValueError("The 'offset' value should be an integer, was given: '{0}'.".format(value))
@property
def order(self):
return self._order;
#return self.api_params.get('order', None)
@order.setter
def order(self, value):
if value is None:
self.parameters.pop("order", None)
self._order = None
else:
if isinstance(value, str):
value = value.lower()
if value not in order_values:
raise ValueError('The "order" parameter must be one '+\
'of these values: {}'.format(order_values))
else:
#self.api_params['order'] = value
self._order = value
else:
raise ValueError('The "order" parameter must be one of '+\
'these values: {} (or None).'.format(order_values))
return self._order
@property
def orderby(self):
return self._orderby # parameters.get('orderby', None)
@orderby.setter
def orderby(self, value):
if value is None:
self.parameters.pop("orderby", None)
self._orderby = None
else:
if isinstance(value, str):
value = value.lower()
if value not in orderby_values:
raise ValueError('The "orderby" parameter must be one '+\
'of these values: {}'.format(orderby_values))
else:
#self.api_params['orderby'] = value
self._orderby = value
else:
raise ValueError('The "orderby" parameter must be one of these '+\
'values: {} (or None).'.format(orderby_values))
return self._orderby
@property
def slugs(self):
'''
The list of post slugs to retrieve.
'''
return self._slugs
@slugs.setter
def slugs(self, values):
if values is None:
self.parameters.pop("slugs", None)
self._slugs = list()
return
elif not isinstance(values, list):
raise ValueError("Slugs must be provided as a list (or append to the existing list).")
for s in values:
if isinstance(s, str):
self._slugs.append(s)
else:
raise ValueError("Unexpected type for property list 'slugs'; expected str, got '{0}'".format(type(s)))
@property
def status(self):
return self._status
@status.setter
def status(self, value):
'''
Note that 'status' may contain one or more values.
Ref: https://developer.wordpress.org/rest-api/reference/posts/#arguments
'''
if value is None:
self.parameters.pop("status", None)
self._status = list() # set default value
return
try:
value = value.lower()
if value in ["draft", "pending", "private", "publish", "future"]:
# may be one or more values; store as a list
if self._status:
self._status.append(value)
else:
self._status = [value]
return
except:
pass
raise ValueError("'status' must be one of ['draft', 'pending', 'private', 'publish', 'future'] ('{0}' given)".format(value))
@property
def categories(self):
return self._category_ids
@categories.setter
def categories(self, values):
'''
This method validates the categories passed to this request.
It accepts category ID (integer or string) or the slug value.
'''
if values is None:
self.parameters.pop("categories", None)
self._category_ids = list()
return
elif not isinstance(values, list):
raise ValueError("Categories must be provided as a list (or append to the existing list, or None).")
for c in values:
cat_id = None
if isinstance(c, Category):
cat_id = c.s.id
# self._category_ids.append(str(c.s.id))
elif isinstance(c, int):
# self._category_ids.append(str(c))
cat_id = c
elif isinstance(c, str):
try:
# is this a category ID value?
cat_id = int(c)
#self._category_ids.append(str(int(c)))
except ValueError:
# not a category ID value, try by slug?
try:
category = self.api.category(slug=c)
cat_id = category.s.id
#self._category_ids.append(category.s.id)
except exc.NoEntityFound:
logger.debug("Asked to find a category with the slug '{0}' but not found.".format(slug))
# Categories are stored as string ID values.
#
self._category_ids.append(str(cat_id))
@property
def categories_exclude(self):
return self._category_exclude_ids
@categories_exclude.setter
def categories_exclude(self, values):
'''
This method validates the categories_exclude passed to this request.
It accepts category ID (integer or string) or the slug value.
'''
if values is None:
self.parameters.pop("categories_exclude", None)
self._category_exclude_ids = list()
return
elif not isinstance(values, list):
raise ValueError("categories_exclude must be provided as a list (or append to the existing list, or None).")
for c in values:
cat_id = None
if isinstance(c, Category):
cat_id = c.s.id
# self._category_exclude_ids.append(str(c.s.id))
elif isinstance(c, int):
# self._category_exclude_ids.append(str(c))
cat_id = c
elif isinstance(c, str):
try:
# is this a category ID value?
cat_id = int(c)
#self._category_exclude_ids.append(str(int(c)))
except ValueError:
# not a category ID value, try by slug?
try:
category = self.api.category(slug=c)
cat_id = category.s.id
#self._category_exclude_ids.append(category.s.id)
except exc.NoEntityFound:
logger.debug("Asked to find a category with the slug '{0}' but not found.".format(slug))
# Categories are stored as string ID values.
#
self._category_exclude_ids.append(str(cat_id))
@property
def tags(self):
'''
Return only items that have these tags.
'''
return self._tags
@tags.setter
def tags(self, values):
'''
List of tag IDs that are required to be attached to items returned from query.
'''
if values is None:
self.parameters.pop("tags", None)
self._tags = list()
return
elif not isinstance(values, list):
raise ValueError("Tags must be provided as a list of IDs (or append to the existing list).")
for tag_id in values:
if isinstance(tag_id, int):
self.tags.append(tag_id)
elif isinstance(tag_id, str):
try:
self.tags.append(str(int(tag_id)))
except ValueError:
raise ValueError("The given tag was in the form of a string but could not be converted to an integer ('{0}').".format(tag_id))
else:
raise ValueError("Unexpected type for property list 'tags'; expected str or int, got '{0}'".format(type(s)))
@property
def tags_exclude(self):
'''
Return only items that do not have these tags.
'''
return self._tags_exclude
@tags.setter
def tags_exclude(self, values):
'''
List of tag IDs attached to items to be excluded from query.
'''
if values is None:
self.parameters.pop("tags", None)
self._tags_exclude = list()
return
elif not isinstance(values, list):
raise ValueError("Tags must be provided as a list of IDs (or append to the existing list).")
for tag_id in values:
if isinstance(tag_id, int):
self._tags_exclude.append(tag_id)
elif isinstance(tag_id, str):
try:
self._tags_exclude.append(str(int(tag_id)))
except ValueError:
raise ValueError("The given tag was in the form of a string but could not be converted to an integer ('{0}').".format(tag_id))
else:
raise ValueError("Unexpected type for property list 'tags'; expected str or int, got '{0}'".format(type(s)))
@property
def sticky(self):
'''
If 'True', limits result set to items that are sticky.
'''
return self._sticky
@sticky.setter
def sticky(self, value):
'''
Set to 'True' to limit result set to items that are sticky, property can be set to one of [True, False, '0', '1', 0, 1].
'''
if value is None:
self._sticky = None
elif value in [True, False]:
self._sticky = (value == True)
elif value in ['1', '0', 1, 0]:
value = (value in ['1',1])
else:
raise Exception("The property 'sticky' is a Boolean, must be set to one of [True, False, '0', '1', 0, 1].")
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,324 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/media.py |
'''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/media/
'''
import os
import json
import logging
import requests
from .wordpress_entity import WPEntity, WPRequest, context_values
from ..cache import WPORMCache, WPORMCacheObjectNotFoundError
logger = logging.getLogger(__name__.split(".")[0]) # package name
status_values = ["publish", "future", "draft", "pending", "private"]
class Media(WPEntity):
def __init__(self, id=None, api=None):
super().__init__(api=api)
# related objects to cache
self._author = None
self._associated_post = None
def __repr__(self):
return "<WP {0} object at {1}, id={2}, type='{3}', file='{4}'>".format(self.__class__.__name__, hex(id(self)),
self.s.id,
self.s.mime_type,
os.path.basename(self.s.source_url))
@property
def schema_fields(self):
if self._schema_fields is None:
self._schema_fields = ["date", "date_gmt", "guid", "id", "link", "modified", "modified_gmt",
"slug", "status", "type", "title", "author", "comment_status",
"ping_status", "meta", "template", "alt_text", "caption", "description",
"media_type", "mime_type", "media_details", "post", "source_url"]
return self._schema_fields
@property
def post_fields(self):
'''
Arguments for Media POST requests.
'''
if self._post_fields is None:
# Note that 'date' is excluded in favor of exclusive use of 'date_gmt'.
self._post_fields = ["date_gmt", "slug", "status", "title", "author",
"comment_status", "ping_status", "meta", "template",
"alt_text", "caption", "description", "post"]
return self._post_fields
@property
def media_type(self):
'''
The media type, one of ["image", "file"].
'''
return self.s.media_type
@property
def author(self):
'''
Returns the author of this post, class: 'User'.
'''
# TODO: check cache first!
if self._author is None:
ur = self.api.UserRequest()
ur.id = self.s.author # ID for the author of the object
user_list = ur.get()
if len(user_list) == 1:
self._author = user_list[0]
else:
raise exc.UserNotFound("User ID '{0}' not found.".format(self.author))
return self._author
@property
def post(self):
'''
The post associated with this media item.
'''
# TODO check cache first
if self._associated_post is None:
pr = self.api.PostRequest()
pr.id = self.s.featured_media
posts = pr.get()
if len(media_list) == 1:
self._associated_post = posts[0]
else:
self._associated_post = None
return self._associated_post
class MediaRequest(WPRequest):
'''
A class that encapsulates requests for WordPress media items.
'''
def __init__(self, api=None):
super().__init__(api=api)
self.id = None # WordPress id
self.url = self.api.base_url + "media"
# parameters that undergo validation, i.e. need custom setter
# default values set here
self._context = None #"view"
self._page = None
self._per_page = None
@property
def parameter_names(self):
if self._parameter_names is None:
self._parameter_names = ["context", "page", "per_page", "search", "after", "author",
"author_exclude", "before", "exclude", "include", "offset",
"order", "orderby", "parent", "parent_exclude", "slug", "status",
"media_type", "mime_type"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
if self.page:
self.parameters["page"] = self.page
if self.per_page:
self.parameters["per_page"] = self.per_page
if self.search:
assert False, "Field 'search' not yet implemented."
if self.after:
assert False, "Field 'after' not yet implemented."
if self.author:
assert False, "Field 'author' not yet implemented."
if self.author_exclude:
assert False, "Field 'author_exclude' not yet implemented."
if self.before:
assert False, "Field 'before' not yet implemented."
if self.exclude:
assert False, "Field 'exclude' not yet implemented."
if self.include:
assert False, "Field 'include' not yet implemented."
if self.offset:
assert False, "Field 'offset' not yet implemented."
if self.order:
assert False, "Field 'order' not yet implemented."
if self.orderby:
assert False, "Field 'orderby' not yet implemented."
if self.parent:
assert False, "Field 'parent' not yet implemented."
if self.parent_exclude:
assert False, "Field 'parent_exclude' not yet implemented."
if self.slug:
self.parameters["slug"] = self.slug
if self.status:
assert False, "Field 'status' not yet implemented."
if self.media_type:
assert False, "Field 'media_type' not yet implemented."
if self.mime_type:
assert False, "Field 'mime_type' not yet implemented."
def get(self, class_object=Media, count=False, embed=True, links=True):
'''
Returns a list of 'Media' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
#if self.id:
# self.url += "/{}".format(self.id)
# logger.debug("URL='{}'".format(self.url))
self.populate_request_parameters()
try:
self.get_response(wpid=self.id)
logger.debug("URL='{}'".format(self.request.url))
except requests.exceptions.HTTPError:
logger.debug("HTTP error! media response code: {}".format(self.response.status_code))
if self.response.status_code == 404:
return None
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
#return len(pages_data)
media_data = self.response.json()
if isinstance(media_data, dict):
# only one object was returned; make it a list
media_data = [media_data]
media_objects = list()
for d in media_data:
# Before we continue, do we have this Media in the cache already?
try:
media = self.api.wordpress_object_cache.get(class_name=class_object.__name__, key=d["id"])
except WPORMCacheObjectNotFoundError:
media = class_object.__new__(class_object) # default = Media()
media.__init__(api=self.api)
media.json = json.dumps(d)
media.update_schema_from_dictionary(d)
if "_embedded" in d:
logger.debug("TODO: implement _embedded content for Media object")
# perform postprocessing for custom fields
media.postprocess_response(data=d)
# add to cache
self.api.wordpress_object_cache.set(value=media, keys=(media.s.id, media.s.slug))
finally:
media_objects.append(media)
return media_objects
@property
def context(self):
return self._context
@context.setter
def context(self, value):
if value is None:
self._context = None
else:
try:
value = value.lower()
if value in ["view", "embed", "edit"]:
self._context = value
return
except:
pass
raise ValueError ("'context' may only be one of ['view', 'embed', 'edit']")
@property
def page(self):
'''
Current page of the collection.
'''
return self._page
@page.setter
def page(self, value):
#
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._page = value
elif isinstance(value, str):
try:
self._page = int(value)
except ValueError:
raise ValueError("The 'page' parameter must be an integer, was given '{0}'".format(value))
@property
def per_page(self):
'''
Maximum number of items to be returned in result set.
'''
return self._per_page
@per_page.setter
def per_page(self, value):
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._per_page = value
elif isinstance(value, str):
try:
self._per_page = int(value)
except ValueError:
raise ValueError("The 'per_page' parameter must be an integer, was given '{0}'".format(value))
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,325 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/exc.py |
class WordPressORMException(Exception):
''' Base exception for this module. '''
pass
class NoEntityFound(WordPressORMException):
''' No WordPress entity was found. '''
pass
class MultipleEntitiesFound(WordPressORMException):
''' Multiple entities were returned when one was expected. '''
pass
class BadRequest(WordPressORMException):
''' Bad HTTP request (400). '''
pass
class AuthenticationRequired(WordPressORMException):
''' Authentication required for this request. '''
pass
class UserNotFound(WordPressORMException):
''' WordPress user not found. '''
pass
class MissingRequiredParameter(WordPressORMException):
''' A required parameter was missing. '''
pass
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,326 | demitri/wordpress_orm | refs/heads/master | /examples/example_1.py | #!/usr/bin/env python
import os
import sys
import json
from contextlib import contextmanager
import requests
import logging
sys.path.append('/Users/demitri/Documents/Repositories/GitHub/wordpress_orm')
import wordpress_orm as wp
from wordpress_orm import wp_session, exc
logger = logging.getLogger("wordpress_orm")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler() # output to console
ch.setLevel(logging.DEBUG) # set log level for output
logger.addHandler(ch) # add to logger
# WP API demo site: https://demo.wp-api.org/wp-json/
api = wp.API(url="http://brie6.cshl.edu/wordpress/index.php/wp-json/wp/v2/")
with wp_session(api):
pr = api.PostRequest()
# pr.arguments = {
# "orderby":"date",
# "order":"desc"
# }
pr.orderby = "date"
pr.order = "desc"
# pr.arguments["filter[category_name]"] = "blog"
posts = pr.get()
for post in posts:
print(post)
post = api.post(id=1)
print (post)
media = api.media(id=32)
print(media)
#user = api.user(id=1)
#print("{0}".format(user))
user = api.user(username="muna")
#user = api.user(slug="muna")
print(user)
for post in user.posts:
print(" {}".format(post.featured_media.s.source_url))
print (" ========== Categories =========== ")
#cr = api.CategoryRequest()
try:
slug = "dfszdfsa"
news_category = api.category(slug=slug)
print(news_category)
except exc.NoEntityFound:
print ("No category found with slug '{0}'.".format(slug))
category_names = [x.s.name for x in api.CategoryRequest().get()]
print ("Available categories: {0}".format(", ".join(category_names)))
print()
post = api.post(slug='the-bloomless-mutant-a-paragon-of-modern-sorghum-genetic-and-genomic-resources')
print(post)
raise Exception()
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,327 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/user.py | '''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/posts/
'''
import json
import logging
import requests
from .wordpress_entity import WPEntity, WPRequest, context_values
from ..cache import WPORMCacheObjectNotFoundError
from ..exc import AuthenticationRequired, MissingRequiredParameter
logger = logging.getLogger(__name__.split(".")[0]) # package name
class User(WPEntity):
def __init__(self, id=None, session=None, api=None, from_dictionary=None):
super().__init__(api=api)
# parameters that undergo validation, i.e. need custom setter
self._context = None
# cache related objects
self._posts = None
@property
def schema_fields(self):
if self._schema_fields is None:
# These are the default WordPress fields for the "user" object.
self._schema_fields = ["id", "username", "name", "first_name", "last_name", "email", "url",
"description", "link", "locale", "nickname", "slug", "registered_date",
"roles", "password", "capabilities", "extra_capabilities", "avatar_urls", "meta"]
return self._schema_fields
@property
def post_fields(self):
if self._post_fields is None:
self._post_fields = ["username", "name", "first_name", "last_name", "email", "url",
"description", "locale", "nickname", "slug", "roles", "password", "meta"]
return self._post_fields
def commit(self):
'''
Creates a new user or updates an existing user via the API.
'''
# is this a new user?
new_user = (self.s.id is None)
post_fields = ["username", "name", "first_name", "last_name", "email", "url",
"description", "locale", "nickname", "slug", "roles", "password", "meta"]
if new_user:
post_fields.append("id")
parameters = dict()
for field in post_fields:
if getattr(self.s, field) is not None:
parameters[field] = getattr(self.s, field)
# new user validation
if new_user:
required_fields = ["username", "email", "password"]
for field in required_fields:
if getattr(self.s, field) is None:
raise MissingRequiredParameter("The '{0}' field must be provided when creating a new user.".format(field))
response = self.api.session.post(url=self.url, params=parameters, auth=self.api.auth())
return response
@property
def posts(self):
if self._posts is None:
pr = self.api.PostRequest()
pr.author = self
self._posts = pr.get()
return self._posts
def __repr__(self):
return "<WP {0} object at {1}, id={2}, name='{3}'>".format(self.__class__.__name__, hex(id(self)), self.s.id, self.s.name)
def gravatar_url(self, size=200, rating='g', default_image_style="mm"):
'''
Returns a URL to the Gravatar image associated with the user's email address.
Ref: https://en.gravatar.com/site/implement/images/
size: int, can be anything from 1 to 2048 px
rating: str, maximum rating of the image, one of ['g', 'pg', 'r', 'x']
default_image: str, type of image if gravatar image doesn't exist, one of ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank']
'''
if rating not in ['g', 'pg', 'r', 'x']:
raise ValueError("The gravatar max rating must be one of ['g', 'pg', 'r', 'x'].")
if default_image_style not in ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank']:
raise ValueError("The gravatar default image style must be one of ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank'].")
if not isinstance(size, int):
try:
size = int(size)
except ValueError:
raise ValueError("The size parameter must be an integer value between 1 and 2048.")
if isinstance(size, int):
if 1 <= size <= 2048:
#
# self.s.avatar_urls is a dictionary with key=size and value=URL.
# Sizes are predetermined, but not documented. Values found were ['24', '48', '96'].
#
grav_urls_dict = self.s.avatar_urls
grav_url = grav_urls_dict[list(grav_urls_dict)[0]] # get any URL (we'll set our own size) / list(d) returns list of dictionary's keys
grav_url_base = grav_url.split("?")[0]
params = list()
params.append("d={0}".format(default_image_style)) # set default image to 'mystery man'
params.append("r={0}".format(rating)) # set max rating to 'g'
params.append("s={0}".format(size))
return "{0}?{1}".format(grav_url_base, "&".join(params))
else:
raise ValueError("The size parameter must be an integer.")
@property
def fullname(self):
return "{0} {1}".format(self.s.first_name, self.s.last_name)
class UserRequest(WPRequest):
'''
A class that encapsulates requests for WordPress users.
'''
def __init__(self, api=None):
super().__init__(api=api)
self.id = None # WordPress ID
self.url = self.api.base_url + 'users'
# values from headers
self.total = None
self.total_pages = None
self._page = None
self._per_page = None
self._offset = None
self._order = None
self._orderby = None
# parameters that undergo validation, i.e. need custom setter
self._includes = list()
self._slugs = list() # can accept more than one
self._roles = list()
@property
def parameter_names(self):
if self._parameter_names is None:
# parameter names defined by WordPress user query
self._parameter_names = ["context", "page", "per_page", "search", "exclude",
"include", "offset", "order", "orderby", "slug", "roles"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
if self.page:
self.parameters["page"] = self.page
if self.per_page:
self.parameters["per_page"] = self.per_page
if self.search:
self.parameters["search"] = self.search
# exclude : Ensure result set excludes specific IDs.
if self.search:
self.parameters["exclude"] = self.search
# include : Limit result set to specific IDs.
if len(self._includes) > 0:
self.parameters["include"] = ",".join.self.includes
# offset : Offset the result set by a specific number of items.
if self.offset:
self.parameters["offset"] = self.search
# order : Order sort attribute ascending or descending, default "asc", one of ["asc", "desc"]
if self.order:
self.parameters["order"] = self.order
# orderby : Sort collection by object attribute.
if self.orderby:
self.parameters["orderby"] = self.orderby
# slug : Limit result set to users with one or more specific slugs.
if len(self.slug) > 0:
self.parameters["slug"] = ",".join(self.slug)
# roles : Limit result set to users matching at least one specific role provided. Accepts csv list or single role.
if len(self.roles) > 0:
self.parameters["roles"] = ",".join(self.roles)
def get(self, class_object=User, count=False, embed=True, links=True):
'''
Returns a list of 'Tag' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
#if self.id:
# self.url += "/{}".format(self.id)
self.populate_request_parameters()
try:
self.get_response(wpid=self.id)
logger.debug("URL='{}'".format(self.request.url))
except requests.exceptions.HTTPError:
logger.debug("User response code: {}".format(self.response.status_code))
if 400 < self.response.status_code < 499:
if self.response.status_code in [401, 403]: # 401 = Unauthorized, 403 = Forbidden
data = self.response.json()
if data["code"] == 'rest_user_cannot_view':
# TODO: write more detailed message and propose solution
raise AuthenticationRequired("WordPress authentication is required for this operation. Response: {0}".format(data))
raise AuthenticationRequired("WordPress authentication is required for this operation. Response: {0}".format(data))
# elif self.response.status_code == 404:
# return None
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
users_data = self.response.json()
if isinstance(users_data, dict):
# only one object was returned; make it a list
users_data = [users_data]
users = list()
for d in users_data:
# Before we continue, do we have this User in the cache already?
try:
user = self.api.wordpress_object_cache.get(class_name=class_object.__name__, key=d["id"])
except WPORMCacheObjectNotFoundError:
user = class_object.__new__(class_object)
user.__init__(api=self.api)
user.json = json.dumps(d)
user.update_schema_from_dictionary(d)
if "_embedded" in d:
logger.debug("TODO: implement _embedded content for User object")
# perform postprocessing for custom fields
user.postprocess_response()
# add to cache
self.api.wordpress_object_cache.set(value=user, keys=(user.s.id, user.s.slug))
finally:
users.append(user)
return users
# ================================= query properties ==============================
@property
def context(self):
return self._context
@context.setter
def context(self, value):
if value is None:
self._context = None
return
else:
try:
value = value.lower()
if value in ["view", "embed", "edit"]:
self._context = value
return
except:
pass
raise ValueError ("'context' may only be one of ['view', 'embed', 'edit'] ('{0}' given)".format(value))
@property
def page(self):
'''
Current page of the collection.
'''
return self._page
@page.setter
def page(self, value):
#
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._page = value
elif isinstance(value, str):
try:
self._page = int(value)
except ValueError:
raise ValueError("The 'page' parameter must be an integer, was given '{0}'".format(value))
@property
def per_page(self):
'''
Maximum number of items to be returned in result set.
'''
return self._per_page
@per_page.setter
def per_page(self, value):
# only accept integers or strings that can become integers
#
if isinstance(value, int):
self._per_page = value
elif isinstance(value, str):
try:
self._per_page = int(value)
except ValueError:
raise ValueError("The 'per_page' parameter must be an integer, was given '{0}'".format(value))
@property
def include(self):
return self._includes
@include.setter
def include(self, values):
'''
Limit result set to specified WordPress user IDs, provided as a list.
'''
if values is None:
self.parameters.pop("include", None)
self._includes = list()
return
elif not isinstance(values, list):
raise ValueError("Includes must be provided as a list (or append to the existing list).")
for inc in values:
if isinstance(inc, int):
self._includes.append(str(inc))
elif isinstance(inc, str):
try:
self._includes.append(str(int(inc)))
except ValueError:
raise ValueError("The WordPress ID (an integer, '{0}' given) must be provided to limit result to specific users.".format(inc))
@property
def offset(self):
return self._offset
@offset.setter
def offset(self, value):
'''
Set value to offset the result set by the specified number of items.
'''
if value is None:
self.parameters.pop("offset", None)
self._offset = None
elif isinstance(value, int):
self._offset = value
elif isinstance(value, str):
try:
self._offset = str(int(str))
except ValueError:
raise ValueError("The 'offset' value should be an integer, was given: '{0}'.".format(value))
@property
def order(self):
return self._order;
#return self.api_params.get('order', None)
@order.setter
def order(self, value):
if value is None:
self.parameters.pop("order", None)
self._order = None
else:
order_values = ['asc', 'desc']
if isinstance(value, str):
value = value.lower()
if value not in order_values:
raise ValueError('The "order" parameter must be one '+\
'of these values: {}'.format(order_values))
else:
#self.api_params['order'] = value
self._order = value
else:
raise ValueError('The "order" parameter must be one of '+\
'these values: {} (or None).'.format(order_values))
return self._order
@property
def orderby(self):
return self._orderby #api_params.get('orderby', None)
@orderby.setter
def orderby(self, value):
if value is None:
self.parameters.pop("orderby", None)
self._orderby = None
else:
order_values = ['asc', 'desc']
if isinstance(value, str):
value = value.lower()
if value not in orderby_values:
raise ValueError('The "orderby" parameter must be one '+\
'of these values: {}'.format(orderby_values))
else:
#self.api_params['orderby'] = value
self._orderby = value
else:
raise ValueError('The "orderby" parameter must be one of these '+\
'values: {} (or None).'.format(orderby_values))
return self._orderby
@property
def slug(self):
return self._slugs
@slug.setter
def slug(self, value):
if value is None:
self._slugs = list()
elif isinstance(value, str):
self._slugs.append(value)
elif isinstance(value, list):
# validate data type
for v in value:
if not isinstance(v, str):
raise ValueError("slugs must be string type; found '{0}'".format(type(v)))
self._slugs = value
@property
def roles(self):
'''
User roles to be used in query.
'''
return self._roles
@roles.setter
def roles(self, values):
if values is None:
self.parameters.pop("roles", None)
self._roles = list()
return
elif not isinstance(values, list):
raise ValueError("Roles must be provided as a list (or append to the existing list).")
for role in values:
if isinstance(role, str):
self.roles.append(role)
else:
raise ValueError("Unexpected type for property list 'roles'; expected str, got '{0}'".format(type(s)))
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,328 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/__init__.py |
from .category import Category
from .comment import Comment
from .media import Media
from .page import Page
#from .post_revision import PostRevision
#from .post_status import PostStatus
#from .post_type import PostType
from .post import Post
#from .settings import Settings
from .tag import Tag
#from .taxonomy import Taxonomy
from .user import User
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,329 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/comment.py | '''
WordPress API reference: https://developer.wordpress.org/rest-api/reference/comments/
'''
import json
import logging
import requests
from .wordpress_entity import WPEntity, WPRequest, context_values
from .post import Post
from ..import exc
from ..cache import WPORMCacheObjectNotFoundError
logger = logging.getLogger(__name__.split(".")[0]) # package name
order_values = ["asc", "desc"]
orderby_values = ["date", "date_gmt", "id", "include", "post", "parent", "type"]
# -
class Comment(WPEntity):
def __init__(self, id=None, session=None, api=None):
super().__init__(api=api)
# cache related objects
self._author = None
def __repr__(self):
if len(self.s.content) < 11:
truncated_content = self.s.content
else:
truncated_content = self.s.content[0:10] + "..."
return "<WP {0} object at {1} content='{2}'>".format(self.__class__.__name__, hex(id(self)), truncated_content)
@property
def schema_fields(self):
if self._schema_fields is None:
self._schema_fields = ["id", "author", "author_email", "author_ip", "author_name",
"author_url", "author_user_agent", "content", "date",
"date_gmt", "link", "parent", "post", "status", "type",
"author_avatar_urls", "meta"]
return self._schema_fields
@property
def post_fields(self):
'''
Arguments for POST requests.
'''
if self._post_fields is None:
# Note that 'date' is excluded from the specification in favor of exclusive use of 'date_gmt'.
self._post_fields = ["author", "author_email", "author_ip", "author_name", "author_url",
"author_user_agent", "content", "date_gmt", "parent", "post", "status", "meta"]
return self._post_fields
def author(self):
'''
Return the WordPress User object that wrote this comment, if it was a WP User, None otherwise.
'''
if self._author is None:
ur = self.api.UserRequest()
ur.id = self.s.author # 'author' field is user ID
users = ur.get()
if len(users) > 0:
self._author = users[0]
else:
self._author = None
return self._author
class CommentRequest(WPRequest):
'''
A class that encapsulates requests for WordPress comments.
'''
def __init__(self, api=None, post=None):
super().__init__(api=api)
self.id = None # WordPress ID
self.url = self.api.base_url + "comments"
self._context = None
self._posts = list()
if post:
# initializer takes one; set the property manually to set several
self.posts = [post]
# parameters that undergo validation, i.e. need custom setter
#
# ...
@property
def parameter_names(self):
if self._parameter_names is None:
self._parameter_names = ["context ", "page", "per_page", "search", "after", "author",
"author_exclude", "author_email", "before", "exclude", "include",
"offset", "order", "orderby", "parent", "parent_exclude", "post",
"status", "type", "password"]
return self._parameter_names
def populate_request_parameters(self):
'''
Populates 'self.parameters' to prepare for executing a request.
'''
if self.context:
self.parameters["context"] = self.context
else:
self.parameters["context"] = "view" # default value
if self.password:
self.parameters["password"] = self.password
if len(self.posts) > 0:
logger.debug("Posts: {0}".format(self.posts))
self.parameters["post"] = ",".join(self.posts) # post ID
def get(self, class_object=Comment, count=False, embed=True, links=True):
'''
Returns a list of 'Comment' objects that match the parameters set in this object.
class_object : the class of the objects to instantiate based on the response, used when implementing custom subclasses
count : BOOL, return the number of entities matching this request, not the objects themselves
embed : BOOL, if True, embed details on linked resources (e.g. URLs) instead of just an ID in response to reduce number of HTTPS calls needed,
see: https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/#embedding
links : BOOL, if True, returns with response a map of links to other API resources
'''
super().get(class_object=class_object, count=count, embed=embed, links=links)
#if self.id:
# self.url += "/{}".format(self.id)
self.populate_request_parameters()
try:
logger.debug("URL='{}'".format(self.request.url))
self.get_response(wpid=self.id)
except requests.exceptions.HTTPError:
logger.debug("Post response code: {}".format(self.response.status_code))
if self.response.status_code == 400: # bad request
logger.debug("URL={}".format(self.response.url))
raise exc.BadRequest("400: Bad request. Error: \n{0}".format(json.dumps(self.response.json(), indent=4)))
elif self.response.status_code == 404: # not found
return None
raise Exception("Unhandled HTTP response, code {0}. Error: \n{1}\n".format(self.response.status_code, self.response.json()))
self.process_response_headers()
if count:
# return just the number of objects that match this request
if self.total is None:
raise Exception("Header 'X-WP-Total' was not found.") # if you are getting this, modify to use len(posts_data)
return self.total
#return len(pages_data)
comments_data = self.response.json()
if isinstance(comments_data, dict):
# only one object was returned, make it a list
comments_data = [comments_data]
comments = list()
for d in comments_data:
# Before we continue, do we have this Comment in the cache already?
try:
comment = self.api.wordpress_object_cache.get(class_name=class_object.__name__, key=d["id"])
except WPORMCacheObjectNotFoundError:
# create new object
comment = class_object.__new__(class_object) # default = Comment()
comment.__init__(api=self.api)
comment.json = json.dumps(d)
comment.update_schema_from_dictionary(d)
if "_embedded" in d:
logger.debug("TODO: implement _embedded content for Comment object")
# perform postprocessing for custom fields
comment.postprocess_response()
# add to cache
self.api.wordpress_object_cache.set(value=comment, keys=(comment.s.id, comment.s.slug))
finally:
comments.append(comment)
return comments
@property
def context(self):
if self._context is None:
self._context = None
return self._context
@context.setter
def context(self, value):
if value is None:
self._context = None
return
else:
try:
value = value.lower()
if value in ["view", "embed", "edit"]:
self._context = value
return
except:
pass
raise ValueError ("'context' may only be one of ['view', 'embed', 'edit']")
@property
def order(self):
return self._order;
#return self.api_params.get('order', None)
@order.setter
def order(self, value):
if value is None:
self._order = None
else:
if isinstance(value, str):
value = value.lower()
if value not in order_values:
raise ValueError('The "order" parameter must be one '+\
'of these values: {}'.format(order_values))
else:
#self.api_params['order'] = value
self._order = value
else:
raise ValueError('The "order" parameter must be one of '+\
'these values: {} (or None).'.format(order_values))
return self._order
@property
def orderby(self):
return self.api_params.get('orderby', None)
@orderby.setter
def orderby(self, value):
if value is None:
self._orderby = None
else:
if isinstance(value, str):
value = value.lower()
if value not in orderby_values:
raise ValueError('The "orderby" parameter must be one '+\
'of these values: {}'.format(orderby_values))
else:
#self.api_params['orderby'] = value
self._orderby = value
else:
raise ValueError('The "orderby" parameter must be one of these '+\
'values: {} (or None).'.format(orderby_values))
return self._orderby
@property
def posts(self):
'''
The list of posts (IDs) to retrieve the comments for.
'''
return self._posts
@posts.setter
def posts(self, values):
'''
Set the list of posts to retrieve comments for.
'''
# internally save the post ID.
if values is None:
self._posts = list()
return
elif not isinstance(values, list):
raise ValueError("Posts must be provided as a list (or append to the existing list).")
for p in values:
post_id = None
if isinstance(p, Post):
post_id = p.s.id
elif isinstance(p, int):
post_id = p
elif isinstance(p, str):
try:
post_id = int(p)
except ValueError:
raise ValueError("Posts must be provided as a list of (or append to the existing list). Accepts 'Post' objects or Post IDs.")
self._posts.append(str(post_id))
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,330 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/__init__.py |
name = "wordpress_orm"
from .api import API
import logging
from .api import wp_session
from .entities.wordpress_entity import WPEntity, WPRequest
from .cache import WPORMCacheObjectNotFoundError
logger = logging.getLogger(__name__.split(".")[0]) # package name
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,331 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/tests/conftest.py |
# This test configuration file is automatically called by pytest.
# Run this on the command line to see what fixtures are available:
#
# % py.test --fixtures
#
# To prevent STDOUT from being captured, add "--capture=no"
import pytest
from ..api import API
from requests.auth import HTTPBasicAuth
#
# Fixtures are pytest resources used for testing. Define fixtures here.
# At the very least, the application must be defined as a fixure named "app".
# A "client" fixture is defined by the pytest-flask extension.
#
# A test function can access a fixture when you provide the fixture name in
# the test function argument list, e.g. `def test_thing(app)`.
#
# Fixture scopes can be one of: "function" (default), "class", "module", "session".
# Ref: https://docs.pytest.org/en/latest/fixture.html#scope-sharing-a-fixture-instance-across-tests-in-a-class-module-or-session
#
# function - one fixture is created for each test function
# class - one fixture is created for each Python test class (if tests are defined that way)
# module - one fixture is created for each module (i.e. test_*py file)
# session - one fixture is reused over the entire test session over all tests
@pytest.fixture(scope="session") #, params=["dev", "production"])
def wp_api(request):
'''
Instance of the WordPress API object.
'''
# Read parameters from "request.param". If more than one
# parameter is provided, more than one fixture is created
# and the tests repeated with it.
# There is no need to iterate over the parameters in this code.
# Ref: https://docs.pytest.org/en/2.8.7/fixture.html#parametrizing-a-fixture
# if request.param == "wp_server_dev":
# return wordpress_orm.API(url= <WP dev URL>)
# elif request.param == "wp.server_prod":
# return wordpress_orm.API(url= <WP prod URL>)
wordpress = API()
wordpress.base_url = "http://brie6.cshl.edu/wordpress/index.php/wp-json/wp/v2/"
wordpress.authenticator = HTTPBasicAuth('', '')
return wordpress
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,332 | demitri/wordpress_orm | refs/heads/master | /wordpress_orm/entities/shared_properties.py |
# Many of the properties in several of the WordPress entities are the same,
# for example, "include", "exclude", "orderby", "order" in User and Post objects.
# The methods to perform validation are exactly the same in each. This file
# collects shared properties to enable the code be reused. There isn't enough
# overlap for subclassing to make sense in this case.
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,333 | demitri/wordpress_orm | refs/heads/master | /examples/POST API test.py | #!/usr/bin/env python
import os
import sys
import logging
import coloredlogs
from requests.auth import HTTPBasicAuth
sys.path.append('/Users/demitri/Documents/Repositories/GitHub/wordpress_orm')
import wordpress_orm as wp
from wordpress_orm import wp_session, exc
from wordpress_orm.entities import Post
# coloredlogs is configured with environment variables... weird
# define them here instead of from the shell
os.environ["COLOREDLOGS_LOG_FORMAT"] = "%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s"
logger = logging.getLogger("wordpress_orm")
logger.setLevel(logging.DEBUG)
use_color_logs = True
if use_color_logs:
coloredlogs.install(level=logging.DEBUG, logger=logger)
else:
ch = logging.StreamHandler() # output to console
ch.setLevel(logging.DEBUG) # set log level for output
logger.addHandler(ch) # add to logger
wordpress_api = wp.API(url="http://brie6.cshl.edu/wordpress/index.php/wp-json/wp/v2/")
wordpress_api.authenticator = HTTPBasicAuth(os.environ['SB_WP_USERNAME'], os.environ['SB_WP_PASSWORD'])
with wordpress_api.Session():
new_post = Post(api=wordpress_api)
logger.debug(new_post)
new_post.s.title = "API POST Test: New Post Title"
new_post.s.slug = "api-post-test-new-post-title"
new_post.s.content = "This is content for a new post."
new_post.s.excerpt = "This is the new post's excerpt, which appears to be required."
new_post.s.sticky = True
new_post.post()
| {"/wordpress_orm/entities/category.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/post_status.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/__init__.py"], "/wordpress_orm/entities/page.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/tests/test_users.py": ["/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/post.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/user.py", "/wordpress_orm/entities/category.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/entities/media.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/example_1.py": ["/wordpress_orm/__init__.py"], "/wordpress_orm/entities/user.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py", "/wordpress_orm/exc.py"], "/wordpress_orm/entities/__init__.py": ["/wordpress_orm/entities/category.py", "/wordpress_orm/entities/comment.py", "/wordpress_orm/entities/media.py", "/wordpress_orm/entities/page.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/entities/user.py"], "/wordpress_orm/entities/comment.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/entities/post.py", "/wordpress_orm/__init__.py", "/wordpress_orm/cache.py"], "/wordpress_orm/__init__.py": ["/wordpress_orm/entities/wordpress_entity.py", "/wordpress_orm/cache.py"], "/examples/POST API test.py": ["/wordpress_orm/__init__.py", "/wordpress_orm/entities/__init__.py"]} |
72,335 | pustoshilov-d/decision_theory | refs/heads/master | /HukJivs.py | import numpy as np
from math import *
class HukJivs(object):
def __init__(self, n, h, d, m, e, f):
self.f = f
self.result = []
self.n = n
self.m = m
self.e = e
self.H = np.array([h] * n)
self.d = d
self.X = np.array([0.0] * 3 * n).reshape(3, n)
self.X[0] = np.array([0.0]*n)
def explore(self):
for i in range(self.n):
self.X[1, i] = self.X[1, i] + self.H[i]
if self.f(self.X[1]) >= self.f(self.X[0]):
self.X[1, i] = self.X[1, i] - 2 * self.H[i]
if self.f(self.X[1]) >= self.f(self.X[0]):
self.X[1, i] = self.X[1, i] + self.H[i]
def match(self):
self.X[2] = self.X[1] + self.m * (self.X[1] - self.X[0])
def eval(self):
k =0
Ostanov = False
while not Ostanov:
self.X[1] = self.X[0]
self.explore()
#удачен ли исслед поиск
if self.f(self.X[1]) == self.f(self.X[0]):
self.H /= self.d
self.explore()
else:
self.match()
#удачен ли поиск по образцу
if self.f(self.X[2]) < self.f(self.X[1]):
if self.f(self.X[2]) < self.f(self.X[0]):
self.X[0] = self.X[2]
else: self.H /= self.d
else:
if self.f(self.X[1]) < self.f(self.X[0]):
self.X[0] = self.X[1]
else: self.H /= self.d
#условие окончания
Ostanov = True
for i in self.H:
if i > self.e: Ostanov = False
k += 1
self.result = self.X[1]
print(k)
if __name__ == '__main__':
from main import f
n = 2
h = 0.2
d = 2
m = 0.5
e = 0.1
my_HukJavis = HukJivs(n, h, d, m, e, f)
my_HukJavis.eval()
print(my_HukJavis.result, f(my_HukJavis.result)) | {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,336 | pustoshilov-d/decision_theory | refs/heads/master | /gradFastStep.py | import numpy as np
from math import *
# import warnings
# warnings.filterwarnings("ignore")
# [0.54326069 0.09303254] -0.2727042740156461
class gradFastStep(object):
def __init__(self, n, e, f):
self.f = f
self.result = np.array([]*n)
self.n = n
self.e = e
self.X = np.array([0.0] * n)
self.grad = np.array([0.0]*n)
self.Gesse = np.array([0.0]*n*n).reshape(n,n)
self.del_x = 0.000001
def change(self, i, del_x, j = None):
mass = np.array(self.X)
mass[i] += del_x
if j != None:
mass[j] += del_x
return mass
def evalGrad(self):
for i in range(self.n):
X_changed = self.change(i, self.del_x)
self.grad[i] = (self.f(X_changed) - self.f(self.X)) / self.del_x
def evalGesse(self):
for i in range(self.n):
for j in range(self.n):
if i == j:
u1 = self.f(self.change(i, self.del_x))
u2 = self.f(self.X)
u3 = self.f(self.change(i, -self.del_x))
self.Gesse[i,j] = (u1-2*u2+u3) / (self.del_x * self.del_x)
else:
u1 = self.f(self.X)
u2 = self.f(self.change(i, -self.del_x))
u3 = self.f(self.change(j, -self.del_x))
u4 = self.f(self.change(i, -self.del_x, j))
self.Gesse[i, j] = (u1 - u2 - u3 + u4) / (self.del_x * self.del_x)
def eval(self):
Ostanov = False
k = 0
while not Ostanov:
#непрерывна ли функция в этой точке
try:
f = self.f(self.X)
except Exception as err:
print(err)
break
#градиент
self.evalGrad()
self.evalGesse()
try:
self.h = np.dot(self.grad, self.grad) / np.dot(np.dot(self.Gesse, self.grad), self.grad)
except Exception as e: self.h = 1
if abs(self.h) == inf: self.h = 1
self.X += - self.h * self.grad
#остановка?
res = 0
self.evalGrad()
for i in self.grad:
res += i*i
Ostanov = sqrt(res) < self.e
k += 1
self.result = self.X
print(k)
if __name__ == '__main__':
from main import f
n = 2
e = 0.0001
my_gradFastStep = gradFastStep(n, e, f)
my_gradFastStep.eval()
print('res: ', my_gradFastStep.result, f(my_gradFastStep.result)) | {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,337 | pustoshilov-d/decision_theory | refs/heads/master | /NedleraMida.py | from math import *
import numpy as np
class NedleraMid:
def compress(self, n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f):
# сжатие
x_mirrowed = x_center + y * (self.X[k_x_high] - x_center)
# 10
if f(x_mirrowed) < f(self.X[k_x_high]):
# сжатие успешно
self.X[k_x_high] = x_mirrowed
else:
self.reduce(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
def expand(self, n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f):
# растяжение
x_mirrowed = x_center + b * (self.X[k_x_high] - x_center)
# 8
if f(x_mirrowed) > f(self.X[k_x_high]):
# растяжение успешно
self.X[k_x_high] = x_mirrowed
else:
# 9
if (F_low < f(x_mirrowed) and f(x_mirrowed) < F_high):
self.compress(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
else:
self.reduce(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
def reduce(self, n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f):
# 11 редукция
F_res = np.array([0.0] * n_1_axis)
for i in range(n_1_axis):
F_res[i] = f(self.X[i])
r_x_min = np.argmin(F_res)
for i in range(n):
if i != r_x_min:
self.X[i] = self.X[r_x_min] + 0.5 * (self.X[i] - self.X[r_x_min])
def eval(self, f,n,m,e,b,y):
# init
Ostanov = False
# X0 = np.array([0.0] * n)
X0 = np.array([-0.64, -2.26])
n_1_axis = n
n += 1
self.X = np.array([0.0] * n_1_axis * n).reshape(n, n_1_axis)
# заполнение числами
d1 = m * (sqrt(n_1_axis + 1) - 1) / (n_1_axis * sqrt(2))
d2 = m * (sqrt(n_1_axis + 1) + n_1_axis - 1) / (n_1_axis * sqrt(2))
k=0
self.X[0] = X0
for i in range(1, n):
for j in range(n_1_axis):
if (j + 1 == i):
self.X[i][j] = self.X[0][j] + d1
else:
self.X[i][j] = self.X[0][j] + d2
#Цикл до условия остановки
while not Ostanov:
#индекс максимального значени f
F_res = np.array([0.0]*n)
for i in range(n):
F_res[i] = f(self.X[i])
k_x_high = np.argmax(F_res)
F_high = F_res[k_x_high]
k_x_low = np.argmin(F_res)
F_low = F_res[k_x_low]
k_x_sec = np.argmax(np.delete(F_res,k_x_high,0))
F_sec = F_res[k_x_sec]
#центр тяжести
x_center = np.array([0.0]*n_1_axis)
for i in range(n):
if i != k_x_high:
x_center += self.X[i]
x_center /= n - 1
#отражение
x_mirrowed = 2 * x_center - self.X[k_x_high]
#6
if f(x_mirrowed) < f(self.X[k_x_high]):
#успешно отражение
self.X[k_x_high] = x_mirrowed
#7
if f(self.X[k_x_high]) < F_low:
self.expand(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
else:
#9
if (F_low < f(x_mirrowed) and f(x_mirrowed) < F_high):
self.compress(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
else:
self.reduce(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
# 9
else:
self.compress(n_1_axis, x_mirrowed, F_low, F_high, x_center, k_x_high, y, b, n, f)
#центр тяжести симлекса
x_center = np.array([0.0]*n_1_axis)
for i in range(n):
x_center += self.X[i]
x_center /= n
#критерий останова
sum = 0
for i in range(n):
sum += pow(f(self.X[i]) - f(x_center),2)
a = sqrt(sum/(n))
Ostanov = a < e
k+=1
#вывод мин решения
F_res = np.array([0.0]*n_1_axis)
for i in range(n_1_axis):
F_res[i] = f(self.X[i])
k_x_min = np.argmax(F_res)
print(k)
return(self.X[k_x_min])
def NedleraMida(f,n,m,e,b,y):
nedleraMida = NedleraMid()
return nedleraMida.eval(f,n,m,e,b,y)
if __name__ == '__main__':
from main import f
n = 2
m = 1.0
e = 0.1
b = 2.8
y = 0.4
print(NedleraMida(f,n,m,e,b,y), f(NedleraMida(f,n,m,e,b,y))) | {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,338 | pustoshilov-d/decision_theory | refs/heads/master | /main.py | from HukJivs import HukJivs
from Simplecs import Simplecs
from NedleraMida import NedleraMida
from gradPermStep import gradPermStep
from gradFastStep import gradFastStep
from gradPoKoor import gradPoKoor
from Fletcher import Fletcher
from Nutona import Nutona
from NutonRafson import NutonRafson
import time
import matplotlib.pyplot as pylab
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import warnings
warnings.filterwarnings("ignore")
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def f(X):
# return X[0]*X[0] + X[0]*X[1] + 3*X[1]*X[1] - X[0]
return X[0]*X[0] - X[0]*X[1] + 3*X[1]*X[1] - X[0] + 13*X[1] + 3
def makeChoice(choise):
n = 2
e = 0.01
if int(choise) == 0:
if n == 2:
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
Z = np.array([0.0]*len(X)*len(X)).reshape(len(X),len(X))
for i in range(len(X)):
for j in range(len(Y)):
Z[i,j] = f(np.array([X[i],Y[j]]))
X, Y = np.meshgrid(X, Y)
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
plt.show()
time_mass = np.array([0.0] * 9)
try:
for i in range(9):
begin_time = time.time()
makeChoice(i+1)
time_mass[i] = time.time()-begin_time
print('Time: ', time_mass[i])
except Exception as err: pass
pylab.plot(range(1,10), time_mass)
pylab.show()
if int(choise) == 1:
m = 0.25
print('1. Симплекс: X[] = ',Simplecs(f,n,m,e),', Y =', f(Simplecs(f,n,m,e)))
if int(choise) == 2:
m = 0.05
b = 2.8
y = 0.4
print('2. Нелдера-Мида: X[] = ',NedleraMida(f,n,m,e,b,y),', Y =', f(NedleraMida(f,n,m,e,b,y)))
if int(choise) == 3:
h = 0.2
d = 2
m = 0.5
my_HukJavis = HukJivs(n, h, d, m, e, f)
my_HukJavis.eval()
print('3. Хук-Дживис: X[] = ',my_HukJavis.result,', Y =', f(my_HukJavis.result))
if int(choise) == 4:
h = 0.4
my_gradPermStep = gradPermStep(n, h, e, f)
my_gradPermStep.eval()
print('4. Градиентного с постоянным шагом: X[] = ',my_gradPermStep.result,', Y =', f(my_gradPermStep.result))
if int(choise) == 5:
my_gradFastStep = gradFastStep(n, e, f)
my_gradFastStep.eval()
print('5. Градиент наискорейшего спуска: X[] = ',my_gradFastStep.result,', Y =', f(my_gradFastStep.result))
if int(choise) == 6:
my_gradPoKoor = gradPoKoor(n, e, f)
my_gradPoKoor.eval()
print('6. Градиент пкоординатного спуска: X[] = ',my_gradPoKoor.result,', Y =', f(my_gradPoKoor.result))
if int(choise) == 7:
n = 2
e = 0.0001
my_Fletcher = Fletcher(n, e, f)
my_Fletcher.eval()
print('7. Фетчера: X[] = ',my_Fletcher.result,', Y =', f(my_Fletcher.result))
if int(choise) == 8:
my_Nutona = Nutona(n, e, f)
my_Nutona.eval()
print('8. Ньютона: X[] = ',my_Nutona.result,', Y =', f(my_Nutona.result))
if int(choise) == 9:
my_NutonRafson = NutonRafson(n, e, f)
my_NutonRafson.eval()
print('9. Ньютона-Рафсона: X[] = ',my_NutonRafson.result,', Y =', f(my_NutonRafson.result))
if __name__ == '__main__':
while True:
print('\n0.Все\n'
'1. Симплекс\n'
'2. Нелдера-Мида\n'
'3. Хук-Дживис\n'
'4. Градиентного с постоянным шагом\n'
'5. Градиент наискорейшего спуска\n'
'6. Градиент пкоординатного спуска\n'
'7. Фетчера\n'
'8. Ньютона\n'
'9. Ньютона-Рафсона')
choise = input('Выберите номер метода: ')
makeChoice(choise)
| {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,339 | pustoshilov-d/decision_theory | refs/heads/master | /gradPermStep.py | import numpy as np
from math import *
class gradPermStep(object):
def __init__(self, n, h, e, f):
self.f = f
self.result = np.array([]*n)
self.n = n
self.e = e
self.h = h
self.X = np.array([0.0] * 3 * n).reshape(3, n)
self.X[0] = np.array([0.0]*n)
self.grad = np.array([0.0]*n)
def eval(self):
Ostanov = False
k = 0
while not Ostanov:
#непрерывна ли функция в этой точке
try:
f = self.f(self.X[0])
except Exception as err:
print(err)
break
#градиент
del_x = 0.0001
for i in range(self.n):
self.X[2] = self.X[0]
self.X[2,i] = self.X[2,i] + del_x
self.grad[i] = (self.f(self.X[2]) - f) / del_x
# шаг
self.X[1] = self.X[0] - self.h * self.grad
#уменьшение шага, пока не будет уменьшение функции
while not (self.f(self.X[1]) < self.f(self.X[0])):
self.h /= 2
self.X[1] = self.X[0] - self.h*self.grad
k += 1
self.X[0] = self.X[1]
#новый градиент
for i in range(self.n):
self.X[2] = self.X[0]
self.X[2,i] = self.X[2,i] + del_x
self.grad[i] = (self.f(self.X[2]) - f) / del_x
#остановка?
res = 0
for i in self.grad:
res += i*i
Ostanov = sqrt(res) < self.e
self.result = self.X[0]
print(k)
if __name__ == '__main__':
from main import f
n = 2
h = 0.4
e = 0.1
my_gradPermStep = gradPermStep(n, h, e, f)
my_gradPermStep.eval()
print('res: ', my_gradPermStep.result, f(my_gradPermStep.result)) | {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,340 | pustoshilov-d/decision_theory | refs/heads/master | /Simplecs.py | from math import *
import numpy as np
def Simplecs(f,n,m, e):
#init
Ostanov = False
X0 = np.array([-0.58,-2.17])
n_1_axis = n
n += 1
X = np.array([0.0]*n_1_axis*n).reshape(n,n_1_axis)
#заполнение числами
d1 = m * (sqrt(n_1_axis + 1) - 1) / (n_1_axis * sqrt(2))
d2 = m * (sqrt(n_1_axis + 1) + n_1_axis - 1) / (n_1_axis * sqrt(2))
k = 0
X[0] = X0
for i in range(1,n):
for j in range(n_1_axis):
if (j+1==i):
X[i][j] = X[0][j] + d1
else:
X[i][j] = X[0][j] + d2
#Цикл до условия остановки
while not Ostanov:
#индекс максимального значени f
F_res = np.array([0.0]*n)
for i in range(n):
F_res[i] = f(X[i])
k_x_max = np.argmax(F_res)
#центр тяжести
x_center = np.array([0.0]*n_1_axis)
for i in range(n):
if i != k_x_max:
x_center += X[i]
x_center /= n -1
#отражение
x_mirrowed = 2 * x_center - X[k_x_max]
if f(x_mirrowed) < f(X[k_x_max]):
X[k_x_max] = x_mirrowed
else:
#редукция
r_x_min = np.argmin(F_res)
for i in range(n):
if i !=r_x_min:
X[i] = X[r_x_min] + 0.5*(X[i] - X[r_x_min])
#центр тяжести симлекса
x_center = np.array([0.0]*n_1_axis)
for i in range(n):
x_center += X[i]
x_center /= n
Ostanov = True
#условие останова
for i in range(n):
if abs(f(X[i])-f(x_center)) >= e: Ostanov = False
k += 1
#вывод мин решения
F_res = np.array([0.0]*n)
for i in range(n):
F_res[i] = f(X[i])
k_x_min = np.argmax(F_res)
print(k)
return(X[k_x_min])
if __name__ == '__main__':
from main import f
n = 2
m = 0.25
e = 0.1
x = Simplecs(f,n,m,e)
print(x,f(x)) | {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,341 | pustoshilov-d/decision_theory | refs/heads/master | /test.py | import numpy as np
x = np.array([1,2,3,4])
print(x.shape[0])
| {"/HukJivs.py": ["/main.py"], "/gradFastStep.py": ["/main.py"], "/NedleraMida.py": ["/main.py"], "/main.py": ["/HukJivs.py", "/Simplecs.py", "/NedleraMida.py", "/gradPermStep.py", "/gradFastStep.py"], "/gradPermStep.py": ["/main.py"], "/Simplecs.py": ["/main.py"]} |
72,374 | LucasGMeneses/HunterOfRectangles | refs/heads/master | /game.py | from tkinter import Canvas
from gameObj import *
import random as rdm
FPS = 30
DELAY = 1000//FPS
time = 0
score = 0
stop = False
class Game(Canvas):
def __init__(self, mst):
super().__init__()
self.mst = mst
self["width"]= 800
self["height"]= 480
self["bg"]= '#000000'
mst.bind_all('<Key>', self.inputs) # key bind
mst.bind_all('<1>', self.inputs) # mouse button bind
self.rectangles = []
self.life = Life(self,180,10,400,25,3) # life bar
self.tic()
def tic(self): # game loop
if stop is False: # game running
self.update()
self.draw()
else: # GAME OVER
file = open('data.txt')
bestScore = int(file.read())
file.close()
if bestScore < score:
file = open('data.txt','w')
bestScore = score
file.write(str(score))
self.create_text(400,240,fill='snow',font=("Times", "24", "bold"), text='GAME OVER') # screen Game Over
self.create_text(400,270,fill='snow',font=("Times", "18", "normal"), text='Best Score: ' + str(bestScore)) # best score
self.create_text(400,290,fill='gray70',font=("Times", "18", "normal"),text='Press key Enter to restart game or press key Esc to quit')
self.after(DELAY, self.tic)
def draw(self): # draw loop
self.delete('all')
self.create_text(160,25,fill='snow', font=("Times", "13", "bold"), text='Life') #title life
self.create_text(700,25,fill='snow', font=("Times", "13", "bold"), text='Score: '+ str(score)) # score
self.life.draw()
for rect in self.rectangles: # draw rectangles
if rect.kill is False:
rect.draw()
def inputs(self, e):
global score
if e.num == 1: #click
for rect in self.rectangles:
if rect.is_colision(e) is True:
score +=1
rect.kill = True
if e.keysym == 'Escape': # quit game
self.mst.destroy()
if e.keysym == 'Return' and stop is True: # reset game
self.reset()
def update(self): # logic loop
global time,stop
flg = False
if time <= 0: # rectangles spwan
self.rectangles.append(Rect(self,0,32,32))
time = rdm.randrange(3,20)
time-=1
for rect in self.rectangles:
if rect.x <= 800:
rect.update()
else:
if rect.kill is False:
flg = True
else:
flg = False
if flg == True:
self.life.w -= 4
self.rectangles.pop(0)
flg = False
if self.life.w < 0:
self.life.w = 400
self.rectangles.clear()
stop = True
def reset(self): # reset game
global score,time,stop
score = 0
self.life.w = 400
stop = False
| {"/game.py": ["/gameObj.py"], "/main.py": ["/game.py"]} |
72,375 | LucasGMeneses/HunterOfRectangles | refs/heads/master | /main.py | import tkinter as tk
import game as gm
win = tk.Tk()
win.title('Hunter of Rectangles')
win.iconphoto(False, tk.PhotoImage(file='icon.png'))
win.resizable(False,False)
cnv = gm.Game(win)
cnv.pack()
win.mainloop() | {"/game.py": ["/gameObj.py"], "/main.py": ["/game.py"]} |
72,376 | LucasGMeneses/HunterOfRectangles | refs/heads/master | /gameObj.py | from color import COLORS
import random
class Life:
def __init__(self, cnv, x,y,w, h,spr):
self.cnv = cnv
self.x = x
self.y = y
self.w = w
self.h = h
self.spr = spr
def draw(self): # draw life
ax = self.x + self.w # position x2
ay = self.y + self.h # position y2
self.cnv.create_rectangle(self.x, self.y, ax, ay,fill="red") # fill bar
self.cnv.create_rectangle(self.x, self.y, self.x + 400, ay,outline='snow') # outline bar
class Rect:
def __init__(self, cnv, x, w, h):
self.cnv = cnv
self.x = x
self.y = random.randrange(35,480-h) # random position y
self.w = w
self.h = h
self.spr = random.randrange(len(COLORS)) # random color
self.kill = False
def draw(self): # draw rect
ax = self.x + self.w # position x2
ay = self.y + self.h # position y2
self.cnv.create_rectangle(self.x, self.y, ax, ay,fill=COLORS[self.spr])
def update(self): # logic rect
self.x+=5
def is_colision(self,obj): # check collision
ax = self.x + self.w # position x2
ay = self.y + self.h # position y2
if (obj.x >= self.x) and (obj.x <= ax) and (obj.y >= self.y) and (obj.y <= ay):
return True
else:
return False
| {"/game.py": ["/gameObj.py"], "/main.py": ["/game.py"]} |
72,377 | nickw444/NWPi | refs/heads/master | /UI/NWPi/UIButton.py |
# Main UIButton Class. Made for subclassing for other buttons
# Whole button is being drawn with code, no images in sight! Woo!
import pygame
from noticer import *
from constants import *
from UIView import *
class UIButton(UIView):
def __init__(self, dimensions, parent):
cont = constants()
UIView.__init__(self, dimensions, parent)
self.userText = ""
self.state = "up"
self.backgroundcolor = (96, 117, 146)
self.paint()
self.font = cont.defaultButtonFont # set the font, default is the default from constants
self.textOffset = (0, 0) # set the text offset, default there is none
def setBackgroundColor(self, color):
self.backgroundcolor = color # Set the background color for later painting referenc e
self.paint() # Paint the object again, this time with the new background
self.setText() # Re-add the text to the object (yes, paint removed the text :( )
def setText(self, text=False):
# This method basically adds text to the object's canvas. Simple really,
# Simply places it in the center of the button and renders it using the default font, unless specified in the init, or later
if text != False:
self.userText = text
font = self.font
text1 = font.render(self.userText, 1, (244, 244, 244))
text1pos = text1.get_rect()
text1pos.centerx = self.rect.width / 2 + self.textOffset[0]
text1pos.centery = self.rect.height / 2 + self.textOffset[1]
font2 = self.font
text2 = font2.render(self.userText, 1, (10, 10, 10))
text2pos = text2.get_rect()
text2pos.centerx = self.rect.width / 2 + self.textOffset[0]
text2pos.centery = self.rect.height / 2 + 1 + self.textOffset[1]
self.image.blit(text2, text2pos)
self.image.blit(text1, text1pos)
def paint(self):
self.image = pygame.Surface((self.rect.width, self.rect.height)) # Fix all the rectangles. Re-init the image
if self.state == "down": # Paint accordingly whether the mouse is inside or not.
bg = list(self.backgroundcolor)
sh = 40 # Shading scale up - Larger the number, the brighter the shaddow
d = 2 # Shading dithering value, the greater the number, the more dithered colours will be.
sh2 = [0,0,0]
self.image.fill((bg[0]/d + sh, bg[1]/d + sh, bg[2]/d + sh), ((1, 1), (self.rect.width - 2, self.rect.height - 2))) # paint the new shadow
else: # No shadow needed, paint accordingly, with inset shadow color.
bg = list(self.backgroundcolor)
self.image.fill(self.backgroundcolor, ((1, 1), (self.rect.width - 2, self.rect.height - 2)))
sh = 100
# Determine the colour of the inset shadow according to the color of the background. Will always have a nice top glow to it.
if (bg[0] + sh) > 255:
bg[0] = 255
else:
bg[0] += sh
if (bg[1] + sh) > 255:
bg[1] = 255
else:
bg[1] += sh
if (bg[2] + sh) > 255:
bg[2] = 255
else:
bg[2] += sh
print bg
self.image.fill((bg[0], bg[1], bg[2]), ((1, 1), (self.rect.width - 2, 1))) # Paint it to the canvas.
def manageEvent(self, event, caller, withinBounds=True):
# Subclass the UIView's manageEvent traverse function.
UIView.manageEvent(self, event, caller, withinBounds) # Allow the UIButton to still send events to lower objects by using UIView's definition. Also allows for custom callbacks
self.manageClickDown(withinBounds, event) # Also allow painting the up and down states for the UIButton (hence making it a button)
def manageClickDown(self, withinBounds, event):
# Manage the painting for up and down states
if withinBounds: # Check if within the button. - Within
if event.type == pygame.MOUSEBUTTONDOWN and self.state == "up": # See if the mouse has been pressed down ,and check the state of the button if it's already up/down to save on extra useless rendering
self.state = "down" # Set the state for later reference/caching
self.paint() # Re-paint the button
self.setText() # Add the text to the button
self.parent.updateView() # Update the parentView, which will traverse up the tree.
if event.type == pygame.MOUSEBUTTONUP and self.state == "down": # See if the button was pressed up, AND, it's state is already down - this needs a repaint to make it look like it's not pressed down
self.state = "up" # Set state for later reference/caching
self.paint() # Re-paint the button
self.setText(False) # add the text for the button
self.parent.updateView() # Update the parentView, which will traverse up the tree.
# print ("Setting state to: " + self.state) | {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,378 | nickw444/NWPi | refs/heads/master | /UI/firstAlternativeView.py |
import pygame
import NWPi
class firstAlternativeView(NWPi.viewController):
def customInitial(self):
self.constants = NWPi.constants()
text = NWPi.textObject("Layout One", False, True)
text.rect.centerx = self.canvas.get_rect().centerx
text.rect.y = 200
self.addSubView(text)
def backToHome(self, event, caller):
if event.type == pygame.MOUSEBUTTONUP:
caller.navigationController.makeKeyAndVisible("HOMEVIEWCONTROLLER")
homeButton = NWPi.fancyButton(self)
homeButton.setText("Go Home!")
homeButton.rect.centerx = self.canvas.get_rect().centerx
homeButton.rect.y = 450
homeButton.setCustomCallback(backToHome)
self.addSubView(homeButton, True)
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,379 | nickw444/NWPi | refs/heads/master | /UI/NWPi/spriteFromRect.py |
# Simple class to return a sprite from a rectangle that is sent to it.
import pygame
from noticer import *
from constants import *
class spriteFromRect(pygame.sprite.Sprite):
def __init__(self, dimensions): # initialise method
pygame.sprite.Sprite.__init__(self)
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,380 | nickw444/NWPi | refs/heads/master | /UI/instructionsViewController.py |
import pygame
import NWPi
class instructionsViewController(NWPi.viewController):
def customInitial(self):
def backToHome(self, event, caller, withinBounds):
if event.type == pygame.MOUSEBUTTONUP:
caller.navigationController.makeKeyAndVisible("HOMEVIEWCONTROLLER")
# Make a button to return home and assign the callback
homeButton = NWPi.UIButton((170, 40), self)
homeButton.setText("Awesome, I Understand")
homeButton.rect.centerx = self.canvas.get_rect().centerx
homeButton.rect.y = 450
homeButton.setCustomCallback(backToHome)
# Load the instructions in to a UIView from the instructions.png file.
instructions = NWPi.UIView((0,0), self)
instructions.setBackgroundImage("instructions.png")
instructions.rect.centerx = self.get_rect().width / 2
# Add all the views
self.addSubView(instructions)
self.addSubView(homeButton, True)
# Set BG color of the view
self.setBackgroundColor((236,236,236))
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,381 | nickw444/NWPi | refs/heads/master | /game.py |
import pygame # Import pygame
import UI # Import all the View Controllers we have custom defined
import UI.NWPi as NWPi # Import the NWPi Framework for local reference. (Nick's Awesome Framework)
import sys # Import the system library. We use this to quit the mainprogram
# Split up the events loop away from the main initialisation for easier reading.
def loop():
for event in pygame.event.get(): # Loop through each event in the pygame events buffer
# print("COCKS")
if event.type == pygame.QUIT: # Check if the event happens to be a quitting event.
sys.exit() # If it is, QUIT pygame.
elif (event.type == pygame.MOUSEBUTTONUP or event.type == pygame.MOUSEBUTTONDOWN): # or event.type == pygame.MOUSEMOTION
# Check if the event is a mousebuttonup/down. We /could/ check for mousemove, but we don't need it, nothing is hovering. Waste of resources
if (event.button != 5 and event.button != 4): # Make sure the button isn't the scrollwheel. Shit gets awkward if it was.
for object in topLevelObjects: # Loop through all RootViews (Should only be one, but it's expandable, hence using a list)
object.manageEvent(event) # On the object for the topLevel Loop, we send the event down to it, the ViewController will now manage the event from here
# elif (event.type == pygame.MOUSEMOTION):
# for object in topLevelObjects: # Loop through all RootViews (Should only be one, but it's expandable, hence using a list)
# object.manageEvent(event)
pygame.display.flip()
# ! Main Game
def main():
# The topLevelObjects is a list to store objects at the top level to listen for events.
# A typical use should only have the navigationViewController inside it as the subclasses manage events
global topLevelObjects # Allow for the topLevelObjects list to be used elsewhere
topLevelObjects = []
# Initialise screen and pyGame
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Set the window title
pygame.display.set_caption('Squares')
# initialisation of the navigation controller.
navigationViewController = NWPi.navigationController(screen) # Create a navigation view controller. Will parent all the Viewcontrollers
topLevelObjects.append(navigationViewController) # This will now be added to topLevelObjects so it can recieve events
# draw each viewController to the navigation controller
home = UI.homeViewController(navigationViewController) # Create a ViewController, from subclass homeViewController where all elements are already defined
navigationViewController.addSubView("HOMEVIEWCONTROLLER", home) # Add the ViewController to the navigation Controller. Do the same with the rest.
secondView = UI.instructionsViewController(navigationViewController)
navigationViewController.addSubView("INSTRUCTIONS", secondView)
gameView = UI.mainGameViewController(navigationViewController)
navigationViewController.addSubView("GAMEVIEW", gameView)
# We need to set a viewController to show as the top level. Choose it here:
navigationViewController.makeKeyAndVisible("INSTRUCTIONS") # Tell the navigation controller to set the view with the specified identifier to the top
# We need a loop to keep the script running. Defining it here
while True:
loop() # Run the loop() function we defined earlier.
if __name__ == '__main__': # Allow for use as a module in an upper class. Run the main loop if this IS the main program
main() # Run the main loop
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,382 | nickw444/NWPi | refs/heads/master | /UI/homeViewController.py |
import pygame
import NWPi
import sys
class homeViewController(NWPi.viewController):
def customInitial(self):
self.constants = NWPi.constants()
title = NWPi.textObject("squares", pygame.font.Font(self.constants.fancyFont, 70), True)
title.rect.centerx = self.canvas.get_rect().centerx
title.rect.y = 30
self.addSubView(title, False)
subtitle = NWPi.textObject("By Nick and Dylan", pygame.font.Font(self.constants.fancyFont, 25), True)
subtitle.rect.centerx = self.canvas.get_rect().centerx
subtitle.rect.y = 100
self.addSubView(subtitle, False)
def showViewOne(self, event, caller, withinBounds):
if event.type == pygame.MOUSEBUTTONUP:
caller.navigationController.makeKeyAndVisible("GAMEVIEW")
button = NWPi.fancyButton(self)
# Initialise a button, easy as pi
button.setText("Play Game")
# Put some text on that button
button.rect.centerx = self.canvas.get_rect().centerx
# Set the center position of the button
button.rect.y = 200
# Offset it from the top a bit
button.setCustomCallback(showViewOne)
# Add the callback to the object
self.addSubView(button, True)
# Add the object to the current View.
def showViewTwo(self, event, caller, withinBounds):
if event.type == pygame.MOUSEBUTTONUP:
caller.navigationController.makeKeyAndVisible("INSTRUCTIONS")
button2 = NWPi.fancyButton(self)
# Initialise a button, easy as pi
button2.setText("Instructions")
# Put some text on that button
button2.rect.centerx = self.canvas.get_rect().centerx
# Set the center position of the button
button2.rect.y = 300
# Offset it from the top a bit
button2.setCustomCallback(showViewTwo)
# button2.setBackgroundColor((160,128,128))
# Add the callback to the object
self.addSubView(button2, True)
# Add the object to the current View.
def quit(self, event, caller, withinBounds):
if event.type == pygame.MOUSEBUTTONUP:
sys.exit()
quitButton = NWPi.UIButton((60, 30), self)
# Initialise a button, easy as pi
quitButton.setText("Quit")
# Put some text on that button
quitButton.rect.x = 30
# Set the center position of the button
quitButton.rect.y = 550
# Offset it from the top a bit
quitButton.setCustomCallback(quit)
quitButton.setBackgroundColor((170,110, 110))
# button2.setBackgroundColor((160,128,128))
# Add the callback to the object
self.addSubView(quitButton, True)
# Add the object to the current View.
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,383 | nickw444/NWPi | refs/heads/master | /UI/NWPi/noticer.py |
# Global logging and error management method.
# Will be turning this on silent after final realease and only Fatal errors and errors will be shown in the console.
from time import strftime, localtime
def noticer(message, level=0, object=False, thread=0):
if level > 1: # Only log fatal errors and errors
f = open('log.txt', 'a')
if object == False:
object = "nil"
if level == 0:
output = ("[Notice][Thread " + str(thread) + "]: " + message + " on object: " + str(object))
elif level == 1:
output = ("[Warning][Thread " + str(thread) + "]: " + message + " on object: " + str(object))
elif level == 2:
output = ("[Error][Thread " + str(thread) + "]: " + message + " on object: " + str(object))
elif level == 3:
output = ("[Fatal Error][Thread " + str(thread) + "]: " + message + " on object: " + str(object))
now = strftime("%Y-%m-%d %H:%M:%S", localtime())
f.write("[" + now + "]" + output + "\n")
f.close()
print(output) | {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,384 | nickw444/NWPi | refs/heads/master | /UI/NWPi/fancyButton.py |
# FancyButton Subclass from UIButton
# Just a custom font, and some offset.
# Easy as Pi
from constants import *
from UIButton import *
class fancyButton(UIButton):
def __init__(self, parent):
UIButton.__init__(self, (160, 60), parent) # Initialise the UIButton
cont = constants() # Grab the constants
self.font = cont.fancyButtonFont # Change the font for this button which is defined in the constants
self.textOffset = (0, 5) # Add an offset because the stupid font is a dick
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,385 | nickw444/NWPi | refs/heads/master | /UI/NWPi/textObject.py |
# Basic class for creating text. Will take preferences from constants class.
from constants import *
class textObject():
def __init__(self, text="", font=False, shadowActive=False, color=(35, 35, 35), shadowColor=(255, 255, 255)):
cont = constants() # Grab the constants
if font == False: # check if the font is defined
font = cont.defaultFont # if font is undefined, go grab the font from the constants instead
if shadowActive: # check if the user wanted shadow
self.image = font.render(text, 1, shadowColor) # if they did, render the shadow first,
self.image.blit(font.render(text, 1, color), (0, -1)) # then render the text on top, -1 pixels on the y axis
else:
self.image = font.render(text, 1, color) # User didn't want shadow, simply render text
self.rect = self.image.get_rect() # set the objects rectangle for centering and placing on a viewController.
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,386 | nickw444/NWPi | refs/heads/master | /UI/mainGameViewController.py |
import pygame
import NWPi
import random
class mainGameViewController(NWPi.viewController):
def checkThreeInARow(self):
# MEthod to check if a winner is present.
self.updateTurnView()
winner = False
drawCounter = 0
i = 0
while i < len(self.squares):
i2 = 0
while i2 < len(self.squares[i]):
if self.squares[i][i2].taken:
if (self.squares[i][i2].occupiedBy == "PLAYER1" or self.squares[i][i2].occupiedBy == "PLAYER2"):
# Check on the horizontal plane
if (i2 + 1) < len(self.squares[i]):
if self.squares[i][i2 + 1].taken and (self.squares[i][i2 + 1].occupiedBy == self.squares[i][i2].occupiedBy):
if (i2 + 2) < len(self.squares[i]):
if self.squares[i][i2 + 2].taken and (self.squares[i][i2 + 2].occupiedBy == self.squares[i][i2].occupiedBy):
winner = self.squares[i][i2].occupiedBy
# Found a winnner, set the winner variable with the winner name
# # Check on the vertical plane
if (i + 1) < len(self.squares):
if self.squares[i + 1][i2].taken and (self.squares[i + 1][i2].occupiedBy == self.squares[i][i2].occupiedBy):
if (i + 2) < len(self.squares):
if self.squares[i + 2][i2].taken and (self.squares[i + 2][i2].occupiedBy == self.squares[i][i2].occupiedBy):
winner = self.squares[i][i2].occupiedBy
# Found a winnner, set the winner variable with the winner name
# Check on the diagonal down right plane
if ((i + 1) < len(self.squares)) and ((i2 + 1) < len(self.squares[i])):
if self.squares[i + 1][i2 + 1].taken and (self.squares[i + 1][i2 + 1].occupiedBy == self.squares[i][i2].occupiedBy):
if ((i + 2) < len(self.squares)) and ((i2 + 2) < len(self.squares[i])):
if self.squares[i + 2][i2 + 2].taken and (self.squares[i + 2][i2 + 2].occupiedBy == self.squares[i][i2].occupiedBy):
winner = self.squares[i][i2].occupiedBy
# Found a winnner, set the winner variable with the winner name
# Check on the diagonal down left plane.
if ((i + 1) < len(self.squares)) and ((i2 - 1) >= 0):
if self.squares[i + 1][i2 - 1].taken and (self.squares[i + 1][i2 - 1].occupiedBy == self.squares[i][i2].occupiedBy):
if ((i + 2) < len(self.squares)) and ((i2 - 2) >= 0):
if self.squares[i + 2][i2 - 2].taken and (self.squares[i + 2][i2 - 2].occupiedBy == self.squares[i][i2].occupiedBy):
winner = self.squares[i][i2].occupiedBy
# Found a winnner, set the winner variable with the winner name
drawCounter += 1
i2 +=1
i += 1
if winner != False:
# IF a winner was found, show a UIAlertView and display the winning message
bg = NWPi.UIView((self.get_rect().width, self.get_rect().height), self, (0,0,0))
bg.setOpacity(128)
alert = NWPi.UIAlertView((300, 90), self, (240,240,240), (2,2,2,2))
alert.bgDelegate = bg
alert.rect.centerx = self.get_rect().width/2
alert.rect.centery = self.get_rect().height/ 2 - 50
if winner == "PLAYER1":
alert.setText("Player 1 (Cross) Wins!")
elif winner == "PLAYER2":
alert.setText("Player 2 (Circle) Wins!")
self.addSubView(bg)
self.addSubView(alert)
# Make a callback on the UIView to be run on close - will reset the gameboard.
def action(self, event, caller, withinBounds):
if event.type == pygame.MOUSEBUTTONUP:
self.parent.parent.resetBoard()
alert.okayAction = action
# A Winner wasn't found, instead, it's a draw
if drawCounter >= len(self.squares) * len(self.squares[0]) and winner == False:
bg = NWPi.UIView((self.get_rect().width, self.get_rect().height), self, (0,0,0))
bg.setOpacity(128)
alert = NWPi.UIAlertView((300, 90), self, (240,240,240), (2,2,2,2))
alert.bgDelegate = bg
alert.rect.centerx = self.get_rect().width/2
alert.rect.centery = self.get_rect().height/ 2 - 50
alert.setText("It's a Draw! No one wins :(")
self.addSubView(bg)
self.addSubView(alert)
def action(self, event, caller, withinBounds):
if event.type == pygame.MOUSEBUTTONUP:
self.parent.parent.resetBoard()
alert.okayAction = action
def generateGameBoard(self, gameView):
# Game board generation method.
# Pretty simple once broken down.
# Set some intitial constants
rows = 6 # Set how many rows the gameboard should have
padd = 1 # Set how much padding should be between each sqaure
cols = 6 # Set how many columns there should be
viewWid = gameView.rect.width # shorten the variable name to the overall viewWidth
viewHeight = gameView.rect.height # ~~ same with the height
colwid = viewWid/cols # Determine how much width needs to be assigned to each columns depending on the width and the amount of columns
colheight = viewHeight/rows # ~~ similarly with the rows
gameView.colWd = colwid # allow global reference.
gameView.rowHt = colheight # ~~
d = 0 # Set an initial counter for the randomBlackSquares
randomBlackSqaures = [] # Set an empty list
while d < random.randint(rows * cols / 8, rows * cols / 2): # begin generating a random amout of black squares, depending on the size of the board.
col = random.randint(0, cols - 1) # Get a random column value
row = random.randint(0, rows - 1) # Get a random row value
randomBlackSqaures.append((col, row)) # add these to a tuple set for later reference and positioning of this black square
d += 1 # Increment the counter
d2 = 0 # Set an initial counter for the randomSquiggleSqaures
randomSquiggleSqaures = [] # Set an empty list
while d2 < random.randint(7,14): # Create a random amount of these, between 7 and 14
col = random.randint(0, cols - 1) # Get a random column value
row = random.randint(0, rows - 1) # get a ranodom row value
randomSquiggleSqaures.append((col, row)) # add the tuple set, along with positioning, etc
d2 += 1 # incremment the counter
# Defintiions for callbacks on the clicking of the squares when a user is to click down on a square.
def customCallback(self, event, caller, within):
if event.type == pygame.MOUSEBUTTONUP: # Ensure it's amouseup event
if self.taken == False: # Make sure it's not already taken
if within: # Yes, ensure the mouse is within.
self.taken = True # Set the objects taken value, so it cannot be changed again
if self.parent.parent.turn == "PLAYER1": # Check who's turn it is. Fill the square with the players counter accordingly. Pretty simple
subImageforsquare = NWPi.UIView((0,0), self, (0,0,0))
subImageforsquare.setBackgroundImage('cross.png')
self.parent.parent.turn = "PLAYER2"
self.occupiedBy = "PLAYER1" # Say that it is now taken by a PLAYER1 for use in the check three in a row method
else:
subImageforsquare = NWPi.UIView((0,0), self, (0,0,0))
subImageforsquare.setBackgroundImage('circle.png')
self.parent.parent.turn = "PLAYER1"
self.occupiedBy = "PLAYER2"
subImageforsquare.rect.centerx = caller.colWd / 2 # Position the players counter in the exact middle of the square
subImageforsquare.rect.centery = caller.rowHt / 2 # ~~~
self.addSubView(subImageforsquare) # Add the subImage/counter icon to the square for display to the user.
caller.updateView() # Update the gameView
self.parent.parent.checkThreeInARow() # Check if this new addition to the game board has made a three in a row.
def squiggleSqaureCallback(self, event, caller, within):
if event.type == pygame.MOUSEBUTTONUP: # Ensure it's a mouseup event
if self.taken == False: # And that the object isn't taken,
if within: # If, the mouse did click within the squiggle,
self.taken = True # Make it marked as taken so it cannot be overwritten again
self.occupiedBy = "SQUIGGLE" # Say that it is now taken by a squiggle for use in the check three in a row method
subImageforsquare = NWPi.UIView((50,50), self, (255,0,0)) # Make a subView ready for the squiggle image
subImageforsquare.setBackgroundImage('squiggle.png') # Load the squiggle image
subImageforsquare.rect.centerx = caller.colWd / 2 # Position the icon in the exact middle of the square
subImageforsquare.rect.centery = caller.rowHt / 2 # ~~
if self.parent.parent.turn == "PLAYER1": # Determine who's turn it is. Toggle the turns around, ensuring the player who clicked the square will miss their turn
self.parent.parent.turn = "PLAYER2"
elif self.parent.parent.turn == "PLAYER2":
self.parent.parent.turn = "PLAYER1"
self.addSubView(subImageforsquare) # Add the subView for the new square
self.parent.parent.checkThreeInARow() # Check if the three in a row has been made
caller.updateView() # Update all the views and stuff
# Some counter variables for the following loop
i = 0 # counter for the row
i2 = 0 # counter for the columns
self.squares = {}
coords = [0,0]
while i < rows:
self.squares[i] = {}
while i2 < cols:
self.squares[i][i2] = NWPi.UIView((colwid, colheight), gameView, (236, 236, 236))
self.squares[i][i2].rect.x, self.squares[i][i2].rect.y = coords
self.squares[i][i2].setCustomCallback(customCallback)
self.squares[i][i2].taken = False
self.squares[i][i2].occupiedBy = "NULL"
if (i, i2) in randomBlackSqaures:
subImageforsquare = NWPi.UIView((self.squares[i][i2].rect.width, self.squares[i][i2].rect.height), self, (50, 50, 50))
self.squares[i][i2].occupiedBy = "BLACKOUT"
self.squares[i][i2].taken = True
subImageforsquare.rect.centerx = gameView.colWd / 2
subImageforsquare.rect.centery = gameView.rowHt / 2
self.squares[i][i2].addSubView(subImageforsquare)
elif (i, i2) in randomSquiggleSqaures:
self.squares[i][i2].setCustomCallback(squiggleSqaureCallback)
subImageforsquare = NWPi.UIView((self.squares[i][i2].rect.width, self.squares[i][i2].rect.height), self, (236, 236, 236))
self.squares[i][i2].addSubView(subImageforsquare)
gameView.addSubView(self.squares[i][i2])
self.squares[i][i2].position = [i2, i]
i2 += 1
coords[0] += colwid + padd
i += 1
i2 = 0
coords[0] = 0
coords[1] += colheight + padd
self.updateView()
def resetBoard(self):
self.turn = "PLAYER1"
self.gameView.clearSubviews()
self.generateGameBoard(self.gameView)
self.updateTurnView()
def customInitial(self): # Custom initialization method for this UIViewController
self.turn = "PLAYER1" # Set the turn for the player. Ensure player1 moves first. This variable keeps track of who's turn it is.
self.setBackgroundColor((150,150,150)) # Set the background color of this view. (Simple i guess?)
# Define some button callbacks (explicitly the buttons to reset the board and to gohome/end game)
def goHome(self, event, caller, within):
if event.type == pygame.MOUSEBUTTONUP:
caller.parent.parent.resetBoard() # Reset the board, in case someone wants to come back and play later.
caller.parent.parent.navigationController.makeKeyAndVisible("HOMEVIEWCONTROLLER") # Navigate back to the homeViewcontroller
def resetBoard(self, event, caller, within):
if event.type == pygame.MOUSEBUTTONUP:
self.parent.parent.parent.turn = "PLAYER1" # Make it player 1's turn again
caller.parent.parent.resetBoard() # Reset the board, regenerate
leftColView = NWPi.UIView((220, self.canvas.get_rect().height), self, (233,233,233), (0,1,0,0)) # Initialize a view for the left column. Allows object nesting
topButtonBorderView = NWPi.UIView((leftColView.rect.width - 1, 90), leftColView, (220,220,220), (0,0,1,0), (160,160,160)) # Initialize a view to place some buttons in. Give it a border below it too.
# Lets draw some buttons.
# Create the backbutton
backButton = NWPi.UIButton((180,30), topButtonBorderView) # init a button, with parent "TopBorderView"
backButton.rect.centerx = topButtonBorderView.rect.width /2 # Set its x position
backButton.rect.y = 10 # Set its y position
backButton.setText("End Game") # Give it some text
backButton.actions = goHome # Assign the callback to the one we defined earlier
topButtonBorderView.addSubView(backButton) # Add it to the topButtonBorderView UIView we created just before.
# Create the reset button
resetButton = NWPi.UIButton((180,30), topButtonBorderView) # init a button, with parent "TopBorderView"
resetButton.rect.centerx = topButtonBorderView.rect.width / 2 # Set its x position
resetButton.rect.y = 50 # Set it's y position
resetButton.setBackgroundColor((170,110, 110)) # Give it a custom color.
resetButton.setText("Reset Game") # Set the text of the button
resetButton.actions = resetBoard # Set the callback method to the one we defined earlier
topButtonBorderView.addSubView(resetButton) # Add it to the topButtonBorderView UIView we created just before.
self.whoseTurnView = NWPi.UIView((leftColView.rect.width - 1, 120), leftColView, (233,233,233), (0,0,1,0), (160,160,160)) # initialize another UIView to show who's turn it is on the left bar
self.whoseTurnView.rect.y = 91 # Set coordinates
self.updateTurnView() # Update this who's turn view with the current persons turn information
leftColView.addSubView(self.whoseTurnView) # Add all of these to the parent classes
leftColView.addSubView(topButtonBorderView) # ~~ once again
self.addSubView(leftColView) # Add the left column to the gameControllerView
# Initialize the gameView UIView. Set it's coordinates, etc.
self.gameView = NWPi.UIView((self.canvas.get_rect().width - leftColView.rect.width, self.canvas.get_rect().height), self, (130, 130, 130))
self.gameView.rect.x = leftColView.rect.width
self.addSubView(self.gameView)
self.generateGameBoard(self.gameView) # Run the gameboard generation method. woo!
def updateTurnView(self):
self.whoseTurnView.clearSubviews() # Remove all objects already on the whosturnView, as we want a clean slate to draw onto
turnIcon = NWPi.UIView((0, 0), self.whoseTurnView, (236, 236, 236)) # Create an empty UIView to load the turnview onto
if self.turn == "PLAYER1": # Check who's turn it is, and set the background image corresponding. Easy as pi.
turnIcon.setBackgroundImage('cross.png')
turnIcon.rect.centerx = self.whoseTurnView.rect.width / 2
turnIcon.rect.y = 15
turnText = NWPi.textObject("Player 1 To Move") # Also set the text.
turnText.rect.centerx = self.whoseTurnView.rect.width / 2
turnText.rect.y = 85
elif self.turn == "PLAYER2":
turnIcon.setBackgroundImage('circle.png')
turnIcon.rect.centerx = self.whoseTurnView.rect.width / 2
turnIcon.rect.y = 15
turnText = NWPi.textObject("Player 2 To Move")
turnText.rect.centerx = self.whoseTurnView.rect.width / 2
turnText.rect.y = 85
self.whoseTurnView.addSubView(turnIcon) # Add all the subViews, and win.
self.whoseTurnView.addSubView(turnText)
self.whoseTurnView.updateView() # Finally, update the view so everything blits, and we're good to go :D
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,387 | nickw444/NWPi | refs/heads/master | /UI/NWPi/UIAlertView.py |
# UIAlertView Class, shows a simple and basic window to the user, and will disable any other views on the viewController whilst it is being shown.
# Strictly, this should only be used on a viewController subclass or superclass. Unexpected results may be present if used on a UIView (well, until I subclass ViewController from UIView)
# Objects of these class need a background deleagate class strictly defined. This is a simple UIView, added to the same UIViewController as self.
# This acts as a "faded out" backdrop for maximum user experience.
import pygame
from UIView import *
from UIButton import *
from textObject import *
class UIAlertView(UIView):
def customInitial(self):
# Define the callback to be run when the user clicks the "Okay" button on the window.
# This will allow a custom callback to be run, but will ALSO remove the UIView from the parent object.
def hideView(self, event, caller, withinBounds):
self.parent.okayAction(self,event, caller, withinBounds) # Run the custom callback
if event.type == pygame.MOUSEBUTTONUP: # Ensure this is the mouseup event
self.parent.parent.removeSubView(self.parent) # Remove this view from the parent
self.parent.parent.removeSubView(self.parent.bgDelegate) # We also need to remove the Background delegate from the parent
for view in self.parent.parent.subViews: # We now need to loop through the subViews of the controller, to set them back to visible
view.isVisible = True # Allow interaction of each subView again!
okayButton = UIButton((70,30), self) # Initialise a UIButton
okayButton.setText("Close") # Give the UIButton some text
okayButton.actions = hideView # Give the UIButton the callback - to hide the self object
okayButton.rect.x = self.rect.width - okayButton.rect.width - 10 # Position the UIButton at the bottom right
okayButton.rect.y = self.rect.height - okayButton.rect.height - 10
self.addSubView(okayButton) # Add the UIButton to the self Object
# Define the default handler for when the hideView method is called
def okay(self, event, caller, withinBounds):
pass # Do nothing, as this will be replaced
self.okayAction = okay # Tell the self object to run the function "okay" when the okay button is pressed
for view in self.parent.subViews: # Because we are showing a UIAlertView, it should be the only clickable object. loop through all of the controllers subviews
if view != self: # Check if the subview is this view.
view.isVisible = False # if it isn't, tell it that it is no longer visible, stopping user interaction with it.
# Basic definition to add text to the UIView. Simply subclasses the textObject class. Easy as pi.
def setText(self, text):
textobj = textObject(text)
textobj.rect.centerx = self.rect.width / 2
textobj.rect.y = 20
self.addSubView(textobj)
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,388 | nickw444/NWPi | refs/heads/master | /UI/NWPi/Images.py |
# Basic image handling functions. These can be called globally.
# Needed for easily importing images from the data folder.
import os # import OS for file paths
import pygame # import pygame for fonts, etc
from pygame.locals import * # get the pygame local variables
def load_image(name, colorkey=None):
fullname = os.path.join('data', name) # Grab the full file path of the images directory (data/file.png)
try:
image = pygame.image.load(fullname) # catch exceptions if the file isn't found
except pygame.error:
# print 'Cannot load image:', fullname
noticer("Cannot load image: " + str(fullname), 2) # Warn the user
# raise SystemExit, message
image = image.convert() # convert the image to a pygame surface object
if colorkey is not None: # check colour keying, allows pngs and other files to be imported
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
def load_image_without_rect(name, colorkey=None):
fullname = os.path.join('data', name) # Grab the full file path of the images directory (data/file.png)
try:
image = pygame.image.load(fullname) # catch exceptions if the file isn't found
except pygame.error:
noticer("Cannot load image: " + str(fullname), 2) # warn the user
image = image.convert()
if colorkey is not None: # convert the image to a pygame surface object
if colorkey is -1: # check colour keying, allows pngs and other files to be imported
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
72,389 | nickw444/NWPi | refs/heads/master | /UI/__init__.py |
# import NWPi
from homeViewController import *
from instructionsViewController import *
from firstAlternativeView import *
from mainGameViewController import *
# ! Definitions for separate view controllers
# Here we will define each view controller for later initialisation and use
# lets put a copyable template here:
# class controllerName(viewController):
# def customInitial(self):
| {"/game.py": ["/UI/__init__.py", "/UI/NWPi/__init__.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.