from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.encoding import iri_to_uri

import datetime

from knights.library import Library

register = Library()

@register.helper
def now(fmt):
    return timezone.now().strftime(fmt)

@register.helper
def url(name, *args, **kwargs):
    try:
        return reverse(name, args=args, kwargs=kwargs)
    except:
        return None

@register.helper
def static(filename):
    try:
        from django.conf import settings
    except ImportError:
        prefix = ''
    else:
        prefix = iri_to_uri(getattr(settings, filename, ''))
    return prefix

Make the `now` helper timezone aware

Response:
<INSERT> django.utils import timezone
from <INSERT_END> <REPLACE_OLD> datetime.datetime.now().strftime(fmt)

@register.helper
def <REPLACE_NEW> timezone.now().strftime(fmt)

@register.helper
def <REPLACE_END> <|endoftext|>
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.encoding import iri_to_uri

import datetime

from knights.library import Library

register = Library()

@register.helper
def now(fmt):
    return timezone.now().strftime(fmt)

@register.helper
def url(name, *args, **kwargs):
    try:
        return reverse(name, args=args, kwargs=kwargs)
    except:
        return None

@register.helper
def static(filename):
    try:
        from django.conf import settings
    except ImportError:
        prefix = ''
    else:
        prefix = iri_to_uri(getattr(settings, filename, ''))
    return prefix

Prompt:
Make the `now` helper timezone aware

Thanks @tysonclugg

from django.core.urlresolvers import reverse
from django.utils.encoding import iri_to_uri

import datetime

from knights.library import Library

register = Library()

@register.helper
def now(fmt):
    return datetime.datetime.now().strftime(fmt)

@register.helper
def url(name, *args, **kwargs):
    try:
        return reverse(name, args=args, kwargs=kwargs)
    except:
        return None

@register.helper
def static(filename):
    try:
        from django.conf import settings
    except ImportError:
        prefix = ''
    else:
        prefix = iri_to_uri(getattr(settings, filename, ''))
    return prefix


"""elmo URL Configuration

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

urlpatterns = [
    url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'),
    url(r'^admin/', admin.site.urls),
    url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'),
    url(r'^auth/', include('social_django.urls', namespace='social')),
    url(r'^', include('moon_tracker.urls')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

Add support for Django debug sidebar.

Add support for Django debug sidebar.

Response:
<INSERT> django.conf import settings
from <INSERT_END> <REPLACE_OLD> include('moon_tracker.urls')),
]
 <REPLACE_NEW> include('moon_tracker.urls')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns
 <REPLACE_END> <|endoftext|> """elmo URL Configuration

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

urlpatterns = [
    url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'),
    url(r'^admin/', admin.site.urls),
    url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'),
    url(r'^auth/', include('social_django.urls', namespace='social')),
    url(r'^', include('moon_tracker.urls')),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

Prompt:
Add support for Django debug sidebar.

"""elmo URL Configuration

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

urlpatterns = [
    url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'),
    url(r'^admin/', admin.site.urls),
    url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'),
    url(r'^auth/', include('social_django.urls', namespace='social')),
    url(r'^', include('moon_tracker.urls')),
]


Add extra space below ending of import

Add extra space below ending of import

Response:
<REPLACE_OLD> models

admin.site.register(models.Weekday)
admin.site.register(models.Meal)
admin.site.register(models.MealOption)
admin.site.register(models.Course)
admin.site.register(models.Timetable)
admin.site.register(models.Dish)
admin.site.register(models.Admin)
 <REPLACE_NEW> models

admin.site.register(models.Weekday)
admin.site.register(models.Meal)
admin.site.register(models.MealOption)
admin.site.register(models.Course)
admin.site.register(models.Timetable)
admin.site.register(models.Dish)
admin.site.register(models.Admin)
 <REPLACE_END> <|endoftext|> from django.contrib import admin

from . import models

admin.site.register(models.Weekday)
admin.site.register(models.Meal)
admin.site.register(models.MealOption)
admin.site.register(models.Course)
admin.site.register(models.Timetable)
admin.site.register(models.Dish)
admin.site.register(models.Admin)

Prompt:
Add extra space below ending of import

from django.contrib import admin

from . import models

admin.site.register(models.Weekday)
admin.site.register(models.Meal)
admin.site.register(models.MealOption)
admin.site.register(models.Course)
admin.site.register(models.Timetable)
admin.site.register(models.Dish)
admin.site.register(models.Admin)


import configparser #To read the profiles.
import os #To join paths.
import pytest

##  Makes sure that the variants for the Ultimaker 3 Extended are exactly the
#   same as for the Ultimaker 3.
#
#   Once we have specialised profiles or a mechanism to inherit variants too, we
#   may remove this test and have different profiles for the extended where
#   needed, but until then we should keep them the same. It's happened all too
#   often that we updated the variants for the UM3 but forgot about the UM3E.
@pytest.mark.parametrize("um3_file, um3e_file", [
    #List the corresponding files below.
    ("ultimaker3_aa0.8.inst.cfg", "ultimaker3_extended_aa0.8.inst.cfg"),
    ("ultimaker3_aa04.inst.cfg", "ultimaker3_extended_aa04.inst.cfg"),
    ("ultimaker3_bb0.8.inst.cfg", "ultimaker3_extended_bb0.8.inst.cfg"),
    ("ultimaker3_bb04.inst.cfg", "ultimaker3_extended_bb04.inst.cfg")
])
def test_ultimaker3extended_variants(um3_file, um3e_file):
    directory = os.path.join(os.path.dirname(__file__), "..", "resources", "variants") #TODO: Hardcoded path relative to this test file.
    um3 = configparser.ConfigParser()
    um3.read_file(open(os.path.join(directory, um3_file)))
    um3e = configparser.ConfigParser()
    um3e.read_file(open(os.path.join(directory, um3e_file)))
    assert um3["values"] == um3e["values"]

Add test to ensure that UM3 and UM3E variants are kept the same

It's a bit chunky, but functional.

Response:
<INSERT> import configparser #To read the profiles.
import os #To join paths.
import pytest

## <INSERT_END> <INSERT> Makes sure that the variants for the Ultimaker 3 Extended are exactly the
#   same as for the Ultimaker 3.
#
#   Once we have specialised profiles or a mechanism to inherit variants too, we
#   may remove this test and have different profiles for the extended where
#   needed, but until then we should keep them the same. It's happened all too
#   often that we updated the variants for the UM3 but forgot about the UM3E.
@pytest.mark.parametrize("um3_file, um3e_file", [
    #List the corresponding files below.
    ("ultimaker3_aa0.8.inst.cfg", "ultimaker3_extended_aa0.8.inst.cfg"),
    ("ultimaker3_aa04.inst.cfg", "ultimaker3_extended_aa04.inst.cfg"),
    ("ultimaker3_bb0.8.inst.cfg", "ultimaker3_extended_bb0.8.inst.cfg"),
    ("ultimaker3_bb04.inst.cfg", "ultimaker3_extended_bb04.inst.cfg")
])
def test_ultimaker3extended_variants(um3_file, um3e_file):
    directory = os.path.join(os.path.dirname(__file__), "..", "resources", "variants") #TODO: Hardcoded path relative to this test file.
    um3 = configparser.ConfigParser()
    um3.read_file(open(os.path.join(directory, um3_file)))
    um3e = configparser.ConfigParser()
    um3e.read_file(open(os.path.join(directory, um3e_file)))
    assert um3["values"] == um3e["values"] <INSERT_END> <|endoftext|> import configparser #To read the profiles.
import os #To join paths.
import pytest

##  Makes sure that the variants for the Ultimaker 3 Extended are exactly the
#   same as for the Ultimaker 3.
#
#   Once we have specialised profiles or a mechanism to inherit variants too, we
#   may remove this test and have different profiles for the extended where
#   needed, but until then we should keep them the same. It's happened all too
#   often that we updated the variants for the UM3 but forgot about the UM3E.
@pytest.mark.parametrize("um3_file, um3e_file", [
    #List the corresponding files below.
    ("ultimaker3_aa0.8.inst.cfg", "ultimaker3_extended_aa0.8.inst.cfg"),
    ("ultimaker3_aa04.inst.cfg", "ultimaker3_extended_aa04.inst.cfg"),
    ("ultimaker3_bb0.8.inst.cfg", "ultimaker3_extended_bb0.8.inst.cfg"),
    ("ultimaker3_bb04.inst.cfg", "ultimaker3_extended_bb04.inst.cfg")
])
def test_ultimaker3extended_variants(um3_file, um3e_file):
    directory = os.path.join(os.path.dirname(__file__), "..", "resources", "variants") #TODO: Hardcoded path relative to this test file.
    um3 = configparser.ConfigParser()
    um3.read_file(open(os.path.join(directory, um3_file)))
    um3e = configparser.ConfigParser()
    um3e.read_file(open(os.path.join(directory, um3e_file)))
    assert um3["values"] == um3e["values"]

Prompt:
Add test to ensure that UM3 and UM3E variants are kept the same

It's a bit chunky, but functional.


# -*- coding: utf-8 -*-

import unittest
from flask import Flask
from flask.ext.knot import Knot, get_container

def create_app():
    app = Flask(__name__)
    app.config['TESTING'] = True
    return app

class TestKnot(unittest.TestCase):
    def test_acts_like_container(self):
        app = create_app()
        dic = Knot(app)

        def foo(c):
            return 'bar'

        dic.add_factory(foo)

        self.assertEqual(dic.provide('foo'), 'bar')

    def test_does_use_app_config_on_initialization(self):
        app = create_app()
        app.config['foo'] = 'bar'
        dic = Knot(app)

        self.assertEqual(dic['foo'], 'bar')

    def test_does_not_use_app_config_after_initialization(self):
        app = create_app()
        app.config['foo'] = 'bar'
        dic = Knot()
        dic.init_app(app)

        self.assertRaises(KeyError, lambda: dic['foo'])

    def test_container_is_shared(self):
        app1 = create_app()
        app2 = create_app()

        dic = Knot()
        dic.init_app(app1)
        dic.init_app(app2)

        dic1 = get_container(app1)
        dic2 = get_container(app2)

        assert dic1 is dic2

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

Add test for shared container.

Add test for shared container.

Response:
<REPLACE_OLD> Knot

def <REPLACE_NEW> Knot, get_container

def <REPLACE_END> <REPLACE_OLD> dic['foo'])

if <REPLACE_NEW> dic['foo'])

    def test_container_is_shared(self):
        app1 = create_app()
        app2 = create_app()

        dic = Knot()
        dic.init_app(app1)
        dic.init_app(app2)

        dic1 = get_container(app1)
        dic2 = get_container(app2)

        assert dic1 is dic2

if <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import unittest
from flask import Flask
from flask.ext.knot import Knot, get_container

def create_app():
    app = Flask(__name__)
    app.config['TESTING'] = True
    return app

class TestKnot(unittest.TestCase):
    def test_acts_like_container(self):
        app = create_app()
        dic = Knot(app)

        def foo(c):
            return 'bar'

        dic.add_factory(foo)

        self.assertEqual(dic.provide('foo'), 'bar')

    def test_does_use_app_config_on_initialization(self):
        app = create_app()
        app.config['foo'] = 'bar'
        dic = Knot(app)

        self.assertEqual(dic['foo'], 'bar')

    def test_does_not_use_app_config_after_initialization(self):
        app = create_app()
        app.config['foo'] = 'bar'
        dic = Knot()
        dic.init_app(app)

        self.assertRaises(KeyError, lambda: dic['foo'])

    def test_container_is_shared(self):
        app1 = create_app()
        app2 = create_app()

        dic = Knot()
        dic.init_app(app1)
        dic.init_app(app2)

        dic1 = get_container(app1)
        dic2 = get_container(app2)

        assert dic1 is dic2

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

Prompt:
Add test for shared container.
# -*- coding: utf-8 -*-

import unittest
from flask import Flask
from flask.ext.knot import Knot

def create_app():
    app = Flask(__name__)
    app.config['TESTING'] = True
    return app

class TestKnot(unittest.TestCase):
    def test_acts_like_container(self):
        app = create_app()
        dic = Knot(app)

        def foo(c):
            return 'bar'

        dic.add_factory(foo)

        self.assertEqual(dic.provide('foo'), 'bar')

    def test_does_use_app_config_on_initialization(self):
        app = create_app()
        app.config['foo'] = 'bar'
        dic = Knot(app)

        self.assertEqual(dic['foo'], 'bar')

    def test_does_not_use_app_config_after_initialization(self):
        app = create_app()
        app.config['foo'] = 'bar'
        dic = Knot()
        dic.init_app(app)

        self.assertRaises(KeyError, lambda: dic['foo'])

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


import numpy as np
from numpy.testing import *

import scipy.ndimage as ndimage

def test_byte_order_median():
    """Regression test for #413: median_filter does not handle bytes orders."""
    a = np.arange(9, dtype='<f4').reshape(3, 3)
    ref = ndimage.filters.median_filter(a,(3, 3))
    b = np.arange(9, dtype='>f4').reshape(3, 3)
    t = ndimage.filters.median_filter(b, (3, 3))
    assert_array_almost_equal(ref, t)

def test_zoom_output_shape():
    """Ticket #643"""
    x = np.arange(12).reshape((3,4))
    ndimage.zoom(x, 2, output=np.zeros((6,8)))

if __name__ == "__main__":
    run_module_suite()

Response:
<REPLACE_OLD> NumpyTest().run()
 <REPLACE_NEW> run_module_suite()
 <REPLACE_END> <|endoftext|> import numpy as np
from numpy.testing import *

import scipy.ndimage as ndimage

def test_byte_order_median():
    """Regression test for #413: median_filter does not handle bytes orders."""
    a = np.arange(9, dtype='<f4').reshape(3, 3)
    ref = ndimage.filters.median_filter(a,(3, 3))
    b = np.arange(9, dtype='>f4').reshape(3, 3)
    t = ndimage.filters.median_filter(b, (3, 3))
    assert_array_almost_equal(ref, t)

def test_zoom_output_shape():
    """Ticket #643"""
    x = np.arange(12).reshape((3,4))
    ndimage.zoom(x, 2, output=np.zeros((6,8)))

if __name__ == "__main__":
    run_module_suite()

Prompt:
Use run_module_suite instead of deprecated NumpyTest.

import numpy as np
from numpy.testing import *

import scipy.ndimage as ndimage

def test_byte_order_median():
    """Regression test for #413: median_filter does not handle bytes orders."""
    a = np.arange(9, dtype='<f4').reshape(3, 3)
    ref = ndimage.filters.median_filter(a,(3, 3))
    b = np.arange(9, dtype='>f4').reshape(3, 3)
    t = ndimage.filters.median_filter(b, (3, 3))
    assert_array_almost_equal(ref, t)

def test_zoom_output_shape():
    """Ticket #643"""
    x = np.arange(12).reshape((3,4))
    ndimage.zoom(x, 2, output=np.zeros((6,8)))

if __name__ == "__main__":
    NumpyTest().run()


# Copyright (c) 2017 Ruben Dulek
# The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.

import re #To perform the search and replace.

from ..Script import Script

##  Performs a search-and-replace on all g-code.
#
#   Due to technical limitations, the search can't cross the border between
#   layers.
class SearchAndReplace(Script):
    def getSettingDataString(self):
        return """{
            "name": "Search and Replace",
            "key": "SearchAndReplace",
            "metadata": {},
            "version": 2,
            "settings":
            {
                "search":
                {
                    "label": "Search",
                    "description": "All occurrences of this text will get replaced by the replacement text.",
                    "type": "str",
                    "default_value": ""
                },
                "replace":
                {
                    "label": "Replace",
                    "description": "The search text will get replaced by this text.",
                    "type": "str",
                    "default_value": ""
                },
                "is_regex":
                {
                    "label": "Use Regular Expressions",
                    "description": "When enabled, the search text will be interpreted as a regular expression.",
                    "type": "bool",
                    "default_value": false
                }
            }
        }"""

    def execute(self, data):
        search_string = self.getSettingValueByKey("search")
        if not self.getSettingValueByKey("is_regex"):
            search_string = re.escape(search_string) #Need to search for the actual string, not as a regex.
        search_regex = re.compile(search_string)

        replace_string = self.getSettingValueByKey("replace")

        for layer_number, layer in enumerate(data):
            data[layer_number] = re.sub(search_regex, replace_string, layer) #Replace all.

        return data

Add search and replace script

Add search and replace script

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Copyright (c) 2017 Ruben Dulek
# The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.

import re #To perform the search and replace.

from ..Script import Script

##  Performs a search-and-replace on all g-code.
#
#   Due to technical limitations, the search can't cross the border between
#   layers.
class SearchAndReplace(Script):
    def getSettingDataString(self):
        return """{
            "name": "Search and Replace",
            "key": "SearchAndReplace",
            "metadata": {},
            "version": 2,
            "settings":
            {
                "search":
                {
                    "label": "Search",
                    "description": "All occurrences of this text will get replaced by the replacement text.",
                    "type": "str",
                    "default_value": ""
                },
                "replace":
                {
                    "label": "Replace",
                    "description": "The search text will get replaced by this text.",
                    "type": "str",
                    "default_value": ""
                },
                "is_regex":
                {
                    "label": "Use Regular Expressions",
                    "description": "When enabled, the search text will be interpreted as a regular expression.",
                    "type": "bool",
                    "default_value": false
                }
            }
        }"""

    def execute(self, data):
        search_string = self.getSettingValueByKey("search")
        if not self.getSettingValueByKey("is_regex"):
            search_string = re.escape(search_string) #Need to search for the actual string, not as a regex.
        search_regex = re.compile(search_string)

        replace_string = self.getSettingValueByKey("replace")

        for layer_number, layer in enumerate(data):
            data[layer_number] = re.sub(search_regex, replace_string, layer) #Replace all.

        return data <REPLACE_END> <|endoftext|> # Copyright (c) 2017 Ruben Dulek
# The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.

import re #To perform the search and replace.

from ..Script import Script

##  Performs a search-and-replace on all g-code.
#
#   Due to technical limitations, the search can't cross the border between
#   layers.
class SearchAndReplace(Script):
    def getSettingDataString(self):
        return """{
            "name": "Search and Replace",
            "key": "SearchAndReplace",
            "metadata": {},
            "version": 2,
            "settings":
            {
                "search":
                {
                    "label": "Search",
                    "description": "All occurrences of this text will get replaced by the replacement text.",
                    "type": "str",
                    "default_value": ""
                },
                "replace":
                {
                    "label": "Replace",
                    "description": "The search text will get replaced by this text.",
                    "type": "str",
                    "default_value": ""
                },
                "is_regex":
                {
                    "label": "Use Regular Expressions",
                    "description": "When enabled, the search text will be interpreted as a regular expression.",
                    "type": "bool",
                    "default_value": false
                }
            }
        }"""

    def execute(self, data):
        search_string = self.getSettingValueByKey("search")
        if not self.getSettingValueByKey("is_regex"):
            search_string = re.escape(search_string) #Need to search for the actual string, not as a regex.
        search_regex = re.compile(search_string)

        replace_string = self.getSettingValueByKey("replace")

        for layer_number, layer in enumerate(data):
            data[layer_number] = re.sub(search_regex, replace_string, layer) #Replace all.

        return data

Prompt: Add search and replace script


import json
import logging
import time
from datetime import datetime

import zmq
from django.conf import settings
from django.core.management.base import NoArgsCommand

from job_runner.apps.job_runner.models import Run

logger = logging.getLogger(__name__)

class Command(NoArgsCommand):
    help = 'Broadcast runs in queue to workers'

    def handle_noargs(self, **options):
        logger.info('Starting queue broadcaster')
        context = zmq.Context(1)
        publisher = context.socket(zmq.PUB)
        publisher.bind(
            'tcp://*:{0}'.format(settings.JOB_RUNNER_BROADCASTER_PORT))

        # give the subscribers some time to (re-)connect.
        time.sleep(2)

        while True:
            self._broadcast(publisher)
            time.sleep(5)

        publisher.close()
        context.term()

    def _broadcast(self, publisher):
        """
        Broadcast runs that are scheduled to run now.

        :param publisher:
            A ``zmq`` publisher.

        """
        enqueueable_runs = Run.objects.awaiting_enqueue().filter(
            schedule_dts__lte=datetime.utcnow()).select_related()

        for run in enqueueable_runs:
            worker = run.job.job_template.worker
            message = [
                'master.broadcast.{0}'.format(worker.api_key),
                json.dumps({'run_id': run.id, 'action': 'enqueue'})
            ]
            logger.debug('Sending: {0}'.format(message))
            publisher.send_multipart(message)

Response:
<INSERT>        # give the subscribers some time to (re-)connect.
        time.sleep(2)

 <INSERT_END> <|endoftext|> import json
import logging
import time
from datetime import datetime

import zmq
from django.conf import settings
from django.core.management.base import NoArgsCommand

from job_runner.apps.job_runner.models import Run

logger = logging.getLogger(__name__)

class Command(NoArgsCommand):
    help = 'Broadcast runs in queue to workers'

    def handle_noargs(self, **options):
        logger.info('Starting queue broadcaster')
        context = zmq.Context(1)
        publisher = context.socket(zmq.PUB)
        publisher.bind(
            'tcp://*:{0}'.format(settings.JOB_RUNNER_BROADCASTER_PORT))

        # give the subscribers some time to (re-)connect.
        time.sleep(2)

        while True:
            self._broadcast(publisher)
            time.sleep(5)

        publisher.close()
        context.term()

    def _broadcast(self, publisher):
        """
        Broadcast runs that are scheduled to run now.

        :param publisher:
            A ``zmq`` publisher.

        """
        enqueueable_runs = Run.objects.awaiting_enqueue().filter(
            schedule_dts__lte=datetime.utcnow()).select_related()

        for run in enqueueable_runs:
            worker = run.job.job_template.worker
            message = [
                'master.broadcast.{0}'.format(worker.api_key),
                json.dumps({'run_id': run.id, 'action': 'enqueue'})
            ]
            logger.debug('Sending: {0}'.format(message))
            publisher.send_multipart(message)

Prompt:
Add time.sleep after binding publisher to give subscribers time to (re-)connect.

import json
import logging
import time
from datetime import datetime

import zmq
from django.conf import settings
from django.core.management.base import NoArgsCommand

from job_runner.apps.job_runner.models import Run

logger = logging.getLogger(__name__)

class Command(NoArgsCommand):
    help = 'Broadcast runs in queue to workers'

    def handle_noargs(self, **options):
        logger.info('Starting queue broadcaster')
        context = zmq.Context(1)
        publisher = context.socket(zmq.PUB)
        publisher.bind(
            'tcp://*:{0}'.format(settings.JOB_RUNNER_BROADCASTER_PORT))

        while True:
            self._broadcast(publisher)
            time.sleep(5)

        publisher.close()
        context.term()

    def _broadcast(self, publisher):
        """
        Broadcast runs that are scheduled to run now.

        :param publisher:
            A ``zmq`` publisher.

        """
        enqueueable_runs = Run.objects.awaiting_enqueue().filter(
            schedule_dts__lte=datetime.utcnow()).select_related()

        for run in enqueueable_runs:
            worker = run.job.job_template.worker
            message = [
                'master.broadcast.{0}'.format(worker.api_key),
                json.dumps({'run_id': run.id, 'action': 'enqueue'})
            ]
            logger.debug('Sending: {0}'.format(message))
            publisher.send_multipart(message)


from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items

class DatasetSpider(CrawlSpider):

    pages = 9466
    name = 'dataset'
    allowed_domains = ['data.gc.ca']
    start_urls = []

    for i in range(1, pages + 1):
        start_urls.append('http://data.gc.ca/data/en/dataset?page=' + str(i))

    rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
                  'parse_dataset')]

    def parse_dataset(self, response):
        sel = Selector(response)
        dataset = items.DatasetItem()
        dataset['url'] = response.url
        dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
        dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").re('[A-Z]{1}[a-z]+')[0].encode('ascii','ignore')

        return dataset

Response:
<REPLACE_OLD> sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract()

 <REPLACE_NEW> sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").re('[A-Z]{1}[a-z]+')[0].encode('ascii','ignore')

 <REPLACE_END> <|endoftext|> from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items

class DatasetSpider(CrawlSpider):

    pages = 9466
    name = 'dataset'
    allowed_domains = ['data.gc.ca']
    start_urls = []

    for i in range(1, pages + 1):
        start_urls.append('http://data.gc.ca/data/en/dataset?page=' + str(i))

    rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
                  'parse_dataset')]

    def parse_dataset(self, response):
        sel = Selector(response)
        dataset = items.DatasetItem()
        dataset['url'] = response.url
        dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
        dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").re('[A-Z]{1}[a-z]+')[0].encode('ascii','ignore')

        return dataset

Prompt:
Add regex to filter out tab/space/newline

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items

class DatasetSpider(CrawlSpider):

    pages = 9466
    name = 'dataset'
    allowed_domains = ['data.gc.ca']
    start_urls = []

    for i in range(1, pages + 1):
        start_urls.append('http://data.gc.ca/data/en/dataset?page=' + str(i))

    rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
                  'parse_dataset')]

    def parse_dataset(self, response):
        sel = Selector(response)
        dataset = items.DatasetItem()
        dataset['url'] = response.url
        dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
        dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract()

        return dataset


import sublime, sublime_plugin

import requests
from requests import delete, get, head, options, patch, post, put

class RequestCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        self.import_variables()
        selections = self.get_selections()
        for s in selections:
            response = eval(s)
            print(response.text)

    def import_variables(self):
        with open('/Users/kylebebak/GoogleDrive/Code/Config/ST/Packages/http_requests/_requests_variables.py') as f:
            exec(f.read(), globals())

    def get_selections(self):
        view = self.view
        selections = []
        for region in view.sel():
            if not region.empty():
                selections.append( view.substr(region) )
            else:
                selections.append( view.substr(view.line(region)) )
        return selections

Response:
<REPLACE_OLD> request = self.view.substr(self.view.line(self.view.sel()[0]))
 <REPLACE_NEW> selections = self.get_selections()
        for s in selections:
     <REPLACE_END> <REPLACE_OLD> eval(request)
 <REPLACE_NEW> eval(s)
     <REPLACE_END> <REPLACE_OLD> open('/Users/kylebebak/GoogleDrive/Code/Config/ST/Packages/http_requests/_request_variables.py') <REPLACE_NEW> open('/Users/kylebebak/GoogleDrive/Code/Config/ST/Packages/http_requests/_requests_variables.py') <REPLACE_END> <REPLACE_OLD> globals())
 <REPLACE_NEW> globals())

    def get_selections(self):
        view = self.view
        selections = []
        for region in view.sel():
            if not region.empty():
                selections.append( view.substr(region) )
            else:
                selections.append( view.substr(view.line(region)) )
        return selections

 <REPLACE_END> <|endoftext|> import sublime, sublime_plugin

import requests
from requests import delete, get, head, options, patch, post, put

class RequestCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        self.import_variables()
        selections = self.get_selections()
        for s in selections:
            response = eval(s)
            print(response.text)

    def import_variables(self):
        with open('/Users/kylebebak/GoogleDrive/Code/Config/ST/Packages/http_requests/_requests_variables.py') as f:
            exec(f.read(), globals())

    def get_selections(self):
        view = self.view
        selections = []
        for region in view.sel():
            if not region.empty():
                selections.append( view.substr(region) )
            else:
                selections.append( view.substr(view.line(region)) )
        return selections

Prompt:
Allow multiple requests to be made at once by iterating over selections

import sublime, sublime_plugin

import requests
from requests import delete, get, head, options, patch, post, put

class RequestCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        self.import_variables()
        request = self.view.substr(self.view.line(self.view.sel()[0]))
        response = eval(request)
        print(response.text)

    def import_variables(self):
        with open('/Users/kylebebak/GoogleDrive/Code/Config/ST/Packages/http_requests/_request_variables.py') as f:
            exec(f.read(), globals())


#!/usr/bin/env python3
# utility.py
# PixPack Photo Organiser
# It contains some useful functions to increase user experience

import locale
import os

def sys_trans_var():
    # check system language
    sys_loc = locale.getlocale()
    sys_lang = sys_loc[0] # system default language
    if sys_lang == 'en_EN' or sys_lang == 'en_GB':
        return 0
    elif sys_lang == 'tr_TR':
        return 1
    else:
        return 0

def name_existing_photos(dest_directory, dest_file, copy_suffix):
    # rename if the file is existed already, for instance: photo_1
    dest_file_path = os.path.join(dest_directory, dest_file)
    i=1
    if os.path.exists(dest_file_path):
        dest_directory = os.path.join(dest_directory, "copies")
        if not os.path.exists(dest_directory):
            os.makedirs(dest_directory)
    while os.path.exists(dest_file_path):
        dest_file_path = os.path.join(dest_directory, dest_file)
        file_name = os.path.basename(dest_file_path)
        name, ext = os.path.splitext(file_name)
        name = name + "_" + str(copy_suffix) + str(i)
        new_name = name + ext
        dest_file_path = os.path.join(dest_directory, new_name)
        i+=1
    return dest_file_path

Response:
<INSERT> if os.path.exists(dest_file_path):
        dest_directory = os.path.join(dest_directory, "copies")
        if not os.path.exists(dest_directory):
            os.makedirs(dest_directory)
    <INSERT_END> <|endoftext|> #!/usr/bin/env python3
# utility.py
# PixPack Photo Organiser
# It contains some useful functions to increase user experience

import locale
import os

def sys_trans_var():
    # check system language
    sys_loc = locale.getlocale()
    sys_lang = sys_loc[0] # system default language
    if sys_lang == 'en_EN' or sys_lang == 'en_GB':
        return 0
    elif sys_lang == 'tr_TR':
        return 1
    else:
        return 0

def name_existing_photos(dest_directory, dest_file, copy_suffix):
    # rename if the file is existed already, for instance: photo_1
    dest_file_path = os.path.join(dest_directory, dest_file)
    i=1
    if os.path.exists(dest_file_path):
        dest_directory = os.path.join(dest_directory, "copies")
        if not os.path.exists(dest_directory):
            os.makedirs(dest_directory)
    while os.path.exists(dest_file_path):
        dest_file_path = os.path.join(dest_directory, dest_file)
        file_name = os.path.basename(dest_file_path)
        name, ext = os.path.splitext(file_name)
        name = name + "_" + str(copy_suffix) + str(i)
        new_name = name + ext
        dest_file_path = os.path.join(dest_directory, new_name)
        i+=1
    return dest_file_path

Prompt:
Store the duplicated items separately in related folder

#!/usr/bin/env python3
# utility.py
# PixPack Photo Organiser
# It contains some useful functions to increase user experience

import locale
import os

def sys_trans_var():
    # check system language
    sys_loc = locale.getlocale()
    sys_lang = sys_loc[0] # system default language
    if sys_lang == 'en_EN' or sys_lang == 'en_GB':
        return 0
    elif sys_lang == 'tr_TR':
        return 1
    else:
        return 0

def name_existing_photos(dest_directory, dest_file, copy_suffix):
    # rename if the file is existed already, for instance: photo_1
    dest_file_path = os.path.join(dest_directory, dest_file)
    i=1
    while os.path.exists(dest_file_path):
        dest_file_path = os.path.join(dest_directory, dest_file)
        file_name = os.path.basename(dest_file_path)
        name, ext = os.path.splitext(file_name)
        name = name + "_" + str(copy_suffix) + str(i)
        new_name = name + ext
        dest_file_path = os.path.join(dest_directory, new_name)
        i+=1
    return dest_file_path


#!/usr/bin/env python

"""
This is the main file. The script finds the game window and sets up the
coordinates for each block.

The MIT License (MIT)
(c) 2016
"""

import pyautogui, logging, time

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S')

# logging.disable(logging.DEBUG) # uncomment to block debug log messages

__author__ = "Alex Flores Escarcega"
__copyright__ = "Copyright 2007, Alex Flores Escarcega"
__credits__ = ["Alex Flores Escarcega"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Alex Flores Escarcega"
__email__ = "alex.floresescar@gmail.com"
__status__ = "Development"

def main():
    """
    No inputs
    No outputs
    Starts up the gameregionfinder
    """

if __name__ == "__main__":
        main()

Response:
<REPLACE_OLD> 2016
"""

def <REPLACE_NEW> 2016
"""

import pyautogui, logging, time

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S')

# logging.disable(logging.DEBUG) # uncomment to block debug log messages

__author__ = "Alex Flores Escarcega"
__copyright__ = "Copyright 2007, Alex Flores Escarcega"
__credits__ = ["Alex Flores Escarcega"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Alex Flores Escarcega"
__email__ = "alex.floresescar@gmail.com"
__status__ = "Development"

def <REPLACE_END> <REPLACE_OLD> """

if <REPLACE_NEW> """

if <REPLACE_END> <|endoftext|> #!/usr/bin/env python

"""
This is the main file. The script finds the game window and sets up the
coordinates for each block.

The MIT License (MIT)
(c) 2016
"""

import pyautogui, logging, time

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S')

# logging.disable(logging.DEBUG) # uncomment to block debug log messages

__author__ = "Alex Flores Escarcega"
__copyright__ = "Copyright 2007, Alex Flores Escarcega"
__credits__ = ["Alex Flores Escarcega"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Alex Flores Escarcega"
__email__ = "alex.floresescar@gmail.com"
__status__ = "Development"

def main():
    """
    No inputs
    No outputs
    Starts up the gameregionfinder
    """

if __name__ == "__main__":
        main()

Prompt:
Add imports, logging configs, and authorship info

#!/usr/bin/env python

"""
This is the main file. The script finds the game window and sets up the
coordinates for each block.

The MIT License (MIT)
(c) 2016
"""

def main():
    """
    No inputs
    No outputs
    Starts up the gameregionfinder
    """

if __name__ == "__main__":
        main()


import os
import pytest
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')

def test_docker_service_enabled(host):
    service = host.service('docker')
    assert service.is_enabled

def test_docker_service_running(host):
    service = host.service('docker')
    assert service.is_running

@pytest.mark.parametrize('socket_def', [
    # all IPv4 tcp sockets on port 8883 (MQQTS)
    ('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
    socket = host.socket(socket_def)
    assert socket.is_listening

# Tests to write:
# - using the localhost listener:
#    - verify that a message can be published
#    - verify that a published message can be subscribed to

Response:
<DELETE>    # listening on localhost, for tcp sockets on port 1883 (MQQT)
    ('tcp://127.0.0.1:1883'),
 <DELETE_END> <|endoftext|> import os
import pytest
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')

def test_docker_service_enabled(host):
    service = host.service('docker')
    assert service.is_enabled

def test_docker_service_running(host):
    service = host.service('docker')
    assert service.is_running

@pytest.mark.parametrize('socket_def', [
    # all IPv4 tcp sockets on port 8883 (MQQTS)
    ('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
    socket = host.socket(socket_def)
    assert socket.is_listening

# Tests to write:
# - using the localhost listener:
#    - verify that a message can be published
#    - verify that a published message can be subscribed to

Prompt:
Remove test enforcing listening on port 1883

import os
import pytest
import testinfra.utils.ansible_runner

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')

def test_docker_service_enabled(host):
    service = host.service('docker')
    assert service.is_enabled

def test_docker_service_running(host):
    service = host.service('docker')
    assert service.is_running

@pytest.mark.parametrize('socket_def', [
    # listening on localhost, for tcp sockets on port 1883 (MQQT)
    ('tcp://127.0.0.1:1883'),
    # all IPv4 tcp sockets on port 8883 (MQQTS)
    ('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
    socket = host.socket(socket_def)
    assert socket.is_listening

# Tests to write:
# - using the localhost listener:
#    - verify that a message can be published
#    - verify that a published message can be subscribed to


import pytest
import bluesky.plans as bp

def test_legacy_plan_names():
    assert bp.outer_product_scan is bp.grid_scan
    assert bp.relative_outer_product_scan is bp.rel_grid_scan
    assert bp.relative_scan is bp.rel_scan
    assert bp.relative_spiral is bp.rel_spiral
    assert bp.relative_spiral_fermat is bp.rel_spiral_fermat
    assert bp.relative_list_scan is bp.rel_list_scan
    assert relative_log_scan is rel_log_scan
    assert relative_adaptive_scan is rel_adaptive_scan

Add test to check for legacy plan names

TST: Add test to check for legacy plan names

Response:
<INSERT> import pytest
import bluesky.plans as bp

def test_legacy_plan_names():
 <INSERT_END> <INSERT>   assert bp.outer_product_scan is bp.grid_scan
    assert bp.relative_outer_product_scan is bp.rel_grid_scan
    assert bp.relative_scan is bp.rel_scan
    assert bp.relative_spiral is bp.rel_spiral
    assert bp.relative_spiral_fermat is bp.rel_spiral_fermat
    assert bp.relative_list_scan is bp.rel_list_scan
    assert relative_log_scan is rel_log_scan
    assert relative_adaptive_scan is rel_adaptive_scan
 <INSERT_END> <|endoftext|> import pytest
import bluesky.plans as bp

def test_legacy_plan_names():
    assert bp.outer_product_scan is bp.grid_scan
    assert bp.relative_outer_product_scan is bp.rel_grid_scan
    assert bp.relative_scan is bp.rel_scan
    assert bp.relative_spiral is bp.rel_spiral
    assert bp.relative_spiral_fermat is bp.rel_spiral_fermat
    assert bp.relative_list_scan is bp.rel_list_scan
    assert relative_log_scan is rel_log_scan
    assert relative_adaptive_scan is rel_adaptive_scan

Prompt: TST: Add test to check for legacy plan names


import csv
import sys

from django.core.management.base import BaseCommand, CommandError

from pombola.core.models import Organisation, OrganisationRelationship

MAPS_URL_TEMPLATE = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'

def encode_row_values_to_utf8(row):
    return {
        k: unicode(v).encode('utf-8')
        for k, v in row.items()
    }

class Command(BaseCommand):

    def handle(self, *args, **options):

        fields = [
            'OfficeID',
            'OfficeName',
            'MapURL',
            'PhysicalAddress',
            'Latitude',
            'Longitude',
            'PartyName',
            'PartyID'
        ]

        writer = csv.DictWriter(sys.stdout, fieldnames=fields)

        writer.writeheader()

        for o in Organisation.objects. \
            filter(kind__slug='constituency-office'). \
            order_by('slug'):
            places = o.place_set.filter(
                kind__slug='constituency-office',
                name__startswith='Approximate position of ',
            )
            place_count = places.count()
            if place_count > 1:
                msg = "Multiple places ({place_count}) found for {organisation_id}"
                raise CommandError(msg.format(
                    place_count=place_count,
                    organisation_id=o.id
                ))
            row = {'OfficeID': o.id, 'OfficeName': o.name}
            if place_count:
                location = places[0].location
                row['Latitude'] = location.y
                row['Longitude'] = location.x
                row['MapURL'] = MAPS_URL_TEMPLATE.format(
                    lat=location.y,
                    lon=location.x,
                )
            # Try to find the party whose office this is:
            try:
                party = OrganisationRelationship.objects.get(
                    organisation_b=o,
                    kind__name='has_office'
                ).organisation_a
                row['PartyID'] = party.id
                row['PartyName'] = party.name
            except OrganisationRelationship.DoesNotExist:
                message = "No party found for office with ID {office_id}\n"
                self.stderr.write(message.format(office_id=o.id))
            # Now try to find the address from the office
            # organisation's contacts:
            addresses = o.contacts.filter(kind__slug='address')
            address_count = addresses.count()
            if address_count > 1:
                msg = "Multiple address found for {organisation_id}"
                raise CommandError(msg.format(
                    address_count=address_count,
                    organisation_id=o.id
                ))
            if address_count:
                row['PhysicalAddress'] = addresses[0].value
            writer.writerow(encode_row_values_to_utf8(row))

ZA: Add a command to output a CSV file of constituency offices

Response:
<REPLACE_OLD>  <REPLACE_NEW> import csv
import sys

from django.core.management.base import BaseCommand, CommandError

from pombola.core.models import Organisation, OrganisationRelationship

MAPS_URL_TEMPLATE = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'

def encode_row_values_to_utf8(row):
    return {
        k: unicode(v).encode('utf-8')
        for k, v in row.items()
    }

class Command(BaseCommand):

    def handle(self, *args, **options):

        fields = [
            'OfficeID',
            'OfficeName',
            'MapURL',
            'PhysicalAddress',
            'Latitude',
            'Longitude',
            'PartyName',
            'PartyID'
        ]

        writer = csv.DictWriter(sys.stdout, fieldnames=fields)

        writer.writeheader()

        for o in Organisation.objects. \
            filter(kind__slug='constituency-office'). \
            order_by('slug'):
            places = o.place_set.filter(
                kind__slug='constituency-office',
                name__startswith='Approximate position of ',
            )
            place_count = places.count()
            if place_count > 1:
                msg = "Multiple places ({place_count}) found for {organisation_id}"
                raise CommandError(msg.format(
                    place_count=place_count,
                    organisation_id=o.id
                ))
            row = {'OfficeID': o.id, 'OfficeName': o.name}
            if place_count:
                location = places[0].location
                row['Latitude'] = location.y
                row['Longitude'] = location.x
                row['MapURL'] = MAPS_URL_TEMPLATE.format(
                    lat=location.y,
                    lon=location.x,
                )
            # Try to find the party whose office this is:
            try:
                party = OrganisationRelationship.objects.get(
                    organisation_b=o,
                    kind__name='has_office'
                ).organisation_a
                row['PartyID'] = party.id
                row['PartyName'] = party.name
            except OrganisationRelationship.DoesNotExist:
                message = "No party found for office with ID {office_id}\n"
                self.stderr.write(message.format(office_id=o.id))
            # Now try to find the address from the office
            # organisation's contacts:
            addresses = o.contacts.filter(kind__slug='address')
            address_count = addresses.count()
            if address_count > 1:
                msg = "Multiple address found for {organisation_id}"
                raise CommandError(msg.format(
                    address_count=address_count,
                    organisation_id=o.id
                ))
            if address_count:
                row['PhysicalAddress'] = addresses[0].value
            writer.writerow(encode_row_values_to_utf8(row))
 <REPLACE_END> <|endoftext|> import csv
import sys

from django.core.management.base import BaseCommand, CommandError

from pombola.core.models import Organisation, OrganisationRelationship

MAPS_URL_TEMPLATE = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'

def encode_row_values_to_utf8(row):
    return {
        k: unicode(v).encode('utf-8')
        for k, v in row.items()
    }

class Command(BaseCommand):

    def handle(self, *args, **options):

        fields = [
            'OfficeID',
            'OfficeName',
            'MapURL',
            'PhysicalAddress',
            'Latitude',
            'Longitude',
            'PartyName',
            'PartyID'
        ]

        writer = csv.DictWriter(sys.stdout, fieldnames=fields)

        writer.writeheader()

        for o in Organisation.objects. \
            filter(kind__slug='constituency-office'). \
            order_by('slug'):
            places = o.place_set.filter(
                kind__slug='constituency-office',
                name__startswith='Approximate position of ',
            )
            place_count = places.count()
            if place_count > 1:
                msg = "Multiple places ({place_count}) found for {organisation_id}"
                raise CommandError(msg.format(
                    place_count=place_count,
                    organisation_id=o.id
                ))
            row = {'OfficeID': o.id, 'OfficeName': o.name}
            if place_count:
                location = places[0].location
                row['Latitude'] = location.y
                row['Longitude'] = location.x
                row['MapURL'] = MAPS_URL_TEMPLATE.format(
                    lat=location.y,
                    lon=location.x,
                )
            # Try to find the party whose office this is:
            try:
                party = OrganisationRelationship.objects.get(
                    organisation_b=o,
                    kind__name='has_office'
                ).organisation_a
                row['PartyID'] = party.id
                row['PartyName'] = party.name
            except OrganisationRelationship.DoesNotExist:
                message = "No party found for office with ID {office_id}\n"
                self.stderr.write(message.format(office_id=o.id))
            # Now try to find the address from the office
            # organisation's contacts:
            addresses = o.contacts.filter(kind__slug='address')
            address_count = addresses.count()
            if address_count > 1:
                msg = "Multiple address found for {organisation_id}"
                raise CommandError(msg.format(
                    address_count=address_count,
                    organisation_id=o.id
                ))
            if address_count:
                row['PhysicalAddress'] = addresses[0].value
            writer.writerow(encode_row_values_to_utf8(row))

Prompt: ZA: Add a command to output a CSV file of constituency offices


# Copyright 2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import time

from mockupdb import MockupDB, wait_until
from pymongo import MongoClient

from tests import unittest

class TestInitialIsMaster(unittest.TestCase):
    def test_initial_ismaster(self):
        server = MockupDB()
        server.run()
        self.addCleanup(server.stop)

        start = time.time()
        client = MongoClient(server.uri)
        self.addCleanup(client.close)

        # A single ismaster is enough for the client to be connected.
        self.assertFalse(client.nodes)
        server.receives('ismaster').ok(ismaster=True)
        wait_until(lambda: client.nodes,
                   'update nodes', timeout=1)

        # At least 10 seconds before next heartbeat.
        server.receives('ismaster').ok(ismaster=True)
        self.assertGreaterEqual(time.time() - start, 10)

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

Response:
<REPLACE_OLD> self.assertIsNone(client.address)
        server.receives('ismaster').ok()
 <REPLACE_NEW> self.assertFalse(client.nodes)
        server.receives('ismaster').ok(ismaster=True)
 <REPLACE_END> <REPLACE_OLD> client.address is not None,
 <REPLACE_NEW> client.nodes,
 <REPLACE_END> <REPLACE_OLD> address', <REPLACE_NEW> nodes', <REPLACE_END> <REPLACE_OLD> server.receives('ismaster').ok()
 <REPLACE_NEW> server.receives('ismaster').ok(ismaster=True)
 <REPLACE_END> <|endoftext|> # Copyright 2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import time

from mockupdb import MockupDB, wait_until
from pymongo import MongoClient

from tests import unittest

class TestInitialIsMaster(unittest.TestCase):
    def test_initial_ismaster(self):
        server = MockupDB()
        server.run()
        self.addCleanup(server.stop)

        start = time.time()
        client = MongoClient(server.uri)
        self.addCleanup(client.close)

        # A single ismaster is enough for the client to be connected.
        self.assertFalse(client.nodes)
        server.receives('ismaster').ok(ismaster=True)
        wait_until(lambda: client.nodes,
                   'update nodes', timeout=1)

        # At least 10 seconds before next heartbeat.
        server.receives('ismaster').ok(ismaster=True)
        self.assertGreaterEqual(time.time() - start, 10)

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

Prompt:
Update for PYTHON 985: MongoClient properties now block until connected.

# Copyright 2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import time

from mockupdb import MockupDB, wait_until
from pymongo import MongoClient

from tests import unittest

class TestInitialIsMaster(unittest.TestCase):
    def test_initial_ismaster(self):
        server = MockupDB()
        server.run()
        self.addCleanup(server.stop)

        start = time.time()
        client = MongoClient(server.uri)
        self.addCleanup(client.close)

        # A single ismaster is enough for the client to be connected.
        self.assertIsNone(client.address)
        server.receives('ismaster').ok()
        wait_until(lambda: client.address is not None,
                   'update address', timeout=1)

        # At least 10 seconds before next heartbeat.
        server.receives('ismaster').ok()
        self.assertGreaterEqual(time.time() - start, 10)

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


import ibmcnx.test.loadFunction

ibmcnx.test.loadFunction.loadFilesService()

FilesPolicyService.browse( "title", "true", 1, 25 )

Customize scripts to work with menu

Customize scripts to work with menu

Response:
<REPLACE_OLD> ibmcnx.test.loadFunction

loadFilesService()

FilesPolicyService.browse( <REPLACE_NEW> ibmcnx.test.loadFunction

ibmcnx.test.loadFunction.loadFilesService()

FilesPolicyService.browse( <REPLACE_END> <|endoftext|> import ibmcnx.test.loadFunction

ibmcnx.test.loadFunction.loadFilesService()

FilesPolicyService.browse( "title", "true", 1, 25 )

Prompt:
Customize scripts to work with menu

import ibmcnx.test.loadFunction

loadFilesService()

FilesPolicyService.browse( "title", "true", 1, 25 )


import unittest

import numpy as np
from sklearn import datasets
from sklearn import decomposition
from sklearn.utils import estimator_checks

import prince

class TestGPA(unittest.TestCase):

    # def setUp(self):
    def __init__(self):
        # Create a list of 2-D circles with different locations and rotations
        n_shapes = 4
        n_points = 12
        n_dims = 2

        shape_sizes = np.arange(1, n_shapes + 1)
        shape_angle_offsets = 10 * np.arange(n_shapes)
        shape_center_offsets = np.tile(np.arange(n_shapes), (n_dims, 1))

        base_angles = np.linspace(0, 2 * np.pi, num=n_points, endpoint=False)
        # Size (n_shapes, n_points)
        angles = base_angles[np.newaxis, :] + shape_angle_offsets[:, np.newaxis]

        # Calculate along dimensions
        x = (
            np.cos(angles) * shape_sizes[:, np.newaxis]
            + shape_center_offsets[0][:, np.newaxis]
        )
        y = (
            np.sin(angles) * shape_sizes[:, np.newaxis]
            + shape_center_offsets[1][:, np.newaxis]
        )

        self.shapes = np.stack([x, y], axis=-1)

    def test_fit(self):
        gpa = prince.GPA()
        self.assertIsInstance(gpa.fit(self.shapes), prince.GPA)

    def test_transform(self):
        gpa = prince.GPA(copy=True)
        aligned_shapes = gpa.fit(self.shapes).transform(self.shapes)
        self.assertIsInstance(aligned_shapes, np.ndarray)
        self.assertEqual(self.shapes.shape, aligned_shapes.shape)

    def test_fit_transform(self):
        gpa = prince.GPA()
        aligned_shapes = gpa.fit_transform(self.shapes)
        self.assertIsInstance(aligned_shapes, np.ndarray)

    def test_fit_transform_single(self):
        """Aligning a single shape should return the same shape."""
        gpa = prince.GPA()
        shapes = self.shapes.shape[0:1]
        aligned_shapes = gpa.fit_transform(shapes)
        np.testing.assert_array_equal(shapes, aligned_shapes)

    def test_copy(self):
        shapes_copy = np.copy(self.shapes)

        gpa = prince.GPA(copy=True)
        gpa.fit(shapes_copy)
        np.testing.assert_array_equal(self.shapes, shapes_copy)

        gpa = prince.GPA(copy=False)
        gpa.fit(shapes_copy)
        self.assertRaises(
            AssertionError, np.testing.assert_array_equal, self.shapes, shapes_copy
        )

    def test_check_estimator(self):
        estimator_checks.check_estimator(prince.GPA(as_array=True))

Add tests for Generalized Procrustes Analysis (GPA)

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest

import numpy as np
from sklearn import datasets
from sklearn import decomposition
from sklearn.utils import estimator_checks

import prince

class TestGPA(unittest.TestCase):

    # def setUp(self):
    def __init__(self):
        # Create a list of 2-D circles with different locations and rotations
        n_shapes = 4
        n_points = 12
        n_dims = 2

        shape_sizes = np.arange(1, n_shapes + 1)
        shape_angle_offsets = 10 * np.arange(n_shapes)
        shape_center_offsets = np.tile(np.arange(n_shapes), (n_dims, 1))

        base_angles = np.linspace(0, 2 * np.pi, num=n_points, endpoint=False)
        # Size (n_shapes, n_points)
        angles = base_angles[np.newaxis, :] + shape_angle_offsets[:, np.newaxis]

        # Calculate along dimensions
        x = (
            np.cos(angles) * shape_sizes[:, np.newaxis]
            + shape_center_offsets[0][:, np.newaxis]
        )
        y = (
            np.sin(angles) * shape_sizes[:, np.newaxis]
            + shape_center_offsets[1][:, np.newaxis]
        )

        self.shapes = np.stack([x, y], axis=-1)

    def test_fit(self):
        gpa = prince.GPA()
        self.assertIsInstance(gpa.fit(self.shapes), prince.GPA)

    def test_transform(self):
        gpa = prince.GPA(copy=True)
        aligned_shapes = gpa.fit(self.shapes).transform(self.shapes)
        self.assertIsInstance(aligned_shapes, np.ndarray)
        self.assertEqual(self.shapes.shape, aligned_shapes.shape)

    def test_fit_transform(self):
        gpa = prince.GPA()
        aligned_shapes = gpa.fit_transform(self.shapes)
        self.assertIsInstance(aligned_shapes, np.ndarray)

    def test_fit_transform_single(self):
        """Aligning a single shape should return the same shape."""
        gpa = prince.GPA()
        shapes = self.shapes.shape[0:1]
        aligned_shapes = gpa.fit_transform(shapes)
        np.testing.assert_array_equal(shapes, aligned_shapes)

    def test_copy(self):
        shapes_copy = np.copy(self.shapes)

        gpa = prince.GPA(copy=True)
        gpa.fit(shapes_copy)
        np.testing.assert_array_equal(self.shapes, shapes_copy)

        gpa = prince.GPA(copy=False)
        gpa.fit(shapes_copy)
        self.assertRaises(
            AssertionError, np.testing.assert_array_equal, self.shapes, shapes_copy
        )

    def test_check_estimator(self):
        estimator_checks.check_estimator(prince.GPA(as_array=True))
 <REPLACE_END> <|endoftext|> import unittest

import numpy as np
from sklearn import datasets
from sklearn import decomposition
from sklearn.utils import estimator_checks

import prince

class TestGPA(unittest.TestCase):

    # def setUp(self):
    def __init__(self):
        # Create a list of 2-D circles with different locations and rotations
        n_shapes = 4
        n_points = 12
        n_dims = 2

        shape_sizes = np.arange(1, n_shapes + 1)
        shape_angle_offsets = 10 * np.arange(n_shapes)
        shape_center_offsets = np.tile(np.arange(n_shapes), (n_dims, 1))

        base_angles = np.linspace(0, 2 * np.pi, num=n_points, endpoint=False)
        # Size (n_shapes, n_points)
        angles = base_angles[np.newaxis, :] + shape_angle_offsets[:, np.newaxis]

        # Calculate along dimensions
        x = (
            np.cos(angles) * shape_sizes[:, np.newaxis]
            + shape_center_offsets[0][:, np.newaxis]
        )
        y = (
            np.sin(angles) * shape_sizes[:, np.newaxis]
            + shape_center_offsets[1][:, np.newaxis]
        )

        self.shapes = np.stack([x, y], axis=-1)

    def test_fit(self):
        gpa = prince.GPA()
        self.assertIsInstance(gpa.fit(self.shapes), prince.GPA)

    def test_transform(self):
        gpa = prince.GPA(copy=True)
        aligned_shapes = gpa.fit(self.shapes).transform(self.shapes)
        self.assertIsInstance(aligned_shapes, np.ndarray)
        self.assertEqual(self.shapes.shape, aligned_shapes.shape)

    def test_fit_transform(self):
        gpa = prince.GPA()
        aligned_shapes = gpa.fit_transform(self.shapes)
        self.assertIsInstance(aligned_shapes, np.ndarray)

    def test_fit_transform_single(self):
        """Aligning a single shape should return the same shape."""
        gpa = prince.GPA()
        shapes = self.shapes.shape[0:1]
        aligned_shapes = gpa.fit_transform(shapes)
        np.testing.assert_array_equal(shapes, aligned_shapes)

    def test_copy(self):
        shapes_copy = np.copy(self.shapes)

        gpa = prince.GPA(copy=True)
        gpa.fit(shapes_copy)
        np.testing.assert_array_equal(self.shapes, shapes_copy)

        gpa = prince.GPA(copy=False)
        gpa.fit(shapes_copy)
        self.assertRaises(
            AssertionError, np.testing.assert_array_equal, self.shapes, shapes_copy
        )

    def test_check_estimator(self):
        estimator_checks.check_estimator(prince.GPA(as_array=True))

Prompt: Add tests for Generalized Procrustes Analysis (GPA)


from django.shortcuts import render_to_response
from django.shortcuts import redirect

from models import DownloadLink

def index(request):
    links = DownloadLink.objects.order_by('-pk')
    context = {'links': list(links)}
    return render_to_response('get/listing.tpl', context)

Order download links by pk.

get: Order download links by pk.

Response:
<REPLACE_OLD> DownloadLink.objects.all()
 <REPLACE_NEW> DownloadLink.objects.order_by('-pk')
 <REPLACE_END> <|endoftext|> from django.shortcuts import render_to_response
from django.shortcuts import redirect

from models import DownloadLink

def index(request):
    links = DownloadLink.objects.order_by('-pk')
    context = {'links': list(links)}
    return render_to_response('get/listing.tpl', context)

Prompt:
get: Order download links by pk.

from django.shortcuts import render_to_response
from django.shortcuts import redirect

from models import DownloadLink

def index(request):
    links = DownloadLink.objects.all()
    context = {'links': list(links)}
    return render_to_response('get/listing.tpl', context)


# Generated by Django 2.2.10 on 2021-11-05 12:29

from django.db import migrations
from django.db.models.query_utils import Q

def update_url_to_community(apps, schema_editor):
  people_url = "/people"
  mentor_url = "/directory"
  community_url = "/community"
  SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
  SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)).update(new_url=community_url)

class Migration(migrations.Migration):

    dependencies = [
        ('accelerator', '0073_auto_20210909_1706'),
    ]

    operations = [
        migrations.RunPython(update_url_to_community,
                             migrations.RunPython.noop)
    ]

Response:
<REPLACE_OLD> for siteredirectpage in SiteRedirectPage.objects.all():
    has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
    if has_old_url.exists():
      has_old_url.update(new_url=community_url)
 <REPLACE_NEW> SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)).update(new_url=community_url)
 <REPLACE_END> <|endoftext|> # Generated by Django 2.2.10 on 2021-11-05 12:29

from django.db import migrations
from django.db.models.query_utils import Q

def update_url_to_community(apps, schema_editor):
  people_url = "/people"
  mentor_url = "/directory"
  community_url = "/community"
  SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
  SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url)).update(new_url=community_url)

class Migration(migrations.Migration):

    dependencies = [
        ('accelerator', '0073_auto_20210909_1706'),
    ]

    operations = [
        migrations.RunPython(update_url_to_community,
                             migrations.RunPython.noop)
    ]

Prompt:
[AC-9046] Fix the query for updating the people and mentor urls to community url

# Generated by Django 2.2.10 on 2021-11-05 12:29

from django.db import migrations
from django.db.models.query_utils import Q

def update_url_to_community(apps, schema_editor):
  people_url = "/people"
  mentor_url = "/directory"
  community_url = "/community"
  SiteRedirectPage = apps.get_model('accelerator', 'SiteRedirectPage')
  for siteredirectpage in SiteRedirectPage.objects.all():
    has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
    if has_old_url.exists():
      has_old_url.update(new_url=community_url)

class Migration(migrations.Migration):

    dependencies = [
        ('accelerator', '0073_auto_20210909_1706'),
    ]

    operations = [
        migrations.RunPython(update_url_to_community,
                             migrations.RunPython.noop)
    ]


# Defining a function to load images
def load_image(image_name, fade_enabled=False):
    """fade_enabled should be True if you want images to be able to fade"""
    try:
        #! Add stuff for loading images of the correct resolution
        # depending on the player's resolution settings
        if not fade_enabled:
            return pygame.image.load("".join((
                file_directory, "assets\\images\\",
                image_name, ".png"
                ))).convert_alpha()   # Fixes per pixel alphas permanently
        else:
            return pygame.image.load("".join((
                file_directory, "assets\\images\\",
                image_name, ".png"
                ))).convert()
    except Exception as error:
        log("".join(("Failed to load image: ", image_name, ".png")))

Response:
<REPLACE_OLD> "Image Files\\",
 <REPLACE_NEW> "assets\\images\\",
 <REPLACE_END> <REPLACE_OLD> "Image Files\\",
 <REPLACE_NEW> "assets\\images\\",
 <REPLACE_END> <|endoftext|> # Defining a function to load images
def load_image(image_name, fade_enabled=False):
    """fade_enabled should be True if you want images to be able to fade"""
    try:
        #! Add stuff for loading images of the correct resolution
        # depending on the player's resolution settings
        if not fade_enabled:
            return pygame.image.load("".join((
                file_directory, "assets\\images\\",
                image_name, ".png"
                ))).convert_alpha()   # Fixes per pixel alphas permanently
        else:
            return pygame.image.load("".join((
                file_directory, "assets\\images\\",
                image_name, ".png"
                ))).convert()
    except Exception as error:
        log("".join(("Failed to load image: ", image_name, ".png")))

Prompt:
Fix error in file path of where images are loaded from in load_image()

# Defining a function to load images
def load_image(image_name, fade_enabled=False):
    """fade_enabled should be True if you want images to be able to fade"""
    try:
        #! Add stuff for loading images of the correct resolution
        # depending on the player's resolution settings
        if not fade_enabled:
            return pygame.image.load("".join((
                file_directory, "Image Files\\",
                image_name, ".png"
                ))).convert_alpha()   # Fixes per pixel alphas permanently
        else:
            return pygame.image.load("".join((
                file_directory, "Image Files\\",
                image_name, ".png"
                ))).convert()
    except Exception as error:
        log("".join(("Failed to load image: ", image_name, ".png")))


from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment

from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter

from girder.plugin import GirderPlugin

@setting_utilities.validator({
    Features.NOTEBOOKS,
    Deployment.SITE,
    Branding.PRIVACY,
    Branding.LICENSE,
    Branding.HEADER_LOGO_ID,
    Branding.FOOTER_LOGO_ID,
    Branding.FOOTER_LOGO_URL,
    Branding.FAVICON_ID
})
def validateSettings(event):
    pass

class AppPlugin(GirderPlugin):
    DISPLAY_NAME = 'OpenChemistry App'

    def load(self, info):
        info['apiRoot'].configuration = Configuration()

        # Twitter and orcid stuff
        info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
        info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
        info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
        info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)

        # Launch a taskflow with a single endpoint
        info['apiRoot'].launch_taskflow = Resource()
        info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)

Response:
<INSERT> girder.api.rest import Resource
from <INSERT_END> <REPLACE_OLD> info['apiRoot'].queues.route('POST', ('launchtaskflow',), <REPLACE_NEW> info['apiRoot'].launch_taskflow = Resource()
        info['apiRoot'].launch_taskflow.route('POST', ('launch',), <REPLACE_END> <|endoftext|> from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment

from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter

from girder.plugin import GirderPlugin

@setting_utilities.validator({
    Features.NOTEBOOKS,
    Deployment.SITE,
    Branding.PRIVACY,
    Branding.LICENSE,
    Branding.HEADER_LOGO_ID,
    Branding.FOOTER_LOGO_ID,
    Branding.FOOTER_LOGO_URL,
    Branding.FAVICON_ID
})
def validateSettings(event):
    pass

class AppPlugin(GirderPlugin):
    DISPLAY_NAME = 'OpenChemistry App'

    def load(self, info):
        info['apiRoot'].configuration = Configuration()

        # Twitter and orcid stuff
        info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
        info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
        info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
        info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)

        # Launch a taskflow with a single endpoint
        info['apiRoot'].launch_taskflow = Resource()
        info['apiRoot'].launch_taskflow.route('POST', ('launch',), launch_taskflow)

Prompt:
Put the endpoint at /launch_taskflow/launch

Put it here instead of under "queues"

Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>

from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment

from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter

from girder.plugin import GirderPlugin

@setting_utilities.validator({
    Features.NOTEBOOKS,
    Deployment.SITE,
    Branding.PRIVACY,
    Branding.LICENSE,
    Branding.HEADER_LOGO_ID,
    Branding.FOOTER_LOGO_ID,
    Branding.FOOTER_LOGO_URL,
    Branding.FAVICON_ID
})
def validateSettings(event):
    pass

class AppPlugin(GirderPlugin):
    DISPLAY_NAME = 'OpenChemistry App'

    def load(self, info):
        info['apiRoot'].configuration = Configuration()

        # Twitter and orcid stuff
        info['apiRoot'].user.route('GET', (':id', 'orcid'), get_orcid)
        info['apiRoot'].user.route('POST', (':id', 'orcid'), set_orcid)
        info['apiRoot'].user.route('GET', (':id', 'twitter'), get_twitter)
        info['apiRoot'].user.route('POST', (':id', 'twitter'), set_twitter)

        # Launch a taskflow with a single endpoint
        info['apiRoot'].queues.route('POST', ('launchtaskflow',), launch_taskflow)


from setuptools import setup

with open('README.md', 'r', encoding='utf-8') as fh:
    long_description = fh.read()

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.2',
    description='ingreedy-py parses recipe ingredient lines into a object',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    extras_require={
        'tests': [
            'pytest',
            'pytest-cov',
        ]
    },
    classifiers=[],
)

Add long description for package

Add long description for package

Response:
<REPLACE_OLD> setup

setup(
 <REPLACE_NEW> setup

with open('README.md', 'r', encoding='utf-8') as fh:
    long_description = fh.read()

setup(
 <REPLACE_END> <INSERT>    long_description=long_description,
    long_description_content_type='text/markdown',
 <INSERT_END> <|endoftext|> from setuptools import setup

with open('README.md', 'r', encoding='utf-8') as fh:
    long_description = fh.read()

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.2',
    description='ingreedy-py parses recipe ingredient lines into a object',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    extras_require={
        'tests': [
            'pytest',
            'pytest-cov',
        ]
    },
    classifiers=[],
)

Prompt:
Add long description for package

from setuptools import setup

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.2',
    description='ingreedy-py parses recipe ingredient lines into a object',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    extras_require={
        'tests': [
            'pytest',
            'pytest-cov',
        ]
    },
    classifiers=[],
)


from setuptools import setup

setup(
    name='slacker',
    version='0.7.0',
    packages=['slacker'],
    description='Slack API client',
    author='Oktay Sancak',
    author_email='oktaysancak@gmail.com',
    url='http://github.com/os/slacker/',
    install_requires=['requests >= 2.2.1'],
    license='http://www.apache.org/licenses/LICENSE-2.0',
    test_suite='tests',
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ),
    keywords='slack api'
)

Set version number to 0.7.0.

Set version number to 0.7.0.

Response:
<REPLACE_OLD> version='0.6.8',
 <REPLACE_NEW> version='0.7.0',
 <REPLACE_END> <|endoftext|> from setuptools import setup

setup(
    name='slacker',
    version='0.7.0',
    packages=['slacker'],
    description='Slack API client',
    author='Oktay Sancak',
    author_email='oktaysancak@gmail.com',
    url='http://github.com/os/slacker/',
    install_requires=['requests >= 2.2.1'],
    license='http://www.apache.org/licenses/LICENSE-2.0',
    test_suite='tests',
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ),
    keywords='slack api'
)

Prompt:
Set version number to 0.7.0.

from setuptools import setup

setup(
    name='slacker',
    version='0.6.8',
    packages=['slacker'],
    description='Slack API client',
    author='Oktay Sancak',
    author_email='oktaysancak@gmail.com',
    url='http://github.com/os/slacker/',
    install_requires=['requests >= 2.2.1'],
    license='http://www.apache.org/licenses/LICENSE-2.0',
    test_suite='tests',
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ),
    keywords='slack api'
)


from pyramid.response import Response
from pi_director.models.models import (
    DBSession,
    MyModel,
    )
from pi_director.models.UserModel import UserModel

def authorize_user(email):
    user=DBSession.query(UserModel).filter(UserModel.email==email).one()
    user.AccessLevel=2
    DBSession.flush()

def delete_user(email):
    DBSession.query(UserModel).filter(UserModel.email==email).delete()

def get_users():
    UserList=DBSession.query(UserModel).all()
    return UserList

def make_an_admin(request):
    email=request.matchdict['email']

    '''First, make sure there aren't already admins in the system'''
    res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
    if res != None:
        msg="User already an admin: {user}".format(user=res.email)
        return False
    user=DBSession.query(UserModel).filter(UserModel.email==email).first()
    if user == None:
        user=UserModel()
        user.email=email
        DBSession.add(user)
    user.AccessLevel=2
    DBSession.flush()
    return True

Response:
<INSERT> if user == None:
        user=UserModel()
        user.email=email
        DBSession.add(user)
    <INSERT_END> <|endoftext|> from pyramid.response import Response
from pi_director.models.models import (
    DBSession,
    MyModel,
    )
from pi_director.models.UserModel import UserModel

def authorize_user(email):
    user=DBSession.query(UserModel).filter(UserModel.email==email).one()
    user.AccessLevel=2
    DBSession.flush()

def delete_user(email):
    DBSession.query(UserModel).filter(UserModel.email==email).delete()

def get_users():
    UserList=DBSession.query(UserModel).all()
    return UserList

def make_an_admin(request):
    email=request.matchdict['email']

    '''First, make sure there aren't already admins in the system'''
    res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
    if res != None:
        msg="User already an admin: {user}".format(user=res.email)
        return False
    user=DBSession.query(UserModel).filter(UserModel.email==email).first()
    if user == None:
        user=UserModel()
        user.email=email
        DBSession.add(user)
    user.AccessLevel=2
    DBSession.flush()
    return True

Prompt:
Create the user if it isn't already in the database first, then make it an admin.

from pyramid.response import Response
from pi_director.models.models import (
    DBSession,
    MyModel,
    )
from pi_director.models.UserModel import UserModel

def authorize_user(email):
    user=DBSession.query(UserModel).filter(UserModel.email==email).one()
    user.AccessLevel=2
    DBSession.flush()

def delete_user(email):
    DBSession.query(UserModel).filter(UserModel.email==email).delete()

def get_users():
    UserList=DBSession.query(UserModel).all()
    return UserList

def make_an_admin(request):
    email=request.matchdict['email']

    '''First, make sure there aren't already admins in the system'''
    res=DBSession.query(UserModel).filter(UserModel.AccessLevel==2).first()
    if res != None:
        msg="User already an admin: {user}".format(user=res.email)
        return False
    user=DBSession.query(UserModel).filter(UserModel.email==email).first()
    user.AccessLevel=2
    DBSession.flush()
    return True


#!/usr/bin/env python
from codecs import open

from setuptools import find_packages, setup

with open('README.rst', 'r', 'utf-8') as f:
    readme = f.read()

setup(
    name='django-paginationlinks',
    version='0.1.1',
    description='Django Pagination Links',
    long_description=readme,
    url='https://github.com/developersociety/django-paginationlinks',
    maintainer='Blanc Ltd',
    maintainer_email='studio@blanc.ltd.uk',
    platforms=['any'],
    packages=find_packages(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    license='BSD',
)

Response:
<REPLACE_OLD> url='https://github.com/blancltd/django-paginationlinks',
 <REPLACE_NEW> url='https://github.com/developersociety/django-paginationlinks',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from codecs import open

from setuptools import find_packages, setup

with open('README.rst', 'r', 'utf-8') as f:
    readme = f.read()

setup(
    name='django-paginationlinks',
    version='0.1.1',
    description='Django Pagination Links',
    long_description=readme,
    url='https://github.com/developersociety/django-paginationlinks',
    maintainer='Blanc Ltd',
    maintainer_email='studio@blanc.ltd.uk',
    platforms=['any'],
    packages=find_packages(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    license='BSD',
)

Prompt:
Update GitHub repos from blancltd to developersociety

#!/usr/bin/env python
from codecs import open

from setuptools import find_packages, setup

with open('README.rst', 'r', 'utf-8') as f:
    readme = f.read()

setup(
    name='django-paginationlinks',
    version='0.1.1',
    description='Django Pagination Links',
    long_description=readme,
    url='https://github.com/blancltd/django-paginationlinks',
    maintainer='Blanc Ltd',
    maintainer_email='studio@blanc.ltd.uk',
    platforms=['any'],
    packages=find_packages(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    license='BSD',
)


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

settings.configure(
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
        }
    },
    ALLOWED_HOSTS=[
        'testserver',
    ],
    INSTALLED_APPS=[
        'django_nose',
        'permissions',
        'permissions.tests',
    ],
    MIDDLEWARE_CLASSES=[],
    ROOT_URLCONF='permissions.tests.urls',
    TEST_RUNNER='django_nose.NoseTestSuiteRunner'
)

if django.VERSION[:2] >= (1, 7):
    from django import setup
else:
    setup = lambda: None

setup()

call_command("test")

Add MIDDLEWARE_CLASSES to test settings

Response:
<INSERT> MIDDLEWARE_CLASSES=[],
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command

settings.configure(
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
        }
    },
    ALLOWED_HOSTS=[
        'testserver',
    ],
    INSTALLED_APPS=[
        'django_nose',
        'permissions',
        'permissions.tests',
    ],
    MIDDLEWARE_CLASSES=[],
    ROOT_URLCONF='permissions.tests.urls',
    TEST_RUNNER='django_nose.NoseTestSuiteRunner'
)

if django.VERSION[:2] >= (1, 7):
    from django import setup
else:
    setup = lambda: None

setup()

call_command("test")

Prompt:
Add MIDDLEWARE_CLASSES to test settings

Squelches a warning when using Django 1.7.

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

settings.configure(
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
        }
    },
    ALLOWED_HOSTS=[
        'testserver',
    ],
    INSTALLED_APPS=[
        'django_nose',
        'permissions',
        'permissions.tests',
    ],
    ROOT_URLCONF='permissions.tests.urls',
    TEST_RUNNER='django_nose.NoseTestSuiteRunner'
)

if django.VERSION[:2] >= (1, 7):
    from django import setup
else:
    setup = lambda: None

setup()

call_command("test")


"""

Revision ID: 0341_new_letter_rates
Revises: 0340_stub_training_broadcasts
Create Date: 2021-01-27 11:58:21.393227

"""
import itertools
import uuid
from datetime import datetime

from alembic import op
from sqlalchemy.sql import text

from app.models import LetterRate

revision = '0341_new_letter_rates'
down_revision = '0340_stub_training_broadcasts'

CHANGEOVER_DATE = datetime(2021, 2, 1, 0, 0)

def get_new_rate(sheet_count, post_class):
    base_prices = {
        'second': 34,
        'first': 64,
        'europe': 81,
        'rest-of-world': 81,
    }
    multiplier = 5 if post_class in ('first', 'second') else 8

    return (base_prices[post_class] + (multiplier * sheet_count)) / 100.0

def upgrade():
    conn = op.get_bind()
    conn.execute(text("UPDATE letter_rates SET end_date = :start WHERE end_date IS NULL"), start=CHANGEOVER_DATE)

    op.bulk_insert(LetterRate.__table__, [
        {
            'id': uuid.uuid4(),
            'start_date': CHANGEOVER_DATE,
            'end_date': None,
            'sheet_count': sheet_count,
            'rate': get_new_rate(sheet_count, post_class),
            'crown': crown,
            'post_class': post_class,
        }
        for sheet_count, crown, post_class in itertools.product(
            range(1, 6),
            [True, False],
            ['first', 'second', 'europe', 'rest-of-world']
        )
    ])

def downgrade():
    # Make sure you've thought about billing implications etc before downgrading!
    conn = op.get_bind()
    conn.execute(text("DELETE FROM letter_rates WHERE start_date = :start"), start=CHANGEOVER_DATE)
    conn.execute(text("UPDATE letter_rates SET end_date = NULL WHERE end_date = :start"), start=CHANGEOVER_DATE)

Add February 2021 letter rates

Add February 2021 letter rates

All rates are changing, so we add an end date for the current rates and
insert new rates for every post_class, sheet count and crown status.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """

Revision ID: 0341_new_letter_rates
Revises: 0340_stub_training_broadcasts
Create Date: 2021-01-27 11:58:21.393227

"""
import itertools
import uuid
from datetime import datetime

from alembic import op
from sqlalchemy.sql import text

from app.models import LetterRate

revision = '0341_new_letter_rates'
down_revision = '0340_stub_training_broadcasts'

CHANGEOVER_DATE = datetime(2021, 2, 1, 0, 0)

def get_new_rate(sheet_count, post_class):
    base_prices = {
        'second': 34,
        'first': 64,
        'europe': 81,
        'rest-of-world': 81,
    }
    multiplier = 5 if post_class in ('first', 'second') else 8

    return (base_prices[post_class] + (multiplier * sheet_count)) / 100.0

def upgrade():
    conn = op.get_bind()
    conn.execute(text("UPDATE letter_rates SET end_date = :start WHERE end_date IS NULL"), start=CHANGEOVER_DATE)

    op.bulk_insert(LetterRate.__table__, [
        {
            'id': uuid.uuid4(),
            'start_date': CHANGEOVER_DATE,
            'end_date': None,
            'sheet_count': sheet_count,
            'rate': get_new_rate(sheet_count, post_class),
            'crown': crown,
            'post_class': post_class,
        }
        for sheet_count, crown, post_class in itertools.product(
            range(1, 6),
            [True, False],
            ['first', 'second', 'europe', 'rest-of-world']
        )
    ])

def downgrade():
    # Make sure you've thought about billing implications etc before downgrading!
    conn = op.get_bind()
    conn.execute(text("DELETE FROM letter_rates WHERE start_date = :start"), start=CHANGEOVER_DATE)
    conn.execute(text("UPDATE letter_rates SET end_date = NULL WHERE end_date = :start"), start=CHANGEOVER_DATE)
 <REPLACE_END> <|endoftext|> """

Revision ID: 0341_new_letter_rates
Revises: 0340_stub_training_broadcasts
Create Date: 2021-01-27 11:58:21.393227

"""
import itertools
import uuid
from datetime import datetime

from alembic import op
from sqlalchemy.sql import text

from app.models import LetterRate

revision = '0341_new_letter_rates'
down_revision = '0340_stub_training_broadcasts'

CHANGEOVER_DATE = datetime(2021, 2, 1, 0, 0)

def get_new_rate(sheet_count, post_class):
    base_prices = {
        'second': 34,
        'first': 64,
        'europe': 81,
        'rest-of-world': 81,
    }
    multiplier = 5 if post_class in ('first', 'second') else 8

    return (base_prices[post_class] + (multiplier * sheet_count)) / 100.0

def upgrade():
    conn = op.get_bind()
    conn.execute(text("UPDATE letter_rates SET end_date = :start WHERE end_date IS NULL"), start=CHANGEOVER_DATE)

    op.bulk_insert(LetterRate.__table__, [
        {
            'id': uuid.uuid4(),
            'start_date': CHANGEOVER_DATE,
            'end_date': None,
            'sheet_count': sheet_count,
            'rate': get_new_rate(sheet_count, post_class),
            'crown': crown,
            'post_class': post_class,
        }
        for sheet_count, crown, post_class in itertools.product(
            range(1, 6),
            [True, False],
            ['first', 'second', 'europe', 'rest-of-world']
        )
    ])

def downgrade():
    # Make sure you've thought about billing implications etc before downgrading!
    conn = op.get_bind()
    conn.execute(text("DELETE FROM letter_rates WHERE start_date = :start"), start=CHANGEOVER_DATE)
    conn.execute(text("UPDATE letter_rates SET end_date = NULL WHERE end_date = :start"), start=CHANGEOVER_DATE)

Prompt:
Add February 2021 letter rates

All rates are changing, so we add an end date for the current rates and
insert new rates for every post_class, sheet count and crown status.