Use global ioloop as we don't pass test ioloop to tornado redis

--- insight_reloaded/tests/test_api.py
+++ insight_reloaded/tests/test_api.py
@@ -5,8 +5,14 @@
 from insight_reloaded.api import application
 from insight_reloaded import __version__ as VERSION

+from tornado import ioloop
+

 class InsightApiHTTPTest(AsyncHTTPTestCase):
+
+    def get_new_ioloop(self):
+        return ioloop.IOLoop.instance()
+
     def get_app(self):
         return application

<|original_code|>
# -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION

class InsightApiHTTPTest(AsyncHTTPTestCase):
    def get_app(self):
        return application

    def test_api_version(self):
        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()
        body_json = json.loads(response.body)
        self.assertIn('version', body_json)
        self.assertIn('insight_reloaded', body_json)

        self.assertEqual('insight-reloaded', body_json['name'])
        self.assertEqual(VERSION, body_json['version'])

    def test_api_request(self):
        self.http_client.fetch(self.get_url('/') +
                               u'?url=http://my_file_url.com/file.pdf',
                               self.stop)
        response = self.wait()
        json_body = json.loads(response.body)
        self.assertIn('insight_reloaded', json_body)
        self.assertEqual(json_body['number_in_queue'], 1)

    def test_api_url_missing(self):
        self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop)
        response = self.wait()
        self.assertEqual(response.code, 404)

<|edits_diff|>
--- insight_reloaded/tests/test_api.py
+++ insight_reloaded/tests/test_api.py
@@ -4,6 +4,8 @@
 from tornado.testing import AsyncHTTPTestCase
 from insight_reloaded.api import application
 from insight_reloaded import __version__ as VERSION
+
+from tornado import ioloop

 class InsightApiHTTPTest(AsyncHTTPTestCase):
<|current_version|>
# -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION

from tornado import ioloop

class InsightApiHTTPTest(AsyncHTTPTestCase):
    def get_app(self):
        return application

    def test_api_version(self):
        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()
        body_json = json.loads(response.body)
        self.assertIn('version', body_json)
        self.assertIn('insight_reloaded', body_json)

        self.assertEqual('insight-reloaded', body_json['name'])
        self.assertEqual(VERSION, body_json['version'])

    def test_api_request(self):
        self.http_client.fetch(self.get_url('/') +
                               u'?url=http://my_file_url.com/file.pdf',
                               self.stop)
        response = self.wait()
        json_body = json.loads(response.body)
        self.assertIn('insight_reloaded', json_body)
        self.assertEqual(json_body['number_in_queue'], 1)

    def test_api_url_missing(self):
        self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop)
        response = self.wait()
        self.assertEqual(response.code, 404)

<|next_version|>
# -*- coding: utf-8 -*-
import json
from mock import MagicMock
from tornado.testing import AsyncHTTPTestCase
from insight_reloaded.api import application
from insight_reloaded import __version__ as VERSION

from tornado import ioloop

class InsightApiHTTPTest(AsyncHTTPTestCase):

    def get_new_ioloop(self):
        return ioloop.IOLoop.instance()

    def get_app(self):
        return application

    def test_api_version(self):
        self.http_client.fetch(self.get_url('/'), self.stop)
        response = self.wait()
        body_json = json.loads(response.body)
        self.assertIn('version', body_json)
        self.assertIn('insight_reloaded', body_json)

        self.assertEqual('insight-reloaded', body_json['name'])
        self.assertEqual(VERSION, body_json['version'])

    def test_api_request(self):
        self.http_client.fetch(self.get_url('/') +
                               u'?url=http://my_file_url.com/file.pdf',
                               self.stop)
        response = self.wait()
        json_body = json.loads(response.body)
        self.assertIn('insight_reloaded', json_body)
        self.assertEqual(json_body['number_in_queue'], 1)

    def test_api_url_missing(self):
        self.http_client.fetch(self.get_url('/') + '?arg=foobar', self.stop)
        response = self.wait()
        self.assertEqual(response.code, 404)


Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE

--- kino/utils/config.py
+++ kino/utils/config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-

 from utils.data_handler import DataHandler

@@ -10,6 +11,7 @@
             config = self.__read_config()
             self.kino = config["kino"]
             self.github = config["github"]
+            self.weather = config["weather"]

         def __read_config(self):
             return self.data_handler.read_file(self.fname)

<|original_code|>

from utils.data_handler import DataHandler

class Config(object):
    class __Config:
        def __init__(self):
            self.data_handler = DataHandler()
            self.fname = "config.json"

            config = self.__read_config()
            self.kino = config["kino"]
            self.github = config["github"]

        def __read_config(self):
            return self.data_handler.read_file(self.fname)

    instance = None
    def __init__(self):
        if not Config.instance:
            Config.instance = Config.__Config()

    def __getattr__(self, name):
        return getattr(self.instance, name)

<|edits_diff|>
--- kino/utils/config.py
+++ kino/utils/config.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-

 from utils.data_handler import DataHandler

<|current_version|>
# -*- coding: utf-8 -*-

from utils.data_handler import DataHandler

class Config(object):
    class __Config:
        def __init__(self):
            self.data_handler = DataHandler()
            self.fname = "config.json"

            config = self.__read_config()
            self.kino = config["kino"]
            self.github = config["github"]

        def __read_config(self):
            return self.data_handler.read_file(self.fname)

    instance = None
    def __init__(self):
        if not Config.instance:
            Config.instance = Config.__Config()

    def __getattr__(self, name):
        return getattr(self.instance, name)

<|next_version|>
# -*- coding: utf-8 -*-

from utils.data_handler import DataHandler

class Config(object):
    class __Config:
        def __init__(self):
            self.data_handler = DataHandler()
            self.fname = "config.json"

            config = self.__read_config()
            self.kino = config["kino"]
            self.github = config["github"]
            self.weather = config["weather"]

        def __read_config(self):
            return self.data_handler.read_file(self.fname)

    instance = None
    def __init__(self):
        if not Config.instance:
            Config.instance = Config.__Config()

    def __getattr__(self, name):
        return getattr(self.instance, name)


Clean up spaces (a little)

Clean up spaces (a little)

--- gitxblob/commands/add.py
+++ gitxblob/commands/add.py
@@ -1,6 +1,7 @@
 """usage: git-xblob add <path> [...]"""

 import os
+import re

 from ..utils import git

@@ -28,6 +29,9 @@
         # Add it to the attributes file.
         head, tail = os.path.split(path)

+        # Clean up spaces.
+        tail = re.sub(r'\s', '[[:space:]]', tail)
+
         attributes_path = os.path.join(head, '.gitattributes')
         with open(attributes_path, 'a') as fh:
             fh.write('/%s filter=xblob\n' % tail)

<|original_code|>
"""usage: git-xblob add <path> [...]"""

import os

from ..utils import git

def bail(code=1):
    print __doc__.strip()
    exit(code)

def run_add(paths):

    if not paths:
        bail()

    missing_any = False
    for path in paths:
        if not os.path.exists(path):
            print path, 'does not exist'
            missing_any = True
    if missing_any:
        return 3

    for path in paths:

        # Add it to the attributes file.
        head, tail = os.path.split(path)

        attributes_path = os.path.join(head, '.gitattributes')
        with open(attributes_path, 'a') as fh:
            fh.write('/%s filter=xblob\n' % tail)

        # Add the file and the attributes.
        git('add -f %s', attributes_path)
        git('add -f %s', path)

<|edits_diff|>
--- gitxblob/commands/add.py
+++ gitxblob/commands/add.py
@@ -1,6 +1,7 @@
 """usage: git-xblob add <path> [...]"""

 import os
+import re

 from ..utils import git

<|current_version|>
"""usage: git-xblob add <path> [...]"""

import os
import re

from ..utils import git

def bail(code=1):
    print __doc__.strip()
    exit(code)

def run_add(paths):

    if not paths:
        bail()

    missing_any = False
    for path in paths:
        if not os.path.exists(path):
            print path, 'does not exist'
            missing_any = True
    if missing_any:
        return 3

    for path in paths:

        # Add it to the attributes file.
        head, tail = os.path.split(path)

        attributes_path = os.path.join(head, '.gitattributes')
        with open(attributes_path, 'a') as fh:
            fh.write('/%s filter=xblob\n' % tail)

        # Add the file and the attributes.
        git('add -f %s', attributes_path)
        git('add -f %s', path)

<|next_version|>
"""usage: git-xblob add <path> [...]"""

import os
import re

from ..utils import git

def bail(code=1):
    print __doc__.strip()
    exit(code)

def run_add(paths):

    if not paths:
        bail()

    missing_any = False
    for path in paths:
        if not os.path.exists(path):
            print path, 'does not exist'
            missing_any = True
    if missing_any:
        return 3

    for path in paths:

        # Add it to the attributes file.
        head, tail = os.path.split(path)

        # Clean up spaces.
        tail = re.sub(r'\s', '[[:space:]]', tail)

        attributes_path = os.path.join(head, '.gitattributes')
        with open(attributes_path, 'a') as fh:
            fh.write('/%s filter=xblob\n' % tail)

        # Add the file and the attributes.
        git('add -f %s', attributes_path)
        git('add -f %s', path)


Add message on profile form save

Add message on profile form save

--- apps/profiles/views.py
+++ apps/profiles/views.py
@@ -1,5 +1,7 @@
 from django.views.generic import DetailView, UpdateView
 from django.core.urlresolvers import reverse_lazy
+from django.contrib import messages
+from django.utils.translation import ugettext_lazy as _

 from braces.views import LoginRequiredMixin

@@ -28,3 +30,7 @@

     def get_success_url(self):
         return reverse_lazy('profile_update', args=[self.object.username])
+
+    def form_valid(self, *args, **kwargs):
+        messages.success(self.request, _('Perfil guardado con exito'))
+        return super(ProfileUpdateView, self).form_valid(*args, **kwargs)

<|original_code|>
from django.views.generic import DetailView, UpdateView
from django.core.urlresolvers import reverse_lazy

from braces.views import LoginRequiredMixin

from .models import User
from .forms import ProfileUpdateForm

class ProfileDetailView(DetailView):
    '''
    Displays the user profile information
    '''
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'

class ProfileUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'
    form_class = ProfileUpdateForm

    def get_queryset(self):
        queryset = super(ProfileUpdateView, self).get_queryset()
        return queryset.filter(pk=self.request.user.pk)

    def get_success_url(self):
        return reverse_lazy('profile_update', args=[self.object.username])

<|edits_diff|>
--- apps/profiles/views.py
+++ apps/profiles/views.py
@@ -1,5 +1,7 @@
 from django.views.generic import DetailView, UpdateView
 from django.core.urlresolvers import reverse_lazy
+from django.contrib import messages
+from django.utils.translation import ugettext_lazy as _

 from braces.views import LoginRequiredMixin

<|current_version|>
from django.views.generic import DetailView, UpdateView
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _

from braces.views import LoginRequiredMixin

from .models import User
from .forms import ProfileUpdateForm

class ProfileDetailView(DetailView):
    '''
    Displays the user profile information
    '''
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'

class ProfileUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'
    form_class = ProfileUpdateForm

    def get_queryset(self):
        queryset = super(ProfileUpdateView, self).get_queryset()
        return queryset.filter(pk=self.request.user.pk)

    def get_success_url(self):
        return reverse_lazy('profile_update', args=[self.object.username])

<|next_version|>
from django.views.generic import DetailView, UpdateView
from django.core.urlresolvers import reverse_lazy
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _

from braces.views import LoginRequiredMixin

from .models import User
from .forms import ProfileUpdateForm

class ProfileDetailView(DetailView):
    '''
    Displays the user profile information
    '''
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'

class ProfileUpdateView(LoginRequiredMixin, UpdateView):
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'
    form_class = ProfileUpdateForm

    def get_queryset(self):
        queryset = super(ProfileUpdateView, self).get_queryset()
        return queryset.filter(pk=self.request.user.pk)

    def get_success_url(self):
        return reverse_lazy('profile_update', args=[self.object.username])

    def form_valid(self, *args, **kwargs):
        messages.success(self.request, _('Perfil guardado con exito'))
        return super(ProfileUpdateView, self).form_valid(*args, **kwargs)


Add API key to context

Add API key to context

--- src/sentry/api/authentication.py
+++ src/sentry/api/authentication.py
@@ -5,6 +5,7 @@
 from rest_framework.authentication import BasicAuthentication
 from rest_framework.exceptions import AuthenticationFailed

+from sentry.app import raven
 from sentry.models import ApiKey, ProjectKey

@@ -26,6 +27,10 @@
         if not key.is_active:
             raise AuthenticationFailed('Key is disabled')

+        raven.tags_context({
+            'api_key': userid,
+        })
+
         return (AnonymousUser(), key)

<|original_code|>
from __future__ import absolute_import

from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed

from sentry.models import ApiKey, ProjectKey

class QuietBasicAuthentication(BasicAuthentication):
    def authenticate_header(self, request):
        return 'xBasic realm="%s"' % self.www_authenticate_realm

class ApiKeyAuthentication(QuietBasicAuthentication):
    def authenticate_credentials(self, userid, password):
        if password:
            return

        try:
            key = ApiKey.objects.get_from_cache(key=userid)
        except ApiKey.DoesNotExist:
            return None

        if not key.is_active:
            raise AuthenticationFailed('Key is disabled')

        return (AnonymousUser(), key)

class ProjectKeyAuthentication(QuietBasicAuthentication):
    def authenticate_credentials(self, userid, password):
        try:
            pk = ProjectKey.objects.get_from_cache(public_key=userid)
        except ProjectKey.DoesNotExist:
            return None

        if not constant_time_compare(pk.secret_key, password):
            return None

        if not pk.is_active:
            raise AuthenticationFailed('Key is disabled')

        if not pk.roles.api:
            raise AuthenticationFailed('Key does not allow API access')

        return (AnonymousUser(), pk)

<|edits_diff|>
--- src/sentry/api/authentication.py
+++ src/sentry/api/authentication.py
@@ -5,6 +5,7 @@
 from rest_framework.authentication import BasicAuthentication
 from rest_framework.exceptions import AuthenticationFailed

+from sentry.app import raven
 from sentry.models import ApiKey, ProjectKey

<|current_version|>
from __future__ import absolute_import

from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed

from sentry.app import raven
from sentry.models import ApiKey, ProjectKey

class QuietBasicAuthentication(BasicAuthentication):
    def authenticate_header(self, request):
        return 'xBasic realm="%s"' % self.www_authenticate_realm

class ApiKeyAuthentication(QuietBasicAuthentication):
    def authenticate_credentials(self, userid, password):
        if password:
            return

        try:
            key = ApiKey.objects.get_from_cache(key=userid)
        except ApiKey.DoesNotExist:
            return None

        if not key.is_active:
            raise AuthenticationFailed('Key is disabled')

        return (AnonymousUser(), key)

class ProjectKeyAuthentication(QuietBasicAuthentication):
    def authenticate_credentials(self, userid, password):
        try:
            pk = ProjectKey.objects.get_from_cache(public_key=userid)
        except ProjectKey.DoesNotExist:
            return None

        if not constant_time_compare(pk.secret_key, password):
            return None

        if not pk.is_active:
            raise AuthenticationFailed('Key is disabled')

        if not pk.roles.api:
            raise AuthenticationFailed('Key does not allow API access')

        return (AnonymousUser(), pk)

<|next_version|>
from __future__ import absolute_import

from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed

from sentry.app import raven
from sentry.models import ApiKey, ProjectKey

class QuietBasicAuthentication(BasicAuthentication):
    def authenticate_header(self, request):
        return 'xBasic realm="%s"' % self.www_authenticate_realm

class ApiKeyAuthentication(QuietBasicAuthentication):
    def authenticate_credentials(self, userid, password):
        if password:
            return

        try:
            key = ApiKey.objects.get_from_cache(key=userid)
        except ApiKey.DoesNotExist:
            return None

        if not key.is_active:
            raise AuthenticationFailed('Key is disabled')

        raven.tags_context({
            'api_key': userid,
        })

        return (AnonymousUser(), key)

class ProjectKeyAuthentication(QuietBasicAuthentication):
    def authenticate_credentials(self, userid, password):
        try:
            pk = ProjectKey.objects.get_from_cache(public_key=userid)
        except ProjectKey.DoesNotExist:
            return None

        if not constant_time_compare(pk.secret_key, password):
            return None

        if not pk.is_active:
            raise AuthenticationFailed('Key is disabled')

        if not pk.roles.api:
            raise AuthenticationFailed('Key does not allow API access')

        return (AnonymousUser(), pk)


Update clean method to ensure that meal end_time is not same as or less than meal start_time

--- app/timetables/models.py
+++ app/timetables/models.py
@@ -1,6 +1,8 @@
 from __future__ import unicode_literals

 from django.db import models
+from django.core.exceptions import ValidationError
+from django.utils.translation import ugettext_lazy as _

 from common.mixins import ForceCapitalizeMixin

@@ -30,5 +32,10 @@

     capitalized_field_names = ('name',)

+    def clean(self):
+        if self.start_time >= self.end_time:
+            raise ValidationError(_('start_time must be less than end_time.'))
+        super().clean()
+
     def __str__(self):
         return self.name

<|original_code|>
from __future__ import unicode_literals

from django.db import models

from common.mixins import ForceCapitalizeMixin

class Weekday(ForceCapitalizeMixin, models.Model):
    """Model representing the day of the week."""

    name = models.CharField(max_length=60, unique=True)

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

class Meal(ForceCapitalizeMixin, models.Model):
    """
    Model representing food occasions.

    This represents an occasion during the day that food
    is scheduled to be served. E.g breakfast, lunch, etc.
    """

    name = models.CharField(max_length=60, unique=True)
    start_time = models.TimeField()
    end_time = models.TimeField()

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

<|edits_diff|>
--- app/timetables/models.py
+++ app/timetables/models.py
@@ -1,6 +1,8 @@
 from __future__ import unicode_literals

 from django.db import models
+from django.core.exceptions import ValidationError
+from django.utils.translation import ugettext_lazy as _

 from common.mixins import ForceCapitalizeMixin

<|current_version|>
from __future__ import unicode_literals

from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from common.mixins import ForceCapitalizeMixin

class Weekday(ForceCapitalizeMixin, models.Model):
    """Model representing the day of the week."""

    name = models.CharField(max_length=60, unique=True)

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

class Meal(ForceCapitalizeMixin, models.Model):
    """
    Model representing food occasions.

    This represents an occasion during the day that food
    is scheduled to be served. E.g breakfast, lunch, etc.
    """

    name = models.CharField(max_length=60, unique=True)
    start_time = models.TimeField()
    end_time = models.TimeField()

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

<|next_version|>
from __future__ import unicode_literals

from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from common.mixins import ForceCapitalizeMixin

class Weekday(ForceCapitalizeMixin, models.Model):
    """Model representing the day of the week."""

    name = models.CharField(max_length=60, unique=True)

    capitalized_field_names = ('name',)

    def __str__(self):
        return self.name

class Meal(ForceCapitalizeMixin, models.Model):
    """
    Model representing food occasions.

    This represents an occasion during the day that food
    is scheduled to be served. E.g breakfast, lunch, etc.
    """

    name = models.CharField(max_length=60, unique=True)
    start_time = models.TimeField()
    end_time = models.TimeField()

    capitalized_field_names = ('name',)

    def clean(self):
        if self.start_time >= self.end_time:
            raise ValidationError(_('start_time must be less than end_time.'))
        super().clean()

    def __str__(self):
        return self.name


Use fresh build environment by default in tests

--- tests/utils.py
+++ tests/utils.py
@@ -22,6 +22,13 @@

 def with_app(*args, **kwargs):
     kwargs = kwargs.copy()
+
+    # Expand test data directory.
     if "srcdir" in kwargs:
         kwargs["srcdir"] = srcdir(kwargs["srcdir"])
+
+    # By default use a fresh build environment.
+    if "freshenv" not in kwargs:
+        kwargs["freshenv"] = True
+
     return sphinx_tests_util.with_app(*args, **kwargs)

<|original_code|>

import os
import sphinx_tests_util
from xml.etree import ElementTree
from xml.dom import minidom

# =============================================================================
# Utility functions

def srcdir(name):
    test_root = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(test_root, "data", name)

def pretty_print_xml(node):
    minidom_xml = minidom.parseString(ElementTree.tostring(node))
    output = minidom_xml.toprettyxml(indent="  ")
    lines = [line for line in output.splitlines() if line.strip()]
    print "\n".join(lines)

def with_app(*args, **kwargs):
    kwargs = kwargs.copy()
    if "srcdir" in kwargs:
        kwargs["srcdir"] = srcdir(kwargs["srcdir"])
    return sphinx_tests_util.with_app(*args, **kwargs)

<|edits_diff|>
--- tests/utils.py
+++ tests/utils.py
@@ -22,6 +22,8 @@

 def with_app(*args, **kwargs):
     kwargs = kwargs.copy()
+
+    # Expand test data directory.
     if "srcdir" in kwargs:
         kwargs["srcdir"] = srcdir(kwargs["srcdir"])
     return sphinx_tests_util.with_app(*args, **kwargs)
<|current_version|>

import os
import sphinx_tests_util
from xml.etree import ElementTree
from xml.dom import minidom

# =============================================================================
# Utility functions

def srcdir(name):
    test_root = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(test_root, "data", name)

def pretty_print_xml(node):
    minidom_xml = minidom.parseString(ElementTree.tostring(node))
    output = minidom_xml.toprettyxml(indent="  ")
    lines = [line for line in output.splitlines() if line.strip()]
    print "\n".join(lines)

def with_app(*args, **kwargs):
    kwargs = kwargs.copy()

    # Expand test data directory.
    if "srcdir" in kwargs:
        kwargs["srcdir"] = srcdir(kwargs["srcdir"])
    return sphinx_tests_util.with_app(*args, **kwargs)

<|next_version|>

import os
import sphinx_tests_util
from xml.etree import ElementTree
from xml.dom import minidom

# =============================================================================
# Utility functions

def srcdir(name):
    test_root = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(test_root, "data", name)

def pretty_print_xml(node):
    minidom_xml = minidom.parseString(ElementTree.tostring(node))
    output = minidom_xml.toprettyxml(indent="  ")
    lines = [line for line in output.splitlines() if line.strip()]
    print "\n".join(lines)

def with_app(*args, **kwargs):
    kwargs = kwargs.copy()

    # Expand test data directory.
    if "srcdir" in kwargs:
        kwargs["srcdir"] = srcdir(kwargs["srcdir"])

    # By default use a fresh build environment.
    if "freshenv" not in kwargs:
        kwargs["freshenv"] = True

    return sphinx_tests_util.with_app(*args, **kwargs)


Use a custom 404 handler to avoid using the default template loader.

--- test_project/test_project/urls.py
+++ test_project/test_project/urls.py
@@ -1,4 +1,5 @@
 from django.conf.urls import patterns, include, url
+from django.http import HttpResponseNotFound

 # Uncomment the next two lines to enable the admin:
 # from django.contrib import admin
@@ -7,3 +8,8 @@
 urlpatterns = patterns('',
     url(r'^', include('test_app.urls')),
 )
+
+def custom404(request):
+    return HttpResponseNotFound(status=404)
+
+handler404 = 'test_project.urls.custom404'

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

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^', include('test_app.urls')),
)

<|edits_diff|>
--- test_project/test_project/urls.py
+++ test_project/test_project/urls.py
@@ -1,4 +1,5 @@
 from django.conf.urls import patterns, include, url
+from django.http import HttpResponseNotFound

 # Uncomment the next two lines to enable the admin:
 # from django.contrib import admin
<|current_version|>
from django.conf.urls import patterns, include, url
from django.http import HttpResponseNotFound

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^', include('test_app.urls')),
)

<|next_version|>
from django.conf.urls import patterns, include, url
from django.http import HttpResponseNotFound

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^', include('test_app.urls')),
)

def custom404(request):
    return HttpResponseNotFound(status=404)

handler404 = 'test_project.urls.custom404'


Add Xception to keras cache

Add Xception to keras cache

--- cache_keras_weights.py
+++ cache_keras_weights.py
@@ -2,8 +2,10 @@
 from keras.applications.vgg16 import VGG16
 from keras.applications.vgg19 import VGG19
 from keras.applications.inception_v3 import InceptionV3
+from keras.applications.xception import Xception

 resnet = ResNet50(weights='imagenet')
 vgg16 = VGG16(weights='imagenet')
 vgg19 = VGG19(weights='imagenet')
 inception = InceptionV3(weights='imagenet')
+xception = Xception(weights='imagenet')

<|original_code|>
from keras.applications.resnet50 import ResNet50
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.inception_v3 import InceptionV3

resnet = ResNet50(weights='imagenet')
vgg16 = VGG16(weights='imagenet')
vgg19 = VGG19(weights='imagenet')
inception = InceptionV3(weights='imagenet')

<|edits_diff|>
--- cache_keras_weights.py
+++ cache_keras_weights.py
@@ -2,6 +2,7 @@
 from keras.applications.vgg16 import VGG16
 from keras.applications.vgg19 import VGG19
 from keras.applications.inception_v3 import InceptionV3
+from keras.applications.xception import Xception

 resnet = ResNet50(weights='imagenet')
 vgg16 = VGG16(weights='imagenet')
<|current_version|>
from keras.applications.resnet50 import ResNet50
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.inception_v3 import InceptionV3
from keras.applications.xception import Xception

resnet = ResNet50(weights='imagenet')
vgg16 = VGG16(weights='imagenet')
vgg19 = VGG19(weights='imagenet')
inception = InceptionV3(weights='imagenet')

<|next_version|>
from keras.applications.resnet50 import ResNet50
from keras.applications.vgg16 import VGG16
from keras.applications.vgg19 import VGG19
from keras.applications.inception_v3 import InceptionV3
from keras.applications.xception import Xception

resnet = ResNet50(weights='imagenet')
vgg16 = VGG16(weights='imagenet')
vgg19 = VGG19(weights='imagenet')
inception = InceptionV3(weights='imagenet')
xception = Xception(weights='imagenet')


Print the time of checking status at github.

--- tardis/tests/tests_slow/runner.py
+++ tardis/tests/tests_slow/runner.py
@@ -1,4 +1,5 @@
 import argparse
+import datetime
 import json
 import os
 import time
@@ -33,4 +34,8 @@
             os.system(test_command.format(args.yaml_filepath,
                                           args.atomic_dataset))
         else:
+            checked = datetime.datetime.now()
+            print "Up-to-date. Checked on {0} {1}".format(
+                checked.strftime("%d-%b-%Y"), checked.strftime("%H:%M:%S")
+            )
             time.sleep(600)

<|original_code|>
import argparse
import json
import os
import time

import requests
from tardis import __githash__ as tardis_githash

parser = argparse.ArgumentParser(description="Run slow integration tests")
parser.add_argument("--yaml", dest="yaml_filepath",
                    help="Path to YAML config file for integration tests.")
parser.add_argument("--atomic-dataset", dest="atomic_dataset",
                    help="Path to atomic dataset.")

test_command = (
    "python setup.py test --test-path=tardis/tests/tests_slow/test_integration.py "
    "--args=\"-rs --integration-tests={0} --atomic-dataset={1} --remote-data\""
)

if __name__ == "__main__":
    args = parser.parse_args()
    while True:
        gh_request = requests.get(
            "https://api.github.com/repos/tardis-sn/tardis/branches/master"
        )
        gh_master_head_data = json.loads(gh_request.content)
        gh_tardis_githash = gh_master_head_data['commit']['sha']

        if gh_tardis_githash != tardis_githash:
            os.system("git pull origin master")
            os.system(test_command.format(args.yaml_filepath,
                                          args.atomic_dataset))
        else:
            time.sleep(600)

<|edits_diff|>
--- tardis/tests/tests_slow/runner.py
+++ tardis/tests/tests_slow/runner.py
@@ -1,4 +1,5 @@
 import argparse
+import datetime
 import json
 import os
 import time
<|current_version|>
import argparse
import datetime
import json
import os
import time

import requests
from tardis import __githash__ as tardis_githash

parser = argparse.ArgumentParser(description="Run slow integration tests")
parser.add_argument("--yaml", dest="yaml_filepath",
                    help="Path to YAML config file for integration tests.")
parser.add_argument("--atomic-dataset", dest="atomic_dataset",
                    help="Path to atomic dataset.")

test_command = (
    "python setup.py test --test-path=tardis/tests/tests_slow/test_integration.py "
    "--args=\"-rs --integration-tests={0} --atomic-dataset={1} --remote-data\""
)

if __name__ == "__main__":
    args = parser.parse_args()
    while True:
        gh_request = requests.get(
            "https://api.github.com/repos/tardis-sn/tardis/branches/master"
        )
        gh_master_head_data = json.loads(gh_request.content)
        gh_tardis_githash = gh_master_head_data['commit']['sha']

        if gh_tardis_githash != tardis_githash:
            os.system("git pull origin master")
            os.system(test_command.format(args.yaml_filepath,
                                          args.atomic_dataset))
        else:
            time.sleep(600)

<|next_version|>
import argparse
import datetime
import json
import os
import time

import requests
from tardis import __githash__ as tardis_githash

parser = argparse.ArgumentParser(description="Run slow integration tests")
parser.add_argument("--yaml", dest="yaml_filepath",
                    help="Path to YAML config file for integration tests.")
parser.add_argument("--atomic-dataset", dest="atomic_dataset",
                    help="Path to atomic dataset.")

test_command = (
    "python setup.py test --test-path=tardis/tests/tests_slow/test_integration.py "
    "--args=\"-rs --integration-tests={0} --atomic-dataset={1} --remote-data\""
)

if __name__ == "__main__":
    args = parser.parse_args()
    while True:
        gh_request = requests.get(
            "https://api.github.com/repos/tardis-sn/tardis/branches/master"
        )
        gh_master_head_data = json.loads(gh_request.content)
        gh_tardis_githash = gh_master_head_data['commit']['sha']

        if gh_tardis_githash != tardis_githash:
            os.system("git pull origin master")
            os.system(test_command.format(args.yaml_filepath,
                                          args.atomic_dataset))
        else:
            checked = datetime.datetime.now()
            print "Up-to-date. Checked on {0} {1}".format(
                checked.strftime("%d-%b-%Y"), checked.strftime("%H:%M:%S")
            )
            time.sleep(600)


Add a default null logger per python recommendations.

--- libpebble2/__init__.py
+++ libpebble2/__init__.py
@@ -1,3 +1,7 @@
 __author__ = 'katharine'

+import logging
+
 from .exceptions import *
+
+logging.getLogger('libpebble2').addHandler(logging.NullHandler())

<|original_code|>
__author__ = 'katharine'

from .exceptions import *

<|edits_diff|>
--- libpebble2/__init__.py
+++ libpebble2/__init__.py
@@ -1,3 +1,5 @@
 __author__ = 'katharine'

+import logging
+
 from .exceptions import *
<|current_version|>
__author__ = 'katharine'

import logging

from .exceptions import *

<|next_version|>
__author__ = 'katharine'

import logging

from .exceptions import *

logging.getLogger('libpebble2').addHandler(logging.NullHandler())


Disable clickjacking protection on demos to display them in iframes

--- dwitter/dweet/views.py
+++ dwitter/dweet/views.py
@@ -4,7 +4,10 @@
 from django.contrib.auth.decorators import login_required

 from dwitter.models import Dweet
+from django.views.decorators.clickjacking import xframe_options_exempt

+
+@xframe_options_exempt
 def fullscreen_dweet(request, dweet_id):
   dweet = get_object_or_404(Dweet, id=dweet_id)

<|original_code|>
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from dwitter.models import Dweet

def fullscreen_dweet(request, dweet_id):
  dweet = get_object_or_404(Dweet, id=dweet_id)

  context = {'dweet': dweet
            }
  return render(request, 'dweet/dweet-id.html', context );

<|edits_diff|>
--- dwitter/dweet/views.py
+++ dwitter/dweet/views.py
@@ -4,6 +4,7 @@
 from django.contrib.auth.decorators import login_required

 from dwitter.models import Dweet
+from django.views.decorators.clickjacking import xframe_options_exempt

 def fullscreen_dweet(request, dweet_id):
   dweet = get_object_or_404(Dweet, id=dweet_id)
<|current_version|>
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from dwitter.models import Dweet
from django.views.decorators.clickjacking import xframe_options_exempt

def fullscreen_dweet(request, dweet_id):
  dweet = get_object_or_404(Dweet, id=dweet_id)

  context = {'dweet': dweet
            }
  return render(request, 'dweet/dweet-id.html', context );

<|next_version|>
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required

from dwitter.models import Dweet
from django.views.decorators.clickjacking import xframe_options_exempt

@xframe_options_exempt
def fullscreen_dweet(request, dweet_id):
  dweet = get_object_or_404(Dweet, id=dweet_id)

  context = {'dweet': dweet
            }
  return render(request, 'dweet/dweet-id.html', context );


Print the traceback as well for debugging purposes.

--- scripts/asgard-deploy.py
+++ scripts/asgard-deploy.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 import sys
 import logging
+import traceback
 import click
 from os import path

@@ -18,6 +19,7 @@
     try:
         asgard.deploy(ami_id)
     except Exception, e:
+        traceback.print_exc()
         click.secho("Error Deploying AMI: {0}.\nMessage: {1}".format(ami_id, e.message), fg='red')
         sys.exit(1)

<|original_code|>
#!/usr/bin/env python
import sys
import logging
import click
from os import path

# Add top-level module path to sys.path before importing tubular code.
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )

from tubular import asgard

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
    try:
        asgard.deploy(ami_id)
    except Exception, e:
        click.secho("Error Deploying AMI: {0}.\nMessage: {1}".format(ami_id, e.message), fg='red')
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__":
    deploy()

<|edits_diff|>
--- scripts/asgard-deploy.py
+++ scripts/asgard-deploy.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 import sys
 import logging
+import traceback
 import click
 from os import path

<|current_version|>
#!/usr/bin/env python
import sys
import logging
import traceback
import click
from os import path

# Add top-level module path to sys.path before importing tubular code.
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )

from tubular import asgard

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
    try:
        asgard.deploy(ami_id)
    except Exception, e:
        click.secho("Error Deploying AMI: {0}.\nMessage: {1}".format(ami_id, e.message), fg='red')
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__":
    deploy()

<|next_version|>
#!/usr/bin/env python
import sys
import logging
import traceback
import click
from os import path

# Add top-level module path to sys.path before importing tubular code.
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )

from tubular import asgard

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

@click.command()
@click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True)
def deploy(ami_id):
    try:
        asgard.deploy(ami_id)
    except Exception, e:
        traceback.print_exc()
        click.secho("Error Deploying AMI: {0}.\nMessage: {1}".format(ami_id, e.message), fg='red')
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__":
    deploy()


Add comments indicating source of formulae..

--- 6/e6.py
+++ 6/e6.py
@@ -1,8 +1,10 @@
 #!/usr/bin/env python

+# http://www.proofwiki.org/wiki/Sum_of_Sequence_of_Squares
 def sum_seq_squares(n):
     return (n * (n+1) * ((2*n)+1)) / 6

+# http://www.regentsprep.org/regents/math/algtrig/ATP2/ArithSeq.htm
 def sum_seq(n):
     return (n * (n + 1)) / 2

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

def sum_seq_squares(n):
    return (n * (n+1) * ((2*n)+1)) / 6

def sum_seq(n):
    return (n * (n + 1)) / 2

def main():
	sum_seq_sq_100 = sum_seq_squares(100)
	sum_seq_100 = sum_seq(100)
	sq_sum_seq_100 = sum_seq_100**2
	diff = sq_sum_seq_100 - sum_seq_sq_100
	print('diff is {0}'.format(diff))

if __name__ == '__main__':
	main()
<|edits_diff|>
--- 6/e6.py
+++ 6/e6.py
@@ -1,5 +1,6 @@
 #!/usr/bin/env python

+# http://www.proofwiki.org/wiki/Sum_of_Sequence_of_Squares
 def sum_seq_squares(n):
     return (n * (n+1) * ((2*n)+1)) / 6

<|current_version|>
#!/usr/bin/env python

# http://www.proofwiki.org/wiki/Sum_of_Sequence_of_Squares
def sum_seq_squares(n):
    return (n * (n+1) * ((2*n)+1)) / 6

def sum_seq(n):
    return (n * (n + 1)) / 2

def main():
	sum_seq_sq_100 = sum_seq_squares(100)
	sum_seq_100 = sum_seq(100)
	sq_sum_seq_100 = sum_seq_100**2
	diff = sq_sum_seq_100 - sum_seq_sq_100
	print('diff is {0}'.format(diff))

if __name__ == '__main__':
	main()
<|next_version|>
#!/usr/bin/env python

# http://www.proofwiki.org/wiki/Sum_of_Sequence_of_Squares
def sum_seq_squares(n):
    return (n * (n+1) * ((2*n)+1)) / 6

# http://www.regentsprep.org/regents/math/algtrig/ATP2/ArithSeq.htm
def sum_seq(n):
    return (n * (n + 1)) / 2

def main():
	sum_seq_sq_100 = sum_seq_squares(100)
	sum_seq_100 = sum_seq(100)
	sq_sum_seq_100 = sum_seq_100**2
	diff = sq_sum_seq_100 - sum_seq_sq_100
	print('diff is {0}'.format(diff))

if __name__ == '__main__':
	main()


Add absolute URL for Surprises

Add absolute URL for Surprises

This allows the CreateView to work correctly

--- mirigata/surprise/models.py
+++ mirigata/surprise/models.py
@@ -1,6 +1,10 @@
+from django.core.urlresolvers import reverse
 from django.db import models

 class Surprise(models.Model):
     link = models.URLField(max_length=500)
     description = models.TextField(max_length=1000)
+
+    def get_absolute_url(self):
+        return reverse('surprise-detail', kwargs={"pk": self.id})

<|original_code|>
from django.db import models

class Surprise(models.Model):
    link = models.URLField(max_length=500)
    description = models.TextField(max_length=1000)

<|edits_diff|>
--- mirigata/surprise/models.py
+++ mirigata/surprise/models.py
@@ -1,3 +1,4 @@
+from django.core.urlresolvers import reverse
 from django.db import models

<|current_version|>
from django.core.urlresolvers import reverse
from django.db import models

class Surprise(models.Model):
    link = models.URLField(max_length=500)
    description = models.TextField(max_length=1000)

<|next_version|>
from django.core.urlresolvers import reverse
from django.db import models

class Surprise(models.Model):
    link = models.URLField(max_length=500)
    description = models.TextField(max_length=1000)

    def get_absolute_url(self):
        return reverse('surprise-detail', kwargs={"pk": self.id})


Fix convert to support python 2 and python 3

--- django_settings/keymaker.py
+++ django_settings/keymaker.py
@@ -1,8 +1,12 @@
+import sys
+
 class KeyMaker(object):
     def __init__(self, prefix):
         self.prefix = prefix

     def convert(self, arg):
+        if sys.version_info < (3,) and isinstance(arg, unicode):
+            return arg.encode(django.settings.DEFAULT_CHARSET)
         return str(arg)

     def args_to_key(self, args):

<|original_code|>
class KeyMaker(object):
    def __init__(self, prefix):
        self.prefix = prefix

    def convert(self, arg):
        return str(arg)

    def args_to_key(self, args):
        return ":".join(map(self.convert, args))

    def kwargs_to_key(self, kwargs):
        return ":".join([
            "%s:%s" % (self.convert(k), self.convert(v))
            for k, v in kwargs.items()
        ])

    def make(self, method_name, args, kwargs):
        key = ":".join((
            self.prefix,
            method_name,
            self.args_to_key(args),
            self.kwargs_to_key(kwargs),
        ))
        return key

<|edits_diff|>
--- django_settings/keymaker.py
+++ django_settings/keymaker.py
@@ -1,3 +1,5 @@
+import sys
+
 class KeyMaker(object):
     def __init__(self, prefix):
         self.prefix = prefix
<|current_version|>
import sys

class KeyMaker(object):
    def __init__(self, prefix):
        self.prefix = prefix

    def convert(self, arg):
        return str(arg)

    def args_to_key(self, args):
        return ":".join(map(self.convert, args))

    def kwargs_to_key(self, kwargs):
        return ":".join([
            "%s:%s" % (self.convert(k), self.convert(v))
            for k, v in kwargs.items()
        ])

    def make(self, method_name, args, kwargs):
        key = ":".join((
            self.prefix,
            method_name,
            self.args_to_key(args),
            self.kwargs_to_key(kwargs),
        ))
        return key

<|next_version|>
import sys

class KeyMaker(object):
    def __init__(self, prefix):
        self.prefix = prefix

    def convert(self, arg):
        if sys.version_info < (3,) and isinstance(arg, unicode):
            return arg.encode(django.settings.DEFAULT_CHARSET)
        return str(arg)

    def args_to_key(self, args):
        return ":".join(map(self.convert, args))

    def kwargs_to_key(self, kwargs):
        return ":".join([
            "%s:%s" % (self.convert(k), self.convert(v))
            for k, v in kwargs.items()
        ])

    def make(self, method_name, args, kwargs):
        key = ":".join((
            self.prefix,
            method_name,
            self.args_to_key(args),
            self.kwargs_to_key(kwargs),
        ))
        return key


Mark beginning of each section with a letter

--- main.py
+++ main.py
@@ -21,5 +21,10 @@

 print('# My Dictionary')
 print('## Definitions')
+curLetter = None
 for k in sort:
+    l = k[0].upper()
+    if curLetter != l:
+        curLetter = l
+        print('### {}'.format(curLetter))
     print('* *{}* - {}'.format(k, defs[k]))

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

"""TODO:
 * more flexible sorting options
 * use -o to specify output file
 * check more explicitly for errors in JSON files
"""

import json, sys

if len(sys.argv) > 1:
    inFn = sys.argv[1]

with open(inFn, 'r') as f:
    try:
        defs = json.load(f)
    except:
        sys.exit('{} has a syntax error'.format(inFn))

sort = sorted(defs)

print('# My Dictionary')
print('## Definitions')
for k in sort:
    print('* *{}* - {}'.format(k, defs[k]))

<|edits_diff|>
--- main.py
+++ main.py
@@ -21,5 +21,6 @@

 print('# My Dictionary')
 print('## Definitions')
+curLetter = None
 for k in sort:
     print('* *{}* - {}'.format(k, defs[k]))
<|current_version|>
#!/usr/bin/env python3

"""TODO:
 * more flexible sorting options
 * use -o to specify output file
 * check more explicitly for errors in JSON files
"""

import json, sys

if len(sys.argv) > 1:
    inFn = sys.argv[1]

with open(inFn, 'r') as f:
    try:
        defs = json.load(f)
    except:
        sys.exit('{} has a syntax error'.format(inFn))

sort = sorted(defs)

print('# My Dictionary')
print('## Definitions')
curLetter = None
for k in sort:
    print('* *{}* - {}'.format(k, defs[k]))

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

"""TODO:
 * more flexible sorting options
 * use -o to specify output file
 * check more explicitly for errors in JSON files
"""

import json, sys

if len(sys.argv) > 1:
    inFn = sys.argv[1]

with open(inFn, 'r') as f:
    try:
        defs = json.load(f)
    except:
        sys.exit('{} has a syntax error'.format(inFn))

sort = sorted(defs)

print('# My Dictionary')
print('## Definitions')
curLetter = None
for k in sort:
    l = k[0].upper()
    if curLetter != l:
        curLetter = l
        print('### {}'.format(curLetter))
    print('* *{}* - {}'.format(k, defs[k]))


Add back imports to repr test.

Add back imports to repr test.

--- tests/test_repr.py
+++ tests/test_repr.py
@@ -5,8 +5,11 @@
 # Author: Dominik Gresch <greschd@gmx.ch>

 import pytest
+import tbmodels  # pylint: disable=unused-import

 import numpy as np
+
+from tbmodels._ptools.sparse_matrix import csr  # pylint: disable=unused-import

 from parameters import T_VALUES, KPT

<|original_code|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>

import pytest

import numpy as np

from parameters import T_VALUES, KPT

@pytest.mark.parametrize('t', T_VALUES)
def test_repr_reload(t, get_model):
    m1 = get_model(*t)
    m2 = eval(repr(m1))
    for k in KPT:
        assert np.isclose(m1.hamilton(k), m2.hamilton(k)).all()

<|edits_diff|>
--- tests/test_repr.py
+++ tests/test_repr.py
@@ -5,6 +5,7 @@
 # Author: Dominik Gresch <greschd@gmx.ch>

 import pytest
+import tbmodels  # pylint: disable=unused-import

 import numpy as np

<|current_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>

import pytest
import tbmodels  # pylint: disable=unused-import

import numpy as np

from parameters import T_VALUES, KPT

@pytest.mark.parametrize('t', T_VALUES)
def test_repr_reload(t, get_model):
    m1 = get_model(*t)
    m2 = eval(repr(m1))
    for k in KPT:
        assert np.isclose(m1.hamilton(k), m2.hamilton(k)).all()

<|next_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>

import pytest
import tbmodels  # pylint: disable=unused-import

import numpy as np

from tbmodels._ptools.sparse_matrix import csr  # pylint: disable=unused-import

from parameters import T_VALUES, KPT

@pytest.mark.parametrize('t', T_VALUES)
def test_repr_reload(t, get_model):
    m1 = get_model(*t)
    m2 = eval(repr(m1))
    for k in KPT:
        assert np.isclose(m1.hamilton(k), m2.hamilton(k)).all()


Add tests for unicode csv files.

Add tests for unicode csv files.

--- test/test_cart.py
+++ test/test_cart.py
@@ -1,4 +1,8 @@
+# -*- coding: utf-8 -*-
+
 import cart
+from cart._compatibility import utf8
+

 def test_valid_cart_from_csv():
     _cart = cart.cart_from_csv('test/cart_files/default_cart.csv')
@@ -6,3 +10,8 @@
                                      'ice cream': 3.49,
                                      'strawberries': 2.00,
                                      'snickers bar': 0.70}
+
+
+def test_unicode_cart_from_csv():
+    _cart = cart.cart_from_csv('test/cart_files/unicode_cart.csv')
+    assert _cart._product_prices == {utf8('somethingä'): 1.0}

<|original_code|>
import cart

def test_valid_cart_from_csv():
    _cart = cart.cart_from_csv('test/cart_files/default_cart.csv')
    assert _cart._product_prices == {'apple': 0.15,
                                     'ice cream': 3.49,
                                     'strawberries': 2.00,
                                     'snickers bar': 0.70}

<|edits_diff|>
--- test/test_cart.py
+++ test/test_cart.py
@@ -1,4 +1,8 @@
+# -*- coding: utf-8 -*-
+
 import cart
+from cart._compatibility import utf8
+

 def test_valid_cart_from_csv():
     _cart = cart.cart_from_csv('test/cart_files/default_cart.csv')
<|current_version|>
# -*- coding: utf-8 -*-

import cart
from cart._compatibility import utf8

def test_valid_cart_from_csv():
    _cart = cart.cart_from_csv('test/cart_files/default_cart.csv')
    assert _cart._product_prices == {'apple': 0.15,
                                     'ice cream': 3.49,
                                     'strawberries': 2.00,
                                     'snickers bar': 0.70}

<|next_version|>
# -*- coding: utf-8 -*-

import cart
from cart._compatibility import utf8

def test_valid_cart_from_csv():
    _cart = cart.cart_from_csv('test/cart_files/default_cart.csv')
    assert _cart._product_prices == {'apple': 0.15,
                                     'ice cream': 3.49,
                                     'strawberries': 2.00,
                                     'snickers bar': 0.70}

def test_unicode_cart_from_csv():
    _cart = cart.cart_from_csv('test/cart_files/unicode_cart.csv')
    assert _cart._product_prices == {utf8('somethingä'): 1.0}


Resolve issuse about cpu, it depends on fps

--- main.py
+++ main.py
@@ -11,6 +11,9 @@

 main_controller.init_game()

+# Control fps
+clock = pygame.time.Clock()
+
 while not main_controller.quit_game:
     # Listen events
     event_controller.run()
@@ -19,4 +22,8 @@
     main_controller.run()

     pygame.display.flip()
+
+    # Approximately 60fps
+    clock.tick(60)
+
 pygame.quit()

<|original_code|>
__author__ = 'tri'
from controller.event_controller import EventController
from controller.env_controller import EnvController
from controller.main_controller import MainController
import pygame

env_controller = EnvController()
event_controller = EventController()
main_controller = MainController(event_controller, env_controller)

main_controller.init_game()

while not main_controller.quit_game:
    # Listen events
    event_controller.run()

    # Update screen
    main_controller.run()

    pygame.display.flip()
pygame.quit()

<|edits_diff|>
--- main.py
+++ main.py
@@ -11,6 +11,9 @@

 main_controller.init_game()

+# Control fps
+clock = pygame.time.Clock()
+
 while not main_controller.quit_game:
     # Listen events
     event_controller.run()
<|current_version|>
__author__ = 'tri'
from controller.event_controller import EventController
from controller.env_controller import EnvController
from controller.main_controller import MainController
import pygame

env_controller = EnvController()
event_controller = EventController()
main_controller = MainController(event_controller, env_controller)

main_controller.init_game()

# Control fps
clock = pygame.time.Clock()

while not main_controller.quit_game:
    # Listen events
    event_controller.run()

    # Update screen
    main_controller.run()

    pygame.display.flip()
pygame.quit()

<|next_version|>
__author__ = 'tri'
from controller.event_controller import EventController
from controller.env_controller import EnvController
from controller.main_controller import MainController
import pygame

env_controller = EnvController()
event_controller = EventController()
main_controller = MainController(event_controller, env_controller)

main_controller.init_game()

# Control fps
clock = pygame.time.Clock()

while not main_controller.quit_game:
    # Listen events
    event_controller.run()

    # Update screen
    main_controller.run()

    pygame.display.flip()

    # Approximately 60fps
    clock.tick(60)

pygame.quit()


Add support for connecting to NCBI database

--- meta/util.py
+++ meta/util.py
@@ -2,7 +2,10 @@
 import sys
 import time
 import math
+import sqlite3
 from contextlib import contextmanager
+
+import meta

 @contextmanager
 def timeit_msg(msg):
@@ -30,4 +33,10 @@
 		res = 'GB'
 	return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)

+def get_ncbi_db_conn():
+	dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db')
+	conn = sqlite3.connect(dbfile)
+	conn.text_factory = str
+	return conn

+

<|original_code|>
import os
import sys
import time
import math
from contextlib import contextmanager

@contextmanager
def timeit_msg(msg):
	print '{}...'.format(msg),
	sys.stdout.flush()

	start = time.time()
	yield
	stop = time.time()

	print ' ({:1.3f} s)'.format((stop-start))

def get_file_size(fname):
	fstats = os.stat(fname)
	size = fstats.st_size
	exponent = int(math.log(size, 10))
	divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9}
	if exponent < 3:
		res = 'B'
	if exponent >= 3 and exponent < 6:
		res = 'kB'
	elif exponent >= 6 and exponent < 9:
		res = 'MB'
	else:
		res = 'GB'
	return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)

<|edits_diff|>
--- meta/util.py
+++ meta/util.py
@@ -2,7 +2,10 @@
 import sys
 import time
 import math
+import sqlite3
 from contextlib import contextmanager
+
+import meta

 @contextmanager
 def timeit_msg(msg):
@@ -30,4 +33,9 @@
 		res = 'GB'
 	return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)

+def get_ncbi_db_conn():
+	dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db')
+	conn = sqlite3.connect(dbfile)
+	conn.text_factory = str
+	return conn

<|current_version|>
import os
import sys
import time
import math
import sqlite3
from contextlib import contextmanager

import meta

@contextmanager
def timeit_msg(msg):
	print '{}...'.format(msg),
	sys.stdout.flush()

	start = time.time()
	yield
	stop = time.time()

	print ' ({:1.3f} s)'.format((stop-start))

def get_file_size(fname):
	fstats = os.stat(fname)
	size = fstats.st_size
	exponent = int(math.log(size, 10))
	divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9}
	if exponent < 3:
		res = 'B'
	if exponent >= 3 and exponent < 6:
		res = 'kB'
	elif exponent >= 6 and exponent < 9:
		res = 'MB'
	else:
		res = 'GB'
	return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)

def get_ncbi_db_conn():
	dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db')
	conn = sqlite3.connect(dbfile)
	conn.text_factory = str
	return conn

<|next_version|>
import os
import sys
import time
import math
import sqlite3
from contextlib import contextmanager

import meta

@contextmanager
def timeit_msg(msg):
	print '{}...'.format(msg),
	sys.stdout.flush()

	start = time.time()
	yield
	stop = time.time()

	print ' ({:1.3f} s)'.format((stop-start))

def get_file_size(fname):
	fstats = os.stat(fname)
	size = fstats.st_size
	exponent = int(math.log(size, 10))
	divisor = {'B': 0, 'kB': 3, 'MB': 6, 'GB': 9}
	if exponent < 3:
		res = 'B'
	if exponent >= 3 and exponent < 6:
		res = 'kB'
	elif exponent >= 6 and exponent < 9:
		res = 'MB'
	else:
		res = 'GB'
	return '{:1.2f} {}'.format(float(size) / 10**divisor[res], res)

def get_ncbi_db_conn():
	dbfile = os.path.join(meta.__path__[0], 'data', 'NCBI.db')
	conn = sqlite3.connect(dbfile)
	conn.text_factory = str
	return conn


Check worker's FQDN against username.

Check worker's FQDN against username.

--- kobo/hub/decorators.py
+++ kobo/hub/decorators.py
@@ -1,5 +1,7 @@
 # -*- coding: utf-8 -*-

+
+import socket

 from django.core.exceptions import PermissionDenied, SuspiciousOperation
 from kobo.decorators import decorator_with_args
@@ -14,6 +16,11 @@
         if getattr(request, 'worker', None) is None:
             raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)

+        fqdn = socket.getfqdn(request.META["REMOTE_ADDR"])
+        prefix, hostname = request.user.username.split("/", 1)
+        if hostname != fqdn:
+            raise SuspiciousOperation("Worker's FQDN (%s) doesn't match username (%s)" % (fqdn, hostname))
+
         return func(request, *args, **kwargs)

     _new_func.__name__ = func.__name__

<|original_code|>
# -*- coding: utf-8 -*-

from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *

def validate_worker(func):
    def _new_func(request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise PermissionDenied("Login required.")

        if getattr(request, 'worker', None) is None:
            raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)

        return func(request, *args, **kwargs)

    _new_func.__name__ = func.__name__
    _new_func.__doc__ = func.__doc__
    _new_func.__dict__.update(func.__dict__)
    return _new_func

<|edits_diff|>
--- kobo/hub/decorators.py
+++ kobo/hub/decorators.py
@@ -1,5 +1,7 @@
 # -*- coding: utf-8 -*-

+
+import socket

 from django.core.exceptions import PermissionDenied, SuspiciousOperation
 from kobo.decorators import decorator_with_args
<|current_version|>
# -*- coding: utf-8 -*-

import socket

from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *

def validate_worker(func):
    def _new_func(request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise PermissionDenied("Login required.")

        if getattr(request, 'worker', None) is None:
            raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)

        return func(request, *args, **kwargs)

    _new_func.__name__ = func.__name__
    _new_func.__doc__ = func.__doc__
    _new_func.__dict__.update(func.__dict__)
    return _new_func

<|next_version|>
# -*- coding: utf-8 -*-

import socket

from django.core.exceptions import PermissionDenied, SuspiciousOperation
from kobo.decorators import decorator_with_args
from kobo.django.xmlrpc.decorators import *

def validate_worker(func):
    def _new_func(request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise PermissionDenied("Login required.")

        if getattr(request, 'worker', None) is None:
            raise SuspiciousOperation("User doesn't match any worker: %s" % request.user.username)

        fqdn = socket.getfqdn(request.META["REMOTE_ADDR"])
        prefix, hostname = request.user.username.split("/", 1)
        if hostname != fqdn:
            raise SuspiciousOperation("Worker's FQDN (%s) doesn't match username (%s)" % (fqdn, hostname))

        return func(request, *args, **kwargs)

    _new_func.__name__ = func.__name__
    _new_func.__doc__ = func.__doc__
    _new_func.__dict__.update(func.__dict__)
    return _new_func


Install relies on Django and factory boy

--- setup.py
+++ setup.py
@@ -5,12 +5,20 @@
 setuptools.setup(
     name='factory_djoy',
     version='0.1',
+
     description="Wrappers over Factory Boy's Django Factories",
     url='http://github.com/jamescooke/factory_djoy',
     author='James Cooke',
     author_email='github@jamescooke.info',
+
     license='MIT',
+
     packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
+    install_requires=[
+        'Django>=1.6',
+        'factory_boy>=2',
+    ],
+
     classifiers=[
         'Development Status :: 5 - Production/Stable',
         'Intended Audience :: Developers',

<|original_code|>
import os
import setuptools

setuptools.setup(
    name='factory_djoy',
    version='0.1',
    description="Wrappers over Factory Boy's Django Factories",
    url='http://github.com/jamescooke/factory_djoy',
    author='James Cooke',
    author_email='github@jamescooke.info',
    license='MIT',
    packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Framework :: Django',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Testing',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -5,11 +5,14 @@
 setuptools.setup(
     name='factory_djoy',
     version='0.1',
+
     description="Wrappers over Factory Boy's Django Factories",
     url='http://github.com/jamescooke/factory_djoy',
     author='James Cooke',
     author_email='github@jamescooke.info',
+
     license='MIT',
+
     packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
     classifiers=[
         'Development Status :: 5 - Production/Stable',
<|current_version|>
import os
import setuptools

setuptools.setup(
    name='factory_djoy',
    version='0.1',

    description="Wrappers over Factory Boy's Django Factories",
    url='http://github.com/jamescooke/factory_djoy',
    author='James Cooke',
    author_email='github@jamescooke.info',

    license='MIT',

    packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Framework :: Django',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Testing',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)

<|next_version|>
import os
import setuptools

setuptools.setup(
    name='factory_djoy',
    version='0.1',

    description="Wrappers over Factory Boy's Django Factories",
    url='http://github.com/jamescooke/factory_djoy',
    author='James Cooke',
    author_email='github@jamescooke.info',

    license='MIT',

    packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    install_requires=[
        'Django>=1.6',
        'factory_boy>=2',
    ],

    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Framework :: Django',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Testing',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)


Add creation of js message files to management command

--- django/publicmapping/redistricting/management/commands/makelanguagefiles.py
+++ django/publicmapping/redistricting/management/commands/makelanguagefiles.py
@@ -15,7 +15,11 @@
         """
         # Make messages for each language defined in settings
         for language in settings.LANGUAGES:
+            # For django templates
             management.call_command('makemessages', locale=language[0], interactive=False)
+
+            # For javascript files
+            management.call_command('makemessages', domain='djangojs', locale=language[0], interactive=False)

         # Compile all message files
         management.call_command('compilemessages', interactive=False)

<|original_code|>
#!/usr/bin/python
from django.core.management.base import BaseCommand
from redistricting.utils import *

class Command(BaseCommand):
    """
    This command prints creates and compiles language message files
    """
    args = None
    help = 'Create and compile language message files'

    def handle(self, *args, **options):
        """
        Create and compile language message files
        """
        # Make messages for each language defined in settings
        for language in settings.LANGUAGES:
            management.call_command('makemessages', locale=language[0], interactive=False)

        # Compile all message files
        management.call_command('compilemessages', interactive=False)

<|edits_diff|>
--- django/publicmapping/redistricting/management/commands/makelanguagefiles.py
+++ django/publicmapping/redistricting/management/commands/makelanguagefiles.py
@@ -15,6 +15,7 @@
         """
         # Make messages for each language defined in settings
         for language in settings.LANGUAGES:
+            # For django templates
             management.call_command('makemessages', locale=language[0], interactive=False)

         # Compile all message files
<|current_version|>
#!/usr/bin/python
from django.core.management.base import BaseCommand
from redistricting.utils import *

class Command(BaseCommand):
    """
    This command prints creates and compiles language message files
    """
    args = None
    help = 'Create and compile language message files'

    def handle(self, *args, **options):
        """
        Create and compile language message files
        """
        # Make messages for each language defined in settings
        for language in settings.LANGUAGES:
            # For django templates
            management.call_command('makemessages', locale=language[0], interactive=False)

        # Compile all message files
        management.call_command('compilemessages', interactive=False)

<|next_version|>
#!/usr/bin/python
from django.core.management.base import BaseCommand
from redistricting.utils import *

class Command(BaseCommand):
    """
    This command prints creates and compiles language message files
    """
    args = None
    help = 'Create and compile language message files'

    def handle(self, *args, **options):
        """
        Create and compile language message files
        """
        # Make messages for each language defined in settings
        for language in settings.LANGUAGES:
            # For django templates
            management.call_command('makemessages', locale=language[0], interactive=False)

            # For javascript files
            management.call_command('makemessages', domain='djangojs', locale=language[0], interactive=False)

        # Compile all message files
        management.call_command('compilemessages', interactive=False)


Add README as long description.

Add README as long description.

--- setup.py
+++ setup.py
@@ -2,6 +2,10 @@
 from setuptools import setup, find_packages

 peavy = __import__('peavy')
+
+with open('README.rst') as file:
+    long_description = file.read()
+
 setup(
     author = 'Fairview Computing LLC',
     author_email = 'john@fairviewcomputing.com',
@@ -16,6 +20,7 @@
         'Topic :: System :: Logging',
     ],
     description = peavy.__doc__,
+    long_description=long_description,
     download_url='http://github.com/fairview/django-peavy/downloads',
     install_requires = [
         'Django>=1.3',

<|original_code|>
import sys
from setuptools import setup, find_packages

peavy = __import__('peavy')
setup(
    author = 'Fairview Computing LLC',
    author_email = 'john@fairviewcomputing.com',
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: System :: Logging',
    ],
    description = peavy.__doc__,
    download_url='http://github.com/fairview/django-peavy/downloads',
    install_requires = [
        'Django>=1.3',
        'South>=0.7.2'
    ],
    license = "MIT License",
    name = 'django-peavy',
    packages = find_packages(),
    package_data = {
        'peavy': [
            'README.rst',
            'LICENSE.txt',
            'templates/*/*.html',
           'static/*/*/*',
        ],
    },
    url = 'http://github.com/fairview/django-peavy',
    version = peavy.get_version(),
    zip_safe = True,
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -2,6 +2,10 @@
 from setuptools import setup, find_packages

 peavy = __import__('peavy')
+
+with open('README.rst') as file:
+    long_description = file.read()
+
 setup(
     author = 'Fairview Computing LLC',
     author_email = 'john@fairviewcomputing.com',
<|current_version|>
import sys
from setuptools import setup, find_packages

peavy = __import__('peavy')

with open('README.rst') as file:
    long_description = file.read()

setup(
    author = 'Fairview Computing LLC',
    author_email = 'john@fairviewcomputing.com',
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: System :: Logging',
    ],
    description = peavy.__doc__,
    download_url='http://github.com/fairview/django-peavy/downloads',
    install_requires = [
        'Django>=1.3',
        'South>=0.7.2'
    ],
    license = "MIT License",
    name = 'django-peavy',
    packages = find_packages(),
    package_data = {
        'peavy': [
            'README.rst',
            'LICENSE.txt',
            'templates/*/*.html',
           'static/*/*/*',
        ],
    },
    url = 'http://github.com/fairview/django-peavy',
    version = peavy.get_version(),
    zip_safe = True,
)

<|next_version|>
import sys
from setuptools import setup, find_packages

peavy = __import__('peavy')

with open('README.rst') as file:
    long_description = file.read()

setup(
    author = 'Fairview Computing LLC',
    author_email = 'john@fairviewcomputing.com',
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: System :: Logging',
    ],
    description = peavy.__doc__,
    long_description=long_description,
    download_url='http://github.com/fairview/django-peavy/downloads',
    install_requires = [
        'Django>=1.3',
        'South>=0.7.2'
    ],
    license = "MIT License",
    name = 'django-peavy',
    packages = find_packages(),
    package_data = {
        'peavy': [
            'README.rst',
            'LICENSE.txt',
            'templates/*/*.html',
           'static/*/*/*',
        ],
    },
    url = 'http://github.com/fairview/django-peavy',
    version = peavy.get_version(),
    zip_safe = True,
)


Configure board ID as party setting for board tests

--- tests/blueprints/board/topic_moderation_base.py
+++ tests/blueprints/board/topic_moderation_base.py
@@ -4,6 +4,7 @@
 """

 from byceps.services.board.models.topic import Topic
+from byceps.services.party import settings_service as party_settings_service

 from testfixtures.board import create_board, create_category, create_topic

@@ -25,6 +26,9 @@

         self.board = self.create_board()

+        party_settings_service.create_setting(self.party.id, 'board_id',
+                                              self.board.id)
+
     # -------------------------------------------------------------------- #
     # helpers

<|original_code|>
"""
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from byceps.services.board.models.topic import Topic

from testfixtures.board import create_board, create_category, create_topic

from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_to_user

class AbstractTopicModerationTest(AbstractAppTestCase):

    def setUp(self):
        super().setUp()

        self.admin = self.create_user('Admin')
        self.create_session_token(self.admin.id)

        self.user = self.create_user('User')

        self.create_brand_and_party()

        self.board = self.create_board()

    # -------------------------------------------------------------------- #
    # helpers

    def setup_admin_with_permission(self, permission_id):
        permission_ids = {'admin.access', permission_id}
        assign_permissions_to_user(self.admin.id, 'admin', permission_ids)

    def create_board(self):
        board_id = self.brand.id
        return create_board(self.brand.id, board_id)

    def create_category(self, number):
        return create_category(self.board.id, number=number)

    def create_topic(self, category_id, creator_id, number):
        return create_topic(category_id, creator_id, number=number)

    def find_topic(self, id):
        return Topic.query.get(id)

<|edits_diff|>
--- tests/blueprints/board/topic_moderation_base.py
+++ tests/blueprints/board/topic_moderation_base.py
@@ -4,6 +4,7 @@
 """

 from byceps.services.board.models.topic import Topic
+from byceps.services.party import settings_service as party_settings_service

 from testfixtures.board import create_board, create_category, create_topic

<|current_version|>
"""
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from byceps.services.board.models.topic import Topic
from byceps.services.party import settings_service as party_settings_service

from testfixtures.board import create_board, create_category, create_topic

from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_to_user

class AbstractTopicModerationTest(AbstractAppTestCase):

    def setUp(self):
        super().setUp()

        self.admin = self.create_user('Admin')
        self.create_session_token(self.admin.id)

        self.user = self.create_user('User')

        self.create_brand_and_party()

        self.board = self.create_board()

    # -------------------------------------------------------------------- #
    # helpers

    def setup_admin_with_permission(self, permission_id):
        permission_ids = {'admin.access', permission_id}
        assign_permissions_to_user(self.admin.id, 'admin', permission_ids)

    def create_board(self):
        board_id = self.brand.id
        return create_board(self.brand.id, board_id)

    def create_category(self, number):
        return create_category(self.board.id, number=number)

    def create_topic(self, category_id, creator_id, number):
        return create_topic(category_id, creator_id, number=number)

    def find_topic(self, id):
        return Topic.query.get(id)

<|next_version|>
"""
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from byceps.services.board.models.topic import Topic
from byceps.services.party import settings_service as party_settings_service

from testfixtures.board import create_board, create_category, create_topic

from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_to_user

class AbstractTopicModerationTest(AbstractAppTestCase):

    def setUp(self):
        super().setUp()

        self.admin = self.create_user('Admin')
        self.create_session_token(self.admin.id)

        self.user = self.create_user('User')

        self.create_brand_and_party()

        self.board = self.create_board()

        party_settings_service.create_setting(self.party.id, 'board_id',
                                              self.board.id)

    # -------------------------------------------------------------------- #
    # helpers

    def setup_admin_with_permission(self, permission_id):
        permission_ids = {'admin.access', permission_id}
        assign_permissions_to_user(self.admin.id, 'admin', permission_ids)

    def create_board(self):
        board_id = self.brand.id
        return create_board(self.brand.id, board_id)

    def create_category(self, number):
        return create_category(self.board.id, number=number)

    def create_topic(self, category_id, creator_id, number):
        return create_topic(category_id, creator_id, number=number)

    def find_topic(self, id):
        return Topic.query.get(id)


Decrease noise from code-style test

Decrease noise from code-style test

--- tests/test_style.py
+++ tests/test_style.py
@@ -1,9 +1,12 @@
+import logging
 import pkg_resources
 import unittest

 class CodeStyleTestCase(unittest.TestCase):
     def test_code_style(self):
+        logger = logging.getLogger('flake8')
+        logger.setLevel(logging.ERROR)
         flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
         try:
             flake8([])

<|original_code|>
import pkg_resources
import unittest

class CodeStyleTestCase(unittest.TestCase):
    def test_code_style(self):
        flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
        try:
            flake8([])
        except SystemExit as e:
            if e.code != 0:
                self.fail('Code style checks failed')

<|edits_diff|>
--- tests/test_style.py
+++ tests/test_style.py
@@ -1,3 +1,4 @@
+import logging
 import pkg_resources
 import unittest

<|current_version|>
import logging
import pkg_resources
import unittest

class CodeStyleTestCase(unittest.TestCase):
    def test_code_style(self):
        flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
        try:
            flake8([])
        except SystemExit as e:
            if e.code != 0:
                self.fail('Code style checks failed')

<|next_version|>
import logging
import pkg_resources
import unittest

class CodeStyleTestCase(unittest.TestCase):
    def test_code_style(self):
        logger = logging.getLogger('flake8')
        logger.setLevel(logging.ERROR)
        flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
        try:
            flake8([])
        except SystemExit as e:
            if e.code != 0:
                self.fail('Code style checks failed')


Add the README as the long description.

Add the README as the long description.

--- setup.py
+++ setup.py
@@ -8,11 +8,14 @@
 _metadata = {}
 with open("src/txkube/_metadata.py") as f:
     exec(f.read(), _metadata)
+with open("README.rst") as f:
+    _metadata["description"] = f.read()

 setuptools.setup(
     name="txkube",
     version=_metadata["version_string"],
     description="A Twisted-based Kubernetes client.",
+    long_description=_metadata["description"],
     author="txkube Developers",
     url="https://github.com/leastauthority.com/txkube",
     license="MIT",

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

# Copyright Least Authority Enterprises.
# See LICENSE for details.

import setuptools

_metadata = {}
with open("src/txkube/_metadata.py") as f:
    exec(f.read(), _metadata)

setuptools.setup(
    name="txkube",
    version=_metadata["version_string"],
    description="A Twisted-based Kubernetes client.",
    author="txkube Developers",
    url="https://github.com/leastauthority.com/txkube",
    license="MIT",
    package_dir={"": "src"},
    packages=setuptools.find_packages(where="src"),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        "zope.interface",
        "attrs",
        "pyrsistent",
        "incremental",
        # See https://github.com/twisted/treq/issues/167
        # And https://twistedmatrix.com/trac/ticket/9032
        "twisted[tls]!=17.1.0",
        "pem",
        "eliot",
        "python-dateutil",
        "pykube",
        "treq",
        "klein",
    ],
    extras_require={
        "dev": [
            "testtools",
            "hypothesis",
            "eliot-tree>=17.0.0",
        ],
    },
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -8,6 +8,8 @@
 _metadata = {}
 with open("src/txkube/_metadata.py") as f:
     exec(f.read(), _metadata)
+with open("README.rst") as f:
+    _metadata["description"] = f.read()

 setuptools.setup(
     name="txkube",
<|current_version|>
#!/usr/bin/env python

# Copyright Least Authority Enterprises.
# See LICENSE for details.

import setuptools

_metadata = {}
with open("src/txkube/_metadata.py") as f:
    exec(f.read(), _metadata)
with open("README.rst") as f:
    _metadata["description"] = f.read()

setuptools.setup(
    name="txkube",
    version=_metadata["version_string"],
    description="A Twisted-based Kubernetes client.",
    author="txkube Developers",
    url="https://github.com/leastauthority.com/txkube",
    license="MIT",
    package_dir={"": "src"},
    packages=setuptools.find_packages(where="src"),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        "zope.interface",
        "attrs",
        "pyrsistent",
        "incremental",
        # See https://github.com/twisted/treq/issues/167
        # And https://twistedmatrix.com/trac/ticket/9032
        "twisted[tls]!=17.1.0",
        "pem",
        "eliot",
        "python-dateutil",
        "pykube",
        "treq",
        "klein",
    ],
    extras_require={
        "dev": [
            "testtools",
            "hypothesis",
            "eliot-tree>=17.0.0",
        ],
    },
)

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

# Copyright Least Authority Enterprises.
# See LICENSE for details.

import setuptools

_metadata = {}
with open("src/txkube/_metadata.py") as f:
    exec(f.read(), _metadata)
with open("README.rst") as f:
    _metadata["description"] = f.read()

setuptools.setup(
    name="txkube",
    version=_metadata["version_string"],
    description="A Twisted-based Kubernetes client.",
    long_description=_metadata["description"],
    author="txkube Developers",
    url="https://github.com/leastauthority.com/txkube",
    license="MIT",
    package_dir={"": "src"},
    packages=setuptools.find_packages(where="src"),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        "zope.interface",
        "attrs",
        "pyrsistent",
        "incremental",
        # See https://github.com/twisted/treq/issues/167
        # And https://twistedmatrix.com/trac/ticket/9032
        "twisted[tls]!=17.1.0",
        "pem",
        "eliot",
        "python-dateutil",
        "pykube",
        "treq",
        "klein",
    ],
    extras_require={
        "dev": [
            "testtools",
            "hypothesis",
            "eliot-tree>=17.0.0",
        ],
    },
)


Patch the GitHub API response to work around the header bug

--- grip/patcher.py
+++ grip/patcher.py
@@ -11,6 +11,11 @@
                      r'checked="" disabled=""> \1\2')

+HEADER_PATCH_RE = re.compile(r'{:"aria-hidden"=>"true", :class=>'
+                             r'"octicon octicon-link"}', re.DOTALL)
+HEADER_PATCH_SUB = r''
+
+
 def patch(html, user_content=False):
     """
     Processes the HTML rendered by the GitHub API, patching
@@ -22,4 +27,8 @@
         html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html)
         html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html)

+    # FUTURE: Remove this once GitHub API fixes the header bug
+    # https://github.com/joeyespo/grip/issues/244
+    html = HEADER_PATCH_RE.sub(HEADER_PATCH_SUB, html)
+
     return html

<|original_code|>
import re

INCOMPLETE_TASK_RE = re.compile(r'
\[ \] (.*?)(
|
)', re.DOTALL)
INCOMPLETE_TASK_SUB = (r'
'
                       r'<input type="checkbox" '
                       r'class="task-list-item-checkbox" disabled=""> \1\2')
COMPLETE_TASK_RE = re.compile(r'
\[x\] (.*?)(
|
)', re.DOTALL)
COMPLETE_TASK_SUB = (r'
'
                     r'<input type="checkbox" class="task-list-item-checkbox" '
                     r'checked="" disabled=""> \1\2')

def patch(html, user_content=False):
    """
    Processes the HTML rendered by the GitHub API, patching
    any inconsistencies from the main site.
    """
    # FUTURE: Remove this once GitHub API renders task lists
    # https://github.com/isaacs/github/issues/309
    if not user_content:
        html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html)
        html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html)

    return html

<|edits_diff|>
--- grip/patcher.py
+++ grip/patcher.py
@@ -9,6 +9,11 @@
 COMPLETE_TASK_SUB = (r'
'
                      r'<input type="checkbox" class="task-list-item-checkbox" '
                      r'checked="" disabled=""> \1\2')
+
+
+HEADER_PATCH_RE = re.compile(r'{:"aria-hidden"=>"true", :class=>'
+                             r'"octicon octicon-link"}', re.DOTALL)
+HEADER_PATCH_SUB = r''

 def patch(html, user_content=False):
<|current_version|>
import re

INCOMPLETE_TASK_RE = re.compile(r'
\[ \] (.*?)(
|
)', re.DOTALL)
INCOMPLETE_TASK_SUB = (r'
'
                       r'<input type="checkbox" '
                       r'class="task-list-item-checkbox" disabled=""> \1\2')
COMPLETE_TASK_RE = re.compile(r'
\[x\] (.*?)(
|
)', re.DOTALL)
COMPLETE_TASK_SUB = (r'
'
                     r'<input type="checkbox" class="task-list-item-checkbox" '
                     r'checked="" disabled=""> \1\2')

HEADER_PATCH_RE = re.compile(r'{:"aria-hidden"=>"true", :class=>'
                             r'"octicon octicon-link"}', re.DOTALL)
HEADER_PATCH_SUB = r''

def patch(html, user_content=False):
    """
    Processes the HTML rendered by the GitHub API, patching
    any inconsistencies from the main site.
    """
    # FUTURE: Remove this once GitHub API renders task lists
    # https://github.com/isaacs/github/issues/309
    if not user_content:
        html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html)
        html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html)

    return html

<|next_version|>
import re

INCOMPLETE_TASK_RE = re.compile(r'
\[ \] (.*?)(
|
)', re.DOTALL)
INCOMPLETE_TASK_SUB = (r'
'
                       r'<input type="checkbox" '
                       r'class="task-list-item-checkbox" disabled=""> \1\2')
COMPLETE_TASK_RE = re.compile(r'
\[x\] (.*?)(
|
)', re.DOTALL)
COMPLETE_TASK_SUB = (r'
'
                     r'<input type="checkbox" class="task-list-item-checkbox" '
                     r'checked="" disabled=""> \1\2')

HEADER_PATCH_RE = re.compile(r'{:"aria-hidden"=>"true", :class=>'
                             r'"octicon octicon-link"}', re.DOTALL)
HEADER_PATCH_SUB = r''

def patch(html, user_content=False):
    """
    Processes the HTML rendered by the GitHub API, patching
    any inconsistencies from the main site.
    """
    # FUTURE: Remove this once GitHub API renders task lists
    # https://github.com/isaacs/github/issues/309
    if not user_content:
        html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html)
        html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html)

    # FUTURE: Remove this once GitHub API fixes the header bug
    # https://github.com/joeyespo/grip/issues/244
    html = HEADER_PATCH_RE.sub(HEADER_PATCH_SUB, html)

    return html


Make cached_function not overwrite signature of wrapped function

--- app/util.py
+++ app/util.py
@@ -1,4 +1,5 @@
 # Various utility functions
+import inspect
 import os
 from typing import Any, Callable

@@ -18,4 +19,5 @@
         return data[cache_key]

     wrapper.__qualname__ = func.__qualname__
+    wrapper.__signature__ = inspect.signature(func)  # type: ignore
     return wrapper

<|original_code|>
# Various utility functions
import os
from typing import Any, Callable

SHOULD_CACHE = os.environ.get('ENV', 'development') == 'production'

def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
    data = {}

    def wrapper(*args: Any) -> Any:
        if not SHOULD_CACHE:
            return func(*args)
        cache_key = ' '.join([str(x) for x in args])
        if cache_key not in data:
            data[cache_key] = func(*args)
        return data[cache_key]

    wrapper.__qualname__ = func.__qualname__
    return wrapper

<|edits_diff|>
--- app/util.py
+++ app/util.py
@@ -1,4 +1,5 @@
 # Various utility functions
+import inspect
 import os
 from typing import Any, Callable

<|current_version|>
# Various utility functions
import inspect
import os
from typing import Any, Callable

SHOULD_CACHE = os.environ.get('ENV', 'development') == 'production'

def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
    data = {}

    def wrapper(*args: Any) -> Any:
        if not SHOULD_CACHE:
            return func(*args)
        cache_key = ' '.join([str(x) for x in args])
        if cache_key not in data:
            data[cache_key] = func(*args)
        return data[cache_key]

    wrapper.__qualname__ = func.__qualname__
    return wrapper

<|next_version|>
# Various utility functions
import inspect
import os
from typing import Any, Callable

SHOULD_CACHE = os.environ.get('ENV', 'development') == 'production'

def cached_function(func: Callable[..., Any]) -> Callable[..., Any]:
    data = {}

    def wrapper(*args: Any) -> Any:
        if not SHOULD_CACHE:
            return func(*args)
        cache_key = ' '.join([str(x) for x in args])
        if cache_key not in data:
            data[cache_key] = func(*args)
        return data[cache_key]

    wrapper.__qualname__ = func.__qualname__
    wrapper.__signature__ = inspect.signature(func)  # type: ignore
    return wrapper


Enable asyncio debugging if settings.DEBUG is True

--- management/commands/startbot.py
+++ management/commands/startbot.py
@@ -1,4 +1,5 @@
 from django.core.management.base import BaseCommand
+from django.conf import settings

 import importlib
 import asyncio
@@ -8,6 +9,8 @@

     def handle(self, *args, **options):
         loop = asyncio.get_event_loop()
+        if settings.DEBUG:
+            loop.set_debug(True)
         bot = None
         while True:
             bot_module = importlib.import_module('dwarf.bot')

<|original_code|>
from django.core.management.base import BaseCommand

import importlib
import asyncio

class Command(BaseCommand):

    def handle(self, *args, **options):
        loop = asyncio.get_event_loop()
        bot = None
        while True:
            bot_module = importlib.import_module('dwarf.bot')
            bot = bot_module.main(loop=loop, bot=bot)
            if not bot.base.restarting_enabled():
                break
            else:
                bot.clear()

<|edits_diff|>
--- management/commands/startbot.py
+++ management/commands/startbot.py
@@ -1,4 +1,5 @@
 from django.core.management.base import BaseCommand
+from django.conf import settings

 import importlib
 import asyncio
<|current_version|>
from django.core.management.base import BaseCommand
from django.conf import settings

import importlib
import asyncio

class Command(BaseCommand):

    def handle(self, *args, **options):
        loop = asyncio.get_event_loop()
        bot = None
        while True:
            bot_module = importlib.import_module('dwarf.bot')
            bot = bot_module.main(loop=loop, bot=bot)
            if not bot.base.restarting_enabled():
                break
            else:
                bot.clear()

<|next_version|>
from django.core.management.base import BaseCommand
from django.conf import settings

import importlib
import asyncio

class Command(BaseCommand):

    def handle(self, *args, **options):
        loop = asyncio.get_event_loop()
        if settings.DEBUG:
            loop.set_debug(True)
        bot = None
        while True:
            bot_module = importlib.import_module('dwarf.bot')
            bot = bot_module.main(loop=loop, bot=bot)
            if not bot.base.restarting_enabled():
                break
            else:
                bot.clear()


Add not implemeted get cluster

Add not implemeted get cluster

--- tests/test_api_info.py
+++ tests/test_api_info.py
@@ -1,4 +1,5 @@
 from tests.types import string
+from tests.conftest import not_implemented_skip

 def test_get(test):
@@ -15,3 +16,8 @@
         assert info['rest_server_url'] is None

     test.run(handle_connect)
+
+
+@not_implemented_skip
+def test_get_cluster(test):
+    pass

<|original_code|>
from tests.types import string

def test_get(test):

    def handle_connect(handler):
        info = handler.api.get_info()
        assert isinstance(info['api_version'], string)
        assert isinstance(info['server_timestamp'], string)
        if info.get('rest_server_url'):
            assert info['websocket_server_url'] is None
            assert isinstance(info['rest_server_url'], string)
            return
        assert isinstance(info['websocket_server_url'], string)
        assert info['rest_server_url'] is None

    test.run(handle_connect)

<|edits_diff|>
--- tests/test_api_info.py
+++ tests/test_api_info.py
@@ -1,4 +1,5 @@
 from tests.types import string
+from tests.conftest import not_implemented_skip

 def test_get(test):
<|current_version|>
from tests.types import string
from tests.conftest import not_implemented_skip

def test_get(test):

    def handle_connect(handler):
        info = handler.api.get_info()
        assert isinstance(info['api_version'], string)
        assert isinstance(info['server_timestamp'], string)
        if info.get('rest_server_url'):
            assert info['websocket_server_url'] is None
            assert isinstance(info['rest_server_url'], string)
            return
        assert isinstance(info['websocket_server_url'], string)
        assert info['rest_server_url'] is None

    test.run(handle_connect)

<|next_version|>
from tests.types import string
from tests.conftest import not_implemented_skip

def test_get(test):

    def handle_connect(handler):
        info = handler.api.get_info()
        assert isinstance(info['api_version'], string)
        assert isinstance(info['server_timestamp'], string)
        if info.get('rest_server_url'):
            assert info['websocket_server_url'] is None
            assert isinstance(info['rest_server_url'], string)
            return
        assert isinstance(info['websocket_server_url'], string)
        assert info['rest_server_url'] is None

    test.run(handle_connect)

@not_implemented_skip
def test_get_cluster(test):
    pass