Make sure we cleanup even if fails in example

--- examples/deploy_local_file_resource.py
+++ examples/deploy_local_file_resource.py
@@ -18,6 +18,7 @@
     # connect to current model with current user, per Juju CLI
     await model.connect()

+    application = None
     try:
         print('Deploying local-charm')
         base_dir = Path(__file__).absolute().parent.parent
@@ -33,6 +34,11 @@

         print('Removing Charm')
         await application.remove()
+    except Exception as e:
+        print(e)
+        if application:
+            await application.remove()
+        await model.disconnect()
     finally:
         print('Disconnecting from model')
         await model.disconnect()

<|original_code|>
"""
This example:

1. Connects to the current model
2. Deploy a local charm with a oci-image resource and waits until it reports
   itself active
3. Destroys the unit and application

"""
from juju import jasyncio
from juju.model import Model
from pathlib import Path

async def main():
    model = Model()
    print('Connecting to model')
    # connect to current model with current user, per Juju CLI
    await model.connect()

    try:
        print('Deploying local-charm')
        base_dir = Path(__file__).absolute().parent.parent
        charm_path = '{}/tests/integration/file-resource-charm'.format(base_dir)
        resources = {"file-res": "test.file"}
        application = await model.deploy(
            charm_path,
            resources=resources,
        )

        print('Waiting for active')
        await model.wait_for_idle()

        print('Removing Charm')
        await application.remove()
    finally:
        print('Disconnecting from model')
        await model.disconnect()

if __name__ == '__main__':
    jasyncio.run(main())

<|edits_diff|>
--- examples/deploy_local_file_resource.py
+++ examples/deploy_local_file_resource.py
@@ -18,6 +18,7 @@
     # connect to current model with current user, per Juju CLI
     await model.connect()

+    application = None
     try:
         print('Deploying local-charm')
         base_dir = Path(__file__).absolute().parent.parent
<|current_version|>
"""
This example:

1. Connects to the current model
2. Deploy a local charm with a oci-image resource and waits until it reports
   itself active
3. Destroys the unit and application

"""
from juju import jasyncio
from juju.model import Model
from pathlib import Path

async def main():
    model = Model()
    print('Connecting to model')
    # connect to current model with current user, per Juju CLI
    await model.connect()

    application = None
    try:
        print('Deploying local-charm')
        base_dir = Path(__file__).absolute().parent.parent
        charm_path = '{}/tests/integration/file-resource-charm'.format(base_dir)
        resources = {"file-res": "test.file"}
        application = await model.deploy(
            charm_path,
            resources=resources,
        )

        print('Waiting for active')
        await model.wait_for_idle()

        print('Removing Charm')
        await application.remove()
    finally:
        print('Disconnecting from model')
        await model.disconnect()

if __name__ == '__main__':
    jasyncio.run(main())

<|next_version|>
"""
This example:

1. Connects to the current model
2. Deploy a local charm with a oci-image resource and waits until it reports
   itself active
3. Destroys the unit and application

"""
from juju import jasyncio
from juju.model import Model
from pathlib import Path

async def main():
    model = Model()
    print('Connecting to model')
    # connect to current model with current user, per Juju CLI
    await model.connect()

    application = None
    try:
        print('Deploying local-charm')
        base_dir = Path(__file__).absolute().parent.parent
        charm_path = '{}/tests/integration/file-resource-charm'.format(base_dir)
        resources = {"file-res": "test.file"}
        application = await model.deploy(
            charm_path,
            resources=resources,
        )

        print('Waiting for active')
        await model.wait_for_idle()

        print('Removing Charm')
        await application.remove()
    except Exception as e:
        print(e)
        if application:
            await application.remove()
        await model.disconnect()
    finally:
        print('Disconnecting from model')
        await model.disconnect()

if __name__ == '__main__':
    jasyncio.run(main())


Make sure land filters are setup when testing

--- geotrek/trekking/tests/test_filters.py
+++ geotrek/trekking/tests/test_filters.py
@@ -1,4 +1,5 @@
 # -*- coding: utf-8 -*-
+from geotrek.land.filters import *
 from geotrek.land.tests.test_filters import LandFiltersTest

 from geotrek.trekking.filters import TrekFilterSet
@@ -10,6 +11,10 @@
     filterclass = TrekFilterSet

+    def test_land_filters_are_well_setup(self):
+        filterset = TrekFilterSet()
+        self.assertIn('work', filterset.filters)
+
     def create_pair_of_distinct_path(self):
         useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path()
         self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path)

<|original_code|>
# -*- coding: utf-8 -*-
from geotrek.land.tests.test_filters import LandFiltersTest

from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory

class TrekFilterLandTest(LandFiltersTest):

    filterclass = TrekFilterSet

    def create_pair_of_distinct_path(self):
        useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path()
        self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path)
        return useless_path, seek_path

<|edits_diff|>
--- geotrek/trekking/tests/test_filters.py
+++ geotrek/trekking/tests/test_filters.py
@@ -1,4 +1,5 @@
 # -*- coding: utf-8 -*-
+from geotrek.land.filters import *
 from geotrek.land.tests.test_filters import LandFiltersTest

 from geotrek.trekking.filters import TrekFilterSet
<|current_version|>
# -*- coding: utf-8 -*-
from geotrek.land.filters import *
from geotrek.land.tests.test_filters import LandFiltersTest

from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory

class TrekFilterLandTest(LandFiltersTest):

    filterclass = TrekFilterSet

    def create_pair_of_distinct_path(self):
        useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path()
        self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path)
        return useless_path, seek_path

<|next_version|>
# -*- coding: utf-8 -*-
from geotrek.land.filters import *
from geotrek.land.tests.test_filters import LandFiltersTest

from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory

class TrekFilterLandTest(LandFiltersTest):

    filterclass = TrekFilterSet

    def test_land_filters_are_well_setup(self):
        filterset = TrekFilterSet()
        self.assertIn('work', filterset.filters)

    def create_pair_of_distinct_path(self):
        useless_path, seek_path = super(TrekFilterLandTest, self).create_pair_of_distinct_path()
        self.create_pair_of_distinct_topologies(TrekFactory, useless_path, seek_path)
        return useless_path, seek_path


Add testing for default grid_* values

Add testing for default grid_* values

--- tests/test_rover_init.py
+++ tests/test_rover_init.py
@@ -5,12 +5,18 @@
     assert rover.y == 0
     assert rover.direction == 'N'

+    assert rover.grid_x == 50
+    assert rover.grid_y == 50
+
 def test_rover_init_with_custom_parameters():
     from rover import Rover
     rover = Rover(3, 7, 'W')
     assert rover.x == 3
     assert rover.y == 7
     assert rover.direction == 'W'
+
+    assert rover.grid_x == 50
+    assert rover.grid_y == 50

 def test_rover_init_custom_grid():

<|original_code|>
def test_rover_init_with_default_parameters():
    from rover import Rover
    rover = Rover()
    assert rover.x == 0
    assert rover.y == 0
    assert rover.direction == 'N'

def test_rover_init_with_custom_parameters():
    from rover import Rover
    rover = Rover(3, 7, 'W')
    assert rover.x == 3
    assert rover.y == 7
    assert rover.direction == 'W'

def test_rover_init_custom_grid():
    from rover import Rover
    rover = Rover(grid_x=100, grid_y=150)
    assert rover.x == 0
    assert rover.y == 0
    assert rover.direction == 'N'

    assert rover.grid_x == 100
    assert rover.grid_y == 150

def test_rover_init_full_custom_grid():
    from rover import Rover
    rover = Rover(5, 9, 'E', 100, 150)
    assert rover.x == 5
    assert rover.y == 9
    assert rover.direction == 'E'

    assert rover.grid_x == 100
    assert rover.grid_y == 150

<|edits_diff|>
--- tests/test_rover_init.py
+++ tests/test_rover_init.py
@@ -4,6 +4,9 @@
     assert rover.x == 0
     assert rover.y == 0
     assert rover.direction == 'N'
+
+    assert rover.grid_x == 50
+    assert rover.grid_y == 50

 def test_rover_init_with_custom_parameters():
     from rover import Rover
<|current_version|>
def test_rover_init_with_default_parameters():
    from rover import Rover
    rover = Rover()
    assert rover.x == 0
    assert rover.y == 0
    assert rover.direction == 'N'

    assert rover.grid_x == 50
    assert rover.grid_y == 50

def test_rover_init_with_custom_parameters():
    from rover import Rover
    rover = Rover(3, 7, 'W')
    assert rover.x == 3
    assert rover.y == 7
    assert rover.direction == 'W'

def test_rover_init_custom_grid():
    from rover import Rover
    rover = Rover(grid_x=100, grid_y=150)
    assert rover.x == 0
    assert rover.y == 0
    assert rover.direction == 'N'

    assert rover.grid_x == 100
    assert rover.grid_y == 150

def test_rover_init_full_custom_grid():
    from rover import Rover
    rover = Rover(5, 9, 'E', 100, 150)
    assert rover.x == 5
    assert rover.y == 9
    assert rover.direction == 'E'

    assert rover.grid_x == 100
    assert rover.grid_y == 150

<|next_version|>
def test_rover_init_with_default_parameters():
    from rover import Rover
    rover = Rover()
    assert rover.x == 0
    assert rover.y == 0
    assert rover.direction == 'N'

    assert rover.grid_x == 50
    assert rover.grid_y == 50

def test_rover_init_with_custom_parameters():
    from rover import Rover
    rover = Rover(3, 7, 'W')
    assert rover.x == 3
    assert rover.y == 7
    assert rover.direction == 'W'

    assert rover.grid_x == 50
    assert rover.grid_y == 50

def test_rover_init_custom_grid():
    from rover import Rover
    rover = Rover(grid_x=100, grid_y=150)
    assert rover.x == 0
    assert rover.y == 0
    assert rover.direction == 'N'

    assert rover.grid_x == 100
    assert rover.grid_y == 150

def test_rover_init_full_custom_grid():
    from rover import Rover
    rover = Rover(5, 9, 'E', 100, 150)
    assert rover.x == 5
    assert rover.y == 9
    assert rover.direction == 'E'

    assert rover.grid_x == 100
    assert rover.grid_y == 150


Make sure we import qtpy before importing any Qt wrappers directly

--- tests/conftest.py
+++ tests/conftest.py
@@ -2,8 +2,13 @@

 def pytest_configure(config):
+
     if 'USE_QT_API' in os.environ:
         os.environ['QT_API'] = os.environ['USE_QT_API'].lower()
+
+    # We need to import qtpy here to make sure that the API versions get set
+    # straight away.
+    import qtpy

 def pytest_report_header(config):

<|original_code|>
import os

def pytest_configure(config):
    if 'USE_QT_API' in os.environ:
        os.environ['QT_API'] = os.environ['USE_QT_API'].lower()

def pytest_report_header(config):

    versions = os.linesep
    versions += 'PyQt4: '

    try:
        from PyQt4 import Qt
        versions += "PyQt: {0} - Qt: {1}".format(Qt.PYQT_VERSION_STR, Qt.QT_VERSION_STR)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep
    versions += 'PyQt5: '

    try:
        from PyQt5 import Qt
        versions += "PyQt: {0} - Qt: {1}".format(Qt.PYQT_VERSION_STR, Qt.QT_VERSION_STR)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep
    versions += 'PySide: '

    try:
        import PySide
        from PySide import QtCore
        versions += "PySide: {0} - Qt: {1}".format(PySide.__version__, QtCore.__version__)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep

    return versions

<|edits_diff|>
--- tests/conftest.py
+++ tests/conftest.py
@@ -2,6 +2,7 @@

 def pytest_configure(config):
+
     if 'USE_QT_API' in os.environ:
         os.environ['QT_API'] = os.environ['USE_QT_API'].lower()

<|current_version|>
import os

def pytest_configure(config):

    if 'USE_QT_API' in os.environ:
        os.environ['QT_API'] = os.environ['USE_QT_API'].lower()

def pytest_report_header(config):

    versions = os.linesep
    versions += 'PyQt4: '

    try:
        from PyQt4 import Qt
        versions += "PyQt: {0} - Qt: {1}".format(Qt.PYQT_VERSION_STR, Qt.QT_VERSION_STR)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep
    versions += 'PyQt5: '

    try:
        from PyQt5 import Qt
        versions += "PyQt: {0} - Qt: {1}".format(Qt.PYQT_VERSION_STR, Qt.QT_VERSION_STR)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep
    versions += 'PySide: '

    try:
        import PySide
        from PySide import QtCore
        versions += "PySide: {0} - Qt: {1}".format(PySide.__version__, QtCore.__version__)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep

    return versions

<|next_version|>
import os

def pytest_configure(config):

    if 'USE_QT_API' in os.environ:
        os.environ['QT_API'] = os.environ['USE_QT_API'].lower()

    # We need to import qtpy here to make sure that the API versions get set
    # straight away.
    import qtpy

def pytest_report_header(config):

    versions = os.linesep
    versions += 'PyQt4: '

    try:
        from PyQt4 import Qt
        versions += "PyQt: {0} - Qt: {1}".format(Qt.PYQT_VERSION_STR, Qt.QT_VERSION_STR)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep
    versions += 'PyQt5: '

    try:
        from PyQt5 import Qt
        versions += "PyQt: {0} - Qt: {1}".format(Qt.PYQT_VERSION_STR, Qt.QT_VERSION_STR)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep
    versions += 'PySide: '

    try:
        import PySide
        from PySide import QtCore
        versions += "PySide: {0} - Qt: {1}".format(PySide.__version__, QtCore.__version__)
    except ImportError:
        versions += 'not installed'
    except AttributeError:
        versions += 'unknown version'

    versions += os.linesep

    return versions


Add js_externs parameter for API

Add js_externs parameter for API

--- compiler.py
+++ compiler.py
@@ -7,6 +7,7 @@
     parser.add_argument("--js", default='/dev/stdin', help="Input file")
     parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
     parser.add_argument("--compilation_level", default='WHITESPACE_ONLY', choices=['WHITESPACE_ONLY', 'SIMPLE_OPTIMIZATIONS', 'ADVANCED_OPTIMIZATIONS'], help="Compilation level")
+    parser.add_argument("--js_externs", default='', help="Declare some external js vars and functions separated with semicolon")
     args = parser.parse_args()
     js_code = open(args.js, 'r')

@@ -15,6 +16,7 @@
         ('compilation_level', args.compilation_level),
         ('output_format', 'text'),
         ('output_info', 'compiled_code'),
+        ('js_externs', args.js_externs),
     ])

     js_code.close()

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

import http.client, urllib.parse, sys, argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--js", default='/dev/stdin', help="Input file")
    parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
    parser.add_argument("--compilation_level", default='WHITESPACE_ONLY', choices=['WHITESPACE_ONLY', 'SIMPLE_OPTIMIZATIONS', 'ADVANCED_OPTIMIZATIONS'], help="Compilation level")
    args = parser.parse_args()
    js_code = open(args.js, 'r')

    params = urllib.parse.urlencode([
        ('js_code', js_code.read()),
        ('compilation_level', args.compilation_level),
        ('output_format', 'text'),
        ('output_info', 'compiled_code'),
    ])

    js_code.close()
    headers = { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }
    conn = http.client.HTTPSConnection('closure-compiler.appspot.com')
    conn.request('POST', '/compile', params, headers)
    response = conn.getresponse()
    data = response.read()
    output_code = open(args.js_output_file, 'w')
    output_code.write(data.decode("utf-8"))
    output_code.close()
    conn.close()

if __name__ == "__main__":
    main()

<|edits_diff|>
--- compiler.py
+++ compiler.py
@@ -7,6 +7,7 @@
     parser.add_argument("--js", default='/dev/stdin', help="Input file")
     parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
     parser.add_argument("--compilation_level", default='WHITESPACE_ONLY', choices=['WHITESPACE_ONLY', 'SIMPLE_OPTIMIZATIONS', 'ADVANCED_OPTIMIZATIONS'], help="Compilation level")
+    parser.add_argument("--js_externs", default='', help="Declare some external js vars and functions separated with semicolon")
     args = parser.parse_args()
     js_code = open(args.js, 'r')

<|current_version|>
#!/usr/local/bin/python3

import http.client, urllib.parse, sys, argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--js", default='/dev/stdin', help="Input file")
    parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
    parser.add_argument("--compilation_level", default='WHITESPACE_ONLY', choices=['WHITESPACE_ONLY', 'SIMPLE_OPTIMIZATIONS', 'ADVANCED_OPTIMIZATIONS'], help="Compilation level")
    parser.add_argument("--js_externs", default='', help="Declare some external js vars and functions separated with semicolon")
    args = parser.parse_args()
    js_code = open(args.js, 'r')

    params = urllib.parse.urlencode([
        ('js_code', js_code.read()),
        ('compilation_level', args.compilation_level),
        ('output_format', 'text'),
        ('output_info', 'compiled_code'),
    ])

    js_code.close()
    headers = { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }
    conn = http.client.HTTPSConnection('closure-compiler.appspot.com')
    conn.request('POST', '/compile', params, headers)
    response = conn.getresponse()
    data = response.read()
    output_code = open(args.js_output_file, 'w')
    output_code.write(data.decode("utf-8"))
    output_code.close()
    conn.close()

if __name__ == "__main__":
    main()

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

import http.client, urllib.parse, sys, argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--js", default='/dev/stdin', help="Input file")
    parser.add_argument("--js_output_file", default='/dev/stdout', help="Output file")
    parser.add_argument("--compilation_level", default='WHITESPACE_ONLY', choices=['WHITESPACE_ONLY', 'SIMPLE_OPTIMIZATIONS', 'ADVANCED_OPTIMIZATIONS'], help="Compilation level")
    parser.add_argument("--js_externs", default='', help="Declare some external js vars and functions separated with semicolon")
    args = parser.parse_args()
    js_code = open(args.js, 'r')

    params = urllib.parse.urlencode([
        ('js_code', js_code.read()),
        ('compilation_level', args.compilation_level),
        ('output_format', 'text'),
        ('output_info', 'compiled_code'),
        ('js_externs', args.js_externs),
    ])

    js_code.close()
    headers = { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }
    conn = http.client.HTTPSConnection('closure-compiler.appspot.com')
    conn.request('POST', '/compile', params, headers)
    response = conn.getresponse()
    data = response.read()
    output_code = open(args.js_output_file, 'w')
    output_code.write(data.decode("utf-8"))
    output_code.close()
    conn.close()

if __name__ == "__main__":
    main()


Add unicode representations for tags/positions

--- appy/models.py
+++ appy/models.py
@@ -5,12 +5,18 @@
 class Tag(models.Model):
     description = models.TextField()

+    def __unicode__(self):
+        return self.description
+

 class Position(models.Model):
     company = models.TextField()
     job_title = models.TextField()
     description = models.TextField()
     tags = models.ManyToManyField(Tag)
+
+    def __unicode__(self):
+        return u'%s at %s' % (self.job_title, self.company)

 class Application(models.Model):

<|original_code|>
from django.db import models
from django.contrib.auth.models import User

class Tag(models.Model):
    description = models.TextField()

class Position(models.Model):
    company = models.TextField()
    job_title = models.TextField()
    description = models.TextField()
    tags = models.ManyToManyField(Tag)

class Application(models.Model):
    user = models.ForeignKey(User)
    position = models.ForeignKey(Position)

    APPLIED = 'APP'
    REJECTED = 'REJ'
    INTERVIEWING = 'INT'
    NEGOTIATING = 'NEG'
    STATUS_CHOICES = (
        (APPLIED, 'Applied'),
        (REJECTED, 'Rejected'),
        (INTERVIEWING, 'Interviewing'),
        (NEGOTIATING, 'Negotiating'),
    )
    status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

<|edits_diff|>
--- appy/models.py
+++ appy/models.py
@@ -4,6 +4,9 @@

 class Tag(models.Model):
     description = models.TextField()
+
+    def __unicode__(self):
+        return self.description

 class Position(models.Model):
<|current_version|>
from django.db import models
from django.contrib.auth.models import User

class Tag(models.Model):
    description = models.TextField()

    def __unicode__(self):
        return self.description

class Position(models.Model):
    company = models.TextField()
    job_title = models.TextField()
    description = models.TextField()
    tags = models.ManyToManyField(Tag)

class Application(models.Model):
    user = models.ForeignKey(User)
    position = models.ForeignKey(Position)

    APPLIED = 'APP'
    REJECTED = 'REJ'
    INTERVIEWING = 'INT'
    NEGOTIATING = 'NEG'
    STATUS_CHOICES = (
        (APPLIED, 'Applied'),
        (REJECTED, 'Rejected'),
        (INTERVIEWING, 'Interviewing'),
        (NEGOTIATING, 'Negotiating'),
    )
    status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

<|next_version|>
from django.db import models
from django.contrib.auth.models import User

class Tag(models.Model):
    description = models.TextField()

    def __unicode__(self):
        return self.description

class Position(models.Model):
    company = models.TextField()
    job_title = models.TextField()
    description = models.TextField()
    tags = models.ManyToManyField(Tag)

    def __unicode__(self):
        return u'%s at %s' % (self.job_title, self.company)

class Application(models.Model):
    user = models.ForeignKey(User)
    position = models.ForeignKey(Position)

    APPLIED = 'APP'
    REJECTED = 'REJ'
    INTERVIEWING = 'INT'
    NEGOTIATING = 'NEG'
    STATUS_CHOICES = (
        (APPLIED, 'Applied'),
        (REJECTED, 'Rejected'),
        (INTERVIEWING, 'Interviewing'),
        (NEGOTIATING, 'Negotiating'),
    )
    status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


Add long description from README

Add long description from README

--- setup.py
+++ setup.py
@@ -1,14 +1,20 @@
 from distutils.core import setup
+from os import path

 from turbasen import VERSION

 name = 'turbasen'
+
+here = path.abspath(path.dirname(__file__))
+with open(path.join(here, 'README.md'), encoding='utf-8') as f:
+    long_description = f.read()

 setup(
     name=name,
     packages=[name],
     version=VERSION,
     description='Client for Nasjonal Turbase REST API',
+    long_description=long_description,
     author='Ali Kaafarani',
     author_email='ali.kaafarani@turistforeningen.no',
     url='https://github.com/Turbasen/turbasen.py',

<|original_code|>
from distutils.core import setup

from turbasen import VERSION

name = 'turbasen'

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    author='Ali Kaafarani',
    author_email='ali.kaafarani@turistforeningen.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests'],
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,8 +1,13 @@
 from distutils.core import setup
+from os import path

 from turbasen import VERSION

 name = 'turbasen'
+
+here = path.abspath(path.dirname(__file__))
+with open(path.join(here, 'README.md'), encoding='utf-8') as f:
+    long_description = f.read()

 setup(
     name=name,
<|current_version|>
from distutils.core import setup
from os import path

from turbasen import VERSION

name = 'turbasen'

here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    author='Ali Kaafarani',
    author_email='ali.kaafarani@turistforeningen.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests'],
)

<|next_version|>
from distutils.core import setup
from os import path

from turbasen import VERSION

name = 'turbasen'

here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    long_description=long_description,
    author='Ali Kaafarani',
    author_email='ali.kaafarani@turistforeningen.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests'],
)


Add version, utf-8 and some comments.

Add version, utf-8 and some comments.

--- lib/DjangoLibrary.py
+++ lib/DjangoLibrary.py
@@ -1,3 +1,6 @@
+# -*- coding: utf-8 -*-
+__version__ = '0.1'
+
 from robot.api import logger

 import os
@@ -24,6 +27,7 @@
         self.port = port

     def start_django(self):
+        """Start the Django server."""
         args = [
             'python',
             'mysite/manage.py',
@@ -38,6 +42,7 @@
         )

     def stop_django(self):
+        """Stop Django server."""
         os.kill(self.django_pid, signal.SIGKILL)
         logger.console(
             "Django stopped (PID: %s)" % self.django_pid,

<|original_code|>
from robot.api import logger

import os
import signal
import subprocess

ROBOT_LIBRARY_DOC_FORMAT = 'reST'

class DjangoLibrary:
    """A library for testing Django with Robot Framework.
    """

    django_pid = None
    selenium_pid = None

    # TEST CASE => New instance is created for every test case.
    # TEST SUITE => New instance is created for every test suite.
    # GLOBAL => Only one instance is created during the whole test execution.
    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

    def __init__(self, host="127.0.0.1", port=8000):
        self.host = host
        self.port = port

    def start_django(self):
        args = [
            'python',
            'mysite/manage.py',
            'runserver',
            '%s:%s' % (self.host, self.port),
            '--nothreading',
            '--noreload',
        ]
        self.django_pid = subprocess.Popen(args).pid
        logger.console(
            "Django started (PID: %s)" % self.django_pid,
        )

    def stop_django(self):
        os.kill(self.django_pid, signal.SIGKILL)
        logger.console(
            "Django stopped (PID: %s)" % self.django_pid,
        )

<|edits_diff|>
--- lib/DjangoLibrary.py
+++ lib/DjangoLibrary.py
@@ -1,3 +1,6 @@
+# -*- coding: utf-8 -*-
+__version__ = '0.1'
+
 from robot.api import logger

 import os
@@ -24,6 +27,7 @@
         self.port = port

     def start_django(self):
+        """Start the Django server."""
         args = [
             'python',
             'mysite/manage.py',
<|current_version|>
# -*- coding: utf-8 -*-
__version__ = '0.1'

from robot.api import logger

import os
import signal
import subprocess

ROBOT_LIBRARY_DOC_FORMAT = 'reST'

class DjangoLibrary:
    """A library for testing Django with Robot Framework.
    """

    django_pid = None
    selenium_pid = None

    # TEST CASE => New instance is created for every test case.
    # TEST SUITE => New instance is created for every test suite.
    # GLOBAL => Only one instance is created during the whole test execution.
    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

    def __init__(self, host="127.0.0.1", port=8000):
        self.host = host
        self.port = port

    def start_django(self):
        """Start the Django server."""
        args = [
            'python',
            'mysite/manage.py',
            'runserver',
            '%s:%s' % (self.host, self.port),
            '--nothreading',
            '--noreload',
        ]
        self.django_pid = subprocess.Popen(args).pid
        logger.console(
            "Django started (PID: %s)" % self.django_pid,
        )

    def stop_django(self):
        os.kill(self.django_pid, signal.SIGKILL)
        logger.console(
            "Django stopped (PID: %s)" % self.django_pid,
        )

<|next_version|>
# -*- coding: utf-8 -*-
__version__ = '0.1'

from robot.api import logger

import os
import signal
import subprocess

ROBOT_LIBRARY_DOC_FORMAT = 'reST'

class DjangoLibrary:
    """A library for testing Django with Robot Framework.
    """

    django_pid = None
    selenium_pid = None

    # TEST CASE => New instance is created for every test case.
    # TEST SUITE => New instance is created for every test suite.
    # GLOBAL => Only one instance is created during the whole test execution.
    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

    def __init__(self, host="127.0.0.1", port=8000):
        self.host = host
        self.port = port

    def start_django(self):
        """Start the Django server."""
        args = [
            'python',
            'mysite/manage.py',
            'runserver',
            '%s:%s' % (self.host, self.port),
            '--nothreading',
            '--noreload',
        ]
        self.django_pid = subprocess.Popen(args).pid
        logger.console(
            "Django started (PID: %s)" % self.django_pid,
        )

    def stop_django(self):
        """Stop Django server."""
        os.kill(self.django_pid, signal.SIGKILL)
        logger.console(
            "Django stopped (PID: %s)" % self.django_pid,
        )


Fix bug with ics url format with latest vobject version

--- pyvac/helpers/calendar.py
+++ pyvac/helpers/calendar.py
@@ -1,3 +1,4 @@
+import urllib
 import logging
 import caldav
 from dateutil.relativedelta import relativedelta
@@ -36,6 +37,7 @@
     log.info('Event %s created' % event)

     url_obj = event.url
+    url_obj = urllib.quote(url_obj, safe='/:')
     return str(url_obj)

<|original_code|>
import logging
import caldav
from dateutil.relativedelta import relativedelta

log = logging.getLogger(__file__)

def addToCal(url, date_from, date_end, summary):
    """ Add entry in calendar to period date_from, date_end """

    vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""

    client = caldav.DAVClient(url)
    principal = client.principal()
    calendars = principal.calendars()
    if not len(calendars):
        return False

    vcal_entry = vcal_entry % (summary,
                               date_from.strftime('%Y%m%d'),
                               (date_end + relativedelta(days=1)).strftime('%Y%m%d'))
    calendar = calendars[0]
    log.info('Using calendar %r' % calendar)
    log.info('Using entry: %s' % vcal_entry)

    event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
    log.info('Event %s created' % event)

    url_obj = event.url
    return str(url_obj)

def delFromCal(url, ics):
    """ Delete entry in calendar"""

    if not url:
        return False

    client = caldav.DAVClient(url)
    log.info('Deleting entry %r' % ics)
    client.delete(ics)

    return True

<|edits_diff|>
--- pyvac/helpers/calendar.py
+++ pyvac/helpers/calendar.py
@@ -1,3 +1,4 @@
+import urllib
 import logging
 import caldav
 from dateutil.relativedelta import relativedelta
<|current_version|>
import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta

log = logging.getLogger(__file__)

def addToCal(url, date_from, date_end, summary):
    """ Add entry in calendar to period date_from, date_end """

    vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""

    client = caldav.DAVClient(url)
    principal = client.principal()
    calendars = principal.calendars()
    if not len(calendars):
        return False

    vcal_entry = vcal_entry % (summary,
                               date_from.strftime('%Y%m%d'),
                               (date_end + relativedelta(days=1)).strftime('%Y%m%d'))
    calendar = calendars[0]
    log.info('Using calendar %r' % calendar)
    log.info('Using entry: %s' % vcal_entry)

    event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
    log.info('Event %s created' % event)

    url_obj = event.url
    return str(url_obj)

def delFromCal(url, ics):
    """ Delete entry in calendar"""

    if not url:
        return False

    client = caldav.DAVClient(url)
    log.info('Deleting entry %r' % ics)
    client.delete(ics)

    return True

<|next_version|>
import urllib
import logging
import caldav
from dateutil.relativedelta import relativedelta

log = logging.getLogger(__file__)

def addToCal(url, date_from, date_end, summary):
    """ Add entry in calendar to period date_from, date_end """

    vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""

    client = caldav.DAVClient(url)
    principal = client.principal()
    calendars = principal.calendars()
    if not len(calendars):
        return False

    vcal_entry = vcal_entry % (summary,
                               date_from.strftime('%Y%m%d'),
                               (date_end + relativedelta(days=1)).strftime('%Y%m%d'))
    calendar = calendars[0]
    log.info('Using calendar %r' % calendar)
    log.info('Using entry: %s' % vcal_entry)

    event = caldav.Event(client, data=vcal_entry, parent=calendar).save()
    log.info('Event %s created' % event)

    url_obj = event.url
    url_obj = urllib.quote(url_obj, safe='/:')
    return str(url_obj)

def delFromCal(url, ics):
    """ Delete entry in calendar"""

    if not url:
        return False

    client = caldav.DAVClient(url)
    log.info('Deleting entry %r' % ics)
    client.delete(ics)

    return True


Add pytest mark database setup for test

Add pytest mark database setup for test

--- tests/test_api_views.py
+++ tests/test_api_views.py
@@ -1,6 +1,7 @@
 import os
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

+import pytest
 import django
 from django.test import TestCase
 from rest_framework.test import APIRequestFactory
@@ -15,6 +16,7 @@
     def setUp(self):
         self.factory = APIRequestFactory()

+    @pytest.mark.postgres
     def test_document_view(self):
         view = DocumentList.as_view()
         request = self.factory.get(

<|original_code|>
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory

from api.webview.views import DocumentList

django.setup()

class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

<|edits_diff|>
--- tests/test_api_views.py
+++ tests/test_api_views.py
@@ -1,6 +1,7 @@
 import os
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

+import pytest
 import django
 from django.test import TestCase
 from rest_framework.test import APIRequestFactory
<|current_version|>
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory

from api.webview.views import DocumentList

django.setup()

class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

<|next_version|>
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

import pytest
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory

from api.webview.views import DocumentList

django.setup()

class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    @pytest.mark.postgres
    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)


Move page cleaning logic to the form.

Move page cleaning logic to the form.

--HG--
branch : result-refactor

--- selectable/forms/base.py
+++ selectable/forms/base.py
@@ -8,6 +8,7 @@
 class BaseLookupForm(forms.Form):
     term = forms.CharField(required=False)
     limit = forms.IntegerField(required=False, min_value=1)
+    page = forms.IntegerField(required=False, min_value=1)

     def clean_limit(self):
         "Ensure given limit is less than default if defined"
@@ -16,3 +17,7 @@
             (not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
             limit = settings.SELECTABLE_MAX_LIMIT
         return limit
+
+    def clean_page(self):
+        "Return the first page if no page or invalid number is given."
+        return self.cleaned_data.get('page', 1) or 1

<|original_code|>
from django import forms
from django.conf import settings

__all__ = ('BaseLookupForm', )

class BaseLookupForm(forms.Form):
    term = forms.CharField(required=False)
    limit = forms.IntegerField(required=False, min_value=1)

    def clean_limit(self):
        "Ensure given limit is less than default if defined"
        limit = self.cleaned_data.get('limit', None)
        if (settings.SELECTABLE_MAX_LIMIT is not None and
            (not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
            limit = settings.SELECTABLE_MAX_LIMIT
        return limit

<|edits_diff|>
--- selectable/forms/base.py
+++ selectable/forms/base.py
@@ -8,6 +8,7 @@
 class BaseLookupForm(forms.Form):
     term = forms.CharField(required=False)
     limit = forms.IntegerField(required=False, min_value=1)
+    page = forms.IntegerField(required=False, min_value=1)

     def clean_limit(self):
         "Ensure given limit is less than default if defined"
<|current_version|>
from django import forms
from django.conf import settings

__all__ = ('BaseLookupForm', )

class BaseLookupForm(forms.Form):
    term = forms.CharField(required=False)
    limit = forms.IntegerField(required=False, min_value=1)
    page = forms.IntegerField(required=False, min_value=1)

    def clean_limit(self):
        "Ensure given limit is less than default if defined"
        limit = self.cleaned_data.get('limit', None)
        if (settings.SELECTABLE_MAX_LIMIT is not None and
            (not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
            limit = settings.SELECTABLE_MAX_LIMIT
        return limit

<|next_version|>
from django import forms
from django.conf import settings

__all__ = ('BaseLookupForm', )

class BaseLookupForm(forms.Form):
    term = forms.CharField(required=False)
    limit = forms.IntegerField(required=False, min_value=1)
    page = forms.IntegerField(required=False, min_value=1)

    def clean_limit(self):
        "Ensure given limit is less than default if defined"
        limit = self.cleaned_data.get('limit', None)
        if (settings.SELECTABLE_MAX_LIMIT is not None and
            (not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
            limit = settings.SELECTABLE_MAX_LIMIT
        return limit

    def clean_page(self):
        "Return the first page if no page or invalid number is given."
        return self.cleaned_data.get('page', 1) or 1


Make a default empty users list

Make a default empty users list

--- stutuz/__init__.py
+++ stutuz/__init__.py
@@ -11,6 +11,8 @@
 from flaskext.genshi import Genshi
 from flaskext.zodb import ZODB, PersistentMapping

+from stutuz.models import Users
+

 logger = Logger(__name__)
 genshi = Genshi()
@@ -22,6 +24,8 @@
     if 'languages' not in root:
         root['languages'] = PersistentMapping({'eng': 'English',
                                                'jbo': 'Lojban'})
+    if 'users' not in root:
+        root['users'] = Users()

 def create_app(config=None):

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

from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals

from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flaskext.zodb import ZODB, PersistentMapping

logger = Logger(__name__)
genshi = Genshi()
db = ZODB()

@db.init
def set_defaults(root):
    if 'languages' not in root:
        root['languages'] = PersistentMapping({'eng': 'English',
                                               'jbo': 'Lojban'})

def create_app(config=None):

    app = Flask(__name__)

    app.config.from_object('stutuz.configs')
    if config is not None:
        app.config.from_object(config)
    app.config.from_envvar('STUTUZ_CONFIG', silent=True)

    handlers = app.config.get('LOGBOOK_HANDLERS')
    with NestedSetup(handlers):
        for extension in genshi, db:
            extension.init_app(app)

        for middleware in app.config.get('MIDDLEWARES', ()):
            app.wsgi_app = middleware(app.wsgi_app)

        return app

<|edits_diff|>
--- stutuz/__init__.py
+++ stutuz/__init__.py
@@ -10,6 +10,8 @@
 from flask import Flask
 from flaskext.genshi import Genshi
 from flaskext.zodb import ZODB, PersistentMapping
+
+from stutuz.models import Users

 logger = Logger(__name__)
<|current_version|>
#-*- coding:utf-8 -*-

from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals

from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flaskext.zodb import ZODB, PersistentMapping

from stutuz.models import Users

logger = Logger(__name__)
genshi = Genshi()
db = ZODB()

@db.init
def set_defaults(root):
    if 'languages' not in root:
        root['languages'] = PersistentMapping({'eng': 'English',
                                               'jbo': 'Lojban'})

def create_app(config=None):

    app = Flask(__name__)

    app.config.from_object('stutuz.configs')
    if config is not None:
        app.config.from_object(config)
    app.config.from_envvar('STUTUZ_CONFIG', silent=True)

    handlers = app.config.get('LOGBOOK_HANDLERS')
    with NestedSetup(handlers):
        for extension in genshi, db:
            extension.init_app(app)

        for middleware in app.config.get('MIDDLEWARES', ()):
            app.wsgi_app = middleware(app.wsgi_app)

        return app

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

from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals

from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flaskext.zodb import ZODB, PersistentMapping

from stutuz.models import Users

logger = Logger(__name__)
genshi = Genshi()
db = ZODB()

@db.init
def set_defaults(root):
    if 'languages' not in root:
        root['languages'] = PersistentMapping({'eng': 'English',
                                               'jbo': 'Lojban'})
    if 'users' not in root:
        root['users'] = Users()

def create_app(config=None):

    app = Flask(__name__)

    app.config.from_object('stutuz.configs')
    if config is not None:
        app.config.from_object(config)
    app.config.from_envvar('STUTUZ_CONFIG', silent=True)

    handlers = app.config.get('LOGBOOK_HANDLERS')
    with NestedSetup(handlers):
        for extension in genshi, db:
            extension.init_app(app)

        for middleware in app.config.get('MIDDLEWARES', ()):
            app.wsgi_app = middleware(app.wsgi_app)

        return app


Fix model definition in signature form

Fix model definition in signature form

--- ankieta/petition_custom/forms.py
+++ ankieta/petition_custom/forms.py
@@ -1,6 +1,9 @@
 from petition.forms import BaseSignatureForm
 from crispy_forms.layout import Layout
 from crispy_forms.bootstrap import PrependedText
+import swapper
+
+Signature = swapper.load_model("petition", "Signature")

 class SignatureForm(BaseSignatureForm):
@@ -15,3 +18,6 @@
                 'giodo',
                 'newsletter',
         )
+
+    class Meta:
+        model = Signature

<|original_code|>
from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText

class SignatureForm(BaseSignatureForm):
    def __init__(self, *args, **kwargs):
        super(SignatureForm, self).__init__(*args, **kwargs)
        self.helper.layout = Layout(
                'first_name',
                'last_name',
                PrependedText('email', '@'),
                PrependedText('city', ''),
                PrependedText('telephone', ''),
                'giodo',
                'newsletter',
        )

<|edits_diff|>
--- ankieta/petition_custom/forms.py
+++ ankieta/petition_custom/forms.py
@@ -1,6 +1,9 @@
 from petition.forms import BaseSignatureForm
 from crispy_forms.layout import Layout
 from crispy_forms.bootstrap import PrependedText
+import swapper
+
+Signature = swapper.load_model("petition", "Signature")

 class SignatureForm(BaseSignatureForm):
<|current_version|>
from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
import swapper

Signature = swapper.load_model("petition", "Signature")

class SignatureForm(BaseSignatureForm):
    def __init__(self, *args, **kwargs):
        super(SignatureForm, self).__init__(*args, **kwargs)
        self.helper.layout = Layout(
                'first_name',
                'last_name',
                PrependedText('email', '@'),
                PrependedText('city', ''),
                PrependedText('telephone', ''),
                'giodo',
                'newsletter',
        )

<|next_version|>
from petition.forms import BaseSignatureForm
from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText
import swapper

Signature = swapper.load_model("petition", "Signature")

class SignatureForm(BaseSignatureForm):
    def __init__(self, *args, **kwargs):
        super(SignatureForm, self).__init__(*args, **kwargs)
        self.helper.layout = Layout(
                'first_name',
                'last_name',
                PrependedText('email', '@'),
                PrependedText('city', ''),
                PrependedText('telephone', ''),
                'giodo',
                'newsletter',
        )

    class Meta:
        model = Signature


Support the Isles of Scilly

Support the Isles of Scilly

--- every_election/apps/organisations/constants.py
+++ every_election/apps/organisations/constants.py
@@ -6,6 +6,7 @@
     'CED': ['CPC',],
     'UTA': ['UTW', 'UTE'],
     'NIA': ['NIE',],
+    'COI': ['COP',],
 }
 CHILD_TO_PARENT_AREAS = {
     'DIW': 'DIS',
@@ -15,4 +16,5 @@
     'CED': 'CTY',
     'LBW': 'LBO',
     'CPC': 'CED',
+    'COP': 'COI',
 }

<|original_code|>
PARENT_TO_CHILD_AREAS = {
    'DIS': ['DIW',],
    'MTD': ['MTW',],
    'CTY': ['CED',],
    'LBO': ['LBW',],
    'CED': ['CPC',],
    'UTA': ['UTW', 'UTE'],
    'NIA': ['NIE',],
}
CHILD_TO_PARENT_AREAS = {
    'DIW': 'DIS',
    'MTW': 'MTD',
    'UTW': 'UTA',
    'UTE': 'UTA',
    'CED': 'CTY',
    'LBW': 'LBO',
    'CPC': 'CED',
}

<|edits_diff|>
--- every_election/apps/organisations/constants.py
+++ every_election/apps/organisations/constants.py
@@ -6,6 +6,7 @@
     'CED': ['CPC',],
     'UTA': ['UTW', 'UTE'],
     'NIA': ['NIE',],
+    'COI': ['COP',],
 }
 CHILD_TO_PARENT_AREAS = {
     'DIW': 'DIS',
<|current_version|>
PARENT_TO_CHILD_AREAS = {
    'DIS': ['DIW',],
    'MTD': ['MTW',],
    'CTY': ['CED',],
    'LBO': ['LBW',],
    'CED': ['CPC',],
    'UTA': ['UTW', 'UTE'],
    'NIA': ['NIE',],
    'COI': ['COP',],
}
CHILD_TO_PARENT_AREAS = {
    'DIW': 'DIS',
    'MTW': 'MTD',
    'UTW': 'UTA',
    'UTE': 'UTA',
    'CED': 'CTY',
    'LBW': 'LBO',
    'CPC': 'CED',
}

<|next_version|>
PARENT_TO_CHILD_AREAS = {
    'DIS': ['DIW',],
    'MTD': ['MTW',],
    'CTY': ['CED',],
    'LBO': ['LBW',],
    'CED': ['CPC',],
    'UTA': ['UTW', 'UTE'],
    'NIA': ['NIE',],
    'COI': ['COP',],
}
CHILD_TO_PARENT_AREAS = {
    'DIW': 'DIS',
    'MTW': 'MTD',
    'UTW': 'UTA',
    'UTE': 'UTA',
    'CED': 'CTY',
    'LBW': 'LBO',
    'CPC': 'CED',
    'COP': 'COI',
}


Reformat test to a standard style.

Reformat test to a standard style.

<|original_code|>
"""Test suite for the deepreload module."""

from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload

@dec.skipif_not_numpy
def test_deepreload_numpy():
    import numpy
    exclude = [
        # Standard exclusions:
        'sys', 'os.path', '__builtin__', '__main__',
        # Test-related exclusions:
        'unittest',
        ]
    dreload(numpy, exclude=exclude)

<|edits_diff|>
--- IPython/lib/tests/test_deepreload.py
+++ IPython/lib/tests/test_deepreload.py
@@ -1,4 +1,9 @@
+# -*- coding: utf-8 -*-
 """Test suite for the deepreload module."""
+
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------

 from IPython.testing import decorators as dec
 from IPython.lib.deepreload import reload as dreload
<|current_version|>
# -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload

@dec.skipif_not_numpy
def test_deepreload_numpy():
    import numpy
    exclude = [
        # Standard exclusions:
        'sys', 'os.path', '__builtin__', '__main__',
        # Test-related exclusions:
        'unittest',
        ]
    dreload(numpy, exclude=exclude)

<|next_version|>
# -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload

#-----------------------------------------------------------------------------
# Test functions begin
#-----------------------------------------------------------------------------

@dec.skipif_not_numpy
def test_deepreload_numpy():
    import numpy
    exclude = [
        # Standard exclusions:
        'sys', 'os.path', '__builtin__', '__main__',
        # Test-related exclusions:
        'unittest',
        ]
    dreload(numpy, exclude=exclude)


Set logging level higher so we don't spam tests with debug messages

--- neo/test/rawiotest/test_alphaomegarawio.py
+++ neo/test/rawiotest/test_alphaomegarawio.py
@@ -22,11 +22,15 @@

 """

+import logging
 import unittest

 from neo.rawio.alphaomegarawio import AlphaOmegaRawIO

 from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
+
+
+logging.getLogger().setLevel(logging.INFO)

 class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):

<|original_code|>
"""
Tests of neo.rawio.examplerawio

Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.

Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.

If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.

Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*

Author: Samuel Garcia

"""

import unittest

from neo.rawio.alphaomegarawio import AlphaOmegaRawIO

from neo.test.rawiotest.common_rawio_test import BaseTestRawIO

class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
    rawioclass = AlphaOmegaRawIO

    entities_to_download = [
        "alphaomega",
    ]

    entities_to_test = [
        "alphaomega/",
    ]

if __name__ == "__main__":
    unittest.main()

<|edits_diff|>
--- neo/test/rawiotest/test_alphaomegarawio.py
+++ neo/test/rawiotest/test_alphaomegarawio.py
@@ -22,6 +22,7 @@

 """

+import logging
 import unittest

 from neo.rawio.alphaomegarawio import AlphaOmegaRawIO
<|current_version|>
"""
Tests of neo.rawio.examplerawio

Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.

Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.

If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.

Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*

Author: Samuel Garcia

"""

import logging
import unittest

from neo.rawio.alphaomegarawio import AlphaOmegaRawIO

from neo.test.rawiotest.common_rawio_test import BaseTestRawIO

class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
    rawioclass = AlphaOmegaRawIO

    entities_to_download = [
        "alphaomega",
    ]

    entities_to_test = [
        "alphaomega/",
    ]

if __name__ == "__main__":
    unittest.main()

<|next_version|>
"""
Tests of neo.rawio.examplerawio

Note for dev:
if you write a new RawIO class your need to put some file
to be tested at g-node portal, Ask neuralensemble list for that.
The file need to be small.

Then you have to copy/paste/renamed the TestExampleRawIO
class and a full test will be done to test if the new coded IO
is compliant with the RawIO API.

If you have problems, do not hesitate to ask help github (prefered)
of neuralensemble list.

Note that same mechanism is used a neo.io API so files are tested
several time with neo.rawio (numpy buffer) and neo.io (neo object tree).
See neo.test.iotest.*

Author: Samuel Garcia

"""

import logging
import unittest

from neo.rawio.alphaomegarawio import AlphaOmegaRawIO

from neo.test.rawiotest.common_rawio_test import BaseTestRawIO

logging.getLogger().setLevel(logging.INFO)

class TestAlphaOmegaRawIO(BaseTestRawIO, unittest.TestCase):
    rawioclass = AlphaOmegaRawIO

    entities_to_download = [
        "alphaomega",
    ]

    entities_to_test = [
        "alphaomega/",
    ]

if __name__ == "__main__":
    unittest.main()


Add tests for eidos found_by annotation

Add tests for eidos found_by annotation

--- indra/tests/test_eidos.py
+++ indra/tests/test_eidos.py
@@ -17,6 +17,9 @@
     assert stmt.obj_delta.get('polarity') == -1
     assert stmt.subj_delta.get('adjectives') == ['large']
     assert stmt.obj_delta.get('adjectives') == ['seriously']
+
+    assert(stmt.evidence[0].annotations['found_by'] == \
+            'causeEffect_ported_syntax_1_verb-${addlabel}')
     print(stmt)

@@ -29,3 +32,5 @@
     assert stmt.subj.name == 'cost of fuel'
     assert stmt.obj.name == 'water trucking'
     assert stmt.obj_delta.get('polarity') == -1
+    assert(stmt.evidence[0].annotations['found_by'] == \
+            'ported_syntax_1_verb-Causal')

<|original_code|>
import os
from indra.sources import eidos
from indra.statements import Influence

path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')

def test_process_json():
    ep = eidos.process_json_file(test_json)
    assert ep is not None
    assert len(ep.statements) == 1
    stmt = ep.statements[0]
    assert isinstance(stmt, Influence)
    assert stmt.subj_delta.get('polarity') == 1
    assert stmt.obj_delta.get('polarity') == -1
    assert stmt.subj_delta.get('adjectives') == ['large']
    assert stmt.obj_delta.get('adjectives') == ['seriously']
    print(stmt)

def test_process_text():
    ep = eidos.process_text('The cost of fuel decreases water trucking.')
    assert ep is not None
    assert len(ep.statements) == 1
    stmt = ep.statements[0]
    assert isinstance(stmt, Influence)
    assert stmt.subj.name == 'cost of fuel'
    assert stmt.obj.name == 'water trucking'
    assert stmt.obj_delta.get('polarity') == -1

<|edits_diff|>
--- indra/tests/test_eidos.py
+++ indra/tests/test_eidos.py
@@ -17,6 +17,9 @@
     assert stmt.obj_delta.get('polarity') == -1
     assert stmt.subj_delta.get('adjectives') == ['large']
     assert stmt.obj_delta.get('adjectives') == ['seriously']
+
+    assert(stmt.evidence[0].annotations['found_by'] == \
+            'causeEffect_ported_syntax_1_verb-${addlabel}')
     print(stmt)

<|current_version|>
import os
from indra.sources import eidos
from indra.statements import Influence

path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')

def test_process_json():
    ep = eidos.process_json_file(test_json)
    assert ep is not None
    assert len(ep.statements) == 1
    stmt = ep.statements[0]
    assert isinstance(stmt, Influence)
    assert stmt.subj_delta.get('polarity') == 1
    assert stmt.obj_delta.get('polarity') == -1
    assert stmt.subj_delta.get('adjectives') == ['large']
    assert stmt.obj_delta.get('adjectives') == ['seriously']

    assert(stmt.evidence[0].annotations['found_by'] == \
            'causeEffect_ported_syntax_1_verb-${addlabel}')
    print(stmt)

def test_process_text():
    ep = eidos.process_text('The cost of fuel decreases water trucking.')
    assert ep is not None
    assert len(ep.statements) == 1
    stmt = ep.statements[0]
    assert isinstance(stmt, Influence)
    assert stmt.subj.name == 'cost of fuel'
    assert stmt.obj.name == 'water trucking'
    assert stmt.obj_delta.get('polarity') == -1

<|next_version|>
import os
from indra.sources import eidos
from indra.statements import Influence

path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')

def test_process_json():
    ep = eidos.process_json_file(test_json)
    assert ep is not None
    assert len(ep.statements) == 1
    stmt = ep.statements[0]
    assert isinstance(stmt, Influence)
    assert stmt.subj_delta.get('polarity') == 1
    assert stmt.obj_delta.get('polarity') == -1
    assert stmt.subj_delta.get('adjectives') == ['large']
    assert stmt.obj_delta.get('adjectives') == ['seriously']

    assert(stmt.evidence[0].annotations['found_by'] == \
            'causeEffect_ported_syntax_1_verb-${addlabel}')
    print(stmt)

def test_process_text():
    ep = eidos.process_text('The cost of fuel decreases water trucking.')
    assert ep is not None
    assert len(ep.statements) == 1
    stmt = ep.statements[0]
    assert isinstance(stmt, Influence)
    assert stmt.subj.name == 'cost of fuel'
    assert stmt.obj.name == 'water trucking'
    assert stmt.obj_delta.get('polarity') == -1
    assert(stmt.evidence[0].annotations['found_by'] == \
            'ported_syntax_1_verb-Causal')


Add django contrib redirects on opps core init

--- opps/core/__init__.py
+++ opps/core/__init__.py
@@ -10,8 +10,12 @@
         'opps.image',
         'opps.channel',
         'opps.source',
+        'django.contrib.redirects',
         'redactor',
         'tagging',)

+settings.MIDDLEWARE_CLASSES += (
+        'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
+
 settings.REDACTOR_OPTIONS = {'lang': 'en'}
 settings.REDACTOR_UPLOAD = 'uploads/'

<|original_code|>
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

trans_app_label = _('Opps')

settings.INSTALLED_APPS += ('opps.article',
        'opps.image',
        'opps.channel',
        'opps.source',
        'redactor',
        'tagging',)

settings.REDACTOR_OPTIONS = {'lang': 'en'}
settings.REDACTOR_UPLOAD = 'uploads/'

<|edits_diff|>
--- opps/core/__init__.py
+++ opps/core/__init__.py
@@ -10,6 +10,7 @@
         'opps.image',
         'opps.channel',
         'opps.source',
+        'django.contrib.redirects',
         'redactor',
         'tagging',)

<|current_version|>
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

trans_app_label = _('Opps')

settings.INSTALLED_APPS += ('opps.article',
        'opps.image',
        'opps.channel',
        'opps.source',
        'django.contrib.redirects',
        'redactor',
        'tagging',)

settings.REDACTOR_OPTIONS = {'lang': 'en'}
settings.REDACTOR_UPLOAD = 'uploads/'

<|next_version|>
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

trans_app_label = _('Opps')

settings.INSTALLED_APPS += ('opps.article',
        'opps.image',
        'opps.channel',
        'opps.source',
        'django.contrib.redirects',
        'redactor',
        'tagging',)

settings.MIDDLEWARE_CLASSES += (
        'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)

settings.REDACTOR_OPTIONS = {'lang': 'en'}
settings.REDACTOR_UPLOAD = 'uploads/'


Update Stylus filter with include paths

Update Stylus filter with include paths

Since the Stylus filter works with stdin, the compiler doesn't know the
source directory, and thus can't resolve any imports. This adds the
source directory to the include path using the `--include` option, and
also adds the `STYLUS_EXTRA_PATHS` option to configure any extra
include paths.

--- src/webassets/filter/stylus.py
+++ src/webassets/filter/stylus.py
@@ -1,3 +1,4 @@
+import os
 from webassets.filter import ExternalTool, option

@@ -24,6 +25,9 @@

     STYLUS_EXTRA_ARGS
         A Python list of any additional command-line arguments.
+
+    STYLUS_EXTRA_PATHS
+        A Python list of any additional import paths.
     """

     name = 'stylus'
@@ -31,11 +35,16 @@
         'stylus': 'STYLUS_BIN',
         'plugins': option('STYLUS_PLUGINS', type=list),
         'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
+        'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
     }
     max_debug_level = None

     def input(self, _in, out, **kwargs):
         args = [self.stylus or 'stylus']
+        source_dir = os.path.dirname(kwargs['source_path'])
+        paths = [source_dir] + (self.extra_paths or [])
+        for path in paths:
+            args.extend(('--include', path))
         for plugin in self.plugins or []:
             args.extend(('--use', plugin))
         if self.extra_args:

<|original_code|>
from webassets.filter import ExternalTool, option

__all__ = ('Stylus',)

class Stylus(ExternalTool):
    """Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.

    Requires the Stylus executable to be available externally. You can install
    it using the `Node Package Manager <http://npmjs.org/>`_::

        $ npm install stylus

    Supported configuration options:

    STYLUS_BIN
        The path to the Stylus binary. If not set, assumes ``stylus`` is in the
        system path.

    STYLUS_PLUGINS
        A Python list of Stylus plugins to use. Each plugin will be included
        via Stylus's command-line ``--use`` argument.

    STYLUS_EXTRA_ARGS
        A Python list of any additional command-line arguments.
    """

    name = 'stylus'
    options = {
        'stylus': 'STYLUS_BIN',
        'plugins': option('STYLUS_PLUGINS', type=list),
        'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
    }
    max_debug_level = None

    def input(self, _in, out, **kwargs):
        args = [self.stylus or 'stylus']
        for plugin in self.plugins or []:
            args.extend(('--use', plugin))
        if self.extra_args:
            args.extend(self.extra_args)
        self.subprocess(args, out, _in)

<|edits_diff|>
--- src/webassets/filter/stylus.py
+++ src/webassets/filter/stylus.py
@@ -1,3 +1,4 @@
+import os
 from webassets.filter import ExternalTool, option

@@ -24,6 +25,9 @@

     STYLUS_EXTRA_ARGS
         A Python list of any additional command-line arguments.
+
+    STYLUS_EXTRA_PATHS
+        A Python list of any additional import paths.
     """

     name = 'stylus'
@@ -31,6 +35,7 @@
         'stylus': 'STYLUS_BIN',
         'plugins': option('STYLUS_PLUGINS', type=list),
         'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
+        'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
     }
     max_debug_level = None

<|current_version|>
import os
from webassets.filter import ExternalTool, option

__all__ = ('Stylus',)

class Stylus(ExternalTool):
    """Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.

    Requires the Stylus executable to be available externally. You can install
    it using the `Node Package Manager <http://npmjs.org/>`_::

        $ npm install stylus

    Supported configuration options:

    STYLUS_BIN
        The path to the Stylus binary. If not set, assumes ``stylus`` is in the
        system path.

    STYLUS_PLUGINS
        A Python list of Stylus plugins to use. Each plugin will be included
        via Stylus's command-line ``--use`` argument.

    STYLUS_EXTRA_ARGS
        A Python list of any additional command-line arguments.

    STYLUS_EXTRA_PATHS
        A Python list of any additional import paths.
    """

    name = 'stylus'
    options = {
        'stylus': 'STYLUS_BIN',
        'plugins': option('STYLUS_PLUGINS', type=list),
        'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
        'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
    }
    max_debug_level = None

    def input(self, _in, out, **kwargs):
        args = [self.stylus or 'stylus']
        for plugin in self.plugins or []:
            args.extend(('--use', plugin))
        if self.extra_args:
            args.extend(self.extra_args)
        self.subprocess(args, out, _in)

<|next_version|>
import os
from webassets.filter import ExternalTool, option

__all__ = ('Stylus',)

class Stylus(ExternalTool):
    """Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.

    Requires the Stylus executable to be available externally. You can install
    it using the `Node Package Manager <http://npmjs.org/>`_::

        $ npm install stylus

    Supported configuration options:

    STYLUS_BIN
        The path to the Stylus binary. If not set, assumes ``stylus`` is in the
        system path.

    STYLUS_PLUGINS
        A Python list of Stylus plugins to use. Each plugin will be included
        via Stylus's command-line ``--use`` argument.

    STYLUS_EXTRA_ARGS
        A Python list of any additional command-line arguments.

    STYLUS_EXTRA_PATHS
        A Python list of any additional import paths.
    """

    name = 'stylus'
    options = {
        'stylus': 'STYLUS_BIN',
        'plugins': option('STYLUS_PLUGINS', type=list),
        'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
        'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
    }
    max_debug_level = None

    def input(self, _in, out, **kwargs):
        args = [self.stylus or 'stylus']
        source_dir = os.path.dirname(kwargs['source_path'])
        paths = [source_dir] + (self.extra_paths or [])
        for path in paths:
            args.extend(('--include', path))
        for plugin in self.plugins or []:
            args.extend(('--use', plugin))
        if self.extra_args:
            args.extend(self.extra_args)
        self.subprocess(args, out, _in)


Add config for different env

Add config for different env

--- mangacork/__init__.py
+++ mangacork/__init__.py
@@ -1,3 +1,4 @@
+import os
 import logging

 from flask import Flask
@@ -5,5 +6,6 @@
 log = logging.getLogger(__name__)

 app = Flask(__name__)
+app.config.from_object(os.environ['APP_SETTINGS'])

 import mangacork.views

<|original_code|>
import logging

from flask import Flask

log = logging.getLogger(__name__)

app = Flask(__name__)

import mangacork.views

<|edits_diff|>
--- mangacork/__init__.py
+++ mangacork/__init__.py
@@ -1,3 +1,4 @@
+import os
 import logging

 from flask import Flask
<|current_version|>
import os
import logging

from flask import Flask

log = logging.getLogger(__name__)

app = Flask(__name__)

import mangacork.views

<|next_version|>
import os
import logging

from flask import Flask

log = logging.getLogger(__name__)

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])

import mangacork.views


Add the query to get the near stations

Add the query to get the near stations

This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box.

--- moveon/managers.py
+++ moveon/managers.py
@@ -1,4 +1,5 @@
 from django.db import models
+from django.db.models import Q

 class CompanyManager(models.Manager):
     def get_by_code(self, company_code):
@@ -11,6 +12,11 @@
 class StationManager(models.Manager):
     def get_by_id(self, station_id):
         return self.get(osmid=station_id)
+
+    def get_near_stations(self, left, bottom, right, top):
+        stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
+                           Q(latitude__lte=right) & Q(longitude__lte=top))
+        return stations

 class NodeManager(models.Manager):
     def get_by_id(self, station_id):

<|original_code|>
from django.db import models

class CompanyManager(models.Manager):
    def get_by_code(self, company_code):
        return self.get(code=company_code)

class TransportManager(models.Manager):
    def get_by_name(self, transport_name):
        return self.get(name=transport_name)

class StationManager(models.Manager):
    def get_by_id(self, station_id):
        return self.get(osmid=station_id)

class NodeManager(models.Manager):
    def get_by_id(self, station_id):
        return self.get(osmid=station_id)

<|edits_diff|>
--- moveon/managers.py
+++ moveon/managers.py
@@ -1,4 +1,5 @@
 from django.db import models
+from django.db.models import Q

 class CompanyManager(models.Manager):
     def get_by_code(self, company_code):
<|current_version|>
from django.db import models
from django.db.models import Q

class CompanyManager(models.Manager):
    def get_by_code(self, company_code):
        return self.get(code=company_code)

class TransportManager(models.Manager):
    def get_by_name(self, transport_name):
        return self.get(name=transport_name)

class StationManager(models.Manager):
    def get_by_id(self, station_id):
        return self.get(osmid=station_id)

class NodeManager(models.Manager):
    def get_by_id(self, station_id):
        return self.get(osmid=station_id)

<|next_version|>
from django.db import models
from django.db.models import Q

class CompanyManager(models.Manager):
    def get_by_code(self, company_code):
        return self.get(code=company_code)

class TransportManager(models.Manager):
    def get_by_name(self, transport_name):
        return self.get(name=transport_name)

class StationManager(models.Manager):
    def get_by_id(self, station_id):
        return self.get(osmid=station_id)

    def get_near_stations(self, left, bottom, right, top):
        stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
                           Q(latitude__lte=right) & Q(longitude__lte=top))
        return stations

class NodeManager(models.Manager):
    def get_by_id(self, station_id):
        return self.get(osmid=station_id)


Fix broken alembic revision generation

Fix broken alembic revision generation

--- alembic/versions/2507366cb6f2_.py
+++ alembic/versions/2507366cb6f2_.py
@@ -10,9 +10,14 @@
 revision = '2507366cb6f2'
 down_revision = '2a31d97fa618'

+from os.path import abspath, dirname, join
+import sys
+
 from alembic import op
 import sqlalchemy as sa

+parentdir = dirname(dirname(dirname(abspath(__file__))))
+sys.path.insert(0,parentdir)
 from models.person import Person
 from utils.nlp.utils.translit import translit

<|original_code|>
"""empty message

Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453

"""

# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'

from alembic import op
import sqlalchemy as sa

from models.person import Person
from utils.nlp.utils.translit import translit

person_t = sa.sql.table(
    'person',
    sa.sql.column('id', sa.Integer),
    sa.sql.column('name', sa.Unicode(20)),
    sa.sql.column('name_en', sa.String(80))
)

def upgrade():
    people = Person.query.all()
    for person in people:
        name_en = translit(person.name, 'ko', 'en', 'name')
        op.execute(person_t.update().\
                where(person_t.c.id == person.id).\
                values({'name_en': op.inline_literal(name_en)})
        )

def downgrade():
    op.execute(person_t.update().\
            values({'name_en': op.inline_literal('')})
    )

<|edits_diff|>
--- alembic/versions/2507366cb6f2_.py
+++ alembic/versions/2507366cb6f2_.py
@@ -9,6 +9,9 @@
 # revision identifiers, used by Alembic.
 revision = '2507366cb6f2'
 down_revision = '2a31d97fa618'
+
+from os.path import abspath, dirname, join
+import sys

 from alembic import op
 import sqlalchemy as sa
<|current_version|>
"""empty message

Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453

"""

# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'

from os.path import abspath, dirname, join
import sys

from alembic import op
import sqlalchemy as sa

from models.person import Person
from utils.nlp.utils.translit import translit

person_t = sa.sql.table(
    'person',
    sa.sql.column('id', sa.Integer),
    sa.sql.column('name', sa.Unicode(20)),
    sa.sql.column('name_en', sa.String(80))
)

def upgrade():
    people = Person.query.all()
    for person in people:
        name_en = translit(person.name, 'ko', 'en', 'name')
        op.execute(person_t.update().\
                where(person_t.c.id == person.id).\
                values({'name_en': op.inline_literal(name_en)})
        )

def downgrade():
    op.execute(person_t.update().\
            values({'name_en': op.inline_literal('')})
    )

<|next_version|>
"""empty message

Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453

"""

# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'

from os.path import abspath, dirname, join
import sys

from alembic import op
import sqlalchemy as sa

parentdir = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0,parentdir)
from models.person import Person
from utils.nlp.utils.translit import translit

person_t = sa.sql.table(
    'person',
    sa.sql.column('id', sa.Integer),
    sa.sql.column('name', sa.Unicode(20)),
    sa.sql.column('name_en', sa.String(80))
)

def upgrade():
    people = Person.query.all()
    for person in people:
        name_en = translit(person.name, 'ko', 'en', 'name')
        op.execute(person_t.update().\
                where(person_t.c.id == person.id).\
                values({'name_en': op.inline_literal(name_en)})
        )

def downgrade():
    op.execute(person_t.update().\
            values({'name_en': op.inline_literal('')})
    )


Add some debug markers for more clearly finding our own rendering code

--- Cura/Qt/MainWindow.py
+++ Cura/Qt/MainWindow.py
@@ -3,6 +3,7 @@
 from PyQt5.QtQuick import QQuickWindow, QQuickItem

 from OpenGL import GL
+from OpenGL.GL.GREMEDY.string_marker import *

 class MainWindow(QQuickWindow):
     def __init__(self, parent = None):
@@ -31,8 +32,16 @@
     backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)

     def _render(self):
+        if bool(glStringMarkerGREMEDY):
+            msg = b"Begin Rendering Background"
+            glStringMarkerGREMEDY(len(msg), msg)
+
         GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
         GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

         if self._app:
             self._app.getController().getActiveView().render()
+
+        if bool(glStringMarkerGREMEDY):
+            msg = "End Rendering Background"
+            glStringMarkerGREMEDY(len(msg), msg)

<|original_code|>
from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem

from OpenGL import GL

class MainWindow(QQuickWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)

        self._app = None
        self._backgroundColor = QColor(204, 204, 204, 255)

        self.setClearBeforeRendering(False)
        self.beforeRendering.connect(self._render)

    def getApplication(self):
        return self._app

    def setApplication(self, app):
        self._app = app

    application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)

    def getBackgroundColor(self):
        return self._backgroundColor

    def setBackgroundColor(self, color):
        self._backgroundColor = color

    backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)

    def _render(self):
        GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        if self._app:
            self._app.getController().getActiveView().render()

<|edits_diff|>
--- Cura/Qt/MainWindow.py
+++ Cura/Qt/MainWindow.py
@@ -3,6 +3,7 @@
 from PyQt5.QtQuick import QQuickWindow, QQuickItem

 from OpenGL import GL
+from OpenGL.GL.GREMEDY.string_marker import *

 class MainWindow(QQuickWindow):
     def __init__(self, parent = None):
@@ -31,6 +32,10 @@
     backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)

     def _render(self):
+        if bool(glStringMarkerGREMEDY):
+            msg = b"Begin Rendering Background"
+            glStringMarkerGREMEDY(len(msg), msg)
+
         GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
         GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

<|current_version|>
from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem

from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *

class MainWindow(QQuickWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)

        self._app = None
        self._backgroundColor = QColor(204, 204, 204, 255)

        self.setClearBeforeRendering(False)
        self.beforeRendering.connect(self._render)

    def getApplication(self):
        return self._app

    def setApplication(self, app):
        self._app = app

    application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)

    def getBackgroundColor(self):
        return self._backgroundColor

    def setBackgroundColor(self, color):
        self._backgroundColor = color

    backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)

    def _render(self):
        if bool(glStringMarkerGREMEDY):
            msg = b"Begin Rendering Background"
            glStringMarkerGREMEDY(len(msg), msg)

        GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        if self._app:
            self._app.getController().getActiveView().render()

<|next_version|>
from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem

from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *

class MainWindow(QQuickWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)

        self._app = None
        self._backgroundColor = QColor(204, 204, 204, 255)

        self.setClearBeforeRendering(False)
        self.beforeRendering.connect(self._render)

    def getApplication(self):
        return self._app

    def setApplication(self, app):
        self._app = app

    application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)

    def getBackgroundColor(self):
        return self._backgroundColor

    def setBackgroundColor(self, color):
        self._backgroundColor = color

    backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)

    def _render(self):
        if bool(glStringMarkerGREMEDY):
            msg = b"Begin Rendering Background"
            glStringMarkerGREMEDY(len(msg), msg)

        GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        if self._app:
            self._app.getController().getActiveView().render()

        if bool(glStringMarkerGREMEDY):
            msg = "End Rendering Background"
            glStringMarkerGREMEDY(len(msg), msg)


Add nice name for working in the shell

Add nice name for working in the shell

--- teami18n/teami18n/models.py
+++ teami18n/teami18n/models.py
@@ -6,6 +6,9 @@
 class Country(models.Model):
     code = models.CharField(max_length=2, choices=tuple(countries),
                             unique=True)
+
+    def __unicode__(self):
+        return self.code

 class Podcast(models.Model):
@@ -18,3 +21,6 @@
     image_link = models.URLField(null=True, blank=True)

     countries = models.ManyToManyField(Country, related_name="podcasts")
+
+    def __unicode__(self):
+        return self.title

<|original_code|>
from django.db import models

from django_countries import countries

class Country(models.Model):
    code = models.CharField(max_length=2, choices=tuple(countries),
                            unique=True)

class Podcast(models.Model):
    story_id = models.CharField(max_length=16, unique=True)
    link = models.URLField()
    title = models.TextField()
    teaser = models.TextField()
    program_name = models.TextField(blank=True)
    show_date = models.DateTimeField(null=True, blank=True)
    image_link = models.URLField(null=True, blank=True)

    countries = models.ManyToManyField(Country, related_name="podcasts")

<|edits_diff|>
--- teami18n/teami18n/models.py
+++ teami18n/teami18n/models.py
@@ -6,6 +6,9 @@
 class Country(models.Model):
     code = models.CharField(max_length=2, choices=tuple(countries),
                             unique=True)
+
+    def __unicode__(self):
+        return self.code

 class Podcast(models.Model):
<|current_version|>
from django.db import models

from django_countries import countries

class Country(models.Model):
    code = models.CharField(max_length=2, choices=tuple(countries),
                            unique=True)

    def __unicode__(self):
        return self.code

class Podcast(models.Model):
    story_id = models.CharField(max_length=16, unique=True)
    link = models.URLField()
    title = models.TextField()
    teaser = models.TextField()
    program_name = models.TextField(blank=True)
    show_date = models.DateTimeField(null=True, blank=True)
    image_link = models.URLField(null=True, blank=True)

    countries = models.ManyToManyField(Country, related_name="podcasts")

<|next_version|>
from django.db import models

from django_countries import countries

class Country(models.Model):
    code = models.CharField(max_length=2, choices=tuple(countries),
                            unique=True)

    def __unicode__(self):
        return self.code

class Podcast(models.Model):
    story_id = models.CharField(max_length=16, unique=True)
    link = models.URLField()
    title = models.TextField()
    teaser = models.TextField()
    program_name = models.TextField(blank=True)
    show_date = models.DateTimeField(null=True, blank=True)
    image_link = models.URLField(null=True, blank=True)

    countries = models.ManyToManyField(Country, related_name="podcasts")

    def __unicode__(self):
        return self.title


Make the related location readonly

[IMP] Make the related location readonly

--- mrp_bom_location/models/mrp_bom.py
+++ mrp_bom_location/models/mrp_bom.py
@@ -9,6 +9,7 @@

     location_id = fields.Many2one(
         related='picking_type_id.default_location_dest_id',
+        readonly=True,
         store=True,
     )

@@ -18,5 +19,6 @@

     location_id = fields.Many2one(
         related='bom_id.picking_type_id.default_location_src_id',
+        readonly=True,
         store=True,
     )

<|original_code|>
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import fields, models

class MrpBom(models.Model):
    _inherit = "mrp.bom"

    location_id = fields.Many2one(
        related='picking_type_id.default_location_dest_id',
        store=True,
    )

class MrpBomLine(models.Model):
    _inherit = "mrp.bom.line"

    location_id = fields.Many2one(
        related='bom_id.picking_type_id.default_location_src_id',
        store=True,
    )

<|edits_diff|>
--- mrp_bom_location/models/mrp_bom.py
+++ mrp_bom_location/models/mrp_bom.py
@@ -9,6 +9,7 @@

     location_id = fields.Many2one(
         related='picking_type_id.default_location_dest_id',
+        readonly=True,
         store=True,
     )

<|current_version|>
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import fields, models

class MrpBom(models.Model):
    _inherit = "mrp.bom"

    location_id = fields.Many2one(
        related='picking_type_id.default_location_dest_id',
        readonly=True,
        store=True,
    )

class MrpBomLine(models.Model):
    _inherit = "mrp.bom.line"

    location_id = fields.Many2one(
        related='bom_id.picking_type_id.default_location_src_id',
        store=True,
    )

<|next_version|>
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import fields, models

class MrpBom(models.Model):
    _inherit = "mrp.bom"

    location_id = fields.Many2one(
        related='picking_type_id.default_location_dest_id',
        readonly=True,
        store=True,
    )

class MrpBomLine(models.Model):
    _inherit = "mrp.bom.line"

    location_id = fields.Many2one(
        related='bom_id.picking_type_id.default_location_src_id',
        readonly=True,
        store=True,
    )


Exit with nonzero when qq strings are missing

Change-Id: Ife0f114dbe48faa445397aa7a94f74de2309d117

--- scripts/missing-qq.py
+++ scripts/missing-qq.py
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 import os
+import sys
 import xml.etree.ElementTree as ET

 RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
@@ -20,6 +21,10 @@
     qqmsgs.add(child.attrib['name'])

 # Iterate through all messages and check that they're documented
+missing = 0
 for child in enroot:
     if child.attrib['name'] not in qqmsgs:
         print(child.attrib['name'] + " is undocumented!")
+        missing += 1
+
+sys.exit(1 if missing else 0)

<|original_code|>
#!/usr/bin/env python
import os
import xml.etree.ElementTree as ET

RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml")
QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml")

# Get ElementTree containing all message names in English
enroot = ET.parse(EN_STRINGS).getroot()

# Get ElementTree containing all documented messages
qqroot = ET.parse(QQ_STRINGS).getroot()

# Create a set to store all documented messages
qqmsgs = set()

# Add all documented messages to that set
for child in qqroot:
    qqmsgs.add(child.attrib['name'])

# Iterate through all messages and check that they're documented
for child in enroot:
    if child.attrib['name'] not in qqmsgs:
        print(child.attrib['name'] + " is undocumented!")

<|edits_diff|>
--- scripts/missing-qq.py
+++ scripts/missing-qq.py
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 import os
+import sys
 import xml.etree.ElementTree as ET

 RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
@@ -20,6 +21,7 @@
     qqmsgs.add(child.attrib['name'])

 # Iterate through all messages and check that they're documented
+missing = 0
 for child in enroot:
     if child.attrib['name'] not in qqmsgs:
         print(child.attrib['name'] + " is undocumented!")
<|current_version|>
#!/usr/bin/env python
import os
import sys
import xml.etree.ElementTree as ET

RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml")
QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml")

# Get ElementTree containing all message names in English
enroot = ET.parse(EN_STRINGS).getroot()

# Get ElementTree containing all documented messages
qqroot = ET.parse(QQ_STRINGS).getroot()

# Create a set to store all documented messages
qqmsgs = set()

# Add all documented messages to that set
for child in qqroot:
    qqmsgs.add(child.attrib['name'])

# Iterate through all messages and check that they're documented
missing = 0
for child in enroot:
    if child.attrib['name'] not in qqmsgs:
        print(child.attrib['name'] + " is undocumented!")

<|next_version|>
#!/usr/bin/env python
import os
import sys
import xml.etree.ElementTree as ET

RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res"))
EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml")
QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml")

# Get ElementTree containing all message names in English
enroot = ET.parse(EN_STRINGS).getroot()

# Get ElementTree containing all documented messages
qqroot = ET.parse(QQ_STRINGS).getroot()

# Create a set to store all documented messages
qqmsgs = set()

# Add all documented messages to that set
for child in qqroot:
    qqmsgs.add(child.attrib['name'])

# Iterate through all messages and check that they're documented
missing = 0
for child in enroot:
    if child.attrib['name'] not in qqmsgs:
        print(child.attrib['name'] + " is undocumented!")
        missing += 1

sys.exit(1 if missing else 0)


Fix tests: Allow for celery not to be running when doing in-memory celery for tests.

--- genome_designer/main/celery_util.py
+++ genome_designer/main/celery_util.py
@@ -5,6 +5,7 @@
 from errno import errorcode

 from celery.task.control import inspect
+from django.conf import settings

 CELERY_ERROR_KEY = 'ERROR'
@@ -14,6 +15,10 @@

     Source: http://stackoverflow.com/questions/8506914/detect-whether-celery-is-available-running
     """
+    if settings.BROKER_BACKEND == 'memory':
+        # We are testing with in-memory celery. Celery is effectively running.
+        return {}
+
     try:
         insp = inspect()
         d = insp.stats()

<|original_code|>
"""
Methods for interfacing with the Celery task queue management library.
"""

from errno import errorcode

from celery.task.control import inspect

CELERY_ERROR_KEY = 'ERROR'

def get_celery_worker_status():
    """Checks whether celery is running and reports the error if not.

    Source: http://stackoverflow.com/questions/8506914/detect-whether-celery-is-available-running
    """
    try:
        insp = inspect()
        d = insp.stats()
        if not d:
            d = { CELERY_ERROR_KEY: 'No running Celery workers were found.' }
    except IOError as e:
        msg = "Error connecting to the backend: " + str(e)
        if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED':
            msg += ' Check that the RabbitMQ server is running.'
        d = { CELERY_ERROR_KEY: msg }
    except ImportError as e:
        d = { CELERY_ERROR_KEY: str(e)}
    return d

<|edits_diff|>
--- genome_designer/main/celery_util.py
+++ genome_designer/main/celery_util.py
@@ -5,6 +5,7 @@
 from errno import errorcode

 from celery.task.control import inspect
+from django.conf import settings

 CELERY_ERROR_KEY = 'ERROR'
<|current_version|>
"""
Methods for interfacing with the Celery task queue management library.
"""

from errno import errorcode

from celery.task.control import inspect
from django.conf import settings

CELERY_ERROR_KEY = 'ERROR'

def get_celery_worker_status():
    """Checks whether celery is running and reports the error if not.

    Source: http://stackoverflow.com/questions/8506914/detect-whether-celery-is-available-running
    """
    try:
        insp = inspect()
        d = insp.stats()
        if not d:
            d = { CELERY_ERROR_KEY: 'No running Celery workers were found.' }
    except IOError as e:
        msg = "Error connecting to the backend: " + str(e)
        if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED':
            msg += ' Check that the RabbitMQ server is running.'
        d = { CELERY_ERROR_KEY: msg }
    except ImportError as e:
        d = { CELERY_ERROR_KEY: str(e)}
    return d

<|next_version|>
"""
Methods for interfacing with the Celery task queue management library.
"""

from errno import errorcode

from celery.task.control import inspect
from django.conf import settings

CELERY_ERROR_KEY = 'ERROR'

def get_celery_worker_status():
    """Checks whether celery is running and reports the error if not.

    Source: http://stackoverflow.com/questions/8506914/detect-whether-celery-is-available-running
    """
    if settings.BROKER_BACKEND == 'memory':
        # We are testing with in-memory celery. Celery is effectively running.
        return {}

    try:
        insp = inspect()
        d = insp.stats()
        if not d:
            d = { CELERY_ERROR_KEY: 'No running Celery workers were found.' }
    except IOError as e:
        msg = "Error connecting to the backend: " + str(e)
        if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED':
            msg += ' Check that the RabbitMQ server is running.'
        d = { CELERY_ERROR_KEY: msg }
    except ImportError as e:
        d = { CELERY_ERROR_KEY: str(e)}
    return d