Add default base data dir for experiments

--- dj_experiment/conf.py
+++ dj_experiment/conf.py
@@ -1,9 +1,12 @@
+import os
+
 from appconf import AppConf
 from django.conf import settings

 class DjExperimentAppConf(AppConf):
     DATA_DIR = "./"
+    BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
     SEPARATOR = "."
     OUTPUT_PREFIX = ""
     OUTPUT_SUFFIX = ".nc"

<|original_code|>
from appconf import AppConf
from django.conf import settings

class DjExperimentAppConf(AppConf):
    DATA_DIR = "./"
    SEPARATOR = "."
    OUTPUT_PREFIX = ""
    OUTPUT_SUFFIX = ".nc"
    CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
    CELERY_RESULT_BACKEND = 'rpc://'

    class Meta:
        prefix = 'dj_experiment'
        holder = 'dj_experiment.conf.settings'

<|edits_diff|>
--- dj_experiment/conf.py
+++ dj_experiment/conf.py
@@ -1,3 +1,5 @@
+import os
+
 from appconf import AppConf
 from django.conf import settings

<|current_version|>
import os

from appconf import AppConf
from django.conf import settings

class DjExperimentAppConf(AppConf):
    DATA_DIR = "./"
    SEPARATOR = "."
    OUTPUT_PREFIX = ""
    OUTPUT_SUFFIX = ".nc"
    CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
    CELERY_RESULT_BACKEND = 'rpc://'

    class Meta:
        prefix = 'dj_experiment'
        holder = 'dj_experiment.conf.settings'

<|next_version|>
import os

from appconf import AppConf
from django.conf import settings

class DjExperimentAppConf(AppConf):
    DATA_DIR = "./"
    BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
    SEPARATOR = "."
    OUTPUT_PREFIX = ""
    OUTPUT_SUFFIX = ".nc"
    CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
    CELERY_RESULT_BACKEND = 'rpc://'

    class Meta:
        prefix = 'dj_experiment'
        holder = 'dj_experiment.conf.settings'


Add basic doc to Neural entities

doc: Add basic doc to Neural entities

--- neuroshare/NeuralEntity.py
+++ neuroshare/NeuralEntity.py
@@ -1,6 +1,10 @@
 from Entity import *

 class NeuralEntity(Entity):
+    """Entity the represents timestamps of action potentials, i.e. spike times.
+    Cutouts of the waveforms corresponding to spike data in a neural entity
+    might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
+    """
     def __init__(self, nsfile, eid, info):
         super(NeuralEntity,self).__init__(eid, nsfile, info)

@@ -10,6 +14,9 @@

     @property
     def source_entity_id(self):
+        """[**Optional**] Id of the source entity of this spike, if any.
+        For example the spike waveform of the action potential corresponding
+        to this spike might have been recoreded in a segment entity."""
 	return self._info['SourceEntityID']

     @property
@@ -17,6 +24,9 @@
         return self._info['SourceUnitID']

     def get_data (self, index=0, count=-1):
+        """Retrieve the spike times associated with this entity. A subset
+        of the data can be requested via the ``inde`` and ``count``
+        parameters."""
         lib = self.file.library
         if count < 0:
             count = self.item_count

<|original_code|>
from Entity import *

class NeuralEntity(Entity):
    def __init__(self, nsfile, eid, info):
        super(NeuralEntity,self).__init__(eid, nsfile, info)

    @property
    def probe_info(self):
        return self._info['ProbeInfo']

    @property
    def source_entity_id(self):
	return self._info['SourceEntityID']

    @property
    def source_unit_id(self):
        return self._info['SourceUnitID']

    def get_data (self, index=0, count=-1):
        lib = self.file.library
        if count < 0:
            count = self.item_count
        data = lib._get_neural_data (self, index, count)
        return data

<|edits_diff|>
--- neuroshare/NeuralEntity.py
+++ neuroshare/NeuralEntity.py
@@ -1,6 +1,10 @@
 from Entity import *

 class NeuralEntity(Entity):
+    """Entity the represents timestamps of action potentials, i.e. spike times.
+    Cutouts of the waveforms corresponding to spike data in a neural entity
+    might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
+    """
     def __init__(self, nsfile, eid, info):
         super(NeuralEntity,self).__init__(eid, nsfile, info)

@@ -10,6 +14,9 @@

     @property
     def source_entity_id(self):
+        """[**Optional**] Id of the source entity of this spike, if any.
+        For example the spike waveform of the action potential corresponding
+        to this spike might have been recoreded in a segment entity."""
 	return self._info['SourceEntityID']

     @property
<|current_version|>
from Entity import *

class NeuralEntity(Entity):
    """Entity the represents timestamps of action potentials, i.e. spike times.
    Cutouts of the waveforms corresponding to spike data in a neural entity
    might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
    """
    def __init__(self, nsfile, eid, info):
        super(NeuralEntity,self).__init__(eid, nsfile, info)

    @property
    def probe_info(self):
        return self._info['ProbeInfo']

    @property
    def source_entity_id(self):
        """[**Optional**] Id of the source entity of this spike, if any.
        For example the spike waveform of the action potential corresponding
        to this spike might have been recoreded in a segment entity."""
	return self._info['SourceEntityID']

    @property
    def source_unit_id(self):
        return self._info['SourceUnitID']

    def get_data (self, index=0, count=-1):
        lib = self.file.library
        if count < 0:
            count = self.item_count
        data = lib._get_neural_data (self, index, count)
        return data

<|next_version|>
from Entity import *

class NeuralEntity(Entity):
    """Entity the represents timestamps of action potentials, i.e. spike times.
    Cutouts of the waveforms corresponding to spike data in a neural entity
    might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
    """
    def __init__(self, nsfile, eid, info):
        super(NeuralEntity,self).__init__(eid, nsfile, info)

    @property
    def probe_info(self):
        return self._info['ProbeInfo']

    @property
    def source_entity_id(self):
        """[**Optional**] Id of the source entity of this spike, if any.
        For example the spike waveform of the action potential corresponding
        to this spike might have been recoreded in a segment entity."""
	return self._info['SourceEntityID']

    @property
    def source_unit_id(self):
        return self._info['SourceUnitID']

    def get_data (self, index=0, count=-1):
        """Retrieve the spike times associated with this entity. A subset
        of the data can be requested via the ``inde`` and ``count``
        parameters."""
        lib = self.file.library
        if count < 0:
            count = self.item_count
        data = lib._get_neural_data (self, index, count)
        return data


Add credit property to member REST API response

--- project/members/rest.py
+++ project/members/rest.py
@@ -18,8 +18,10 @@
     queryset = MembershipApplicationTag.objects.all()

 class MemberSerializer(serializers.HyperlinkedModelSerializer):
+    credit = serializers.CharField(read_only=True)
     class Meta:
         model = Member
+        fields = '__all__'

 class MemberViewSet(viewsets.ModelViewSet):
     serializer_class = MemberSerializer

<|original_code|>
from rest_framework import viewsets, serializers
from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication

class MemberTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MemberType

class MemberTypeViewSet(viewsets.ModelViewSet):
    serializer_class = MemberTypeSerializer
    queryset = MemberType.objects.all()

class MembershipApplicationTagSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MembershipApplicationTag

class MembershipApplicationTagViewSet(viewsets.ModelViewSet):
    serializer_class = MembershipApplicationTagSerializer
    queryset = MembershipApplicationTag.objects.all()

class MemberSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Member

class MemberViewSet(viewsets.ModelViewSet):
    serializer_class = MemberSerializer
    queryset = Member.objects.all()

class MembershipApplicationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MembershipApplication

class MembershipApplicationSerializerViewSet(viewsets.ModelViewSet):
    serializer_class = MembershipApplicationSerializer
    queryset = MembershipApplication.objects.all()

<|edits_diff|>
--- project/members/rest.py
+++ project/members/rest.py
@@ -18,6 +18,7 @@
     queryset = MembershipApplicationTag.objects.all()

 class MemberSerializer(serializers.HyperlinkedModelSerializer):
+    credit = serializers.CharField(read_only=True)
     class Meta:
         model = Member

<|current_version|>
from rest_framework import viewsets, serializers
from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication

class MemberTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MemberType

class MemberTypeViewSet(viewsets.ModelViewSet):
    serializer_class = MemberTypeSerializer
    queryset = MemberType.objects.all()

class MembershipApplicationTagSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MembershipApplicationTag

class MembershipApplicationTagViewSet(viewsets.ModelViewSet):
    serializer_class = MembershipApplicationTagSerializer
    queryset = MembershipApplicationTag.objects.all()

class MemberSerializer(serializers.HyperlinkedModelSerializer):
    credit = serializers.CharField(read_only=True)
    class Meta:
        model = Member

class MemberViewSet(viewsets.ModelViewSet):
    serializer_class = MemberSerializer
    queryset = Member.objects.all()

class MembershipApplicationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MembershipApplication

class MembershipApplicationSerializerViewSet(viewsets.ModelViewSet):
    serializer_class = MembershipApplicationSerializer
    queryset = MembershipApplication.objects.all()

<|next_version|>
from rest_framework import viewsets, serializers
from .models import MemberType, Member, MembershipApplicationTag, MembershipApplication

class MemberTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MemberType

class MemberTypeViewSet(viewsets.ModelViewSet):
    serializer_class = MemberTypeSerializer
    queryset = MemberType.objects.all()

class MembershipApplicationTagSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MembershipApplicationTag

class MembershipApplicationTagViewSet(viewsets.ModelViewSet):
    serializer_class = MembershipApplicationTagSerializer
    queryset = MembershipApplicationTag.objects.all()

class MemberSerializer(serializers.HyperlinkedModelSerializer):
    credit = serializers.CharField(read_only=True)
    class Meta:
        model = Member
        fields = '__all__'

class MemberViewSet(viewsets.ModelViewSet):
    serializer_class = MemberSerializer
    queryset = Member.objects.all()

class MembershipApplicationSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MembershipApplication

class MembershipApplicationSerializerViewSet(viewsets.ModelViewSet):
    serializer_class = MembershipApplicationSerializer
    queryset = MembershipApplication.objects.all()


Fix login permissions for ticketing

Fix login permissions for ticketing

--- ticketing/app.py
+++ ticketing/app.py
@@ -1,4 +1,5 @@
 from django.conf.urls.defaults import patterns, url
+from django.contrib.auth.decorators import login_required

 from oscar.core.application import Application

@@ -34,5 +35,8 @@
         )
         return self.post_process_urls(urlpatterns)

+    def get_url_decorator(self, url_name):
+        return login_required
+

 application = TicketingApplication()

<|original_code|>
from django.conf.urls.defaults import patterns, url

from oscar.core.application import Application

from ticketing import views

class TicketingApplication(Application):
    name = 'ticketing'

    ticket_list_view = views.TicketListView
    ticket_create_view = views.TicketCreateView
    ticket_update_view = views.TicketUpdateView

    def get_urls(self):
        urlpatterns = super(TicketingApplication, self).get_urls()

        urlpatterns += patterns('',
            url(
                r'accounts/support/$',
                self.ticket_list_view.as_view(),
                name='customer-ticket-list'
            ),
            url(
                r'accounts/support/ticket/create/$',
                self.ticket_create_view.as_view(),
                name='customer-ticket-create'
            ),
            url(
                r'accounts/support/ticket/(?P<pk>\d+)/update/$',
                self.ticket_update_view.as_view(),
                name='customer-ticket-update'
            ),
        )
        return self.post_process_urls(urlpatterns)

application = TicketingApplication()

<|edits_diff|>
--- ticketing/app.py
+++ ticketing/app.py
@@ -1,4 +1,5 @@
 from django.conf.urls.defaults import patterns, url
+from django.contrib.auth.decorators import login_required

 from oscar.core.application import Application

<|current_version|>
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from oscar.core.application import Application

from ticketing import views

class TicketingApplication(Application):
    name = 'ticketing'

    ticket_list_view = views.TicketListView
    ticket_create_view = views.TicketCreateView
    ticket_update_view = views.TicketUpdateView

    def get_urls(self):
        urlpatterns = super(TicketingApplication, self).get_urls()

        urlpatterns += patterns('',
            url(
                r'accounts/support/$',
                self.ticket_list_view.as_view(),
                name='customer-ticket-list'
            ),
            url(
                r'accounts/support/ticket/create/$',
                self.ticket_create_view.as_view(),
                name='customer-ticket-create'
            ),
            url(
                r'accounts/support/ticket/(?P<pk>\d+)/update/$',
                self.ticket_update_view.as_view(),
                name='customer-ticket-update'
            ),
        )
        return self.post_process_urls(urlpatterns)

application = TicketingApplication()

<|next_version|>
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.decorators import login_required

from oscar.core.application import Application

from ticketing import views

class TicketingApplication(Application):
    name = 'ticketing'

    ticket_list_view = views.TicketListView
    ticket_create_view = views.TicketCreateView
    ticket_update_view = views.TicketUpdateView

    def get_urls(self):
        urlpatterns = super(TicketingApplication, self).get_urls()

        urlpatterns += patterns('',
            url(
                r'accounts/support/$',
                self.ticket_list_view.as_view(),
                name='customer-ticket-list'
            ),
            url(
                r'accounts/support/ticket/create/$',
                self.ticket_create_view.as_view(),
                name='customer-ticket-create'
            ),
            url(
                r'accounts/support/ticket/(?P<pk>\d+)/update/$',
                self.ticket_update_view.as_view(),
                name='customer-ticket-update'
            ),
        )
        return self.post_process_urls(urlpatterns)

    def get_url_decorator(self, url_name):
        return login_required

application = TicketingApplication()


Add `id` to `SystemHealthEndpoint` response.

--- src/sentry/api/endpoints/system_health.py
+++ src/sentry/api/endpoints/system_health.py
@@ -1,6 +1,7 @@
 from __future__ import absolute_import

 import itertools
+from hashlib import md5

 from rest_framework.response import Response

@@ -17,6 +18,7 @@
         return Response({
             'problems': map(
                 lambda problem: {
+                    'id': md5(problem.message).hexdigest(),
                     'message': problem.message,
                     'severity': problem.severity,
                     'url': problem.url,

<|original_code|>
from __future__ import absolute_import

import itertools

from rest_framework.response import Response

from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission

class SystemHealthEndpoint(Endpoint):
    permission_classes = (SuperuserPermission,)

    def get(self, request):
        results = status_checks.check_all()
        return Response({
            'problems': map(
                lambda problem: {
                    'message': problem.message,
                    'severity': problem.severity,
                    'url': problem.url,
                },
                sorted(itertools.chain.from_iterable(results.values()), reverse=True),
            ),
            'healthy': {type(check).__name__: not problems for check, problems in results.items()},
        })

<|edits_diff|>
--- src/sentry/api/endpoints/system_health.py
+++ src/sentry/api/endpoints/system_health.py
@@ -1,6 +1,7 @@
 from __future__ import absolute_import

 import itertools
+from hashlib import md5

 from rest_framework.response import Response

<|current_version|>
from __future__ import absolute_import

import itertools
from hashlib import md5

from rest_framework.response import Response

from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission

class SystemHealthEndpoint(Endpoint):
    permission_classes = (SuperuserPermission,)

    def get(self, request):
        results = status_checks.check_all()
        return Response({
            'problems': map(
                lambda problem: {
                    'message': problem.message,
                    'severity': problem.severity,
                    'url': problem.url,
                },
                sorted(itertools.chain.from_iterable(results.values()), reverse=True),
            ),
            'healthy': {type(check).__name__: not problems for check, problems in results.items()},
        })

<|next_version|>
from __future__ import absolute_import

import itertools
from hashlib import md5

from rest_framework.response import Response

from sentry import status_checks
from sentry.api.base import Endpoint
from sentry.api.permissions import SuperuserPermission

class SystemHealthEndpoint(Endpoint):
    permission_classes = (SuperuserPermission,)

    def get(self, request):
        results = status_checks.check_all()
        return Response({
            'problems': map(
                lambda problem: {
                    'id': md5(problem.message).hexdigest(),
                    'message': problem.message,
                    'severity': problem.severity,
                    'url': problem.url,
                },
                sorted(itertools.chain.from_iterable(results.values()), reverse=True),
            ),
            'healthy': {type(check).__name__: not problems for check, problems in results.items()},
        })


Add index for image metainformation

Add index for image metainformation

--- dvhb_hybrid/files/models.py
+++ dvhb_hybrid/files/models.py
@@ -2,6 +2,7 @@

 from django.conf import settings
 from django.contrib.postgres.fields import JSONField
+from django.contrib.postgres.indexes import GinIndex
 from django.db import models
 from django.utils.translation import ugettext_lazy as _

@@ -22,6 +23,7 @@
         verbose_name = _('image')
         verbose_name_plural = _('images')
         ordering = ('-created_at',)
+        indexes = [GinIndex(fields=['meta'])]

     def __str__(self):
         return self.image.name

<|original_code|>
import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.translation import ugettext_lazy as _

from ..models import UpdatedMixin
from .storages import image_storage

class Image(UpdatedMixin, models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='images',
        verbose_name=_('Author'), on_delete=models.PROTECT)
    uuid = models.UUIDField(_('UUID'), primary_key=True)
    image = models.ImageField(storage=image_storage)
    mime_type = models.CharField(_('content type'), max_length=99, blank=True)
    meta = JSONField(_('meta-information'), default={}, blank=True)

    class Meta:
        verbose_name = _('image')
        verbose_name_plural = _('images')
        ordering = ('-created_at',)

    def __str__(self):
        return self.image.name

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if not self.uuid:
            uid = uuid.uuid4()
            self.uuid = uid
            self.image.name = image_storage.get_available_name(
                self.image.name, uuid=uid)

        super(Image, self).save(force_insert=force_insert,
                                force_update=force_update,
                                using=using,
                                update_fields=update_fields)

<|edits_diff|>
--- dvhb_hybrid/files/models.py
+++ dvhb_hybrid/files/models.py
@@ -2,6 +2,7 @@

 from django.conf import settings
 from django.contrib.postgres.fields import JSONField
+from django.contrib.postgres.indexes import GinIndex
 from django.db import models
 from django.utils.translation import ugettext_lazy as _

<|current_version|>
import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _

from ..models import UpdatedMixin
from .storages import image_storage

class Image(UpdatedMixin, models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='images',
        verbose_name=_('Author'), on_delete=models.PROTECT)
    uuid = models.UUIDField(_('UUID'), primary_key=True)
    image = models.ImageField(storage=image_storage)
    mime_type = models.CharField(_('content type'), max_length=99, blank=True)
    meta = JSONField(_('meta-information'), default={}, blank=True)

    class Meta:
        verbose_name = _('image')
        verbose_name_plural = _('images')
        ordering = ('-created_at',)

    def __str__(self):
        return self.image.name

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if not self.uuid:
            uid = uuid.uuid4()
            self.uuid = uid
            self.image.name = image_storage.get_available_name(
                self.image.name, uuid=uid)

        super(Image, self).save(force_insert=force_insert,
                                force_update=force_update,
                                using=using,
                                update_fields=update_fields)

<|next_version|>
import uuid

from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils.translation import ugettext_lazy as _

from ..models import UpdatedMixin
from .storages import image_storage

class Image(UpdatedMixin, models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='images',
        verbose_name=_('Author'), on_delete=models.PROTECT)
    uuid = models.UUIDField(_('UUID'), primary_key=True)
    image = models.ImageField(storage=image_storage)
    mime_type = models.CharField(_('content type'), max_length=99, blank=True)
    meta = JSONField(_('meta-information'), default={}, blank=True)

    class Meta:
        verbose_name = _('image')
        verbose_name_plural = _('images')
        ordering = ('-created_at',)
        indexes = [GinIndex(fields=['meta'])]

    def __str__(self):
        return self.image.name

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if not self.uuid:
            uid = uuid.uuid4()
            self.uuid = uid
            self.image.name = image_storage.get_available_name(
                self.image.name, uuid=uid)

        super(Image, self).save(force_insert=force_insert,
                                force_update=force_update,
                                using=using,
                                update_fields=update_fields)


Add pupular RC objects to index view.

Add pupular RC objects to index view.

Earlier they was at context processor.

--- real_estate_agency/real_estate_agency/views.py
+++ real_estate_agency/real_estate_agency/views.py
@@ -15,9 +15,12 @@
     feedbacks = Feedback.objects.all()[:4].prefetch_related(
         'bought').prefetch_related(
         'bought__type_of_complex').prefetch_related('social_media_links')
+    residental_complexes = ResidentalComplex.objects.filter(
+        is_popular=True)
     context = {
         'feedbacks': feedbacks,
         'form': SearchForm,
+        'residental_complexes': residental_complexes,
     }
     return render(request,
                   'index.html',

<|original_code|>
from django.shortcuts import render, render_to_response
from django.template import RequestContext

from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback

def corporation_benefit_plan(request):
    return render(request, 'corporation_benefit_plan.html')

def index(request):
    # Only 4 requests to DB
    feedbacks = Feedback.objects.all()[:4].prefetch_related(
        'bought').prefetch_related(
        'bought__type_of_complex').prefetch_related('social_media_links')
    context = {
        'feedbacks': feedbacks,
        'form': SearchForm,
    }
    return render(request,
                  'index.html',
                  context,
                  )

def privacy_policy(request):
    return render(request, 'privacy_policy.html')

def thanks(request):
    return render(request, 'thanks.html')

<|edits_diff|>
--- real_estate_agency/real_estate_agency/views.py
+++ real_estate_agency/real_estate_agency/views.py
@@ -15,6 +15,8 @@
     feedbacks = Feedback.objects.all()[:4].prefetch_related(
         'bought').prefetch_related(
         'bought__type_of_complex').prefetch_related('social_media_links')
+    residental_complexes = ResidentalComplex.objects.filter(
+        is_popular=True)
     context = {
         'feedbacks': feedbacks,
         'form': SearchForm,
<|current_version|>
from django.shortcuts import render, render_to_response
from django.template import RequestContext

from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback

def corporation_benefit_plan(request):
    return render(request, 'corporation_benefit_plan.html')

def index(request):
    # Only 4 requests to DB
    feedbacks = Feedback.objects.all()[:4].prefetch_related(
        'bought').prefetch_related(
        'bought__type_of_complex').prefetch_related('social_media_links')
    residental_complexes = ResidentalComplex.objects.filter(
        is_popular=True)
    context = {
        'feedbacks': feedbacks,
        'form': SearchForm,
    }
    return render(request,
                  'index.html',
                  context,
                  )

def privacy_policy(request):
    return render(request, 'privacy_policy.html')

def thanks(request):
    return render(request, 'thanks.html')

<|next_version|>
from django.shortcuts import render, render_to_response
from django.template import RequestContext

from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback

def corporation_benefit_plan(request):
    return render(request, 'corporation_benefit_plan.html')

def index(request):
    # Only 4 requests to DB
    feedbacks = Feedback.objects.all()[:4].prefetch_related(
        'bought').prefetch_related(
        'bought__type_of_complex').prefetch_related('social_media_links')
    residental_complexes = ResidentalComplex.objects.filter(
        is_popular=True)
    context = {
        'feedbacks': feedbacks,
        'form': SearchForm,
        'residental_complexes': residental_complexes,
    }
    return render(request,
                  'index.html',
                  context,
                  )

def privacy_policy(request):
    return render(request, 'privacy_policy.html')

def thanks(request):
    return render(request, 'thanks.html')


Add url for static files

Add url for static files [development]

--- delphi/urls.py
+++ delphi/urls.py
@@ -12,9 +12,14 @@
 Including another URLconf
     1. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
 """
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 from django.conf.urls import include, url
 from django.contrib import admin

 urlpatterns = [
     url(r'^admin/', include(admin.site.urls)),
 ]
+
+#serving static
+urlpatterns += staticfiles_urlpatterns()
+

<|original_code|>
"""delphi URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

<|edits_diff|>
--- delphi/urls.py
+++ delphi/urls.py
@@ -12,6 +12,7 @@
 Including another URLconf
     1. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
 """
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns
 from django.conf.urls import include, url
 from django.contrib import admin

<|current_version|>
"""delphi URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

<|next_version|>
"""delphi URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

#serving static
urlpatterns += staticfiles_urlpatterns()


Modify to avoid excessive logger initialization

--- simplesqlite/_logger.py
+++ simplesqlite/_logger.py
@@ -7,7 +7,9 @@
 from __future__ import absolute_import
 from __future__ import unicode_literals

+import dataproperty
 import logbook
+import pytablereader

 logger = logbook.Logger("SimpleSQLie")
@@ -15,10 +17,16 @@

 def set_logger(is_enable):
+    if is_enable != logger.disabled:
+        return
+
     if is_enable:
         logger.enable()
     else:
         logger.disable()
+
+    dataproperty.set_logger(is_enable)
+    pytablereader.set_logger(is_enable)

 def set_log_level(log_level):
@@ -32,8 +40,14 @@
         Disabled logging if ``log_level`` is ``logbook.NOTSET``.
     """

+    if log_level == logger.level:
+        return
+
     if log_level == logbook.NOTSET:
         set_logger(is_enable=False)
     else:
         set_logger(is_enable=True)
         logger.level = log_level
+
+    dataproperty.set_log_level(log_level)
+    pytablereader.set_log_level(log_level)

<|original_code|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
from __future__ import unicode_literals

import logbook

logger = logbook.Logger("SimpleSQLie")
logger.disable()

def set_logger(is_enable):
    if is_enable:
        logger.enable()
    else:
        logger.disable()

def set_log_level(log_level):
    """
    Set logging level of this module. Using
    `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging.

    :param int log_level:
        One of the log level of
        `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__.
        Disabled logging if ``log_level`` is ``logbook.NOTSET``.
    """

    if log_level == logbook.NOTSET:
        set_logger(is_enable=False)
    else:
        set_logger(is_enable=True)
        logger.level = log_level

<|edits_diff|>
--- simplesqlite/_logger.py
+++ simplesqlite/_logger.py
@@ -7,7 +7,9 @@
 from __future__ import absolute_import
 from __future__ import unicode_literals

+import dataproperty
 import logbook
+import pytablereader

 logger = logbook.Logger("SimpleSQLie")
@@ -15,10 +17,16 @@

 def set_logger(is_enable):
+    if is_enable != logger.disabled:
+        return
+
     if is_enable:
         logger.enable()
     else:
         logger.disable()
+
+    dataproperty.set_logger(is_enable)
+    pytablereader.set_logger(is_enable)

 def set_log_level(log_level):
@@ -32,6 +40,9 @@
         Disabled logging if ``log_level`` is ``logbook.NOTSET``.
     """

+    if log_level == logger.level:
+        return
+
     if log_level == logbook.NOTSET:
         set_logger(is_enable=False)
     else:
<|current_version|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
from __future__ import unicode_literals

import dataproperty
import logbook
import pytablereader

logger = logbook.Logger("SimpleSQLie")
logger.disable()

def set_logger(is_enable):
    if is_enable != logger.disabled:
        return

    if is_enable:
        logger.enable()
    else:
        logger.disable()

    dataproperty.set_logger(is_enable)
    pytablereader.set_logger(is_enable)

def set_log_level(log_level):
    """
    Set logging level of this module. Using
    `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging.

    :param int log_level:
        One of the log level of
        `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__.
        Disabled logging if ``log_level`` is ``logbook.NOTSET``.
    """

    if log_level == logger.level:
        return

    if log_level == logbook.NOTSET:
        set_logger(is_enable=False)
    else:
        set_logger(is_enable=True)
        logger.level = log_level

<|next_version|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
from __future__ import unicode_literals

import dataproperty
import logbook
import pytablereader

logger = logbook.Logger("SimpleSQLie")
logger.disable()

def set_logger(is_enable):
    if is_enable != logger.disabled:
        return

    if is_enable:
        logger.enable()
    else:
        logger.disable()

    dataproperty.set_logger(is_enable)
    pytablereader.set_logger(is_enable)

def set_log_level(log_level):
    """
    Set logging level of this module. Using
    `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging.

    :param int log_level:
        One of the log level of
        `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__.
        Disabled logging if ``log_level`` is ``logbook.NOTSET``.
    """

    if log_level == logger.level:
        return

    if log_level == logbook.NOTSET:
        set_logger(is_enable=False)
    else:
        set_logger(is_enable=True)
        logger.level = log_level

    dataproperty.set_log_level(log_level)
    pytablereader.set_log_level(log_level)


Fix missing metaclass for an interface class

--- pingparsing/_interface.py
+++ pingparsing/_interface.py
@@ -9,7 +9,10 @@

 import abc

+import six

+
+@six.add_metaclass(abc.ABCMeta)
 class PingParserInterface(object):

     @abc.abstractproperty

<|original_code|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division

import abc

class PingParserInterface(object):

    @abc.abstractproperty
    def packet_transmit(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_receive(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_loss_rate(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_loss_count(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_min(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_avg(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_max(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_mdev(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_duplicate_rate(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_duplicate_count(self):  # pragma: no cover
        pass

<|edits_diff|>
--- pingparsing/_interface.py
+++ pingparsing/_interface.py
@@ -9,6 +9,7 @@

 import abc

+import six

 class PingParserInterface(object):

<|current_version|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division

import abc

import six

class PingParserInterface(object):

    @abc.abstractproperty
    def packet_transmit(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_receive(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_loss_rate(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_loss_count(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_min(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_avg(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_max(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_mdev(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_duplicate_rate(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_duplicate_count(self):  # pragma: no cover
        pass

<|next_version|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division

import abc

import six

@six.add_metaclass(abc.ABCMeta)
class PingParserInterface(object):

    @abc.abstractproperty
    def packet_transmit(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_receive(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_loss_rate(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_loss_count(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_min(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_avg(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_max(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def rtt_mdev(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_duplicate_rate(self):  # pragma: no cover
        pass

    @abc.abstractproperty
    def packet_duplicate_count(self):  # pragma: no cover
        pass


[telemetry] Disable power and smoke unit tests on Mac 10.9.

powermetrics is failing on the bots.

BUG=423688
TEST=trybots
R=tonyg

Review URL: https://codereview.chromium.org/746793002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#305147}

--- telemetry/telemetry/core/platform/platform_backend_unittest.py
+++ telemetry/telemetry/core/platform/platform_backend_unittest.py
@@ -6,10 +6,12 @@
 import time
 import unittest

+from telemetry import decorators
 from telemetry.core import platform as platform_module

 class PlatformBackendTest(unittest.TestCase):
+  @decorators.Disabled('mavericks')  # crbug.com/423688
   def testPowerMonitoringSync(self):
     # Tests that the act of monitoring power doesn't blow up.
     platform = platform_module.GetHostPlatform()

<|original_code|>
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import logging
import time
import unittest

from telemetry.core import platform as platform_module

class PlatformBackendTest(unittest.TestCase):
  def testPowerMonitoringSync(self):
    # Tests that the act of monitoring power doesn't blow up.
    platform = platform_module.GetHostPlatform()
    can_monitor_power = platform.CanMonitorPower()
    self.assertIsInstance(can_monitor_power, bool)
    if not can_monitor_power:
      logging.warning('Test not supported on this platform.')
      return

    browser_mock = lambda: None
    # Android needs to access the package of the monitored app.
    if platform.GetOSName() == 'android':
      # pylint: disable=W0212
      browser_mock._browser_backend = lambda: None
      # Monitor the launcher, which is always present.
      browser_mock._browser_backend.package = 'com.android.launcher'

    platform.StartMonitoringPower(browser_mock)
    time.sleep(0.001)
    output = platform.StopMonitoringPower()
    self.assertTrue(output.has_key('energy_consumption_mwh'))
    self.assertTrue(output.has_key('identifier'))

<|edits_diff|>
--- telemetry/telemetry/core/platform/platform_backend_unittest.py
+++ telemetry/telemetry/core/platform/platform_backend_unittest.py
@@ -6,6 +6,7 @@
 import time
 import unittest

+from telemetry import decorators
 from telemetry.core import platform as platform_module

<|current_version|>
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import logging
import time
import unittest

from telemetry import decorators
from telemetry.core import platform as platform_module

class PlatformBackendTest(unittest.TestCase):
  def testPowerMonitoringSync(self):
    # Tests that the act of monitoring power doesn't blow up.
    platform = platform_module.GetHostPlatform()
    can_monitor_power = platform.CanMonitorPower()
    self.assertIsInstance(can_monitor_power, bool)
    if not can_monitor_power:
      logging.warning('Test not supported on this platform.')
      return

    browser_mock = lambda: None
    # Android needs to access the package of the monitored app.
    if platform.GetOSName() == 'android':
      # pylint: disable=W0212
      browser_mock._browser_backend = lambda: None
      # Monitor the launcher, which is always present.
      browser_mock._browser_backend.package = 'com.android.launcher'

    platform.StartMonitoringPower(browser_mock)
    time.sleep(0.001)
    output = platform.StopMonitoringPower()
    self.assertTrue(output.has_key('energy_consumption_mwh'))
    self.assertTrue(output.has_key('identifier'))

<|next_version|>
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import logging
import time
import unittest

from telemetry import decorators
from telemetry.core import platform as platform_module

class PlatformBackendTest(unittest.TestCase):
  @decorators.Disabled('mavericks')  # crbug.com/423688
  def testPowerMonitoringSync(self):
    # Tests that the act of monitoring power doesn't blow up.
    platform = platform_module.GetHostPlatform()
    can_monitor_power = platform.CanMonitorPower()
    self.assertIsInstance(can_monitor_power, bool)
    if not can_monitor_power:
      logging.warning('Test not supported on this platform.')
      return

    browser_mock = lambda: None
    # Android needs to access the package of the monitored app.
    if platform.GetOSName() == 'android':
      # pylint: disable=W0212
      browser_mock._browser_backend = lambda: None
      # Monitor the launcher, which is always present.
      browser_mock._browser_backend.package = 'com.android.launcher'

    platform.StartMonitoringPower(browser_mock)
    time.sleep(0.001)
    output = platform.StopMonitoringPower()
    self.assertTrue(output.has_key('energy_consumption_mwh'))
    self.assertTrue(output.has_key('identifier'))


Add README as long_description to package

--- setup.py
+++ setup.py
@@ -1,8 +1,13 @@
 from setuptools import setup
+
+with open("README.md", 'r') as f:
+    long_description = f.read()

 setup(name='fortdepend',
       version='0.1.0',
       description='Automatically generate Fortran dependencies',
+      long_description=long_description,
+      long_description_content_type="test/markdown",
       author='Peter Hill',
       author_email='peter@fusionplasma.co.uk',
       url='https://github.com/ZedThree/fort_depend.py/',

<|original_code|>
from setuptools import setup

setup(name='fortdepend',
      version='0.1.0',
      description='Automatically generate Fortran dependencies',
      author='Peter Hill',
      author_email='peter@fusionplasma.co.uk',
      url='https://github.com/ZedThree/fort_depend.py/',
      download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0',
      license='MIT',
      classifiers=[
          'Development Status :: 3 - Alpha',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Fortran',
      ],
      packages=['fortdepend'],
      install_requires=[
          'colorama >= 0.3.9',
          'pcpp >= 1.1.0'
      ],
      extras_require={
          'tests': ['pytest >= 3.3.0'],
          'docs': [
              'sphinx >= 1.4',
              'sphinx-argparse >= 0.2.3'
          ],
      },
      keywords=['build', 'dependencies', 'fortran'],
      entry_points={
          'console_scripts': [
              'fortdepend = fortdepend.__main__:main',
          ],
      },
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,4 +1,7 @@
 from setuptools import setup
+
+with open("README.md", 'r') as f:
+    long_description = f.read()

 setup(name='fortdepend',
       version='0.1.0',
<|current_version|>
from setuptools import setup

with open("README.md", 'r') as f:
    long_description = f.read()

setup(name='fortdepend',
      version='0.1.0',
      description='Automatically generate Fortran dependencies',
      author='Peter Hill',
      author_email='peter@fusionplasma.co.uk',
      url='https://github.com/ZedThree/fort_depend.py/',
      download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0',
      license='MIT',
      classifiers=[
          'Development Status :: 3 - Alpha',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Fortran',
      ],
      packages=['fortdepend'],
      install_requires=[
          'colorama >= 0.3.9',
          'pcpp >= 1.1.0'
      ],
      extras_require={
          'tests': ['pytest >= 3.3.0'],
          'docs': [
              'sphinx >= 1.4',
              'sphinx-argparse >= 0.2.3'
          ],
      },
      keywords=['build', 'dependencies', 'fortran'],
      entry_points={
          'console_scripts': [
              'fortdepend = fortdepend.__main__:main',
          ],
      },
)

<|next_version|>
from setuptools import setup

with open("README.md", 'r') as f:
    long_description = f.read()

setup(name='fortdepend',
      version='0.1.0',
      description='Automatically generate Fortran dependencies',
      long_description=long_description,
      long_description_content_type="test/markdown",
      author='Peter Hill',
      author_email='peter@fusionplasma.co.uk',
      url='https://github.com/ZedThree/fort_depend.py/',
      download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0',
      license='MIT',
      classifiers=[
          'Development Status :: 3 - Alpha',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Fortran',
      ],
      packages=['fortdepend'],
      install_requires=[
          'colorama >= 0.3.9',
          'pcpp >= 1.1.0'
      ],
      extras_require={
          'tests': ['pytest >= 3.3.0'],
          'docs': [
              'sphinx >= 1.4',
              'sphinx-argparse >= 0.2.3'
          ],
      },
      keywords=['build', 'dependencies', 'fortran'],
      entry_points={
          'console_scripts': [
              'fortdepend = fortdepend.__main__:main',
          ],
      },
)


Add bulk updating of a model's published status

--- registry/admin.py
+++ registry/admin.py
@@ -1,11 +1,16 @@
 from models import Resource, ResourceCollection, Contact
 from django.contrib import admin
+
+def make_published(modeladmin, request, queryset):
+    queryset.update(published=True)
+make_published.short_description = "Mark selected resources as published"

 class ResourceAdmin(admin.ModelAdmin):
     list_display = ('title', 'couchDB_link', 'edit_metadata_link', 'published')
     filter_horizontal = ['editors', 'collections']
     list_filter = ('published', 'collections')
     search_fields = ['title', 'metadata_id']
+    actions = [make_published]

 class ResourceCollectionAdmin(admin.ModelAdmin):
     filter_horizontal = [ 'editors', 'parents' ]

<|original_code|>
from models import Resource, ResourceCollection, Contact
from django.contrib import admin

class ResourceAdmin(admin.ModelAdmin):
    list_display = ('title', 'couchDB_link', 'edit_metadata_link', 'published')
    filter_horizontal = ['editors', 'collections']
    list_filter = ('published', 'collections')
    search_fields = ['title', 'metadata_id']

class ResourceCollectionAdmin(admin.ModelAdmin):
    filter_horizontal = [ 'editors', 'parents' ]
    list_display = ('title', 'collection_id', 'couchDB_link')
    search_fields = ['title', 'collection_id']

admin.site.register(Resource, ResourceAdmin)
admin.site.register(ResourceCollection, ResourceCollectionAdmin)
admin.site.register(Contact)

<|edits_diff|>
--- registry/admin.py
+++ registry/admin.py
@@ -1,5 +1,9 @@
 from models import Resource, ResourceCollection, Contact
 from django.contrib import admin
+
+def make_published(modeladmin, request, queryset):
+    queryset.update(published=True)
+make_published.short_description = "Mark selected resources as published"

 class ResourceAdmin(admin.ModelAdmin):
     list_display = ('title', 'couchDB_link', 'edit_metadata_link', 'published')
<|current_version|>
from models import Resource, ResourceCollection, Contact
from django.contrib import admin

def make_published(modeladmin, request, queryset):
    queryset.update(published=True)
make_published.short_description = "Mark selected resources as published"

class ResourceAdmin(admin.ModelAdmin):
    list_display = ('title', 'couchDB_link', 'edit_metadata_link', 'published')
    filter_horizontal = ['editors', 'collections']
    list_filter = ('published', 'collections')
    search_fields = ['title', 'metadata_id']

class ResourceCollectionAdmin(admin.ModelAdmin):
    filter_horizontal = [ 'editors', 'parents' ]
    list_display = ('title', 'collection_id', 'couchDB_link')
    search_fields = ['title', 'collection_id']

admin.site.register(Resource, ResourceAdmin)
admin.site.register(ResourceCollection, ResourceCollectionAdmin)
admin.site.register(Contact)

<|next_version|>
from models import Resource, ResourceCollection, Contact
from django.contrib import admin

def make_published(modeladmin, request, queryset):
    queryset.update(published=True)
make_published.short_description = "Mark selected resources as published"

class ResourceAdmin(admin.ModelAdmin):
    list_display = ('title', 'couchDB_link', 'edit_metadata_link', 'published')
    filter_horizontal = ['editors', 'collections']
    list_filter = ('published', 'collections')
    search_fields = ['title', 'metadata_id']
    actions = [make_published]

class ResourceCollectionAdmin(admin.ModelAdmin):
    filter_horizontal = [ 'editors', 'parents' ]
    list_display = ('title', 'collection_id', 'couchDB_link')
    search_fields = ['title', 'collection_id']

admin.site.register(Resource, ResourceAdmin)
admin.site.register(ResourceCollection, ResourceCollectionAdmin)
admin.site.register(Contact)


Improve usability of the command "TsurfSetRoot"

--- autoload/tsurf/core.py
+++ autoload/tsurf/core.py
@@ -10,6 +10,7 @@

 """

+import os
 import vim

 from tsurf import ui
@@ -35,6 +36,11 @@
     def SetProjectRoot(self, root=""):
         """To set the current project root to the current working directory or
         to the directory passed as argument."""
+        home = os.path.expanduser("~")
+        if root.startswith("~"):
+            root = root.replace("~", home)
+        elif root.startswith("$HOME"):
+            root = root.replace("$HOME", home)
         self.services.curr_project.set_root(
                 root if root else vim.eval("getcwd()"))

<|original_code|>
# -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~

This module defines the TagSurfer class. This class serve two purpose:

  1) Defines the methods that are used by tsurf-owned vim commands.
  2) Creates all tsurf components and acts as a brigde among them.

"""

import vim

from tsurf import ui
from tsurf import finder
from tsurf import services

class TagSurfer:

    def __init__(self):
        self.services = services.Services(self)
        self.finder = finder.Finder(self)
        self.ui = ui.UserInterface(self)

    def close(self):
        """To performs cleanup actions."""
        self.finder.close()

    def Open(self):
        """To open the Tag Surfer user interface."""
        self.ui.open()

    def SetProjectRoot(self, root=""):
        """To set the current project root to the current working directory or
        to the directory passed as argument."""
        self.services.curr_project.set_root(
                root if root else vim.eval("getcwd()"))

    def UnsetProjectRoot(self):
        """To unset the current project root."""
        self.services.curr_project.set_root("")

<|edits_diff|>
--- autoload/tsurf/core.py
+++ autoload/tsurf/core.py
@@ -10,6 +10,7 @@

 """

+import os
 import vim

 from tsurf import ui
<|current_version|>
# -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~

This module defines the TagSurfer class. This class serve two purpose:

  1) Defines the methods that are used by tsurf-owned vim commands.
  2) Creates all tsurf components and acts as a brigde among them.

"""

import os
import vim

from tsurf import ui
from tsurf import finder
from tsurf import services

class TagSurfer:

    def __init__(self):
        self.services = services.Services(self)
        self.finder = finder.Finder(self)
        self.ui = ui.UserInterface(self)

    def close(self):
        """To performs cleanup actions."""
        self.finder.close()

    def Open(self):
        """To open the Tag Surfer user interface."""
        self.ui.open()

    def SetProjectRoot(self, root=""):
        """To set the current project root to the current working directory or
        to the directory passed as argument."""
        self.services.curr_project.set_root(
                root if root else vim.eval("getcwd()"))

    def UnsetProjectRoot(self):
        """To unset the current project root."""
        self.services.curr_project.set_root("")

<|next_version|>
# -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~

This module defines the TagSurfer class. This class serve two purpose:

  1) Defines the methods that are used by tsurf-owned vim commands.
  2) Creates all tsurf components and acts as a brigde among them.

"""

import os
import vim

from tsurf import ui
from tsurf import finder
from tsurf import services

class TagSurfer:

    def __init__(self):
        self.services = services.Services(self)
        self.finder = finder.Finder(self)
        self.ui = ui.UserInterface(self)

    def close(self):
        """To performs cleanup actions."""
        self.finder.close()

    def Open(self):
        """To open the Tag Surfer user interface."""
        self.ui.open()

    def SetProjectRoot(self, root=""):
        """To set the current project root to the current working directory or
        to the directory passed as argument."""
        home = os.path.expanduser("~")
        if root.startswith("~"):
            root = root.replace("~", home)
        elif root.startswith("$HOME"):
            root = root.replace("$HOME", home)
        self.services.curr_project.set_root(
                root if root else vim.eval("getcwd()"))

    def UnsetProjectRoot(self):
        """To unset the current project root."""
        self.services.curr_project.set_root("")


Return an error when number of jobs exceeds max_jobs

ghactions API call we're using limits number of jobs
returned in one call. If jobs exceed this number they are
grouped into "pages". Page handling code shall be added
when we exceed this number.

--- wait-for-statuses.py
+++ wait-for-statuses.py
@@ -3,6 +3,7 @@
 import subprocess
 import time
 import os
+import sys

 # We're limited to this number by GH Actions API
 # https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
@@ -16,6 +17,10 @@
          + "?per_page=" + str(max_jobs)

 numOfJobs = int(os.environ['NUM_OF_JOBS'])
+
+
+if(numOfJobs > max_jobs):
+  sys.exit("ERROR: number of jobs exceeded max_jobs: " + str(max_jobs))

 while(True):
   time.sleep(60)

<|original_code|>
import urllib.request
import json
import subprocess
import time
import os

# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100

status_url = "https://api.github.com/repos/" \
         + os.environ['GITHUB_REPOSITORY'] \
         + "/actions/runs/" \
         + os.environ['GITHUB_RUN_ID'] \
         + "/jobs" \
         + "?per_page=" + str(max_jobs)

numOfJobs = int(os.environ['NUM_OF_JOBS'])

while(True):
  time.sleep(60)
  countCompleted = 0

  with urllib.request.urlopen(status_url) as url:
    data = json.loads(url.read().decode())
    for j in data["jobs"]:
      if(j["status"] == "completed"):
        countCompleted += 1

  print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs))
  if(countCompleted >= numOfJobs):
    break

subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh")
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")

<|edits_diff|>
--- wait-for-statuses.py
+++ wait-for-statuses.py
@@ -3,6 +3,7 @@
 import subprocess
 import time
 import os
+import sys

 # We're limited to this number by GH Actions API
 # https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
<|current_version|>
import urllib.request
import json
import subprocess
import time
import os
import sys

# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100

status_url = "https://api.github.com/repos/" \
         + os.environ['GITHUB_REPOSITORY'] \
         + "/actions/runs/" \
         + os.environ['GITHUB_RUN_ID'] \
         + "/jobs" \
         + "?per_page=" + str(max_jobs)

numOfJobs = int(os.environ['NUM_OF_JOBS'])

while(True):
  time.sleep(60)
  countCompleted = 0

  with urllib.request.urlopen(status_url) as url:
    data = json.loads(url.read().decode())
    for j in data["jobs"]:
      if(j["status"] == "completed"):
        countCompleted += 1

  print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs))
  if(countCompleted >= numOfJobs):
    break

subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh")
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")

<|next_version|>
import urllib.request
import json
import subprocess
import time
import os
import sys

# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100

status_url = "https://api.github.com/repos/" \
         + os.environ['GITHUB_REPOSITORY'] \
         + "/actions/runs/" \
         + os.environ['GITHUB_RUN_ID'] \
         + "/jobs" \
         + "?per_page=" + str(max_jobs)

numOfJobs = int(os.environ['NUM_OF_JOBS'])

if(numOfJobs > max_jobs):
  sys.exit("ERROR: number of jobs exceeded max_jobs: " + str(max_jobs))

while(True):
  time.sleep(60)
  countCompleted = 0

  with urllib.request.urlopen(status_url) as url:
    data = json.loads(url.read().decode())
    for j in data["jobs"]:
      if(j["status"] == "completed"):
        countCompleted += 1

  print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs))
  if(countCompleted >= numOfJobs):
    break

subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh")
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")


Tag filtering infrastructure up (currently stubbed).

--- main.py
+++ main.py
@@ -9,17 +9,28 @@
 import jinja2
 import yaml

+def filter_db(db, tags):
+    return db
+
 def main(args):
     parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
     parser.add_argument("source", help="The YAML database to source from.")
     parser.add_argument("template", help="The template to build the CV from.")
     parser.add_argument("output", help="The file to output.")
+    parser.add_argument("--tags", help="A comma-separated list of tags. If present, only items tagged with those specified appear in the output.")

     args = parser.parse_args(args)
+
+    tags = None
+    if args.tags is not None:
+        tags = args.tags.split(",")

     db = None
     with open(args.source, "r") as source_file:
         db = yaml.load(source_file)
+
+    if tags is not None:
+        db = filter_db(db, tags)

     env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
     template = None

<|original_code|>
#!/usr/bin/env python3

# Standard imports
import argparse
import sys
import os.path

# Non-standard imports
import jinja2
import yaml

def main(args):
    parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
    parser.add_argument("source", help="The YAML database to source from.")
    parser.add_argument("template", help="The template to build the CV from.")
    parser.add_argument("output", help="The file to output.")

    args = parser.parse_args(args)

    db = None
    with open(args.source, "r") as source_file:
        db = yaml.load(source_file)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
    template = None
    try:
        template = env.get_template(os.path.basename(args.template))
    except jinja2.TemplateSyntaxError as ex:
        print(
            ("Failed to load template from {filename}. "
            "Error on line {lineno}: {message}").format(
                filename=ex.filename,
                lineno=ex.lineno,
                message=ex.message))
        sys.exit(1)

    with open(args.output, "w") as output_file:
        output_file.write(template.render(db))

if __name__ == "__main__":
    main(sys.argv[1:])

<|edits_diff|>
--- main.py
+++ main.py
@@ -9,13 +9,21 @@
 import jinja2
 import yaml

+def filter_db(db, tags):
+    return db
+
 def main(args):
     parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
     parser.add_argument("source", help="The YAML database to source from.")
     parser.add_argument("template", help="The template to build the CV from.")
     parser.add_argument("output", help="The file to output.")
+    parser.add_argument("--tags", help="A comma-separated list of tags. If present, only items tagged with those specified appear in the output.")

     args = parser.parse_args(args)
+
+    tags = None
+    if args.tags is not None:
+        tags = args.tags.split(",")

     db = None
     with open(args.source, "r") as source_file:
<|current_version|>
#!/usr/bin/env python3

# Standard imports
import argparse
import sys
import os.path

# Non-standard imports
import jinja2
import yaml

def filter_db(db, tags):
    return db

def main(args):
    parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
    parser.add_argument("source", help="The YAML database to source from.")
    parser.add_argument("template", help="The template to build the CV from.")
    parser.add_argument("output", help="The file to output.")
    parser.add_argument("--tags", help="A comma-separated list of tags. If present, only items tagged with those specified appear in the output.")

    args = parser.parse_args(args)

    tags = None
    if args.tags is not None:
        tags = args.tags.split(",")

    db = None
    with open(args.source, "r") as source_file:
        db = yaml.load(source_file)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
    template = None
    try:
        template = env.get_template(os.path.basename(args.template))
    except jinja2.TemplateSyntaxError as ex:
        print(
            ("Failed to load template from {filename}. "
            "Error on line {lineno}: {message}").format(
                filename=ex.filename,
                lineno=ex.lineno,
                message=ex.message))
        sys.exit(1)

    with open(args.output, "w") as output_file:
        output_file.write(template.render(db))

if __name__ == "__main__":
    main(sys.argv[1:])

<|next_version|>
#!/usr/bin/env python3

# Standard imports
import argparse
import sys
import os.path

# Non-standard imports
import jinja2
import yaml

def filter_db(db, tags):
    return db

def main(args):
    parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
    parser.add_argument("source", help="The YAML database to source from.")
    parser.add_argument("template", help="The template to build the CV from.")
    parser.add_argument("output", help="The file to output.")
    parser.add_argument("--tags", help="A comma-separated list of tags. If present, only items tagged with those specified appear in the output.")

    args = parser.parse_args(args)

    tags = None
    if args.tags is not None:
        tags = args.tags.split(",")

    db = None
    with open(args.source, "r") as source_file:
        db = yaml.load(source_file)

    if tags is not None:
        db = filter_db(db, tags)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
    template = None
    try:
        template = env.get_template(os.path.basename(args.template))
    except jinja2.TemplateSyntaxError as ex:
        print(
            ("Failed to load template from {filename}. "
            "Error on line {lineno}: {message}").format(
                filename=ex.filename,
                lineno=ex.lineno,
                message=ex.message))
        sys.exit(1)

    with open(args.output, "w") as output_file:
        output_file.write(template.render(db))

if __name__ == "__main__":
    main(sys.argv[1:])


Add a hook we'll eventually use to install the activate scripts

--- virtualenv/builders/base.py
+++ virtualenv/builders/base.py
@@ -16,5 +16,11 @@
         # Actually Create the virtual environment
         self.create_virtual_environment(destination)

+        # Install our activate scripts into the virtual environment
+        self.install_scripts(destination)
+
     def create_virtual_environment(self, destination):
         raise NotImplementedError
+
+    def install_scripts(self, destination):
+        pass

<|original_code|>
import sys

class BaseBuilder(object):

    def __init__(self, python, system_site_packages=False, clear=False):
        # We default to sys.executable if we're not given a Python.
        if python is None:
            python = sys.executable

        self.python = python
        self.system_site_packages = system_site_packages
        self.clear = clear

    def create(self, destination):
        # Actually Create the virtual environment
        self.create_virtual_environment(destination)

    def create_virtual_environment(self, destination):
        raise NotImplementedError

<|edits_diff|>
--- virtualenv/builders/base.py
+++ virtualenv/builders/base.py
@@ -16,5 +16,8 @@
         # Actually Create the virtual environment
         self.create_virtual_environment(destination)

+        # Install our activate scripts into the virtual environment
+        self.install_scripts(destination)
+
     def create_virtual_environment(self, destination):
         raise NotImplementedError
<|current_version|>
import sys

class BaseBuilder(object):

    def __init__(self, python, system_site_packages=False, clear=False):
        # We default to sys.executable if we're not given a Python.
        if python is None:
            python = sys.executable

        self.python = python
        self.system_site_packages = system_site_packages
        self.clear = clear

    def create(self, destination):
        # Actually Create the virtual environment
        self.create_virtual_environment(destination)

        # Install our activate scripts into the virtual environment
        self.install_scripts(destination)

    def create_virtual_environment(self, destination):
        raise NotImplementedError

<|next_version|>
import sys

class BaseBuilder(object):

    def __init__(self, python, system_site_packages=False, clear=False):
        # We default to sys.executable if we're not given a Python.
        if python is None:
            python = sys.executable

        self.python = python
        self.system_site_packages = system_site_packages
        self.clear = clear

    def create(self, destination):
        # Actually Create the virtual environment
        self.create_virtual_environment(destination)

        # Install our activate scripts into the virtual environment
        self.install_scripts(destination)

    def create_virtual_environment(self, destination):
        raise NotImplementedError

    def install_scripts(self, destination):
        pass


Add playback states to GStreamer

Add playback states to GStreamer

--- mopidy/backends/gstreamer.py
+++ mopidy/backends/gstreamer.py
@@ -1,4 +1,6 @@
 import logging
+
+import gst

 from mopidy.backends import BaseBackend, BasePlaybackController

@@ -11,5 +13,9 @@
         self.playback = GStreamerPlaybackController(self)

 class GStreamerPlaybackController(BasePlaybackController):
+    PAUSED = gst.STATE_PAUSED
+    PLAYING = gst.STATE_PLAYING
+    STOPPED = gst.STATE_NULL
+
     def __init__(self, backend):
         super(GStreamerPlaybackController, self).__init__(backend)

<|original_code|>
import logging

from mopidy.backends import BaseBackend, BasePlaybackController

logger = logging.getLogger(u'backends.gstreamer')

class GStreamerBackend(BaseBackend):
    def __init__(self, *args, **kwargs):
        super(GStreamerBackend, self).__init__(*args, **kwargs)

        self.playback = GStreamerPlaybackController(self)

class GStreamerPlaybackController(BasePlaybackController):
    def __init__(self, backend):
        super(GStreamerPlaybackController, self).__init__(backend)

<|edits_diff|>
--- mopidy/backends/gstreamer.py
+++ mopidy/backends/gstreamer.py
@@ -1,4 +1,6 @@
 import logging
+
+import gst

 from mopidy.backends import BaseBackend, BasePlaybackController

<|current_version|>
import logging

import gst

from mopidy.backends import BaseBackend, BasePlaybackController

logger = logging.getLogger(u'backends.gstreamer')

class GStreamerBackend(BaseBackend):
    def __init__(self, *args, **kwargs):
        super(GStreamerBackend, self).__init__(*args, **kwargs)

        self.playback = GStreamerPlaybackController(self)

class GStreamerPlaybackController(BasePlaybackController):
    def __init__(self, backend):
        super(GStreamerPlaybackController, self).__init__(backend)

<|next_version|>
import logging

import gst

from mopidy.backends import BaseBackend, BasePlaybackController

logger = logging.getLogger(u'backends.gstreamer')

class GStreamerBackend(BaseBackend):
    def __init__(self, *args, **kwargs):
        super(GStreamerBackend, self).__init__(*args, **kwargs)

        self.playback = GStreamerPlaybackController(self)

class GStreamerPlaybackController(BasePlaybackController):
    PAUSED = gst.STATE_PAUSED
    PLAYING = gst.STATE_PLAYING
    STOPPED = gst.STATE_NULL

    def __init__(self, backend):
        super(GStreamerPlaybackController, self).__init__(backend)


Add Basic URL for Project

Add Basic URL for Project

--- taOonja/taOonja/urls.py
+++ taOonja/taOonja/urls.py
@@ -18,8 +18,11 @@
 from django.conf.urls import url
 from django.contrib import admin

+from game.views import LocationListView
 urlpatterns = [
     url(r'^admin/', admin.site.urls),
+    url(r'^location/$', LocationListView.as_view(), name='location-list')
+
 ]

<|original_code|>
"""taOonja URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

<|edits_diff|>
--- taOonja/taOonja/urls.py
+++ taOonja/taOonja/urls.py
@@ -18,6 +18,7 @@
 from django.conf.urls import url
 from django.contrib import admin

+from game.views import LocationListView
 urlpatterns = [
     url(r'^admin/', admin.site.urls),
 ]
<|current_version|>
"""taOonja URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin

from game.views import LocationListView
urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

<|next_version|>
"""taOonja URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.contrib import admin

from game.views import LocationListView
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^location/$', LocationListView.as_view(), name='location-list')

]

if settings.DEBUG is True:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Clear content-io pipeline after rendering admin panel

--- djedi/templatetags/djedi_admin.py
+++ djedi/templatetags/djedi_admin.py
@@ -12,9 +12,14 @@
 @register.simple_tag(takes_context=True)
 def djedi_admin(context):
     output = u''
+
     if has_permission(context.get('user')):
         defaults = dict((node.uri.clone(version=None), node.initial) for node in pipeline.history.list('get'))
         output = render_to_string('djedi/cms/embed.html', {
             'json_nodes': json.dumps(defaults).replace('</', '\\x3C/'),
         })
+
+    # Clear pipeline
+    pipeline.clear()
+
     return output

<|original_code|>
import json
import logging
from django import template
from django.template.loader import render_to_string
from cio.pipeline import pipeline
from ..auth import has_permission

register = template.Library()
logger = logging.getLogger(__name__)

@register.simple_tag(takes_context=True)
def djedi_admin(context):
    output = u''
    if has_permission(context.get('user')):
        defaults = dict((node.uri.clone(version=None), node.initial) for node in pipeline.history.list('get'))
        output = render_to_string('djedi/cms/embed.html', {
            'json_nodes': json.dumps(defaults).replace('</', '\\x3C/'),
        })
    return output

<|edits_diff|>
--- djedi/templatetags/djedi_admin.py
+++ djedi/templatetags/djedi_admin.py
@@ -12,6 +12,7 @@
 @register.simple_tag(takes_context=True)
 def djedi_admin(context):
     output = u''
+
     if has_permission(context.get('user')):
         defaults = dict((node.uri.clone(version=None), node.initial) for node in pipeline.history.list('get'))
         output = render_to_string('djedi/cms/embed.html', {
<|current_version|>
import json
import logging
from django import template
from django.template.loader import render_to_string
from cio.pipeline import pipeline
from ..auth import has_permission

register = template.Library()
logger = logging.getLogger(__name__)

@register.simple_tag(takes_context=True)
def djedi_admin(context):
    output = u''

    if has_permission(context.get('user')):
        defaults = dict((node.uri.clone(version=None), node.initial) for node in pipeline.history.list('get'))
        output = render_to_string('djedi/cms/embed.html', {
            'json_nodes': json.dumps(defaults).replace('</', '\\x3C/'),
        })
    return output

<|next_version|>
import json
import logging
from django import template
from django.template.loader import render_to_string
from cio.pipeline import pipeline
from ..auth import has_permission

register = template.Library()
logger = logging.getLogger(__name__)

@register.simple_tag(takes_context=True)
def djedi_admin(context):
    output = u''

    if has_permission(context.get('user')):
        defaults = dict((node.uri.clone(version=None), node.initial) for node in pipeline.history.list('get'))
        output = render_to_string('djedi/cms/embed.html', {
            'json_nodes': json.dumps(defaults).replace('</', '\\x3C/'),
        })

    # Clear pipeline
    pipeline.clear()

    return output


Add a new context processor to include the NAME_TYPE_CHOICES in every request context.

--- name/context_processors.py
+++ name/context_processors.py
@@ -1,3 +1,6 @@
+from name.models import NAME_TYPE_CHOICES
+
+
 def baseurl(request):
     """
     Return a BASE_URL template context for the current request
@@ -10,3 +13,7 @@
     return {
         'BASE_URL': scheme + request.get_host(),
     }
+
+
+def name_types(request):
+    return {'name_types': dict(NAME_TYPE_CHOICES)}

<|original_code|>
def baseurl(request):
    """
    Return a BASE_URL template context for the current request
    """
    if request.is_secure():
        scheme = 'https://'
    else:
        scheme = 'http://'

    return {
        'BASE_URL': scheme + request.get_host(),
    }

<|edits_diff|>
--- name/context_processors.py
+++ name/context_processors.py
@@ -1,3 +1,6 @@
+from name.models import NAME_TYPE_CHOICES
+
+
 def baseurl(request):
     """
     Return a BASE_URL template context for the current request
<|current_version|>
from name.models import NAME_TYPE_CHOICES

def baseurl(request):
    """
    Return a BASE_URL template context for the current request
    """
    if request.is_secure():
        scheme = 'https://'
    else:
        scheme = 'http://'

    return {
        'BASE_URL': scheme + request.get_host(),
    }

<|next_version|>
from name.models import NAME_TYPE_CHOICES

def baseurl(request):
    """
    Return a BASE_URL template context for the current request
    """
    if request.is_secure():
        scheme = 'https://'
    else:
        scheme = 'http://'

    return {
        'BASE_URL': scheme + request.get_host(),
    }

def name_types(request):
    return {'name_types': dict(NAME_TYPE_CHOICES)}


Set logging level depenging on environment

--- apps.py
+++ apps.py
@@ -1,10 +1,13 @@
 import os
 import webapp2
+import logging

 import handlers

 debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
+loglevel = logging.DEBUG if debug else logging.INFO
+logging.getLogger().setLevel(loglevel)

 task_app = webapp2.WSGIApplication([
     ('/task/index', handlers.IndexTaskHandler),

<|original_code|>
import os
import webapp2

import handlers

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')

task_app = webapp2.WSGIApplication([
    ('/task/index', handlers.IndexTaskHandler),
    ('/task/torrent', handlers.TorrentTaskHandler),
    ('/task/update_feeds', handlers.FeedTaskHandler),
    ('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)

manage_app = webapp2.WSGIApplication([
    ('/manage/', handlers.DashboardHandler),
], debug=debug)

<|edits_diff|>
--- apps.py
+++ apps.py
@@ -1,5 +1,6 @@
 import os
 import webapp2
+import logging

 import handlers

<|current_version|>
import os
import webapp2
import logging

import handlers

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')

task_app = webapp2.WSGIApplication([
    ('/task/index', handlers.IndexTaskHandler),
    ('/task/torrent', handlers.TorrentTaskHandler),
    ('/task/update_feeds', handlers.FeedTaskHandler),
    ('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)

manage_app = webapp2.WSGIApplication([
    ('/manage/', handlers.DashboardHandler),
], debug=debug)

<|next_version|>
import os
import webapp2
import logging

import handlers

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
loglevel = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(loglevel)

task_app = webapp2.WSGIApplication([
    ('/task/index', handlers.IndexTaskHandler),
    ('/task/torrent', handlers.TorrentTaskHandler),
    ('/task/update_feeds', handlers.FeedTaskHandler),
    ('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)

manage_app = webapp2.WSGIApplication([
    ('/manage/', handlers.DashboardHandler),
], debug=debug)


Mark multi memory management test flaky

Mark multi memory management test flaky

--- tests/multi_memory_mgmt_test.py
+++ tests/multi_memory_mgmt_test.py
@@ -5,9 +5,11 @@
 import pycurl
 import unittest
 import gc
+import flaky

 debug = False

+@flaky.flaky(max_runs=3)
 class MultiMemoryMgmtTest(unittest.TestCase):
     def test_opensocketfunction_collection(self):
         self.check_callback(pycurl.M_SOCKETFUNCTION)

<|original_code|>
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et

import pycurl
import unittest
import gc

debug = False

class MultiMemoryMgmtTest(unittest.TestCase):
    def test_opensocketfunction_collection(self):
        self.check_callback(pycurl.M_SOCKETFUNCTION)

    def test_seekfunction_collection(self):
        self.check_callback(pycurl.M_TIMERFUNCTION)

    def check_callback(self, callback):
        # Note: extracting a context manager seems to result in
        # everything being garbage collected even if the C code
        # does not clear the callback
        object_count = 0
        gc.collect()
        # gc.collect() can create new objects... running it again here
        # settles tracked object count for the actual test below
        gc.collect()
        object_count = len(gc.get_objects())

        c = pycurl.CurlMulti()
        c.setopt(callback, lambda x: True)
        del c

        gc.collect()
        new_object_count = len(gc.get_objects())
        # it seems that GC sometimes collects something that existed
        # before this test ran, GH issues #273/#274
        self.assertTrue(new_object_count in (object_count, object_count-1))

<|edits_diff|>
--- tests/multi_memory_mgmt_test.py
+++ tests/multi_memory_mgmt_test.py
@@ -5,6 +5,7 @@
 import pycurl
 import unittest
 import gc
+import flaky

 debug = False

<|current_version|>
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et

import pycurl
import unittest
import gc
import flaky

debug = False

class MultiMemoryMgmtTest(unittest.TestCase):
    def test_opensocketfunction_collection(self):
        self.check_callback(pycurl.M_SOCKETFUNCTION)

    def test_seekfunction_collection(self):
        self.check_callback(pycurl.M_TIMERFUNCTION)

    def check_callback(self, callback):
        # Note: extracting a context manager seems to result in
        # everything being garbage collected even if the C code
        # does not clear the callback
        object_count = 0
        gc.collect()
        # gc.collect() can create new objects... running it again here
        # settles tracked object count for the actual test below
        gc.collect()
        object_count = len(gc.get_objects())

        c = pycurl.CurlMulti()
        c.setopt(callback, lambda x: True)
        del c

        gc.collect()
        new_object_count = len(gc.get_objects())
        # it seems that GC sometimes collects something that existed
        # before this test ran, GH issues #273/#274
        self.assertTrue(new_object_count in (object_count, object_count-1))

<|next_version|>
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et

import pycurl
import unittest
import gc
import flaky

debug = False

@flaky.flaky(max_runs=3)
class MultiMemoryMgmtTest(unittest.TestCase):
    def test_opensocketfunction_collection(self):
        self.check_callback(pycurl.M_SOCKETFUNCTION)

    def test_seekfunction_collection(self):
        self.check_callback(pycurl.M_TIMERFUNCTION)

    def check_callback(self, callback):
        # Note: extracting a context manager seems to result in
        # everything being garbage collected even if the C code
        # does not clear the callback
        object_count = 0
        gc.collect()
        # gc.collect() can create new objects... running it again here
        # settles tracked object count for the actual test below
        gc.collect()
        object_count = len(gc.get_objects())

        c = pycurl.CurlMulti()
        c.setopt(callback, lambda x: True)
        del c

        gc.collect()
        new_object_count = len(gc.get_objects())
        # it seems that GC sometimes collects something that existed
        # before this test ran, GH issues #273/#274
        self.assertTrue(new_object_count in (object_count, object_count-1))


Make testrunner work with Django 1.7).

Make testrunner work with Django 1.7).

--- runtests.py
+++ runtests.py
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+import django
 from django.conf import settings
 from django.core.management import call_command

@@ -29,4 +30,7 @@
 if not settings.configured:
     settings.configure(**SETTINGS)

+if django.VERSION >= (1, 7):
+        django.setup()
+
 call_command('test', 'dbsettings')

<|original_code|>
#!/usr/bin/env python
from django.conf import settings
from django.core.management import call_command

INSTALLED_APPS = (
    # Required contrib apps.
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.sessions',
    # Our app and it's test app.
    'dbsettings',
)

SETTINGS = {
    'INSTALLED_APPS': INSTALLED_APPS,
    'SITE_ID': 1,
    'ROOT_URLCONF': 'dbsettings.tests.test_urls',
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
        }
    },
}

if not settings.configured:
    settings.configure(**SETTINGS)

call_command('test', 'dbsettings')

<|edits_diff|>
--- runtests.py
+++ runtests.py
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+import django
 from django.conf import settings
 from django.core.management import call_command

<|current_version|>
#!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command

INSTALLED_APPS = (
    # Required contrib apps.
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.sessions',
    # Our app and it's test app.
    'dbsettings',
)

SETTINGS = {
    'INSTALLED_APPS': INSTALLED_APPS,
    'SITE_ID': 1,
    'ROOT_URLCONF': 'dbsettings.tests.test_urls',
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
        }
    },
}

if not settings.configured:
    settings.configure(**SETTINGS)

call_command('test', 'dbsettings')

<|next_version|>
#!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command

INSTALLED_APPS = (
    # Required contrib apps.
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.sessions',
    # Our app and it's test app.
    'dbsettings',
)

SETTINGS = {
    'INSTALLED_APPS': INSTALLED_APPS,
    'SITE_ID': 1,
    'ROOT_URLCONF': 'dbsettings.tests.test_urls',
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
        }
    },
}

if not settings.configured:
    settings.configure(**SETTINGS)

if django.VERSION >= (1, 7):
        django.setup()

call_command('test', 'dbsettings')


Fix URLLIb3 Insecure Platform Warning

Fix URLLIb3 Insecure Platform Warning

--- platformio_api/__main__.py
+++ platformio_api/__main__.py
@@ -3,6 +3,7 @@

 from sys import exit as sys_exit

+import requests
 from click import echo, group, version_option

 from platformio_api import __version__
@@ -45,6 +46,10 @@

 def main():
+    # https://urllib3.readthedocs.org
+    # /en/latest/security.html#insecureplatformwarning
+    requests.packages.urllib3.disable_warnings()
+
     cli()

<|original_code|>
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

from sys import exit as sys_exit

from click import echo, group, version_option

from platformio_api import __version__
from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats,
                                    sync_libs)
from platformio_api.database import sync_db
from platformio_api.web import app

@group()
@version_option(__version__, prog_name="PlatformIO-API")
def cli():
    pass

@cli.command()
def syncdb():
    sync_db()
    echo("The database has been successfully synchronized!")

@cli.command()
def pendinglibs():
    process_pending_libs()

@cli.command()
def synclibs():
    sync_libs()

@cli.command()
def rotatelibsdlstats():
    rotate_libs_dlstats()

@cli.command("run")
def runserver():
    app.run(debug=True, reloader=True)

def main():
    cli()

if __name__ == "__main__":
    sys_exit(main())

<|edits_diff|>
--- platformio_api/__main__.py
+++ platformio_api/__main__.py
@@ -3,6 +3,7 @@

 from sys import exit as sys_exit

+import requests
 from click import echo, group, version_option

 from platformio_api import __version__
<|current_version|>
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

from sys import exit as sys_exit

import requests
from click import echo, group, version_option

from platformio_api import __version__
from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats,
                                    sync_libs)
from platformio_api.database import sync_db
from platformio_api.web import app

@group()
@version_option(__version__, prog_name="PlatformIO-API")
def cli():
    pass

@cli.command()
def syncdb():
    sync_db()
    echo("The database has been successfully synchronized!")

@cli.command()
def pendinglibs():
    process_pending_libs()

@cli.command()
def synclibs():
    sync_libs()

@cli.command()
def rotatelibsdlstats():
    rotate_libs_dlstats()

@cli.command("run")
def runserver():
    app.run(debug=True, reloader=True)

def main():
    cli()

if __name__ == "__main__":
    sys_exit(main())

<|next_version|>
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

from sys import exit as sys_exit

import requests
from click import echo, group, version_option

from platformio_api import __version__
from platformio_api.crawler import (process_pending_libs, rotate_libs_dlstats,
                                    sync_libs)
from platformio_api.database import sync_db
from platformio_api.web import app

@group()
@version_option(__version__, prog_name="PlatformIO-API")
def cli():
    pass

@cli.command()
def syncdb():
    sync_db()
    echo("The database has been successfully synchronized!")

@cli.command()
def pendinglibs():
    process_pending_libs()

@cli.command()
def synclibs():
    sync_libs()

@cli.command()
def rotatelibsdlstats():
    rotate_libs_dlstats()

@cli.command("run")
def runserver():
    app.run(debug=True, reloader=True)

def main():
    # https://urllib3.readthedocs.org
    # /en/latest/security.html#insecureplatformwarning
    requests.packages.urllib3.disable_warnings()

    cli()

if __name__ == "__main__":
    sys_exit(main())