'''
Information about this python-fedora release
'''

from fedora import _

NAME = 'python-fedora'
VERSION = '0.3.6'
DESCRIPTION = _('Python modules for interacting with Fedora Services')
LONG_DESCRIPTION = _('''
The Fedora Project runs many different services.  These services help us to
package software, develop new programs, and generally put together the distro.
This package contains software that helps us do that.
''')
AUTHOR = 'Toshio Kuratomi, Luke Macken'
EMAIL = 'tkuratom@redhat.com'
COPYRIGHT = '2007-2008 Red Hat, Inc.'
URL = 'https://fedorahosted.org/python-fedora'
DOWNLOAD_URL = 'https://fedorahosted.org/releases/p/y/python-fedora/'
LICENSE = 'GPLv2'

Correct minor typo in a string.

Correct minor typo in a string.

Response:
'''
Information about this python-fedora release
'''

from fedora import _

NAME = 'python-fedora'
VERSION = '0.3.6'
DESCRIPTION = _('Python modules for interacting with Fedora Services')
LONG_DESCRIPTION = _('''
The Fedora Project runs many different services.  These services help us to
package software, develop new programs, and generally put together the distro.
This package contains software that helps us do that.
''')
AUTHOR = 'Toshio Kuratomi, Luke Macken'
EMAIL = 'tkuratom@redhat.com'
COPYRIGHT = '2007-2008 Red Hat, Inc.'
URL = 'https://fedorahosted.org/python-fedora'
DOWNLOAD_URL = 'https://fedorahosted.org/releases/p/y/python-fedora/'
LICENSE = 'GPLv2'

Prompt:
Correct minor typo in a string.

'''
Information about this python-fedora release
'''

from fedora import _

NAME = 'python-fedora'
VERSION = '0.3.6'
DESCRIPTION = _('Python modules for interacting with Fedora services')
LONG_DESCRIPTION = _('''
The Fedora Project runs many different services.  These services help us to
package software, develop new programs, and generally put together the distro.
This package contains software that helps us do that.
''')
AUTHOR = 'Toshio Kuratomi, Luke Macken'
EMAIL = 'tkuratom@redhat.com'
COPYRIGHT = '2007-2008 Red Hat, Inc.'
URL = 'https://fedorahosted.org/python-fedora'
DOWNLOAD_URL = 'https://fedorahosted.org/releases/p/y/python-fedora/'
LICENSE = 'GPLv2'


# All rights reserved.
#
#    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.

from neutron_lib._i18n import _
from neutron_lib import exceptions

class AddressGroupNotFound(exceptions.NotFound):
    message = _("Address group %(address_group_id)s could not be found.")

class AddressGroupInUse(exceptions.InUse):
    message = _("Address group %(address_group_id)s is in use on one or more "
                "security group rules.")

class AddressesNotFound(exceptions.NotFound):
    message = _("Addresses %(addresses)s not found in the address group "
                "%(address_group_id)s.")

class AddressesAlreadyExist(exceptions.BadRequest):
    message = _("Addresses %(addresses)s already exist in the "
                "address group %(address_group_id)s.")

Add address group in use exception

Response:
# All rights reserved.
#
#    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.

from neutron_lib._i18n import _
from neutron_lib import exceptions

class AddressGroupNotFound(exceptions.NotFound):
    message = _("Address group %(address_group_id)s could not be found.")

class AddressGroupInUse(exceptions.InUse):
    message = _("Address group %(address_group_id)s is in use on one or more "
                "security group rules.")

class AddressesNotFound(exceptions.NotFound):
    message = _("Addresses %(addresses)s not found in the address group "
                "%(address_group_id)s.")

class AddressesAlreadyExist(exceptions.BadRequest):
    message = _("Addresses %(addresses)s already exist in the "
                "address group %(address_group_id)s.")

Prompt:
Add address group in use exception

Related change: https://review.opendev.org/#/c/751110/

Change-Id: I2a9872890ca4d5e59a9e266c1dcacd3488a3265c

# All rights reserved.
#
#    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.

from neutron_lib._i18n import _
from neutron_lib import exceptions

class AddressGroupNotFound(exceptions.NotFound):
    message = _("Address group %(address_group_id)s could not be found.")

class AddressesNotFound(exceptions.NotFound):
    message = _("Addresses %(addresses)s not found in the address group "
                "%(address_group_id)s.")

class AddressesAlreadyExist(exceptions.BadRequest):
    message = _("Addresses %(addresses)s already exist in the "
                "address group %(address_group_id)s.")


from django.conf import settings
from django.forms import widgets

#JS_URL is the url to the filepicker.io javascript library
JS_VERSION = 1
JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION)

if hasattr(settings, 'FILEPICKER_INPUT_TYPE'):
    INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE
else:
    INPUT_TYPE = 'filepicker-dragdrop'

class FPFileWidget(widgets.Input):
    input_type = INPUT_TYPE
    needs_multipart_form = False

    def value_from_datadict_old(self, data, files, name):
        #If we are using the middleware, then the data will already be
        #in FILES, if not it will be in POST
        if name not in data:
            return super(FPFileWidget, self).value_from_datadict(
                    data, files, name)

        return data

    class Media:
        js = (JS_URL,)

Use version 1 of Filepicker.js

Use version 1 of Filepicker.js

Response:
from django.conf import settings
from django.forms import widgets

#JS_URL is the url to the filepicker.io javascript library
JS_VERSION = 1
JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION)

if hasattr(settings, 'FILEPICKER_INPUT_TYPE'):
    INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE
else:
    INPUT_TYPE = 'filepicker-dragdrop'

class FPFileWidget(widgets.Input):
    input_type = INPUT_TYPE
    needs_multipart_form = False

    def value_from_datadict_old(self, data, files, name):
        #If we are using the middleware, then the data will already be
        #in FILES, if not it will be in POST
        if name not in data:
            return super(FPFileWidget, self).value_from_datadict(
                    data, files, name)

        return data

    class Media:
        js = (JS_URL,)

Prompt:
Use version 1 of Filepicker.js
from django.conf import settings
from django.forms import widgets

#JS_URL is the url to the filepicker.io javascript library
JS_VERSION = 0
JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION)

if hasattr(settings, 'FILEPICKER_INPUT_TYPE'):
    INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE
else:
    INPUT_TYPE = 'filepicker-dragdrop'

class FPFileWidget(widgets.Input):
    input_type = INPUT_TYPE
    needs_multipart_form = False

    def value_from_datadict_old(self, data, files, name):
        #If we are using the middleware, then the data will already be
        #in FILES, if not it will be in POST
        if name not in data:
            return super(FPFileWidget, self).value_from_datadict(
                    data, files, name)

        return data

    class Media:
        js = (JS_URL,)


import unittest

from shapely.geometry import LineString, Point

from directions.base import _parse_points

class DirectionsTest(unittest.TestCase):
    def setUp(self):
        self.p = [(1,2), (3,4), (5,6), (7,8)]
        self.line = LineString(self.p)

    def test_origin_dest(self):
        result = _parse_points(self.p[0], self.p[-1])
        self.assertEqual([self.p[0], self.p[-1]], result)

    def test_origin_dest_waypoints(self):
        result = _parse_points(self.p[0], self.p[-1], self.p[1:-1])
        self.assertEqual(self.p, result)

    def test_line(self):
        result = _parse_points(self.line)
        self.assertEqual(self.p, result)

    def test_points(self):
        p0 = Point(self.line.coords[0])
        p1 = Point(self.line.coords[-1])
        result = _parse_points(p0, p1)
        self.assertEqual([self.p[0], self.p[-1]], result)

    def test_points_array(self):
        p0 = Point(self.p[0])
        p1 = Point(self.p[-1])
        result = _parse_points([p0, p1])
        self.assertEqual([self.p[0], self.p[-1]], result)

    def test_mixed_types(self):
        origin = 'blah'
        destination = Point(self.p[-1])
        points = self.p[1:-1]
        expected = list(self.p)  # Copy it
        expected[0] = 'blah'
        result = _parse_points(origin, destination, points)
        self.assertEqual(expected, result)

    def test_no_dest_waypoints(self):
        # Can't specify waypoints without destination
        with self.assertRaises(ValueError):
            _parse_points('origin', waypoints=['p1'])

    def test_bad_input(self):
        # Test points not length 2
        with self.assertRaises(ValueError):
            _parse_points(self.p[0], (1.0, 2.0, 3.0))

Add tests for the different input variations.

Response:
import unittest

from shapely.geometry import LineString, Point

from directions.base import _parse_points

class DirectionsTest(unittest.TestCase):
    def setUp(self):
        self.p = [(1,2), (3,4), (5,6), (7,8)]
        self.line = LineString(self.p)

    def test_origin_dest(self):
        result = _parse_points(self.p[0], self.p[-1])
        self.assertEqual([self.p[0], self.p[-1]], result)

    def test_origin_dest_waypoints(self):
        result = _parse_points(self.p[0], self.p[-1], self.p[1:-1])
        self.assertEqual(self.p, result)

    def test_line(self):
        result = _parse_points(self.line)
        self.assertEqual(self.p, result)

    def test_points(self):
        p0 = Point(self.line.coords[0])
        p1 = Point(self.line.coords[-1])
        result = _parse_points(p0, p1)
        self.assertEqual([self.p[0], self.p[-1]], result)

    def test_points_array(self):
        p0 = Point(self.p[0])
        p1 = Point(self.p[-1])
        result = _parse_points([p0, p1])
        self.assertEqual([self.p[0], self.p[-1]], result)

    def test_mixed_types(self):
        origin = 'blah'
        destination = Point(self.p[-1])
        points = self.p[1:-1]
        expected = list(self.p)  # Copy it
        expected[0] = 'blah'
        result = _parse_points(origin, destination, points)
        self.assertEqual(expected, result)

    def test_no_dest_waypoints(self):
        # Can't specify waypoints without destination
        with self.assertRaises(ValueError):
            _parse_points('origin', waypoints=['p1'])

    def test_bad_input(self):
        # Test points not length 2
        with self.assertRaises(ValueError):
            _parse_points(self.p[0], (1.0, 2.0, 3.0))

Prompt: Add tests for the different input variations.


#!/usr/bin/env python
#
# Utility script to run pyflakes with the modules we care about and
# exclude errors we know to be fine.

import os
import subprocess
import sys

module_exclusions = [
    'djblets',
    'django_evolution',
    'dist',
    'ez_setup.py',
    'htdocs',
    'settings_local.py',
    'ReviewBoard.egg-info',
]

def scan_for_modules():
    return [entry
            for entry in os.listdir(os.getcwd())
            if ((os.path.isdir(entry) or entry.endswith(".py")) and
                entry not in module_exclusions)]

def main():
    cur_dir = os.path.dirname(__file__)
    os.chdir(os.path.join(cur_dir, "..", ".."))
    modules = sys.argv[1:]

    if not modules:
        # The user didn't specify anything specific. Scan for modules.
        modules = scan_for_modules()

    p = subprocess.Popen(['pyflakes'] + modules,
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         close_fds=True)

    contents = p.stdout.readlines()

    # Read in the exclusions file
    exclusions = {}
    fp = open(os.path.join(cur_dir, "pyflakes.exclude"), "r")

    for line in fp.readlines():
        exclusions[line.rstrip()] = 1

    fp.close()

    # Now filter thin
    for line in contents:
        line = line.rstrip()
        if line not in exclusions:
            print line

if __name__ == "__main__":
    main()

Response:
#!/usr/bin/env python
#
# Utility script to run pyflakes with the modules we care about and
# exclude errors we know to be fine.

import os
import subprocess
import sys

module_exclusions = [
    'djblets',
    'django_evolution',
    'dist',
    'ez_setup.py',
    'htdocs',
    'settings_local.py',
    'ReviewBoard.egg-info',
]

def scan_for_modules():
    return [entry
            for entry in os.listdir(os.getcwd())
            if ((os.path.isdir(entry) or entry.endswith(".py")) and
                entry not in module_exclusions)]

def main():
    cur_dir = os.path.dirname(__file__)
    os.chdir(os.path.join(cur_dir, "..", ".."))
    modules = sys.argv[1:]

    if not modules:
        # The user didn't specify anything specific. Scan for modules.
        modules = scan_for_modules()

    p = subprocess.Popen(['pyflakes'] + modules,
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         close_fds=True)

    contents = p.stdout.readlines()

    # Read in the exclusions file
    exclusions = {}
    fp = open(os.path.join(cur_dir, "pyflakes.exclude"), "r")

    for line in fp.readlines():
        exclusions[line.rstrip()] = 1

    fp.close()

    # Now filter thin
    for line in contents:
        line = line.rstrip()
        if line not in exclusions:
            print line

if __name__ == "__main__":
    main()

Prompt:
Exclude htdocs, because that just takes way too long to scan.

#!/usr/bin/env python
#
# Utility script to run pyflakes with the modules we care about and
# exclude errors we know to be fine.

import os
import subprocess
import sys

module_exclusions = [
    'djblets',
    'django_evolution',
    'dist',
    'ez_setup.py',
    'settings_local.py',
    'ReviewBoard.egg-info',
]

def scan_for_modules():
    return [entry
            for entry in os.listdir(os.getcwd())
            if ((os.path.isdir(entry) or entry.endswith(".py")) and
                entry not in module_exclusions)]

def main():
    cur_dir = os.path.dirname(__file__)
    os.chdir(os.path.join(cur_dir, "..", ".."))
    modules = sys.argv[1:]

    if not modules:
        # The user didn't specify anything specific. Scan for modules.
        modules = scan_for_modules()

    p = subprocess.Popen(['pyflakes'] + modules,
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         close_fds=True)

    contents = p.stdout.readlines()

    # Read in the exclusions file
    exclusions = {}
    fp = open(os.path.join(cur_dir, "pyflakes.exclude"), "r")

    for line in fp.readlines():
        exclusions[line.rstrip()] = 1

    fp.close()

    # Now filter thin
    for line in contents:
        line = line.rstrip()
        if line not in exclusions:
            print line

if __name__ == "__main__":
    main()


import math
from django import template
from ..conf import settings

register = template.Library()

@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
    max_pages = int(math.ceil(context['total_results'] /
                              settings.GOOGLE_SEARCH_RESULTS_PER_PAGE))

    prev_page = context['current_page'] - 1
    next_page = context['current_page'] + 1

    context.update({
        'pages': range(1, max_pages + 1),
        'prev_page': prev_page if context['current_page'] - 1 > 0 else None,
        'next_page': next_page if next_page < max_pages else None,
    })

    return context

Remove last_page not needed anymore.

Remove last_page not needed anymore.

Response:
import math
from django import template
from ..conf import settings

register = template.Library()

@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
    max_pages = int(math.ceil(context['total_results'] /
                              settings.GOOGLE_SEARCH_RESULTS_PER_PAGE))

    prev_page = context['current_page'] - 1
    next_page = context['current_page'] + 1

    context.update({
        'pages': range(1, max_pages + 1),
        'prev_page': prev_page if context['current_page'] - 1 > 0 else None,
        'next_page': next_page if next_page < max_pages else None,
    })

    return context

Prompt:
Remove last_page not needed anymore.

import math
from django import template
from ..conf import settings

register = template.Library()

@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
    max_pages = int(math.ceil(context['total_results'] /
                              settings.GOOGLE_SEARCH_RESULTS_PER_PAGE))

    last_page = int(context['current_page']) + pages_to_show - 1
    last_page = max_pages if last_page > max_pages else last_page

    prev_page = context['current_page'] - 1
    next_page = context['current_page'] + 1

    context.update({
        'pages': range(1, max_pages + 1),
        'prev_page': prev_page if context['current_page'] - 1 > 0 else None,
        'next_page': next_page if next_page < max_pages else None,
    })

    return context


from spicedham.basewrapper import BaseWrapper

class DigitDestroyer(object):
    def train(*args):
        pass
    def classify(self, response):
        if all(map(unicode.isdigit, response)):
            return 1
        else:
            return None

Fix inheritence error and return value

Response:
from spicedham.basewrapper import BaseWrapper

class DigitDestroyer(object):
    def train(*args):
        pass
    def classify(self, response):
        if all(map(unicode.isdigit, response)):
            return 1
        else:
            return None

Prompt:
Fix inheritence error and return value

It shouldn't inherit from BaseWrapper, but merely object.
It should return None instead of 0.5 so it will have no effect on the average.

from spicedham.basewrapper import BaseWrapper

class DigitDestroyer(BaseWrapper):
    def train(*args):
        pass
    def classify(self, response):
        if all(map(unicode.isdigit, response)):
            return 1
        else:
            return 0.5


# -*- encoding: utf-8

import pytest

from reports import NGINX_LOG_REGEX

@pytest.mark.parametrize('log_line', [
    # Unusual methods
    '0.0.0.0 - - [01/Jan/2001:00:00:00 +0000] "HEAD /example HTTP/1.0" 200 0 "http://referrer.org" "Example user agent" "1.2.3.4"',
    '0.0.0.0 - - [01/Jan/2001:00:00:00 +0000] "OPTIONS /example HTTP/1.0" 200 0 "http://referrer.org" "Example user agent" "1.2.3.4"',

    # Referrer is empty
    '0.0.0.0 - - [01/Jan/2001:00:00:00 +0000] "GET /example HTTP/1.0" 200 0 "" "Example user agent" "1.2.3.4"',
])
def test_nginx_regex(log_line):
    assert NGINX_LOG_REGEX.match(log_line) is not None

Add a few tests for the analytics code

Add a few tests for the analytics code

Response:
# -*- encoding: utf-8

import pytest

from reports import NGINX_LOG_REGEX

@pytest.mark.parametrize('log_line', [
    # Unusual methods
    '0.0.0.0 - - [01/Jan/2001:00:00:00 +0000] "HEAD /example HTTP/1.0" 200 0 "http://referrer.org" "Example user agent" "1.2.3.4"',
    '0.0.0.0 - - [01/Jan/2001:00:00:00 +0000] "OPTIONS /example HTTP/1.0" 200 0 "http://referrer.org" "Example user agent" "1.2.3.4"',

    # Referrer is empty
    '0.0.0.0 - - [01/Jan/2001:00:00:00 +0000] "GET /example HTTP/1.0" 200 0 "" "Example user agent" "1.2.3.4"',
])
def test_nginx_regex(log_line):
    assert NGINX_LOG_REGEX.match(log_line) is not None

Prompt: Add a few tests for the analytics code


def sieve(n):
    if n < 2:
        return []
    not_prime = set()
    prime = [2]
    for i in range(3, n+1, 2):
        if i not in not_prime:
            prime.append(i)
            not_prime.update(range(i*i, n+1, i))
    return prime

Response:
def sieve(n):
    if n < 2:
        return []
    not_prime = set()
    prime = [2]
    for i in range(3, n+1, 2):
        if i not in not_prime:
            prime.append(i)
            not_prime.update(range(i*i, n+1, i))
    return prime

Prompt:
Fix bug where n is the square of a prime

def sieve(n):
    if n < 2:
        return []
    not_prime = set()
    prime = [2]
    for i in range(3, n+1, 2):
        if i not in not_prime:
            prime.append(i)
            not_prime.update(range(i*i, n, i))
    return prime


from setuptools import setup, find_packages

# Dynamically calculate the version based on dbsettings.VERSION
version_tuple = (0, 4, None)
if version_tuple[2] is not None:
    if type(version_tuple[2]) == int:
        version = "%d.%d.%s" % version_tuple
    else:
        version = "%d.%d_%s" % version_tuple
else:
    version = "%d.%d" % version_tuple[:2]

setup(
    name='django-dbsettings',
    version=version,
    description='Application settings whose values can be updated while a project is up and running.',
    long_description=open('README.rst').read(),
    author='Samuel Cormier-Iijima',
    author_email='sciyoshi@gmail.com',
    maintainer='Jacek Tomaszewski',
    maintainer_email='jacek.tomek@gmail.com',
    url='http://github.com/zlorf/django-dbsettings',
    packages=find_packages(),
    include_package_data=True,
    license='BSD',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Utilities'
    ],
)

Allow version to have subrevision.

Allow version to have subrevision.

Response:
from setuptools import setup, find_packages

# Dynamically calculate the version based on dbsettings.VERSION
version_tuple = (0, 4, None)
if version_tuple[2] is not None:
    if type(version_tuple[2]) == int:
        version = "%d.%d.%s" % version_tuple
    else:
        version = "%d.%d_%s" % version_tuple
else:
    version = "%d.%d" % version_tuple[:2]

setup(
    name='django-dbsettings',
    version=version,
    description='Application settings whose values can be updated while a project is up and running.',
    long_description=open('README.rst').read(),
    author='Samuel Cormier-Iijima',
    author_email='sciyoshi@gmail.com',
    maintainer='Jacek Tomaszewski',
    maintainer_email='jacek.tomek@gmail.com',
    url='http://github.com/zlorf/django-dbsettings',
    packages=find_packages(),
    include_package_data=True,
    license='BSD',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Utilities'
    ],
)

Prompt:
Allow version to have subrevision.

from setuptools import setup, find_packages

# Dynamically calculate the version based on dbsettings.VERSION
version_tuple = (0, 4, None)
if version_tuple[2] is not None:
    version = "%d.%d_%s" % version_tuple
else:
    version = "%d.%d" % version_tuple[:2]

setup(
    name='django-dbsettings',
    version=version,
    description='Application settings whose values can be updated while a project is up and running.',
    long_description=open('README.rst').read(),
    author='Samuel Cormier-Iijima',
    author_email='sciyoshi@gmail.com',
    maintainer='Jacek Tomaszewski',
    maintainer_email='jacek.tomek@gmail.com',
    url='http://github.com/zlorf/django-dbsettings',
    packages=find_packages(),
    include_package_data=True,
    license='BSD',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Utilities'
    ],
)


import os

import pytest
import requests

@pytest.fixture
def url():
    return os.getenv("SITE", "http://localhost:5000")

def test_post_images(expect, url):
    params = {"key": "iw", "lines": ["test", "deployment"]}
    response = requests.post(f"{url}/api/images", json=params)
    expect(response.status_code) == 201
    expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")

def test_get_image(expect, url):
    response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
    expect(response.status_code) == 200
    expect(response.headers["Content-Type"]) == "image/jpeg"

def test_get_image_custom(expect, url):
    response = requests.get(
        f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
    )
    expect(response.status_code) == 200
    expect(response.headers["Content-Type"]) == "image/png"

Add test for custom images

Add test for custom images

Response:
import os

import pytest
import requests

@pytest.fixture
def url():
    return os.getenv("SITE", "http://localhost:5000")

def test_post_images(expect, url):
    params = {"key": "iw", "lines": ["test", "deployment"]}
    response = requests.post(f"{url}/api/images", json=params)
    expect(response.status_code) == 201
    expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")

def test_get_image(expect, url):
    response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
    expect(response.status_code) == 200
    expect(response.headers["Content-Type"]) == "image/jpeg"

def test_get_image_custom(expect, url):
    response = requests.get(
        f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
    )
    expect(response.status_code) == 200
    expect(response.headers["Content-Type"]) == "image/png"

Prompt:
Add test for custom images

import os

import pytest
import requests

@pytest.fixture
def url():
    return os.getenv("SITE", "http://localhost:5000")

def test_post_images(expect, url):
    params = {"key": "iw", "lines": ["test", "deployment"]}
    response = requests.post(f"{url}/api/images", json=params)
    expect(response.status_code) == 201
    expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")

def test_get_image(expect, url):
    response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
    expect(response.status_code) == 200
    expect(response.headers["Content-Type"]) == "image/jpeg"


BASE_URL = 'https://api.box.com/2.0'

FOLDERS_URL = '{}/folders/{{}}/items'.format(BASE_URL)

MAX_FOLDERS = 1000

class Client(object):
    def __init__(self, provider_logic):
        """
        Box client constructor
        :param provider_logic: oauthclient ProviderLogic instance
        :return:
        """
        self.provider_logic = provider_logic

    def folders(self, parent=None, limit=100, offset=0):
        if parent:
            folder_id = parent['id']
        else:
            folder_id = 0

        url = FOLDERS_URL.format(folder_id)

        count = 0
        while count < limit:
            params = {
                # this is the request limit, not the number of folders we actually want
                'limit': 100,

                'offset': offset+count,
            }

            response = self.provider_logic.get(url, params=params)
            response.raise_for_status()

            json_data = response.json()

            # if we hit the total number of entries, we have to be done
            total_count = json_data['total_count']
            if count >= total_count:
                break

            # determine how many more entries to get from the result set
            entry_count = limit - count
            entries = json_data['entries'][:entry_count]
            for entry in entries:
                yield entry

            # increment the count by the number of entries
            count += len(entries)

Response:
BASE_URL = 'https://api.box.com/2.0'

FOLDERS_URL = '{}/folders/{{}}/items'.format(BASE_URL)

MAX_FOLDERS = 1000

class Client(object):
    def __init__(self, provider_logic):
        """
        Box client constructor
        :param provider_logic: oauthclient ProviderLogic instance
        :return:
        """
        self.provider_logic = provider_logic

    def folders(self, parent=None, limit=100, offset=0):
        if parent:
            folder_id = parent['id']
        else:
            folder_id = 0

        url = FOLDERS_URL.format(folder_id)

        count = 0
        while count < limit:
            params = {
                # this is the request limit, not the number of folders we actually want
                'limit': 100,

                'offset': offset+count,
            }

            response = self.provider_logic.get(url, params=params)
            response.raise_for_status()

            json_data = response.json()

            # if we hit the total number of entries, we have to be done
            total_count = json_data['total_count']
            if count >= total_count:
                break

            # determine how many more entries to get from the result set
            entry_count = limit - count
            entries = json_data['entries'][:entry_count]
            for entry in entries:
                yield entry

            # increment the count by the number of entries
            count += len(entries)

Prompt:
Raise an exception when the API response is not successful

BASE_URL = 'https://api.box.com/2.0'

FOLDERS_URL = '{}/folders/{{}}/items'.format(BASE_URL)

MAX_FOLDERS = 1000

class Client(object):
    def __init__(self, provider_logic):
        """
        Box client constructor
        :param provider_logic: oauthclient ProviderLogic instance
        :return:
        """
        self.provider_logic = provider_logic

    def folders(self, parent=None, limit=100, offset=0):
        if parent:
            folder_id = parent['id']
        else:
            folder_id = 0

        url = FOLDERS_URL.format(folder_id)

        count = 0
        while count < limit:
            params = {
                # this is the request limit, not the number of folders we actually want
                'limit': 100,

                'offset': offset+count,
            }

            response = self.provider_logic.get(url, params=params)

            json_data = response.json()

            # if we hit the total number of entries, we have to be done
            total_count = json_data['total_count']
            if count >= total_count:
                break

            # determine how many more entries to get from the result set
            entry_count = limit - count
            entries = json_data['entries'][:entry_count]
            for entry in entries:
                yield entry

            # increment the count by the number of entries
            count += len(entries)


from tools import add_constant, categorical

from statsmodels import NoseWrapper as Tester
test = Tester().test

Remove import of moved file

REF: Remove import of moved file

Response:
from tools import add_constant, categorical

from statsmodels import NoseWrapper as Tester
test = Tester().test

Prompt:
REF: Remove import of moved file

from tools import add_constant, categorical
from datautils import Dataset

from statsmodels import NoseWrapper as Tester
test = Tester().test


from setuptools import setup, find_packages

setup(name='mutube',
      version='0.1',
      description='Scrape YouTube links from 4chan threads.',
      url='https://github.com/AP-e/mutube',
      license='unlicense',
      classifiers=['Development Status :: 2 - Pre-Alpha',
                   'Programming Language :: Python'],
      keywords='4chan youtube',
      packages=find_packages(),
      install_requires=['bs4'])

Remove Python 3 only classifier

Remove Python 3 only classifier

Response:
from setuptools import setup, find_packages

setup(name='mutube',
      version='0.1',
      description='Scrape YouTube links from 4chan threads.',
      url='https://github.com/AP-e/mutube',
      license='unlicense',
      classifiers=['Development Status :: 2 - Pre-Alpha',
                   'Programming Language :: Python'],
      keywords='4chan youtube',
      packages=find_packages(),
      install_requires=['bs4'])

Prompt:
Remove Python 3 only classifier

from setuptools import setup, find_packages

setup(name='mutube',
      version='0.1',
      description='Scrape YouTube links from 4chan threads.',
      url='https://github.com/AP-e/mutube',
      license='unlicense',
      classifiers=['Development Status :: 2 - Pre-Alpha',
                   'Programming Language :: Python :: 3 :: Only'],
      keywords='4chan youtube',
      packages=find_packages(),
      install_requires=['bs4'])


import numpy as np
import matplotlib.pyplot as plt

class Agent(object):
    def __init__(self, dim_action):
        self.dim_action = dim_action

    def act(self, ob, reward, done, vision_on):
        #print("ACT!")

        # Get an Observation from the environment.
        # Each observation vectors are numpy array.
        # focus, opponents, track sensors are scaled into [0, 1]. When the agent
        # is out of the road, sensor variables return -1/200.
        # rpm, wheelSpinVel are raw values and then needed to be preprocessed.
        # vision is given as a tensor with size of (64*64, 3) = (4096, 3) <-- rgb
        # and values are in [0, 255]
        if vision_on is False:
            focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel = ob
        else:
            focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel, vision = ob

            """ The code below is for checking the vision input. This is very heavy for real-time Control
                So you may need to remove.
            """
            print(vision.shape)
            """
            img = np.ndarray((64,64,3))
            for i in range(3):
                img[:, :, i] = 255 - vision[:, i].reshape((64, 64))

            plt.imshow(img, origin='lower')
            plt.draw()
            plt.pause(0.001)
            """
        return np.tanh(np.random.randn(self.dim_action)) # random action

Response:
import numpy as np
import matplotlib.pyplot as plt

class Agent(object):
    def __init__(self, dim_action):
        self.dim_action = dim_action

    def act(self, ob, reward, done, vision_on):
        #print("ACT!")

        # Get an Observation from the environment.
        # Each observation vectors are numpy array.
        # focus, opponents, track sensors are scaled into [0, 1]. When the agent
        # is out of the road, sensor variables return -1/200.
        # rpm, wheelSpinVel are raw values and then needed to be preprocessed.
        # vision is given as a tensor with size of (64*64, 3) = (4096, 3) <-- rgb
        # and values are in [0, 255]
        if vision_on is False:
            focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel = ob
        else:
            focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel, vision = ob

            """ The code below is for checking the vision input. This is very heavy for real-time Control
                So you may need to remove.
            """
            print(vision.shape)
            """
            img = np.ndarray((64,64,3))
            for i in range(3):
                img[:, :, i] = 255 - vision[:, i].reshape((64, 64))

            plt.imshow(img, origin='lower')
            plt.draw()
            plt.pause(0.001)
            """
        return np.tanh(np.random.randn(self.dim_action)) # random action

Prompt:
Update to follow the new observation format
(follow the vision input of OpenAI ATARI environment)

import numpy as np
import matplotlib.pyplot as plt

class Agent(object):
    def __init__(self, dim_action):
        self.dim_action = dim_action

    def act(self, ob, reward, done, vision):
        #print("ACT!")

        # Get an Observation from the environment.
        # Each observation vectors are numpy array.
        # focus, opponents, track sensors are scaled into [0, 1]. When the agent
        # is out of the road, sensor variables return -1/200.
        # rpm, wheelSpinVel are raw values and then needed to be preprocessed.
        # vision is given as a tensor with size of (3, 64, 64) <-- rgb
        # and values are in [0, 255]
        if vision is False:
            focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel = ob
        else:
            focus, speedX, speedY, speedZ, opponents, rpm, track, wheelSpinVel, vision = ob

            """ The code below is for checking the vision input. This is very heavy for real-time Control
                So you may need to remove.
            """
            """
            img = np.ndarray((64,64,3))
            for i in range(3):
                img[:, :, i] = 255 - vision[i]

            plt.imshow(img, origin='lower')
            plt.draw()
            plt.pause(0.001)
            """
        return np.tanh(np.random.randn(self.dim_action)) # random action


from contextlib import contextmanager
from os import path
from unittest import TestCase

from dictdiffer import diff
from jsontest import JsonTest
from mock import patch

from canaryd_packages import six

from canaryd.plugin import get_plugin_by_name

class TestPluginRealStates(TestCase):
    def run_plugin(self, plugin_name):
        plugin = get_plugin_by_name(plugin_name)
        plugin.get_state({})

    def test_meta_plugin(self):
        self.run_plugin('meta')

    def test_services_plugin(self):
        self.run_plugin('services')

    def test_containers_plugin(self):
        self.run_plugin('containers')

@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
    jsontest_files = path.join('tests/plugins')

    @contextmanager
    def patch_commands(self, commands):
        def handle_command(command, *args, **kwargs):
            command = command[0]

            if command not in commands:
                raise ValueError('Broken tests: {0} not in commands: {1}'.format(
                    command, commands.keys(),
                ))

            return '\n'.join(commands[command])

        check_output_patch = patch(
            'canaryd.subprocess.check_output',
            handle_command,
        )
        check_output_patch.start()

        yield

        check_output_patch.stop()

    def jsontest_function(self, test_name, test_data):
        plugin = get_plugin_by_name(test_data['plugin'])

        with self.patch_commands(test_data['commands']):
            state = plugin.get_state({})

        try:
            self.assertEqual(state, test_data['state'])
        except AssertionError:
            print(list(diff(test_data['state'], state)))
            raise

Response:
from contextlib import contextmanager
from os import path
from unittest import TestCase

from dictdiffer import diff
from jsontest import JsonTest
from mock import patch

from canaryd_packages import six

from canaryd.plugin import get_plugin_by_name

class TestPluginRealStates(TestCase):
    def run_plugin(self, plugin_name):
        plugin = get_plugin_by_name(plugin_name)
        plugin.get_state({})

    def test_meta_plugin(self):
        self.run_plugin('meta')

    def test_services_plugin(self):
        self.run_plugin('services')

    def test_containers_plugin(self):
        self.run_plugin('containers')

@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
    jsontest_files = path.join('tests/plugins')

    @contextmanager
    def patch_commands(self, commands):
        def handle_command(command, *args, **kwargs):
            command = command[0]

            if command not in commands:
                raise ValueError('Broken tests: {0} not in commands: {1}'.format(
                    command, commands.keys(),
                ))

            return '\n'.join(commands[command])

        check_output_patch = patch(
            'canaryd.subprocess.check_output',
            handle_command,
        )
        check_output_patch.start()

        yield

        check_output_patch.stop()

    def jsontest_function(self, test_name, test_data):
        plugin = get_plugin_by_name(test_data['plugin'])

        with self.patch_commands(test_data['commands']):
            state = plugin.get_state({})

        try:
            self.assertEqual(state, test_data['state'])
        except AssertionError:
            print(list(diff(test_data['state'], state)))
            raise

Prompt:
Add real plugin state tests for plugins that always work (meta, containers, services).

from contextlib import contextmanager
from os import path
from unittest import TestCase

from canaryd_packages import six
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch

from canaryd.plugin import get_plugin_by_name

@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
    jsontest_files = path.join('tests/plugins')

    @contextmanager
    def patch_commands(self, commands):
        def handle_command(command, *args, **kwargs):
            command = command[0]

            if command not in commands:
                raise ValueError(
                    'Broken tests: {0} not in commands'.format(command),
                )

            return '\n'.join(commands[command])

        check_output_patch = patch(
            'canaryd.subprocess.check_output',
            handle_command,
        )
        check_output_patch.start()

        yield

        check_output_patch.stop()

    def jsontest_function(self, test_name, test_data):
        plugin = get_plugin_by_name(test_data['plugin'])

        with self.patch_commands(test_data['commands']):
            state = plugin.get_state({})

        try:
            self.assertEqual(state, test_data['state'])
        except AssertionError:
            print(list(diff(test_data['state'], state)))
            raise


#!/usr/bin/env python

import os
import random
import string
import sys

from django.utils.crypto import get_random_string

## Check if the script was already executed
flag_filename = '/opt/graphite/post-setup-complete'
if os.path.isfile(flag_filename):
    sys.exit(0)

## Add SECRET_KEY to local_settings.py
settings_filename = '/opt/graphite/webapp/graphite/local_settings.py'
secret_key = get_random_string(
    50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')

with open(settings_filename, 'a') as f:
    f.write("SECRET_KEY = '%s'\n" % (secret_key, ))
    if '--debug' in sys.argv:
        f.write('DEBUG = True\n')

import django
django.setup()

from django.contrib.auth.models import User

## Create Superuser
password = ''.join(
    (random.choice(string.letters + string.digits + string.punctuation))
    for x in range(20))

if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', 'admin@localhost', password)
    print '[graphite-web] Superuser: admin, Password: %s' % (password, )

## Set flag file
with open(flag_filename, 'w'):
    os.utime(flag_filename, None)

Response:
#!/usr/bin/env python

import os
import random
import string
import sys

from django.utils.crypto import get_random_string

## Check if the script was already executed
flag_filename = '/opt/graphite/post-setup-complete'
if os.path.isfile(flag_filename):
    sys.exit(0)

## Add SECRET_KEY to local_settings.py
settings_filename = '/opt/graphite/webapp/graphite/local_settings.py'
secret_key = get_random_string(
    50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')

with open(settings_filename, 'a') as f:
    f.write("SECRET_KEY = '%s'\n" % (secret_key, ))
    if '--debug' in sys.argv:
        f.write('DEBUG = True\n')

import django
django.setup()

from django.contrib.auth.models import User

## Create Superuser
password = ''.join(
    (random.choice(string.letters + string.digits + string.punctuation))
    for x in range(20))

if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', 'admin@localhost', password)
    print '[graphite-web] Superuser: admin, Password: %s' % (password, )

## Set flag file
with open(flag_filename, 'w'):
    os.utime(flag_filename, None)

Prompt:
Check if admin user exists before creating one

#!/usr/bin/env python

import os
import random
import string
import sys

from django.utils.crypto import get_random_string

## Check if the script was already executed
flag_filename = '/opt/graphite/post-setup-complete'
if os.path.isfile(flag_filename):
    sys.exit(0)

## Add SECRET_KEY to local_settings.py
settings_filename = '/opt/graphite/webapp/graphite/local_settings.py'
secret_key = get_random_string(
    50, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')

with open(settings_filename, 'a') as f:
    f.write("SECRET_KEY = '%s'\n" % (secret_key, ))
    if '--debug' in sys.argv:
        f.write('DEBUG = True\n')

import django
django.setup()

from django.contrib.auth.models import User

## Create Superuser
password = ''.join(
    (random.choice(string.letters + string.digits + string.punctuation))
    for x in range(20))

User.objects.create_superuser('admin', 'admin@localhost', password)
print '[graphite-web] Superuser: admin, Password: %s' % (password, )

## Set flag file
with open(flag_filename, 'w'):
    os.utime(flag_filename, None)


import argparse

parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
parser.parse_args()

Add cmd for getting version

Add cmd for getting version

Response:
import argparse

parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
parser.parse_args()

Prompt: Add cmd for getting version


import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY

log = logging.getLogger(__name__)

@special_command('\\dt', '\\dt [table]', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
def list_tables(cur, arg=None, arg_type=PARSED_QUERY):
    if arg:
        query = 'SHOW FIELDS FROM {0}'.format(arg)
    else:
        query = 'SHOW TABLES'
    log.debug(query)
    cur.execute(query)
    if cur.description:
        headers = [x[0] for x in cur.description]
        return [(None, cur, headers, '')]
    else:
        return [(None, None, None, '')]

@special_command('\\l', '\\l', 'List databases.', arg_type=RAW_QUERY, case_sensitive=True)
def list_databases(cur, **_):
    query = 'SHOW DATABASES'
    log.debug(query)
    cur.execute(query)
    if cur.description:
        headers = [x[0] for x in cur.description]
        return [(None, cur, headers, '')]
    else:
        return [(None, None, None, '')]

Response:
import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY

log = logging.getLogger(__name__)

@special_command('\\dt', '\\dt [table]', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
def list_tables(cur, arg=None, arg_type=PARSED_QUERY):
    if arg:
        query = 'SHOW FIELDS FROM {0}'.format(arg)
    else:
        query = 'SHOW TABLES'
    log.debug(query)
    cur.execute(query)
    if cur.description:
        headers = [x[0] for x in cur.description]
        return [(None, cur, headers, '')]
    else:
        return [(None, None, None, '')]

@special_command('\\l', '\\l', 'List databases.', arg_type=RAW_QUERY, case_sensitive=True)
def list_databases(cur, **_):
    query = 'SHOW DATABASES'
    log.debug(query)
    cur.execute(query)
    if cur.description:
        headers = [x[0] for x in cur.description]
        return [(None, cur, headers, '')]
    else:
        return [(None, None, None, '')]

Prompt:
Change \dt syntax to add an optional table name.

import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY

log = logging.getLogger(__name__)

@special_command('\\dt', '\\dt', 'List or describe tables.', arg_type=PARSED_QUERY, case_sensitive=True)
def list_tables(cur, arg=None, arg_type=PARSED_QUERY):
    if arg:
        query = 'SHOW FIELDS FROM {0}'.format(arg)
    else:
        query = 'SHOW TABLES'
    log.debug(query)
    cur.execute(query)
    if cur.description:
        headers = [x[0] for x in cur.description]
        return [(None, cur, headers, '')]
    else:
        return [(None, None, None, '')]

@special_command('\\l', '\\l', 'List databases.', arg_type=RAW_QUERY, case_sensitive=True)
def list_databases(cur, **_):
    query = 'SHOW DATABASES'
    log.debug(query)
    cur.execute(query)
    if cur.description:
        headers = [x[0] for x in cur.description]
        return [(None, cur, headers, '')]
    else:
        return [(None, None, None, '')]


import pytest
from nose.tools import assert_raises

from framework.celery_tasks import handlers
from website.project.tasks import on_node_updated

class TestCeleryHandlers:

    @pytest.fixture()
    def queue(self):
        return handlers.queue()

    def test_get_task_from_queue_not_there(self):
        task = handlers.get_task_from_queue(
            'website.project.tasks.on_node_updated',
            predicate=lambda task: task.kwargs['node_id'] == 'woop'
        )
        assert task is False

    def test_get_task_from_queue(self, queue):
        handlers.queue().append(
            on_node_updated.s(node_id='woop', user_id='heyyo', first_save=False, saved_fields={'contributors'})
        )
        task = handlers.get_task_from_queue(
            'website.project.tasks.on_node_updated',
            predicate=lambda task: task.kwargs['node_id'] == 'woop'
        )
        assert task

    def test_get_task_from_queue_errors_with_two_tasks(self, queue):
        tasks = [
            on_node_updated.s(node_id='woop', user_id='heyyo', first_save=False, saved_fields={'title'}),
            on_node_updated.s(node_id='woop', user_id='heyyo', first_save=False, saved_fields={'contributors'})
        ]
        queue += tasks

        with assert_raises(ValueError):
            handlers.get_task_from_queue(
                'website.project.tasks.on_node_updated',
                predicate=lambda task: task.kwargs['node_id'] == 'woop'
            )

Add tests for new get_task_from_queue celery helper

Response:
import pytest
from nose.tools import assert_raises

from framework.celery_tasks import handlers
from website.project.tasks import on_node_updated

class TestCeleryHandlers:

    @pytest.fixture()
    def queue(self):
        return handlers.queue()

    def test_get_task_from_queue_not_there(self):
        task = handlers.get_task_from_queue(
            'website.project.tasks.on_node_updated',
            predicate=lambda task: task.kwargs['node_id'] == 'woop'
        )
        assert task is False

    def test_get_task_from_queue(self, queue):
        handlers.queue().append(
            on_node_updated.s(node_id='woop', user_id='heyyo', first_save=False, saved_fields={'contributors'})
        )
        task = handlers.get_task_from_queue(
            'website.project.tasks.on_node_updated',
            predicate=lambda task: task.kwargs['node_id'] == 'woop'
        )
        assert task

    def test_get_task_from_queue_errors_with_two_tasks(self, queue):
        tasks = [
            on_node_updated.s(node_id='woop', user_id='heyyo', first_save=False, saved_fields={'title'}),
            on_node_updated.s(node_id='woop', user_id='heyyo', first_save=False, saved_fields={'contributors'})
        ]
        queue += tasks

        with assert_raises(ValueError):
            handlers.get_task_from_queue(
                'website.project.tasks.on_node_updated',
                predicate=lambda task: task.kwargs['node_id'] == 'woop'
            )

Prompt: Add tests for new get_task_from_queue celery helper


import numpy as np

from eigen3 import toEigenX
import rbdyn as rbd

class WLSSolver(object):
  def __init__(self):
    self.tasks = []

  def addTask(self, task, weight):
    t = [task, weight]
    self.tasks.append(t)

    return t

  def rmTask(self, taskDef):
    self.tasks.remove(taskDef)

  def solve(self, mb, mbc):
    err = np.mat(np.empty((0, 1)))
    jac = np.mat(np.empty((0, mb.nrDof())))

    for t in self.tasks:
      t[0].update(mb, mbc)
      err = np.vstack((err, t[1]*t[0].error()))
      jac = np.vstack((jac, t[1]*t[0].jacobian()))

    #alpha1 = np.linalg.lstsq(jac, err)[0]
    alpha2 = np.linalg.pinv(jac)*err

    mbc.alpha = rbd.vectorToDof(mb, toEigenX(alpha2))

Fix a bad eigen vector cast.

Fix a bad eigen vector cast.

Response:
import numpy as np

from eigen3 import toEigenX
import rbdyn as rbd

class WLSSolver(object):
  def __init__(self):
    self.tasks = []

  def addTask(self, task, weight):
    t = [task, weight]
    self.tasks.append(t)

    return t

  def rmTask(self, taskDef):
    self.tasks.remove(taskDef)

  def solve(self, mb, mbc):
    err = np.mat(np.empty((0, 1)))
    jac = np.mat(np.empty((0, mb.nrDof())))

    for t in self.tasks:
      t[0].update(mb, mbc)
      err = np.vstack((err, t[1]*t[0].error()))
      jac = np.vstack((jac, t[1]*t[0].jacobian()))

    #alpha1 = np.linalg.lstsq(jac, err)[0]
    alpha2 = np.linalg.pinv(jac)*err

    mbc.alpha = rbd.vectorToDof(mb, toEigenX(alpha2))

Prompt:
Fix a bad eigen vector cast.

import numpy as np

from eigen3 import toEigen
import rbdyn as rbd

class WLSSolver(object):
  def __init__(self):
    self.tasks = []

  def addTask(self, task, weight):
    t = [task, weight]
    self.tasks.append(t)

    return t

  def rmTask(self, taskDef):
    self.tasks.remove(taskDef)

  def solve(self, mb, mbc):
    err = np.mat(np.empty((0, 1)))
    jac = np.mat(np.empty((0, mb.nrDof())))

    for t in self.tasks:
      t[0].update(mb, mbc)
      err = np.vstack((err, t[1]*t[0].error()))
      jac = np.vstack((jac, t[1]*t[0].jacobian()))

    #alpha1 = np.linalg.lstsq(jac, err)[0]
    alpha2 = np.linalg.pinv(jac)*err

    mbc.alpha = rbd.vectorToDof(mb, toEigen(alpha2))


import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
from tests import TestCase

class TestAggregatesWithManyToManyRelationships(TestCase):
    dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'

    def create_models(self):
        user_group = sa.Table('user_group', self.Base.metadata,
            sa.Column('user_id', sa.Integer, sa.ForeignKey('user.id')),
            sa.Column('group_id', sa.Integer, sa.ForeignKey('group.id'))
        )

        class User(self.Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

            @aggregated('groups', sa.Column(sa.Integer, default=0))
            def group_count(self):
                return sa.func.count('1')

            groups = sa.orm.relationship(
                'Group',
                backref='users',
                secondary=user_group
            )

        class Group(self.Base):
            __tablename__ = 'group'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

        self.User = User
        self.Group = Group

    def test_assigns_aggregates_on_insert(self):
        user = self.User(
            name=u'John Matrix'
        )
        self.session.add(user)
        self.session.commit()
        group = self.Group(
            name=u'Some group',
            users=[user]
        )
        self.session.add(group)
        self.session.commit()
        self.session.refresh(user)
        assert user.group_count == 1

    def test_updates_aggregates_on_delete(self):
        user = self.User(
            name=u'John Matrix'
        )
        self.session.add(user)
        self.session.commit()
        group = self.Group(
            name=u'Some group',
            users=[user]
        )
        self.session.add(group)
        self.session.commit()
        self.session.refresh(user)
        user.groups = []
        self.session.commit()
        self.session.refresh(user)
        assert user.group_count == 0

Add tests for many to many aggregates

Add tests for many to many aggregates

Response:
import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
from tests import TestCase

class TestAggregatesWithManyToManyRelationships(TestCase):
    dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'

    def create_models(self):
        user_group = sa.Table('user_group', self.Base.metadata,
            sa.Column('user_id', sa.Integer, sa.ForeignKey('user.id')),
            sa.Column('group_id', sa.Integer, sa.ForeignKey('group.id'))
        )

        class User(self.Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

            @aggregated('groups', sa.Column(sa.Integer, default=0))
            def group_count(self):
                return sa.func.count('1')

            groups = sa.orm.relationship(
                'Group',
                backref='users',
                secondary=user_group
            )

        class Group(self.Base):
            __tablename__ = 'group'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

        self.User = User
        self.Group = Group

    def test_assigns_aggregates_on_insert(self):
        user = self.User(
            name=u'John Matrix'
        )
        self.session.add(user)
        self.session.commit()
        group = self.Group(
            name=u'Some group',
            users=[user]
        )
        self.session.add(group)
        self.session.commit()
        self.session.refresh(user)
        assert user.group_count == 1

    def test_updates_aggregates_on_delete(self):
        user = self.User(
            name=u'John Matrix'
        )
        self.session.add(user)
        self.session.commit()
        group = self.Group(
            name=u'Some group',
            users=[user]
        )
        self.session.add(group)
        self.session.commit()
        self.session.refresh(user)
        user.groups = []
        self.session.commit()
        self.session.refresh(user)
        assert user.group_count == 0

Prompt: Add tests for many to many aggregates


from flask import request, Flask

from st2reactor.sensor.base import Sensor

class EchoFlaskSensor(Sensor):
    def __init__(self, sensor_service, config):
        super(EchoFlaskSensor, self).__init__(
            sensor_service=sensor_service,
            config=config
        )

        self._host = '127.0.0.1'
        self._port = 5000
        self._path = '/echo'

        self._log = self._sensor_service.get_logger(__name__)
        self._app = Flask(__name__)

    def setup(self):
        pass

    def run(self):
        @self._app.route(self._path, methods=['POST'])
        def echo():
            payload = request.get_json(force=True)
            self._sensor_service.dispatch(trigger="examples.echo_flask",
                                          payload=payload)
            return request.data

        self._log.info('Listening for payload on http://{}:{}{}'.format(
            self._host, self._port, self._path))
        self._app.run(host=self._host, port=self._port, threaded=True)

    def cleanup(self):
        pass

    def add_trigger(self, trigger):
        # This method is called when trigger is created
        pass

    def update_trigger(self, trigger):
        # This method is called when trigger is updated
        pass

    def remove_trigger(self, trigger):
        # This method is called when trigger is deleted
        pass

Update the port to be an integer.

Response:
from flask import request, Flask

from st2reactor.sensor.base import Sensor

class EchoFlaskSensor(Sensor):
    def __init__(self, sensor_service, config):
        super(EchoFlaskSensor, self).__init__(
            sensor_service=sensor_service,
            config=config
        )

        self._host = '127.0.0.1'
        self._port = 5000
        self._path = '/echo'

        self._log = self._sensor_service.get_logger(__name__)
        self._app = Flask(__name__)

    def setup(self):
        pass

    def run(self):
        @self._app.route(self._path, methods=['POST'])
        def echo():
            payload = request.get_json(force=True)
            self._sensor_service.dispatch(trigger="examples.echo_flask",
                                          payload=payload)
            return request.data

        self._log.info('Listening for payload on http://{}:{}{}'.format(
            self._host, self._port, self._path))
        self._app.run(host=self._host, port=self._port, threaded=True)

    def cleanup(self):
        pass

    def add_trigger(self, trigger):
        # This method is called when trigger is created
        pass

    def update_trigger(self, trigger):
        # This method is called when trigger is updated
        pass

    def remove_trigger(self, trigger):
        # This method is called when trigger is deleted
        pass

Prompt:
Update the port to be an integer.

Fix the port to be an integer. Use the format function for string formatting.
from flask import request, Flask

from st2reactor.sensor.base import Sensor

class EchoFlaskSensor(Sensor):

    def __init__(self, sensor_service, config):
        super(EchoFlaskSensor, self).__init__(
            sensor_service=sensor_service,
            config=config
        )

        self._host = '127.0.0.1'
        self._port = '5000'
        self._path = '/echo'

        self._log = self._sensor_service.get_logger(__name__)
        self._app = Flask(__name__)

    def setup(self):
        pass

    def run(self):
        @self._app.route(self._path, methods=['POST'])
        def echo():
            payload = request.get_json(force=True)
            self._sensor_service.dispatch(trigger="examples.echo_flask",
                                          payload=payload)
            return request.data

        self._log.info('Listening for payload on http://%s:%s%s' %
                       (self._host, self._port, self._path))
        self._app.run(host=self._host, port=self._port, threaded=True)

    def cleanup(self):
        pass

    def add_trigger(self, trigger):
        # This method is called when trigger is created
        pass

    def update_trigger(self, trigger):
        # This method is called when trigger is updated
        pass

    def remove_trigger(self, trigger):
        # This method is called when trigger is deleted
        pass


from cheesefolder import Cheesefolder
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from rcswitch import RCSwitch

##########
# config #
##########
photodirectory = '/var/www/html/'
cheesepicpath = '/home/pi/cheesepics/'
windowwidth = 1024
windowheight = 768
camera = Gphoto()
switch = RCSwitch(2352753, 2352754, "NOT_IMPLEMENTED")
##########
filesystemFolder = RealFolder(photodirectory)
cheesepicFolder = RealFolder(cheesepicpath)
cheesef = Cheesefolder(cheesepicFolder)
photofolder = Photofolder(filesystemFolder)
photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch, cheesef)
photobox.start()

Use the correct chesefolder objects

Use the correct chesefolder objects

Response:
from cheesefolder import Cheesefolder
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from rcswitch import RCSwitch

##########
# config #
##########
photodirectory = '/var/www/html/'
cheesepicpath = '/home/pi/cheesepics/'
windowwidth = 1024
windowheight = 768
camera = Gphoto()
switch = RCSwitch(2352753, 2352754, "NOT_IMPLEMENTED")
##########
filesystemFolder = RealFolder(photodirectory)
cheesepicFolder = RealFolder(cheesepicpath)
cheesef = Cheesefolder(cheesepicFolder)
photofolder = Photofolder(filesystemFolder)
photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch, cheesef)
photobox.start()

Prompt:
Use the correct chesefolder objects

from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from rcswitch import RCSwitch

##########
# config #
##########
photodirectory = '/var/www/html/'
cheesepicfolder = '/home/pi/cheesepics/'
windowwidth = 1024
windowheight = 768
camera = Gphoto()
switch = RCSwitch(2352753, 2352754, "NOT_IMPLEMENTED")
##########
filesystemFolder = RealFolder(photodirectory)
cheesepicFolder = RealFolder(cheesepicfolder)
photofolder = Photofolder(filesystemFolder)
photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch)
photobox.start()


import os
import unittest
from webtest import TestApp

from ..run_webservices import app
from ..directory_helpers import _get_clean_directory_path

test_app = TestApp(app)

class TestDirectoryPathCleaner(unittest.TestCase):
    PATH_LEADER = '/tmp/foo'
    VALID_CLEAN_DIR = '/tmp/foo/bar'

    if not os.path.exists(PATH_LEADER): os.mkdir(PATH_LEADER)
    if not os.path.exists(VALID_CLEAN_DIR): os.mkdir(VALID_CLEAN_DIR)

    def test_valid_directory_path(self):
        clean_path = _get_clean_directory_path(self.PATH_LEADER, '/bar')
        self.assertEquals(clean_path, self.VALID_CLEAN_DIR)

Add valid directory cleaner helper test

Add valid directory cleaner helper test

git-svn-id: https://svn.apache.org/repos/asf/incubator/climate/trunk@1563517 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: a23ba7556854cb30faaa0dfc19fdbcc6cb67382c

Response:
import os
import unittest
from webtest import TestApp

from ..run_webservices import app
from ..directory_helpers import _get_clean_directory_path

test_app = TestApp(app)

class TestDirectoryPathCleaner(unittest.TestCase):
    PATH_LEADER = '/tmp/foo'
    VALID_CLEAN_DIR = '/tmp/foo/bar'

    if not os.path.exists(PATH_LEADER): os.mkdir(PATH_LEADER)
    if not os.path.exists(VALID_CLEAN_DIR): os.mkdir(VALID_CLEAN_DIR)

    def test_valid_directory_path(self):
        clean_path = _get_clean_directory_path(self.PATH_LEADER, '/bar')
        self.assertEquals(clean_path, self.VALID_CLEAN_DIR)

Prompt:
Add valid directory cleaner helper test

git-svn-id: https://svn.apache.org/repos/asf/incubator/climate/trunk@1563517 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: a23ba7556854cb30faaa0dfc19fdbcc6cb67382c


from enum import IntEnum

class RuntimePlatform(IntEnum):
	OSXEditor = 0
	OSXPlayer = 1
	WindowsPlayer = 2
	OSXWebPlayer = 3
	OSXDashboardPlayer = 4
	WindowsWebPlayer = 5
	WindowsEditor = 7
	IPhonePlayer = 8
	PS3 = 9
	XBOX360 = 10
	Android = 11
	NaCl = 12
	LinuxPlayer = 13
	FlashPlayer = 15
	WebGLPlayer = 17
	MetroPlayerX86 = 18
	WSAPlayerX86 = 18
	MetroPlayerX64 = 19
	WSAPlayerX64 = 19
	MetroPlayerARM = 20
	WSAPlayerARM = 20
	WP8Player = 21
	BB10Player = 22
	BlackBerryPlayer = 22
	TizenPlayer = 23
	PSP2 = 24
	PS4 = 25
	PSM = 26
	PSMPlayer = 26
	XboxOne = 27
	SamsungTVPlayer = 28

Response:
from enum import IntEnum

class RuntimePlatform(IntEnum):
	OSXEditor = 0
	OSXPlayer = 1
	WindowsPlayer = 2
	OSXWebPlayer = 3
	OSXDashboardPlayer = 4
	WindowsWebPlayer = 5
	WindowsEditor = 7
	IPhonePlayer = 8
	PS3 = 9
	XBOX360 = 10
	Android = 11
	NaCl = 12
	LinuxPlayer = 13
	FlashPlayer = 15
	WebGLPlayer = 17
	MetroPlayerX86 = 18
	WSAPlayerX86 = 18
	MetroPlayerX64 = 19
	WSAPlayerX64 = 19
	MetroPlayerARM = 20
	WSAPlayerARM = 20
	WP8Player = 21
	BB10Player = 22
	BlackBerryPlayer = 22
	TizenPlayer = 23
	PSP2 = 24
	PS4 = 25
	PSM = 26
	PSMPlayer = 26
	XboxOne = 27
	SamsungTVPlayer = 28

Prompt:
Add PSMPlayer and SamsungTVPlayer platforms

from enum import IntEnum

class RuntimePlatform(IntEnum):
	OSXEditor = 0
	OSXPlayer = 1
	WindowsPlayer = 2
	OSXWebPlayer = 3
	OSXDashboardPlayer = 4
	WindowsWebPlayer = 5
	WindowsEditor = 7
	IPhonePlayer = 8
	PS3 = 9
	XBOX360 = 10
	Android = 11
	NaCl = 12
	LinuxPlayer = 13
	FlashPlayer = 15
	WebGLPlayer = 17
	MetroPlayerX86 = 18
	WSAPlayerX86 = 18
	MetroPlayerX64 = 19
	WSAPlayerX64 = 19
	MetroPlayerARM = 20
	WSAPlayerARM = 20
	WP8Player = 21
	BB10Player = 22
	BlackBerryPlayer = 22
	TizenPlayer = 23
	PSP2 = 24
	PS4 = 25
	PSM = 26
	XboxOne = 27


from string import Template

__author__ = 'maa'

templates_folder = 'file_templates_folder\\'

def create_and_full_fill_file(template_file_name, destination_file_path, kwargs):
    template_file = open(template_file_name, 'r')
    file_content = template_file.read()
    template_file.close()

    template = Template(file_content)

    final_content = template.substitute(kwargs)

    final_file = open(destination_file_path, 'w')
    final_file.write(final_content)
    final_file.close()

Response:
from string import Template

__author__ = 'maa'

templates_folder = 'file_templates_folder\\'

def create_and_full_fill_file(template_file_name, destination_file_path, kwargs):
    template_file = open(template_file_name, 'r')
    file_content = template_file.read()
    template_file.close()

    template = Template(file_content)

    final_content = template.substitute(kwargs)

    final_file = open(destination_file_path, 'w')
    final_file.write(final_content)
    final_file.close()

Prompt:
[dev] Change method params because they are not necessary.

from string import Template

__author__ = 'maa'

templates_folder = 'file_templates_folder\\'

def create_and_full_fill_file(template_file_name, destination_file_path, file_name, kwargs):
    template_file = open(templates_folder + template_file_name, 'r')
    file_content = template_file.read()
    template_file.close()

    template = Template(file_content)

    final_content = template.substitute(kwargs)

    final_file = open(destination_file_path + '\\' + file_name, 'w')
    final_file.write(final_content)
    final_file.close()


from __future__ import absolute_import, division, print_function

from odo.backends.dask_array import append, Array, merge
from dask.array.core import insert_to_ooc
from dask import core
from odo import convert, into
from odo.utils import tmpfile
import numpy as np
import bcolz

def eq(a, b):
    c = a == b
    if isinstance(c, np.ndarray):
        c = c.all()
    return c

def test_convert():
    x = np.arange(600).reshape((20, 30))
    d = convert(Array, x, blockshape=(4, 5))

    assert isinstance(d, Array)

def test_convert_to_numpy_array():
    x = np.arange(600).reshape((20, 30))
    d = convert(Array, x, blockshape=(4, 5))
    x2 = convert(np.ndarray, d)

    assert eq(x, x2)

def test_append_to_array():
    x = np.arange(600).reshape((20, 30))
    a = into(Array, x, blockshape=(4, 5))
    b = bcolz.zeros(shape=(0, 30), dtype=x.dtype)

    append(b, a)
    assert eq(b[:], x)

    with tmpfile('hdf5') as fn:
        h = into(fn+'::/data', a)
        assert eq(h[:], x)
        h.file.close()

def test_into_inplace():
    x = np.arange(600).reshape((20, 30))
    a = into(Array, x, blockshape=(4, 5))
    b = bcolz.zeros(shape=(20, 30), dtype=x.dtype)

    append(b, a, inplace=True)
    assert eq(b[:], x)

def test_insert_to_ooc():
    x = np.arange(600).reshape((20, 30))
    y = np.empty(shape=x.shape, dtype=x.dtype)
    a = convert(Array, x, blockshape=(4, 5))

    dsk = insert_to_ooc(y, a)
    core.get(merge(dsk, a.dask), list(dsk.keys()))

    assert eq(y, x)

def test__array__():
    x = np.arange(600).reshape((20, 30))
    d = convert(Array, x, blockshape=(4, 5))

    assert eq(x, np.array(d))

Migrate tests for dask array conversions from dask package.

Response:
from __future__ import absolute_import, division, print_function

from odo.backends.dask_array import append, Array, merge
from dask.array.core import insert_to_ooc
from dask import core
from odo import convert, into
from odo.utils import tmpfile
import numpy as np
import bcolz

def eq(a, b):
    c = a == b
    if isinstance(c, np.ndarray):
        c = c.all()
    return c

def test_convert():
    x = np.arange(600).reshape((20, 30))
    d = convert(Array, x, blockshape=(4, 5))

    assert isinstance(d, Array)

def test_convert_to_numpy_array():
    x = np.arange(600).reshape((20, 30))
    d = convert(Array, x, blockshape=(4, 5))
    x2 = convert(np.ndarray, d)

    assert eq(x, x2)

def test_append_to_array():
    x = np.arange(600).reshape((20, 30))
    a = into(Array, x, blockshape=(4, 5))
    b = bcolz.zeros(shape=(0, 30), dtype=x.dtype)

    append(b, a)
    assert eq(b[:], x)

    with tmpfile('hdf5') as fn:
        h = into(fn+'::/data', a)
        assert eq(h[:], x)
        h.file.close()

def test_into_inplace():
    x = np.arange(600).reshape((20, 30))
    a = into(Array, x, blockshape=(4, 5))
    b = bcolz.zeros(shape=(20, 30), dtype=x.dtype)

    append(b, a, inplace=True)
    assert eq(b[:], x)

def test_insert_to_ooc():
    x = np.arange(600).reshape((20, 30))
    y = np.empty(shape=x.shape, dtype=x.dtype)
    a = convert(Array, x, blockshape=(4, 5))

    dsk = insert_to_ooc(y, a)
    core.get(merge(dsk, a.dask), list(dsk.keys()))

    assert eq(y, x)

def test__array__():
    x = np.arange(600).reshape((20, 30))
    d = convert(Array, x, blockshape=(4, 5))

    assert eq(x, np.array(d))

Prompt: Migrate tests for dask array conversions from dask package.


import unittest
from rcsparse import rcsfile
from os.path import dirname, join

REV_NUMBER = 0
REV_STATE = 3

class Test(unittest.TestCase):

    def test_rcsfile(self):
        f = rcsfile(join(dirname(__file__), 'data', 'patch-copyin_c,v'))
        self.assertEquals(f.head, '1.1')
        self.assertEquals(f.revs[f.head][REV_NUMBER], '1.1')
        self.assertEquals(f.revs[f.head][REV_STATE], 'dead')

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

Add a test case for Simon Schubert's rcsparse library

Response:
import unittest
from rcsparse import rcsfile
from os.path import dirname, join

REV_NUMBER = 0
REV_STATE = 3

class Test(unittest.TestCase):

    def test_rcsfile(self):
        f = rcsfile(join(dirname(__file__), 'data', 'patch-copyin_c,v'))
        self.assertEquals(f.head, '1.1')
        self.assertEquals(f.revs[f.head][REV_NUMBER], '1.1')
        self.assertEquals(f.revs[f.head][REV_STATE], 'dead')

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

Prompt: Add a test case for Simon Schubert's rcsparse library


try:
    from collections import Mapping
except ImportError:
    # compatibility with Python 2.5
    Mapping = dict

def quacks_like_dict(object):
    """Check if object is dict-like"""
    return isinstance(object, Mapping)

def deep_merge(a, b):
    """Merge two deep dicts non-destructively

    Uses a stack to avoid maximum recursion depth exceptions

    >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
    >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
    >>> c = merge(a, b)
    >>> from pprint import pprint; pprint(c)
    {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
    """
    assert quacks_like_dict(a), quacks_like_dict(b)
    dst = a.copy()

    stack = [(dst, b)]
    while stack:
        current_dst, current_src = stack.pop()
        for key in current_src:
            if key not in current_dst:
                current_dst[key] = current_src[key]
            else:
                if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
                    stack.append((current_dst[key], current_src[key]))
                else:
                    current_dst[key] = current_src[key]
    return dst

Response:
try:
    from collections import Mapping
except ImportError:
    # compatibility with Python 2.5
    Mapping = dict

def quacks_like_dict(object):
    """Check if object is dict-like"""
    return isinstance(object, Mapping)

def deep_merge(a, b):
    """Merge two deep dicts non-destructively

    Uses a stack to avoid maximum recursion depth exceptions

    >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
    >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
    >>> c = merge(a, b)
    >>> from pprint import pprint; pprint(c)
    {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
    """
    assert quacks_like_dict(a), quacks_like_dict(b)
    dst = a.copy()

    stack = [(dst, b)]
    while stack:
        current_dst, current_src = stack.pop()
        for key in current_src:
            if key not in current_dst:
                current_dst[key] = current_src[key]
            else:
                if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
                    stack.append((current_dst[key], current_src[key]))
                else:
                    current_dst[key] = current_src[key]
    return dst

Prompt:
Adjust for compatibility with Python 2.5

import collections

def quacks_like_dict(object):
    """Check if object is dict-like"""
    return isinstance(object, collections.Mapping)

def deep_merge(a, b):
    """Merge two deep dicts non-destructively

    Uses a stack to avoid maximum recursion depth exceptions

    >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
    >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
    >>> c = merge(a, b)
    >>> from pprint import pprint; pprint(c)
    {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
    """
    assert quacks_like_dict(a), quacks_like_dict(b)
    dst = a.copy()

    stack = [(dst, b)]
    while stack:
        current_dst, current_src = stack.pop()
        for key in current_src:
            if key not in current_dst:
                current_dst[key] = current_src[key]
            else:
                if quacks_like_dict(current_src[key]) and quacks_like_dict(current_dst[key]) :
                    stack.append((current_dst[key], current_src[key]))
                else:
                    current_dst[key] = current_src[key]
    return dst


from flask import render_template, Blueprint, url_for, \
    redirect, flash, request

from project.models import Category, Webinar

category_blueprint = Blueprint('category', __name__,)

@category_blueprint.route('/categories')
def index():
    categories = Category.query.all()
    return render_template('category/categories.html', categories=categories)

@category_blueprint.route('/category/<category_slug>')
def show(category_slug):
    category = Category.query.filter_by(slug=category_slug)
    return render_template('category/category.html', category=category)

Response:
from flask import render_template, Blueprint, url_for, \
    redirect, flash, request

from project.models import Category, Webinar

category_blueprint = Blueprint('category', __name__,)

@category_blueprint.route('/categories')
def index():
    categories = Category.query.all()
    return render_template('category/categories.html', categories=categories)

@category_blueprint.route('/category/<category_slug>')
def show(category_slug):
    category = Category.query.filter_by(slug=category_slug)
    return render_template('category/category.html', category=category)

Prompt:
Add basic view to see category show page

from flask import render_template, Blueprint, url_for, \
    redirect, flash, request

from project.models import Category, Webinar

category_blueprint = Blueprint('category', __name__,)

@category_blueprint.route('/categories')
def index():
    categories = Category.query.all()
    return render_template('category/categories.html', categories=categories)


from imaplib import IMAP4, IMAP4_SSL

from .base import EmailTransport, MessageParseError

class ImapTransport(EmailTransport):
    def __init__(self, hostname, port=None, ssl=False, archive=''):
        self.hostname = hostname
        self.port = port
        self.archive = archive
        if ssl:
            self.transport = IMAP4_SSL
            if not self.port:
                self.port = 993
        else:
            self.transport = IMAP4
            if not self.port:
                self.port = 143

    def connect(self, username, password):
        self.server = self.transport(self.hostname, self.port)
        typ, msg = self.server.login(username, password)
        self.server.select()

    def get_message(self):
        typ, inbox = self.server.search(None, 'ALL')

        if not inbox[0]:
            return

        if self.archive:
            typ, folders = self.server.list(pattern=self.archive)
            if folders[0] is None:
                # If the archive folder does not exist, create it
                self.server.create(self.archive)

        for key in inbox[0].split():
            try:
                typ, msg_contents = self.server.fetch(key, '(RFC822)')
                message = self.get_email_from_bytes(msg_contents[0][1])
                yield message
            except MessageParseError:
                continue

            if self.archive:
                self.server.copy(key, self.archive)

            self.server.store(key, "+FLAGS", "\\Deleted")
        self.server.expunge()
        return

Response:
from imaplib import IMAP4, IMAP4_SSL

from .base import EmailTransport, MessageParseError

class ImapTransport(EmailTransport):
    def __init__(self, hostname, port=None, ssl=False, archive=''):
        self.hostname = hostname
        self.port = port
        self.archive = archive
        if ssl:
            self.transport = IMAP4_SSL
            if not self.port:
                self.port = 993
        else:
            self.transport = IMAP4
            if not self.port:
                self.port = 143

    def connect(self, username, password):
        self.server = self.transport(self.hostname, self.port)
        typ, msg = self.server.login(username, password)
        self.server.select()

    def get_message(self):
        typ, inbox = self.server.search(None, 'ALL')

        if not inbox[0]:
            return

        if self.archive:
            typ, folders = self.server.list(pattern=self.archive)
            if folders[0] is None:
                # If the archive folder does not exist, create it
                self.server.create(self.archive)

        for key in inbox[0].split():
            try:
                typ, msg_contents = self.server.fetch(key, '(RFC822)')
                message = self.get_email_from_bytes(msg_contents[0][1])
                yield message
            except MessageParseError:
                continue

            if self.archive:
                self.server.copy(key, self.archive)

            self.server.store(key, "+FLAGS", "\\Deleted")
        self.server.expunge()
        return

Prompt:
Create archive folder if it does not exist.

from imaplib import IMAP4, IMAP4_SSL

from .base import EmailTransport, MessageParseError

class ImapTransport(EmailTransport):
    def __init__(self, hostname, port=None, ssl=False, archive=''):
        self.hostname = hostname
        self.port = port
        self.archive = archive
        if ssl:
            self.transport = IMAP4_SSL
            if not self.port:
                self.port = 993
        else:
            self.transport = IMAP4
            if not self.port:
                self.port = 143

    def connect(self, username, password):
        self.server = self.transport(self.hostname, self.port)
        typ, msg = self.server.login(username, password)
        self.server.select()

    def get_message(self):
        typ, inbox = self.server.search(None, 'ALL')

        if not inbox[0]:
            return

        if self.archive:
            typ, folders = self.server.list(pattern=self.archive)
            if folders[0] == None:
                self.archive = False

        for key in inbox[0].split():
            try:
                typ, msg_contents = self.server.fetch(key, '(RFC822)')
                message = self.get_email_from_bytes(msg_contents[0][1])
                yield message
            except MessageParseError:
                continue

            if self.archive:
                self.server.copy(key, self.archive)

            self.server.store(key, "+FLAGS", "\\Deleted")
        self.server.expunge()
        return


"""
==============
Hinton diagram
==============

Hinton diagrams are useful for visualizing the values of a 2D array: Positive
and negative values are represented by white and black squares, respectively,
and the size of each square represents the magnitude of each value.

``special.hinton`` is based off of the `Hinton demo`_ in the matplotlib gallery. This implementation, however, uses a ``RegularPolyCollection`` to draw
squares, which is much more efficient than drawing individual rectangles.

Obscure example use: For my Ph.D., I wrote a numerical solver using
finite-differences. For speed, the Jacobian matrices were calculated
analytically, which was incredibly-prone to bugs. To debug my code,
I calculated the numerical Jacobian (calculated using
``scipy.optimize.slsqp.approx_jacobian``) and plotted the Hinton diagram for
the difference of the numerical and analytical results. That allowed me to
narrow down where the bugs were (boundary conditions!) instead of blindly
checking every equation. You could, of course, use ``pcolor`` or ``imshow`` in
a similar situation.

.. _Hinton demo: http://matplotlib.sourceforge.net/examples/api/hinton_demo.html

"""
import numpy as np
import matplotlib.pyplot as plt

from mpltools import special

A = np.random.uniform(-1, 1, size=(20, 20))
special.hinton(A)
plt.show()

Clean up hinton example text.

DOC: Clean up hinton example text.

Response:
"""
==============
Hinton diagram
==============

Hinton diagrams are useful for visualizing the values of a 2D array: Positive
and negative values are represented by white and black squares, respectively,
and the size of each square represents the magnitude of each value.

``special.hinton`` is based off of the `Hinton demo`_ in the matplotlib gallery. This implementation, however, uses a ``RegularPolyCollection`` to draw
squares, which is much more efficient than drawing individual rectangles.

Obscure example use: For my Ph.D., I wrote a numerical solver using
finite-differences. For speed, the Jacobian matrices were calculated
analytically, which was incredibly-prone to bugs. To debug my code,
I calculated the numerical Jacobian (calculated using
``scipy.optimize.slsqp.approx_jacobian``) and plotted the Hinton diagram for
the difference of the numerical and analytical results. That allowed me to
narrow down where the bugs were (boundary conditions!) instead of blindly
checking every equation. You could, of course, use ``pcolor`` or ``imshow`` in
a similar situation.

.. _Hinton demo: http://matplotlib.sourceforge.net/examples/api/hinton_demo.html

"""
import numpy as np
import matplotlib.pyplot as plt

from mpltools import special

A = np.random.uniform(-1, 1, size=(20, 20))
special.hinton(A)
plt.show()

Prompt:
DOC: Clean up hinton example text.

"""
==============
Hinton diagram
==============

Hinton diagrams are useful for visualizing the values of a 2D array. Positive
and negative values represented by white and black squares, respectively, and
the size of each square represents the magnitude of each value.

The `special.hinton` function is based off of the Hinton demo in the matplotlib
gallery [1]_. This implementation, however, uses a `RegularPolyCollection` to
draw squares, which is much more efficient than drawing individual rectangles.

Obscure example use: For my Ph.D., I wrote a numerical solver using
finite-differences and writing down Jacobian matrices analytically, was
incredibly-prone to bugs. To debug my code, I calculated the numerical Jacobian
(calculated using `scipy.optimize.slsqp.approx_jacobian`) and plotted the
Hinton diagram for for the difference of the numerical and analytical results.
You could, of course, use `pcolor` or `imshow` in a similar situation.

"""
import numpy as np
import matplotlib.pyplot as plt

from mpltools import special

A = np.random.uniform(-1, 1, size=(20, 20))
special.hinton(A)
plt.show()


"""
This module contains the SESBackend class, which is what you'll want to set in
your settings.py::

    EMAIL_BACKEND = 'seacucumber.backend.SESBackend'
"""
from django.core.mail.backends.base import BaseEmailBackend
from seacucumber.tasks import SendEmailTask

class SESBackend(BaseEmailBackend):
    """
    A Django Email backend that uses Amazon's Simple Email Service.
    """
    def send_messages(self, email_messages):
        """
        Sends one or more EmailMessage objects and returns the number of
        email messages sent.

        :param EmailMessage email_messages: A list of Django's EmailMessage
            object instances.
        :rtype: int
        :returns: The number of EmailMessage objects that were successfully
            queued up. Note that these are not in a state where we can
            guarantee delivery just yet.
        """
        num_sent = 0
        for message in email_messages:
            # Hand this off to a celery task.
            SendEmailTask.delay(
                message.from_email,
                message.recipients(),
                message.message().as_string().decode('utf8'),
            )
            num_sent += 1
        return num_sent

Patch to send mails with UTF8 encoding

Response:
"""
This module contains the SESBackend class, which is what you'll want to set in
your settings.py::

    EMAIL_BACKEND = 'seacucumber.backend.SESBackend'
"""
from django.core.mail.backends.base import BaseEmailBackend
from seacucumber.tasks import SendEmailTask

class SESBackend(BaseEmailBackend):
    """
    A Django Email backend that uses Amazon's Simple Email Service.
    """
    def send_messages(self, email_messages):
        """
        Sends one or more EmailMessage objects and returns the number of
        email messages sent.

        :param EmailMessage email_messages: A list of Django's EmailMessage
            object instances.
        :rtype: int
        :returns: The number of EmailMessage objects that were successfully
            queued up. Note that these are not in a state where we can
            guarantee delivery just yet.
        """
        num_sent = 0
        for message in email_messages:
            # Hand this off to a celery task.
            SendEmailTask.delay(
                message.from_email,
                message.recipients(),
                message.message().as_string().decode('utf8'),
            )
            num_sent += 1
        return num_sent

Prompt:
Patch to send mails with UTF8 encoding

Just a temp fix

"""
This module contains the SESBackend class, which is what you'll want to set in
your settings.py::

    EMAIL_BACKEND = 'seacucumber.backend.SESBackend'
"""
from django.core.mail.backends.base import BaseEmailBackend
from seacucumber.tasks import SendEmailTask

class SESBackend(BaseEmailBackend):
    """
    A Django Email backend that uses Amazon's Simple Email Service.
    """
    def send_messages(self, email_messages):
        """
        Sends one or more EmailMessage objects and returns the number of
        email messages sent.

        :param EmailMessage email_messages: A list of Django's EmailMessage
            object instances.
        :rtype: int
        :returns: The number of EmailMessage objects that were successfully
            queued up. Note that these are not in a state where we can
            guarantee delivery just yet.
        """
        num_sent = 0
        for message in email_messages:
            # Hand this off to a celery task.
            SendEmailTask.delay(
                message.from_email,
                message.recipients(),
                message.message().as_string(),
            )
            num_sent += 1
        return num_sent


import xml.dom.minidom
from xml.dom.minidom import Node
import time
import sys, os

PROPERTIES = {2: ("nie:title", str),
              3: ("nfo:uri", str),
              4: ("nie:usageCounter", int),
              6: ("nie:lastRefreshed", time.struct_time)}
# Use time.struct_time as type for dates, even when the format is not that!

def get_text (node):
    text = ""
    for subnode in node.childNodes:
      if subnode.nodeType == Node.TEXT_NODE:
        text += subnode.data
    return text.encode ('utf8').replace ('"', '') # Use a safer method!

def process_file (filename):
    doc = xml.dom.minidom.parse(filename)

    for node in doc.getElementsByTagName ("node"):
        print "<uri:uuid:epiphany-webhistory-%s> a nfo:WebHistory" % (node.getAttribute ("id")),

        for prop in node.getElementsByTagName ("property"):
            prop_id = int(prop.getAttribute ("id"))

            if (PROPERTIES.has_key (prop_id)):
                prop_name, prop_type = PROPERTIES [prop_id]

                if (prop_type == str):
                    print  ';\n\t%s "%s"' % (prop_name, get_text (prop)),

                elif (prop_type == int):
                    print ';\n\t%s %s' % (prop_name, get_text (prop)),

                elif (prop_type == time.struct_time):
                    print ';\n\t%s "%s"' % (prop_name, time.strftime ("%Y%m%dT%H:%m:%S",time.localtime (int(get_text (prop))))),
        print ".\n"

def print_headers ():
    print "@prefix nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>."
    print "@prefix nie: <http://www.semanticdesktop.org/ontologies/2007/01/19/nie#> ."

if __name__ == "__main__":

    epi_history = os.path.join (os.getenv ("HOME"), ".gnome2", "epiphany", "ephy-history.xml")
    print >> sys.stderr, "Scanning", epi_history

    print_headers ()
    if (os.path.exists (epi_history)):
        process_file (epi_history)

Add util to generate real webhistory

Add util to generate real webhistory

Added program that reads epiphany web browsing history and print it
in turtle format.

Response:
import xml.dom.minidom
from xml.dom.minidom import Node
import time
import sys, os

PROPERTIES = {2: ("nie:title", str),
              3: ("nfo:uri", str),
              4: ("nie:usageCounter", int),
              6: ("nie:lastRefreshed", time.struct_time)}
# Use time.struct_time as type for dates, even when the format is not that!

def get_text (node):
    text = ""
    for subnode in node.childNodes:
      if subnode.nodeType == Node.TEXT_NODE:
        text += subnode.data
    return text.encode ('utf8').replace ('"', '') # Use a safer method!

def process_file (filename):
    doc = xml.dom.minidom.parse(filename)

    for node in doc.getElementsByTagName ("node"):
        print "<uri:uuid:epiphany-webhistory-%s> a nfo:WebHistory" % (node.getAttribute ("id")),

        for prop in node.getElementsByTagName ("property"):
            prop_id = int(prop.getAttribute ("id"))

            if (PROPERTIES.has_key (prop_id)):
                prop_name, prop_type = PROPERTIES [prop_id]

                if (prop_type == str):
                    print  ';\n\t%s "%s"' % (prop_name, get_text (prop)),

                elif (prop_type == int):
                    print ';\n\t%s %s' % (prop_name, get_text (prop)),

                elif (prop_type == time.struct_time):
                    print ';\n\t%s "%s"' % (prop_name, time.strftime ("%Y%m%dT%H:%m:%S",time.localtime (int(get_text (prop))))),
        print ".\n"

def print_headers ():
    print "@prefix nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#>."
    print "@prefix nie: <http://www.semanticdesktop.org/ontologies/2007/01/19/nie#> ."

if __name__ == "__main__":

    epi_history = os.path.join (os.getenv ("HOME"), ".gnome2", "epiphany", "ephy-history.xml")
    print >> sys.stderr, "Scanning", epi_history

    print_headers ()
    if (os.path.exists (epi_history)):
        process_file (epi_history)

Prompt:
Add util to generate real webhistory

Added program that reads epiphany web browsing history and print it
in turtle format.


RAW_VALUE_BY_DEFAULT = False

def env_to_statement(env):
    ''' Return the abstraction description of an environment variable definition
    into a statement for shell script.

    >>> env_to_statement(dict(name='X', value='Y'))
    'X="Y"; export X'
    >>> env_to_statement(dict(name='X', value='Y', raw=True))
    'X=Y; export X'
    >>> env_to_statement(dict(name='X', value='"A","B","C"'))
    'X="\\\\"A\\\\",\\\\"B\\\\",\\\\"C\\\\""; export X'
    '''
    name = env['name']
    value = env['value']
    raw = env.get('raw', RAW_VALUE_BY_DEFAULT)
    if not raw:
        value = '"' + value.replace('"', '\\"') + '"'
    return '%s=%s; export %s' % (name, value, name)

Add missing file from previous commit (thanks Izzet Fatih).

Response:
RAW_VALUE_BY_DEFAULT = False

def env_to_statement(env):
    ''' Return the abstraction description of an environment variable definition
    into a statement for shell script.

    >>> env_to_statement(dict(name='X', value='Y'))
    'X="Y"; export X'
    >>> env_to_statement(dict(name='X', value='Y', raw=True))
    'X=Y; export X'
    >>> env_to_statement(dict(name='X', value='"A","B","C"'))
    'X="\\\\"A\\\\",\\\\"B\\\\",\\\\"C\\\\""; export X'
    '''
    name = env['name']
    value = env['value']
    raw = env.get('raw', RAW_VALUE_BY_DEFAULT)
    if not raw:
        value = '"' + value.replace('"', '\\"') + '"'
    return '%s=%s; export %s' % (name, value, name)

Prompt: Add missing file from previous commit (thanks Izzet Fatih).


import pytest

from django.core.exceptions import ObjectDoesNotExist

from adhocracy4.ratings import models

@pytest.mark.django_db
def test_delete_of_content_object(rating):
    question = rating.content_object
    question.delete()

    with pytest.raises(ObjectDoesNotExist):
        models.Rating.objects.get(id=rating.id)

Add test for rating signals

Add test for rating signals

Response:
import pytest

from django.core.exceptions import ObjectDoesNotExist

from adhocracy4.ratings import models

@pytest.mark.django_db
def test_delete_of_content_object(rating):
    question = rating.content_object
    question.delete()

    with pytest.raises(ObjectDoesNotExist):
        models.Rating.objects.get(id=rating.id)

Prompt: Add test for rating signals