from flask import Flask, render_template
from redis import StrictRedis
import random
import config

app = Flask(__name__)
app.debug = config.DEBUG

db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)

@app.route('/')
def main():
    available_quizzes = db.smembers('quizzes')
    return render_template('main.html', quizzes=available_quizzes)

@app.route('/quiz/start/<quiz_url_name>')
def start_quiz(quiz_url_name):
    description, created_by, quiz_name = db.hmget(quiz_url_name,
            'description', 'created_by', 'quiz_name')
    return render_template('quiz-start.html', quiz_name=quiz_name,
            description=description, created_by=created_by,
            quiz_url_name=quiz_url_name)

@app.route('/quiz/<quiz_url_name>')
def quiz(quiz_url_name):
    #FIXME: naive random implementation, needs to be score-weighted
    hash_name = "{0}:questions".format(quiz_url_name)
    all_questions = db.hkeys(hash_name)
    question = random.choice(all_questions)
    answer = db.hget(hash_name, question)
    quiz_name = db.hget(quiz_url_name, 'quiz_name')

    return render_template('quiz.html', quiz_name=quiz_name,
            question=question, answer=answer,
            quiz_url_name=quiz_url_name)

if __name__ == '__main__':
    app.run()

Change key lookups and fix typos

Response:
from flask import Flask, render_template
from redis import StrictRedis
import random
import config

app = Flask(__name__)
app.debug = config.DEBUG

db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)

@app.route('/')
def main():
    available_quizzes = db.smembers('quizzes')
    return render_template('main.html', quizzes=available_quizzes)

@app.route('/quiz/start/<quiz_url_name>')
def start_quiz(quiz_url_name):
    description, created_by, quiz_name = db.hmget(quiz_url_name,
            'description', 'created_by', 'quiz_name')
    return render_template('quiz-start.html', quiz_name=quiz_name,
            description=description, created_by=created_by,
            quiz_url_name=quiz_url_name)

@app.route('/quiz/<quiz_url_name>')
def quiz(quiz_url_name):
    #FIXME: naive random implementation, needs to be score-weighted
    hash_name = "{0}:questions".format(quiz_url_name)
    all_questions = db.hkeys(hash_name)
    question = random.choice(all_questions)
    answer = db.hget(hash_name, question)
    quiz_name = db.hget(quiz_url_name, 'quiz_name')

    return render_template('quiz.html', quiz_name=quiz_name,
            question=question, answer=answer,
            quiz_url_name=quiz_url_name)

if __name__ == '__main__':
    app.run()

Prompt:
Change key lookups and fix typos

Revamped the way URLs were handled from Redis by differentiating the URL
friendly name from the actual name. Fixed bad paths in render_template
for all routes.

from flask import Flask, render_template
from redis import StrictRedis
import random
import config

app = Flask(__name__)
app.debug = config.DEBUG

db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)

@app.route('/')
def main():
    available_quizzes = db.smembers('quizzes')
    return render_template('templates/main.html', quizzes=available_quizzes)

@app.route('/quiz/start/<quiz_name>')
def start_quiz(quiz_name):
    return render_template('templates/quiz-start.html', quiz_name=quiz_name)

@app.route('/quiz/<quiz_name>')
def quiz(quiz_name):
    #FIXME: naive random implementation, needs to be score-weighted
    all_questions = db.hkeys(quiz_name)
    question = random.choice(all_questions)
    answer = db.hget(quiz_name, question)

    return render_template('templates/quiz.html', quiz_name=quiz_name,
            question=question, answer=answer)


"""Command to import PMG's constitiency office data

PMG are undertaking an exercise to visit all the constituency
offices and collect accurate locations and photographs.
The data from this is available at

https://app.m4jam.com/app/campaigns/2298/export/

This script parses the resulting CSV file and updates our data
on constituency offices to have the correct location.
"""

import csv
import re

from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.geos import Point

from pombola.core.models import (
    Organisation,
    )

# Matches the format of the locations in the CSV we get from PMG.
location_re = re.compile(
    r'SRID=4326;POINT\((-?[0-9]+\.[0-9]+) (-?[0-9]+\.[0-9]+)\)')

class Command(BaseCommand):
    args = '<path to csv file>'
    help = 'Updates constituency offices based on the supplied CSV file.'

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError(
                "You must provide the path to the CSV file as an argument."
                )

        constituency_offices = Organisation.objects.filter(
            kind__slug='constituency-office')

        with open(args[0]) as csvfile:
            reader = csv.DictReader(csvfile)

            for row in reader:
                poi_ref = row['POI_REFERENCE']
                party, name = (
                    re.match(
                        '(.*) Constituency Office (.*)', poi_ref
                        ).groups()
                    )
                name = re.sub('\s+', ' ', name)

                qs = constituency_offices.filter(
                    name__regex=r'^{}.+: {}$'.format(party, name))

                try:
                    org = qs.get()
                except Organisation.MultipleObjectsReturned:
                    print "Skipping {} as multiple orgs returned: {}".format(
                        poi_ref,
                        repr(qs),
                        )
                    continue
                except Organisation.DoesNotExist:
                    # Fall back to searching for the name and the party in the
                    # constituency office name
                    qs = (
                        Organisation.objects
                        .filter(kind__slug='constituency-office')
                        .filter(name__contains=name)
                        .filter(name__contains=party)
                        )

                    org = qs.get()

                place = (
                    org.place_set
                    .filter(name__contains='Approximate position of')
                    .filter(kind__slug='constituency-office')
                    .get()  # There should be only one.
                    )

                lon, lat = location_re.match(row['Constituency_Pin']).groups()

                place.location = Point(float(lon), float(lat))
                place.save()

Add a script to import new constituency office locations.

PMG are conducting an exercise to go to all the constituency offices
and get accurate locations for them and photographs. The data they
collect is available as a CSV, and this new management command
processes that CSV and updates our data with the improved locations.

Response:
"""Command to import PMG's constitiency office data

PMG are undertaking an exercise to visit all the constituency
offices and collect accurate locations and photographs.
The data from this is available at

https://app.m4jam.com/app/campaigns/2298/export/

This script parses the resulting CSV file and updates our data
on constituency offices to have the correct location.
"""

import csv
import re

from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.geos import Point

from pombola.core.models import (
    Organisation,
    )

# Matches the format of the locations in the CSV we get from PMG.
location_re = re.compile(
    r'SRID=4326;POINT\((-?[0-9]+\.[0-9]+) (-?[0-9]+\.[0-9]+)\)')

class Command(BaseCommand):
    args = '<path to csv file>'
    help = 'Updates constituency offices based on the supplied CSV file.'

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError(
                "You must provide the path to the CSV file as an argument."
                )

        constituency_offices = Organisation.objects.filter(
            kind__slug='constituency-office')

        with open(args[0]) as csvfile:
            reader = csv.DictReader(csvfile)

            for row in reader:
                poi_ref = row['POI_REFERENCE']
                party, name = (
                    re.match(
                        '(.*) Constituency Office (.*)', poi_ref
                        ).groups()
                    )
                name = re.sub('\s+', ' ', name)

                qs = constituency_offices.filter(
                    name__regex=r'^{}.+: {}$'.format(party, name))

                try:
                    org = qs.get()
                except Organisation.MultipleObjectsReturned:
                    print "Skipping {} as multiple orgs returned: {}".format(
                        poi_ref,
                        repr(qs),
                        )
                    continue
                except Organisation.DoesNotExist:
                    # Fall back to searching for the name and the party in the
                    # constituency office name
                    qs = (
                        Organisation.objects
                        .filter(kind__slug='constituency-office')
                        .filter(name__contains=name)
                        .filter(name__contains=party)
                        )

                    org = qs.get()

                place = (
                    org.place_set
                    .filter(name__contains='Approximate position of')
                    .filter(kind__slug='constituency-office')
                    .get()  # There should be only one.
                    )

                lon, lat = location_re.match(row['Constituency_Pin']).groups()

                place.location = Point(float(lon), float(lat))
                place.save()

Prompt:
Add a script to import new constituency office locations.

PMG are conducting an exercise to go to all the constituency offices
and get accurate locations for them and photographs. The data they
collect is available as a CSV, and this new management command
processes that CSV and updates our data with the improved locations.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
sys.path.insert(0, os.path.abspath(".."))
from pyqode.core import backend

if __name__ == '__main__':
    print('Server started')
    print(sys.path)
    print(os.getcwd())
    backend.CodeCompletionWorker.providers.append(
        backend.DocumentWordsProvider())
    backend.serve_forever()

Response:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
sys.path.insert(0, os.path.abspath(".."))
from pyqode.core import backend

if __name__ == '__main__':
    print('Server started')
    print(sys.path)
    print(os.getcwd())
    backend.CodeCompletionWorker.providers.append(
        backend.DocumentWordsProvider())
    backend.serve_forever()

Prompt:
Fix test suite on travis (restore previous path config)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Server used for tests
"""
import sys
import os
# ensure sys knows about pyqode.core in the test env
sys.path.insert(0, os.getcwd())
from pyqode.core import backend

if __name__ == '__main__':
    print('Server started')
    print(sys.path)
    print(os.getcwd())
    backend.CodeCompletionWorker.providers.append(
        backend.DocumentWordsProvider())
    backend.serve_forever()


"""
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.

Usage as a context manager:

    with manual_report("stats entry name"):
        # Run time of this block will be reported under a stats entry called "stats entry name"
        # do stuff here, if an Exception is raised, it'll be reported as a failure

Usage as a decorator:

    @task
    @manual_report
    def my_task(self):
       # The run time of this task will be reported under a stats entry called "my task" (type "manual").
       # If an Exception is raised, it'll be reported as a failure

"""

import random
from contextlib import contextmanager, ContextDecorator
from time import time, sleep

from locust import User, task, constant, events

@contextmanager
def _manual_report(name):
    start_time = time()
    try:
        yield
    except Exception as e:
        events.request_failure.fire(
            request_type="manual",
            name=name,
            response_time=(time() - start_time) * 1000,
            response_length=0,
            exception=e,
        )
        raise
    else:
        events.request_success.fire(
            request_type="manual",
            name=name,
            response_time=(time() - start_time) * 1000,
            response_length=0,
        )

def manual_report(name_or_func):
    if callable(name_or_func):
        # used as decorator without name argument specified
        return _manual_report(name_or_func.__name__)(name_or_func)
    else:
        return _manual_report(name_or_func)

class MyUser(User):
    wait_time = constant(1)

    @task
    def successful_task(self):
        with manual_report("successful_task"):
            sleep(random.random())

    @task
    @manual_report
    def decorator_test(self):
        if random.random() > 0.5:
            raise Exception("decorator_task failed")
        sleep(random.random())

    @task
    def failing_task(self):
        with manual_report("failing_task"):
            sleep(random.random())
            raise Exception("Oh nooes!")

Add example with a manual_report decorator/context manager that can be used to easily measure the time of functions/code blocks and manually report them as stats entries to the Locust statistics

Response:
"""
Example of a manual_report() function that can be used either as a context manager
(with statement), or a decorator, to manually add entries to Locust's statistics.

Usage as a context manager:

    with manual_report("stats entry name"):
        # Run time of this block will be reported under a stats entry called "stats entry name"
        # do stuff here, if an Exception is raised, it'll be reported as a failure

Usage as a decorator:

    @task
    @manual_report
    def my_task(self):
       # The run time of this task will be reported under a stats entry called "my task" (type "manual").
       # If an Exception is raised, it'll be reported as a failure

"""

import random
from contextlib import contextmanager, ContextDecorator
from time import time, sleep

from locust import User, task, constant, events

@contextmanager
def _manual_report(name):
    start_time = time()
    try:
        yield
    except Exception as e:
        events.request_failure.fire(
            request_type="manual",
            name=name,
            response_time=(time() - start_time) * 1000,
            response_length=0,
            exception=e,
        )
        raise
    else:
        events.request_success.fire(
            request_type="manual",
            name=name,
            response_time=(time() - start_time) * 1000,
            response_length=0,
        )

def manual_report(name_or_func):
    if callable(name_or_func):
        # used as decorator without name argument specified
        return _manual_report(name_or_func.__name__)(name_or_func)
    else:
        return _manual_report(name_or_func)

class MyUser(User):
    wait_time = constant(1)

    @task
    def successful_task(self):
        with manual_report("successful_task"):
            sleep(random.random())

    @task
    @manual_report
    def decorator_test(self):
        if random.random() > 0.5:
            raise Exception("decorator_task failed")
        sleep(random.random())

    @task
    def failing_task(self):
        with manual_report("failing_task"):
            sleep(random.random())
            raise Exception("Oh nooes!")

Prompt: Add example with a manual_report decorator/context manager that can be used to easily measure the time of functions/code blocks and manually report them as stats entries to the Locust statistics


from unittest import TestCase

from pymemcache.serde import (python_memcache_serializer,
                              python_memcache_deserializer, FLAG_PICKLE,
                              FLAG_INTEGER, FLAG_LONG, FLAG_TEXT)
import pytest
import six

@pytest.mark.unit()
class TestSerde(TestCase):

    def check(self, value, expected_flags=0):
        serialized, flags = python_memcache_serializer(b'key', value)
        assert flags == expected_flags

        # pymemcache stores values as byte strings, so we immediately the value
        # if needed so deserialized works as it would with a real server
        if not isinstance(serialized, six.binary_type):
            serialized = six.text_type(serialized).encode('ascii')

        deserialized = python_memcache_deserializer(b'key', serialized, flags)
        assert deserialized == value

    def test_bytes(self):
        self.check(b'value')

    def test_unicode(self):
        self.check(u'value', FLAG_TEXT)

    def test_int(self):
        self.check(1, FLAG_INTEGER)

    def test_long(self):
        # long only exists with Python 2, so we're just testing for another
        # integer with Python 3
        if six.PY2:
            expected_flags = FLAG_LONG
        else:
            expected_flags = FLAG_INTEGER
        self.check(123123123123123123123, expected_flags)

    def test_pickleable(self):
        self.check({'a': 'dict'}, FLAG_PICKLE)

Response:
from unittest import TestCase

from pymemcache.serde import (python_memcache_serializer,
                              python_memcache_deserializer, FLAG_PICKLE,
                              FLAG_INTEGER, FLAG_LONG, FLAG_TEXT)
import pytest
import six

@pytest.mark.unit()
class TestSerde(TestCase):

    def check(self, value, expected_flags=0):
        serialized, flags = python_memcache_serializer(b'key', value)
        assert flags == expected_flags

        # pymemcache stores values as byte strings, so we immediately the value
        # if needed so deserialized works as it would with a real server
        if not isinstance(serialized, six.binary_type):
            serialized = six.text_type(serialized).encode('ascii')

        deserialized = python_memcache_deserializer(b'key', serialized, flags)
        assert deserialized == value

    def test_bytes(self):
        self.check(b'value')

    def test_unicode(self):
        self.check(u'value', FLAG_TEXT)

    def test_int(self):
        self.check(1, FLAG_INTEGER)

    def test_long(self):
        # long only exists with Python 2, so we're just testing for another
        # integer with Python 3
        if six.PY2:
            expected_flags = FLAG_LONG
        else:
            expected_flags = FLAG_INTEGER
        self.check(123123123123123123123, expected_flags)

    def test_pickleable(self):
        self.check({'a': 'dict'}, FLAG_PICKLE)

Prompt:
Test for expected flags with serde tests

from unittest import TestCase

from pymemcache.serde import (python_memcache_serializer,
                              python_memcache_deserializer)
import pytest
import six

@pytest.mark.unit()
class TestSerde(TestCase):

    def check(self, value):
        serialized, flags = python_memcache_serializer(b'key', value)

        # pymemcache stores values as byte strings, so we immediately the value
        # if needed so deserialized works as it would with a real server
        if not isinstance(serialized, six.binary_type):
            serialized = six.text_type(serialized).encode('ascii')

        deserialized = python_memcache_deserializer(b'key', serialized, flags)
        assert deserialized == value

    def test_bytes(self):
        self.check(b'value')

    def test_unicode(self):
        self.check(u'value')

    def test_int(self):
        self.check(1)

    def test_long(self):
        self.check(123123123123123123123)

    def test_pickleable(self):
        self.check({'a': 'dict'})


import os
import sysctl
from sysctl.tests import SysctlTestBase

class TestSysctlANum(SysctlTestBase):

    def test_sysctl_setvalue(self):
        dummy = sysctl.filter('kern.dummy')[0]
        try:
            self.command("/sbin/sysctl kern.dummy=0")
        except:
            if os.getuid() == 0:
                raise

        try:
            dummy.value = 1
        except TypeError:
            if os.getuid() == 0:
                raise

        if os.getuid() == 0:
            value = int(self.command("/sbin/sysctl -n kern.dummy"))
            if value != 1:
                raise ValueError("Failed to set kern.dummy")

Add test to set a sysctl value

Add test to set a sysctl value

Response:
import os
import sysctl
from sysctl.tests import SysctlTestBase

class TestSysctlANum(SysctlTestBase):

    def test_sysctl_setvalue(self):
        dummy = sysctl.filter('kern.dummy')[0]
        try:
            self.command("/sbin/sysctl kern.dummy=0")
        except:
            if os.getuid() == 0:
                raise

        try:
            dummy.value = 1
        except TypeError:
            if os.getuid() == 0:
                raise

        if os.getuid() == 0:
            value = int(self.command("/sbin/sysctl -n kern.dummy"))
            if value != 1:
                raise ValueError("Failed to set kern.dummy")

Prompt: Add test to set a sysctl value


"""Adaptive configuration dialogs.

Attributes:
    __version__: The current version string.
"""

import os
import subprocess

def _get_version(version=None):  # overwritten by setup.py
    if version is None:
        pkg_dir = os.path.dirname(__file__)
        src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
        git_dir = os.path.join(src_dir, ".git")
        git_args = ("git", "--work-tree", src_dir, "--git-dir",
                    git_dir, "describe", "--tags", "--always")
        output = subprocess.check_output(git_args)
        version = output.decode("utf-8").strip()
        if version.rfind("-") >= 0:
            version = version[:version.rfind("-")]  # strip SHA1 hash
            version = version.replace("-", ".post")  # PEP 440 compatible
    return version

__version__ = _get_version()

Response:
"""Adaptive configuration dialogs.

Attributes:
    __version__: The current version string.
"""

import os
import subprocess

def _get_version(version=None):  # overwritten by setup.py
    if version is None:
        pkg_dir = os.path.dirname(__file__)
        src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
        git_dir = os.path.join(src_dir, ".git")
        git_args = ("git", "--work-tree", src_dir, "--git-dir",
                    git_dir, "describe", "--tags", "--always")
        output = subprocess.check_output(git_args)
        version = output.decode("utf-8").strip()
        if version.rfind("-") >= 0:
            version = version[:version.rfind("-")]  # strip SHA1 hash
            version = version.replace("-", ".post")  # PEP 440 compatible
    return version

__version__ = _get_version()

Prompt:
Use git describe --always in _get_version()

Travis CI does a truncated clone and causes 'git describe' to fail if
the version tag is not part of the truncated history.

"""Adaptive configuration dialogs.

Attributes:
    __version__: The current version string.
"""

import os
import subprocess

def _get_version(version=None):  # overwritten by setup.py
    if version is None:
        pkg_dir = os.path.dirname(__file__)
        src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir))
        git_dir = os.path.join(src_dir, ".git")
        git_args = ("git", "--work-tree", src_dir, "--git-dir",
                    git_dir, "describe", "--tags")
        output = subprocess.check_output(git_args)
        version = output.decode("utf-8").strip()
        if version.rfind("-") >= 0:
            version = version[:version.rfind("-")]  # strip SHA1 hash
            version = version.replace("-", ".post")  # PEP 440 compatible
    return version

__version__ = _get_version()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import random

import pytest

from ..pages.home import HomePage

@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
    page = HomePage(base_url, selenium).open()
    initial = page.footer.language
    # avoid selecting the same language or locales that have homepage redirects
    excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
    available = [l for l in page.footer.languages if l not in excluded]
    new = random.choice(available)
    page.footer.select_language(new)
    assert '/{0}/'.format(new) in selenium.current_url, 'Language is not in URL'
    assert new == page.footer.language, 'Language has not been selected'

Response:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import random

import pytest

from ..pages.home import HomePage

@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
    page = HomePage(base_url, selenium).open()
    initial = page.footer.language
    # avoid selecting the same language or locales that have homepage redirects
    excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
    available = [l for l in page.footer.languages if l not in excluded]
    new = random.choice(available)
    page.footer.select_language(new)
    assert '/{0}/'.format(new) in selenium.current_url, 'Language is not in URL'
    assert new == page.footer.language, 'Language has not been selected'

Prompt:
Fix intermittent failure in l10n language selector test

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import random

import pytest

from ..pages.home import HomePage

@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
    page = HomePage(base_url, selenium).open()
    initial = page.footer.language
    # avoid selecting the same language or locales that have homepage redirects
    excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
    available = [l for l in page.footer.languages if l not in excluded]
    new = random.choice(available)
    page.footer.select_language(new)
    assert new in selenium.current_url, 'Language is not in URL'
    assert new == page.footer.language, 'Language has not been selected'


#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Configuration file for ipython-notebook.

c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888

# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.tornado_settings = {
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}

Configure the IPython notebook user settings

Response:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Configuration file for ipython-notebook.

c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888

# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.tornado_settings = {
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}

Prompt: Configure the IPython notebook user settings


import plata

def plata_context(request):
    """
    Adds a few variables from Plata to the context if they are available:

    * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
    * ``plata.order``: The current order
    * ``plata.contact``: The current contact instance
    * ``plata.price_includes_tax``: Whether prices include tax or not
    """

    shop = plata.shop_instance()
    if not shop:
        return {}

    return {'plata': {
        'shop': shop,
        'order': shop.order_from_request(request),
        'contact': shop.contact_from_user(request.user),
        'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX,
        }}

Response:
import plata

def plata_context(request):
    """
    Adds a few variables from Plata to the context if they are available:

    * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
    * ``plata.order``: The current order
    * ``plata.contact``: The current contact instance
    * ``plata.price_includes_tax``: Whether prices include tax or not
    """

    shop = plata.shop_instance()
    if not shop:
        return {}

    return {'plata': {
        'shop': shop,
        'order': shop.order_from_request(request),
        'contact': shop.contact_from_user(request.user),
        'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX,
        }}

Prompt:
Add the variable `plata.price_includes_tax` to the template context

import plata

def plata_context(request):
    """
    Adds a few variables from Plata to the context if they are available:

    * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
    * ``plata.order``: The current order
    * ``plata.contact``: The current contact instance
    """

    shop = plata.shop_instance()
    if not shop:
        return {}

    return {'plata': {
        'shop': shop,
        'order': shop.order_from_request(request),
        'contact': shop.contact_from_user(request.user),
        }}


from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language

from simpleseo import settings
from simpleseo.models import SeoMetadata

register = Library()

@register.filter
def single_quotes(description):
    return description.replace('\"', '\'')

@register.inclusion_tag('simpleseo/metadata.html', takes_context=True)
def get_seo(context, **kwargs):
    path = context['request'].path
    lang_code = get_language()[:2]
    try:
        metadata = model_to_dict(SeoMetadata.objects.get(path=path,
                                                         lang_code=lang_code))
    except SeoMetadata.DoesNotExist:
        metadata = {}
    result = {}
    for item in ['title', 'description']:
        result[item] = (metadata.get(item) or
                        kwargs.get(item) or
                        getattr(settings, 'FALLBACK_{0}'.format(item.upper())))
    return result

@register.simple_tag(takes_context=True)
def get_seo_title(context, default=''):
    return get_seo(context, title=default).get('title')

@register.simple_tag(takes_context=True)
def get_seo_description(context, default=''):
    return get_seo(context, description=default).get('description')

Allow to set default value in template

Allow to set default value in template

Response:
from django.forms.models import model_to_dict
from django.template import Library
from django.utils.translation import get_language

from simpleseo import settings
from simpleseo.models import SeoMetadata

register = Library()

@register.filter
def single_quotes(description):
    return description.replace('\"', '\'')

@register.inclusion_tag('simpleseo/metadata.html', takes_context=True)
def get_seo(context, **kwargs):
    path = context['request'].path
    lang_code = get_language()[:2]
    try:
        metadata = model_to_dict(SeoMetadata.objects.get(path=path,
                                                         lang_code=lang_code))
    except SeoMetadata.DoesNotExist:
        metadata = {}
    result = {}
    for item in ['title', 'description']:
        result[item] = (metadata.get(item) or
                        kwargs.get(item) or
                        getattr(settings, 'FALLBACK_{0}'.format(item.upper())))
    return result

@register.simple_tag(takes_context=True)
def get_seo_title(context, default=''):
    return get_seo(context, title=default).get('title')

@register.simple_tag(takes_context=True)
def get_seo_description(context, default=''):
    return get_seo(context, description=default).get('description')

Prompt:
Allow to set default value in template

from django.template import Library
from django.utils.translation import get_language

from simpleseo import settings
from simpleseo.models import SeoMetadata

register = Library()

@register.filter
def single_quotes(description):
    return description.replace('\"', '\'')

@register.inclusion_tag('simpleseo/metadata.html', takes_context=True)
def get_seo(context):
    lang_code = get_language()[:2]
    path = context['request'].path
    try:
        metadata = SeoMetadata.objects.get(path=path, lang_code=lang_code)
    except SeoMetadata.DoesNotExist:
        metadata = None
    if metadata is None:
        return {'title': settings.FALLBACK_TITLE,
                'description': settings.FALLBACK_DESCRIPTION}
    return {'title': metadata.title, 'description': metadata.description}

@register.simple_tag(takes_context=True)
def get_seo_title(context):
    return get_seo(context)['title']

@register.simple_tag(takes_context=True)
def get_seo_description(context):
    return get_seo(context)['description']


#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('git_externals/__init__.py') as fp:
    exec(fp.read())

classifiers = [
    'Development Status :: 4 - Beta',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='git-externals',
    version=__version__,
    description='utility to manage svn externals',
    long_description='',
    packages=['git_externals'],
    install_requires=['click',
                      'pathlib'],
    entry_points={
        'console_scripts': [
            'git-externals = git_externals.git_externals:cli',
            'gittify-cleanup = git_externals.cleanup_repo:main',
            'svn-externals-info = git_externals.process_externals:main',
            'gittify = git_externals.gittify:main',
            'gittify-gen = git_externals.makefiles:cli',
        ],
    },
    author=__author__,
    author_email=__email__,
    license='MIT',
    classifiers=classifiers,
)

Remove version requirement, add pathlib

Remove version requirement, add pathlib

Response:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('git_externals/__init__.py') as fp:
    exec(fp.read())

classifiers = [
    'Development Status :: 4 - Beta',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='git-externals',
    version=__version__,
    description='utility to manage svn externals',
    long_description='',
    packages=['git_externals'],
    install_requires=['click',
                      'pathlib'],
    entry_points={
        'console_scripts': [
            'git-externals = git_externals.git_externals:cli',
            'gittify-cleanup = git_externals.cleanup_repo:main',
            'svn-externals-info = git_externals.process_externals:main',
            'gittify = git_externals.gittify:main',
            'gittify-gen = git_externals.makefiles:cli',
        ],
    },
    author=__author__,
    author_email=__email__,
    license='MIT',
    classifiers=classifiers,
)

Prompt:
Remove version requirement, add pathlib

#!/usr/bin/env python
# -*- coding: utf-8 -*-

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

with open('git_externals/__init__.py') as fp:
    exec(fp.read())

classifiers = [
    'Development Status :: 4 - Beta',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='git-externals',
    version=__version__,
    description='utility to manage svn externals',
    long_description='',
    packages=['git_externals'],
    install_requires=['click>=6.0'],
    entry_points={
        'console_scripts': [
            'git-externals = git_externals.git_externals:cli',
            'gittify-cleanup = git_externals.cleanup_repo:main',
            'svn-externals-info = git_externals.process_externals:main',
            'gittify = git_externals.gittify:main',
            'gittify-gen = git_externals.makefiles:cli',
        ],
    },
    author=__author__,
    author_email=__email__,
    license='MIT',
    classifiers=classifiers,
)


from unittest import TestCase

from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier

class ConstructIGTTests(TestCase):

    def setUp(self):
        self.lines = [{'text':'This is a test','tag':'L'},
                      {'text':'blah blah blah blah','tag':'G'}]

    def test_add_raw_lines(self):
        inst = Igt(id='i1')
        add_raw_tier(inst, self.lines)
        self.assertEqual(len(raw_tier(inst)), 2)

    def test_add_clean_lines(self):
        inst = Igt(id='i1')
        add_clean_tier(inst, self.lines)
        self.assertEqual(len(cleaned_tier(inst)), 2)

    def test_add_norm_lines(self):
        inst = Igt(id='i1')
        add_normal_tier(inst, self.lines)
        self.assertEqual(len(normalized_tier(inst)), 2)

Move testcases here from INTENT.

Move testcases here from INTENT.

Response:
from unittest import TestCase

from intent.igt.references import raw_tier, cleaned_tier, normalized_tier
from intent.igt.rgxigt import Igt
from yggdrasil.igt_operations import add_raw_tier, add_clean_tier, add_normal_tier

class ConstructIGTTests(TestCase):

    def setUp(self):
        self.lines = [{'text':'This is a test','tag':'L'},
                      {'text':'blah blah blah blah','tag':'G'}]

    def test_add_raw_lines(self):
        inst = Igt(id='i1')
        add_raw_tier(inst, self.lines)
        self.assertEqual(len(raw_tier(inst)), 2)

    def test_add_clean_lines(self):
        inst = Igt(id='i1')
        add_clean_tier(inst, self.lines)
        self.assertEqual(len(cleaned_tier(inst)), 2)

    def test_add_norm_lines(self):
        inst = Igt(id='i1')
        add_normal_tier(inst, self.lines)
        self.assertEqual(len(normalized_tier(inst)), 2)

Prompt: Move testcases here from INTENT.


# -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel

def channel_context(request):
    """ Channel context processors
    """
    opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
                                       published=True)

    return {'opps_menu': opps_menu}

Response:
# -*- coding: utf-8 -*-
from django.utils import timezone
from .models import Channel

def channel_context(request):
    """ Channel context processors
    """
    opps_menu = Channel.objects.filter(date_available__lte=timezone.now(),
                                       published=True)

    return {'opps_menu': opps_menu}

Prompt:
Apply filter channel published on menu list (channel context processors)

# -*- coding: utf-8 -*-
from .models import Channel

def channel_context(request):
    return {'opps_menu': Channel.objects.all()}


import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.requestdata.model import setup as model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth

class RequestdataPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IConfigurable)
    plugins.implements(plugins.IActions)
    plugins.implements(plugins.IAuthFunctions)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'requestdata')

    # IMapper

    def before_map(self, map):
        controller =\
            'ckanext.requestdata.controllers.package:PackageController'

        map.connect('/dataset/make_active/{pkg_name}', controller=controller,
                    action='make_active')

        return map

    # IConfigurable

    def configure(self, config):

        # Setup requestdata model
        model_setup()

    # IActions

    def get_actions(self):
        return {
            'requestdata_request_create': actions.request_create,
            'requestdata_request_show': actions.request_show,
            'requestdata_request_list': actions.request_list,
            'requestdata_request_patch': actions.request_patch,
            'requestdata_request_update': actions.request_update,
            'requestdata_request_delete': actions.request_delete
        }

    # IAuthFunctions

    def get_auth_functions(self):
        return {
            'requestdata_request_create': auth.request_create
        }

Define actions and auth functions

Define actions and auth functions

Response:
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.requestdata.model import setup as model_setup
from ckanext.requestdata.logic import actions
from ckanext.requestdata.logic import auth

class RequestdataPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IConfigurable)
    plugins.implements(plugins.IActions)
    plugins.implements(plugins.IAuthFunctions)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'requestdata')

    # IMapper

    def before_map(self, map):
        controller =\
            'ckanext.requestdata.controllers.package:PackageController'

        map.connect('/dataset/make_active/{pkg_name}', controller=controller,
                    action='make_active')

        return map

    # IConfigurable

    def configure(self, config):

        # Setup requestdata model
        model_setup()

    # IActions

    def get_actions(self):
        return {
            'requestdata_request_create': actions.request_create,
            'requestdata_request_show': actions.request_show,
            'requestdata_request_list': actions.request_list,
            'requestdata_request_patch': actions.request_patch,
            'requestdata_request_update': actions.request_update,
            'requestdata_request_delete': actions.request_delete
        }

    # IAuthFunctions

    def get_auth_functions(self):
        return {
            'requestdata_request_create': auth.request_create
        }

Prompt:
Define actions and auth functions

import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.requestdata.model import setup as model_setup

class RequestdataPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IConfigurable)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'requestdata')

    # IMapper

    def before_map(self, map):
        controller =\
            'ckanext.requestdata.controllers.package:PackageController'

        map.connect('/dataset/make_active/{pkg_name}', controller=controller,
                    action='make_active')

        return map

    # IConfigurable

    def configure(self, config):

        # Setup requestdata model
        model_setup()


# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = False
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = False

Disable SQL logging in appengine

Disable SQL logging in appengine

Response:
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = False
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = False

Prompt:
Disable SQL logging in appengine

# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = True
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = False


from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_test_srs = g.live_config.get("adzerk_test_srs")
        if adzerk_test_srs and c.site.name in adzerk_test_srs:
            self.ad_url = g.config["adzerk_url"]
            self.frame_id = "ad_main"

Set the frame id to what aderk expects.

Response:
from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_test_srs = g.live_config.get("adzerk_test_srs")
        if adzerk_test_srs and c.site.name in adzerk_test_srs:
            self.ad_url = g.config["adzerk_url"]
            self.frame_id = "ad_main"

Prompt:
Set the frame id to what aderk expects.

(See a corresponding change to ads.html in reddit)

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_test_srs = g.live_config.get("adzerk_test_srs")
        if adzerk_test_srs and c.site.name in adzerk_test_srs:
            self.ad_url = g.config["adzerk_url"]


"""Test IAM Policy templates are valid JSON."""
import jinja2

from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES

def iam_templates():
    """Generate list of IAM templates."""
    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))

    iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
        x.startswith('infrastructure/iam/'),
        'trust' not in x,
        'wrapper' not in x, ]))

    for iam_template_name in iam_template_names:
        yield iam_template_name

        items = ['resource1', 'resource2']

        if service == 'rds-db':
            items = {
                'resource1': 'user1',
                'resource2': 'user2',
            }

        rendered = render_policy_template(
            account_number='',
            app='coreforrest',
            env='dev',
            group='forrest',
            items=items,
            pipeline_settings={
                'lambda': {
                    'vpc_enabled': False,
                },
            },
            region='us-east-1',
            service=service)

        assert isinstance(rendered, list)

Use generator for IAM template names

Response:
"""Test IAM Policy templates are valid JSON."""
import jinja2

from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES

def iam_templates():
    """Generate list of IAM templates."""
    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))

    iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
        x.startswith('infrastructure/iam/'),
        'trust' not in x,
        'wrapper' not in x, ]))

    for iam_template_name in iam_template_names:
        yield iam_template_name

        items = ['resource1', 'resource2']

        if service == 'rds-db':
            items = {
                'resource1': 'user1',
                'resource2': 'user2',
            }

        rendered = render_policy_template(
            account_number='',
            app='coreforrest',
            env='dev',
            group='forrest',
            items=items,
            pipeline_settings={
                'lambda': {
                    'vpc_enabled': False,
                },
            },
            region='us-east-1',
            service=service)

        assert isinstance(rendered, list)

Prompt:
test: Use generator for IAM template names

See also: #208

"""Test IAM Policy templates are valid JSON."""
import jinja2

from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES

def test_all_iam_templates():
    """Verify all IAM templates render as proper JSON."""
    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))

    iam_templates = jinjaenv.list_templates(filter_func=lambda x: all([
        x.startswith('infrastructure/iam/'),
        'trust' not in x,
        'wrapper' not in x, ]))

    for template in iam_templates:
        *_, service_json = template.split('/')
        service, *_ = service_json.split('.')

        items = ['resource1', 'resource2']

        if service == 'rds-db':
            items = {
                'resource1': 'user1',
                'resource2': 'user2',
            }

        rendered = render_policy_template(
            account_number='',
            app='coreforrest',
            env='dev',
            group='forrest',
            items=items,
            pipeline_settings={
                'lambda': {
                    'vpc_enabled': False,
                },
            },
            region='us-east-1',
            service=service)

        assert isinstance(rendered, list)


"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

from datetime import tzinfo

class UTC(tzinfo):
    """
    The one true time zone.
    """

    def utcoffset(self, dt):
        """
        Return the offset to UTC.
        """

        from datetime import timedelta

        return timedelta(0)

    def tzname(self, dt):
        """
        Return the time zone name.
        """

        return "UTC"

    def dst(self, dt):
        """
        Return the DST offset.
        """

        from datetime import timedelta

        return timedelta(0)

def utc_now():
    """
    Return a non-naive UTC datetime instance.
    """

    from datetime import datetime as DateTime

    return DateTime.now(UTC())

def seconds(value):
    """
    Return the equivalent number of seconds, floating-point.
    """

    return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6

Response:
"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

from datetime import tzinfo

class UTC(tzinfo):
    """
    The one true time zone.
    """

    def utcoffset(self, dt):
        """
        Return the offset to UTC.
        """

        from datetime import timedelta

        return timedelta(0)

    def tzname(self, dt):
        """
        Return the time zone name.
        """

        return "UTC"

    def dst(self, dt):
        """
        Return the DST offset.
        """

        from datetime import timedelta

        return timedelta(0)

def utc_now():
    """
    Return a non-naive UTC datetime instance.
    """

    from datetime import datetime as DateTime

    return DateTime.now(UTC())

def seconds(value):
    """
    Return the equivalent number of seconds, floating-point.
    """

    return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6

Prompt:
Fix comment after dropping the pytz dependency.

"""
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""

from datetime import tzinfo

class UTC(tzinfo):
    """
    The one true time zone.
    """

    def utcoffset(self, dt):
        """
        Return the offset to UTC.
        """

        from datetime import timedelta

        return timedelta(0)

    def tzname(self, dt):
        """
        Return the time zone name.
        """

        return "UTC"

    def dst(self, dt):
        """
        Return the DST offset.
        """

        from datetime import timedelta

        return timedelta(0)

def utc_now():
    """
    Return a non-naive UTC datetime instance, zoned pytz.utc.
    """

    from datetime import datetime as DateTime

    return DateTime.now(UTC())

def seconds(value):
    """
    Return the equivalent number of seconds, floating-point.
    """

    return value.days * 8.64e4 + value.seconds + value.microseconds / 1e6


import overview
import personnel
import match
import events
import statistics

CSV_ETL_CLASSES = {
    'Overview': {
        'Competitions': overview.CompetitionIngest,
        'Clubs': overview.ClubIngest,
        'Venues': overview.VenueIngest
    },
    'Personnel': {
        'Players': personnel.PlayerIngest,
        'Managers': personnel.ManagerIngest,
        'Referees': personnel.RefereeIngest
    },
    'Match': {
        'Matches': match.MatchIngest,
        'Lineups': match.MatchLineupIngest,
        'Goals': events.GoalIngest,
        'Penalties': events.PenaltyIngest,
        'Bookables': events.BookableIngest,
        'Substitutions': events.SubstitutionIngest,
        'PlayerStats': [
            statistics.AssistsIngest,
            statistics.ClearancesIngest,
            statistics.CornerCrossesIngest,
            statistics.CornersIngest,
            statistics.CrossesIngest,
            statistics.DefensivesIngest,
            statistics.DisciplineIngest,
            statistics.DuelsIngest,
            statistics.FoulWinsIngest,
            statistics.FreeKicksIngest,
            statistics.GKActionsIngest,
            statistics.GKAllowedGoalsIngest,
            statistics.GKAllowedShotsIngest,
            statistics.GKSavesIngest,
            statistics.GoalBodyPartsIngest,
            statistics.GoalLineClearancesIngest,
            statistics.GoalLocationsIngest,
            statistics.GoalTotalsIngest,
            statistics.ImportantPlaysIngest,
            statistics.MatchStatIngest,
            statistics.PassDirectionsIngest,
            statistics.PassLengthsIngest,
            statistics.PassLocationsIngest,
            statistics.PassTotalsIngest,
            statistics.PenaltyActionsIngest,
            statistics.ShotBlocksIngest,
            statistics.ShotBodyPartsIngest,
            statistics.ShotLocationsIngest,
            statistics.ShotPlaysIngest,
            statistics.TacklesIngest,
            statistics.ThrowinsIngest,
            statistics.TouchesIngest,
            statistics.TouchLocationsIngest
        ]
    }
}

Create dictionary to map ETL data files to ingestion classes

Response:
import overview
import personnel
import match
import events
import statistics

CSV_ETL_CLASSES = {
    'Overview': {
        'Competitions': overview.CompetitionIngest,
        'Clubs': overview.ClubIngest,
        'Venues': overview.VenueIngest
    },
    'Personnel': {
        'Players': personnel.PlayerIngest,
        'Managers': personnel.ManagerIngest,
        'Referees': personnel.RefereeIngest
    },
    'Match': {
        'Matches': match.MatchIngest,
        'Lineups': match.MatchLineupIngest,
        'Goals': events.GoalIngest,
        'Penalties': events.PenaltyIngest,
        'Bookables': events.BookableIngest,
        'Substitutions': events.SubstitutionIngest,
        'PlayerStats': [
            statistics.AssistsIngest,
            statistics.ClearancesIngest,
            statistics.CornerCrossesIngest,
            statistics.CornersIngest,
            statistics.CrossesIngest,
            statistics.DefensivesIngest,
            statistics.DisciplineIngest,
            statistics.DuelsIngest,
            statistics.FoulWinsIngest,
            statistics.FreeKicksIngest,
            statistics.GKActionsIngest,
            statistics.GKAllowedGoalsIngest,
            statistics.GKAllowedShotsIngest,
            statistics.GKSavesIngest,
            statistics.GoalBodyPartsIngest,
            statistics.GoalLineClearancesIngest,
            statistics.GoalLocationsIngest,
            statistics.GoalTotalsIngest,
            statistics.ImportantPlaysIngest,
            statistics.MatchStatIngest,
            statistics.PassDirectionsIngest,
            statistics.PassLengthsIngest,
            statistics.PassLocationsIngest,
            statistics.PassTotalsIngest,
            statistics.PenaltyActionsIngest,
            statistics.ShotBlocksIngest,
            statistics.ShotBodyPartsIngest,
            statistics.ShotLocationsIngest,
            statistics.ShotPlaysIngest,
            statistics.TacklesIngest,
            statistics.ThrowinsIngest,
            statistics.TouchesIngest,
            statistics.TouchLocationsIngest
        ]
    }
}

Prompt: Create dictionary to map ETL data files to ingestion classes


from sublime_plugin import TextCommand

from ...core.base_command import BaseCommand
from ..github import open_file_in_browser

class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):

    """
    Open a new browser window to the web-version of the currently opened
    (or specified) file. If `preselect` is `True`, include the selected
    lines in the request.

    At present, this only supports github.com and GitHub enterprise.
    """

    def run(self, edit, preselect=False, fpath=None):
        fpath = fpath or self.get_rel_path()
        start_line = None
        end_line = None

        if preselect:
            selections = self.view.sel()
            if len(selections) >= 1:
                first_selection = selections[0]
                last_selection = selections[-1]
                # Git lines are 1-indexed; Sublime rows are 0-indexed.
                start_line = self.view.rowcol(first_selection.begin())[0] + 1
                end_line = self.view.rowcol(last_selection.end())[0] + 1

        default_name, default_remote_url = self.get_remotes().popitem(last=False)

        open_file_in_browser(
            fpath,
            default_remote_url,
            self.get_commit_hash_for_head(),
            start_line=start_line,
            end_line=end_line
        )

Response:
from sublime_plugin import TextCommand

from ...core.base_command import BaseCommand
from ..github import open_file_in_browser

class GsOpenFileOnRemoteCommand(TextCommand, BaseCommand):

    """
    Open a new browser window to the web-version of the currently opened
    (or specified) file. If `preselect` is `True`, include the selected
    lines in the request.

    At present, this only supports github.com and GitHub enterprise.
    """

    def run(self, edit, preselect=False, fpath=None):
        fpath = fpath or self.get_rel_path()
        start_line = None
        end_line = None

        if preselect:
            selections = self.view.sel()
            if len(selections) >= 1:
                first_selection = selections[0]
                last_selection = selections[-1]
                # Git lines are 1-indexed; Sublime rows are 0-indexed.
                start_line = self.view.rowcol(first_selection.begin())[0] + 1
                end_line = self.view.rowcol(last_selection.end())[0] + 1

        default_name, default_remote_url = self.get_remotes().popitem(last=False)

        open_file_in_browser(
            fpath,
            default_remote_url,
            self.get_commit_hash_for_head(),
            start_line=start_line,
            end_line=end_line
        )

Prompt:
Fix regression where unable to open file on remote.

from sublime_plugin import TextCommand

from ...common.file_and_repo import FileAndRepo
from ..github import open_file_in_browser

class GsOpenFileOnRemoteCommand(TextCommand, FileAndRepo):

    """
    Open a new browser window to the web-version of the currently opened
    (or specified) file. If `preselect` is `True`, include the selected
    lines in the request.

    At present, this only supports github.com and GitHub enterprise.
    """

    def run(self, preselect=False, fpath=None):
        fpath = fpath or self.get_rel_path()
        start_line = None
        end_line = None

        if preselect:
            selections = self.view.sel()
            if len(selections) >= 1:
                first_selection = selections[0]
                last_selection = selections[-1]
                # Git lines are 1-indexed; Sublime rows are 0-indexed.
                start_line = self.view.rowcol(first_selection.begin())[0] + 1
                end_line = self.view.rowcol(last_selection.end())[0] + 1

        default_name, default_remote_url = self.get_remotes().popitem(last=False)

        open_file_in_browser(
            fpath,
            default_remote_url,
            self.get_commit_hash_for_head(),
            start_line=start_line,
            end_line=end_line
        )


from . import models
from django.conf import settings
from django.contrib.auth import hashers

def groups(request):
    return {
            'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
            'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
            }

def statistics(request):
    return {
            'gestalt_count': models.Gestalt.objects.exclude(user__password__startswith=hashers.UNUSABLE_PASSWORD_PREFIX).count,
            'group_count': models.Group.objects.count
            }

Exclude unusable users from stats

Exclude unusable users from stats

Response:
from . import models
from django.conf import settings
from django.contrib.auth import hashers

def groups(request):
    return {
            'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
            'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
            }

def statistics(request):
    return {
            'gestalt_count': models.Gestalt.objects.exclude(user__password__startswith=hashers.UNUSABLE_PASSWORD_PREFIX).count,
            'group_count': models.Group.objects.count
            }

Prompt:
Exclude unusable users from stats

from . import models
from django.conf import settings

def groups(request):
    return {
            'about_group': models.Group.objects.filter(id=settings.ABOUT_GROUP_ID).first(),
            'all_sidebar_groups': models.Group.objects.scored().order_by('-score'),
            }

def statistics(request):
    return {
            'gestalt_count': models.Gestalt.objects.count,
            'group_count': models.Group.objects.count
            }


from runtests import Tester
import os.path
import sys

tester = Tester(os.path.abspath(__file__), "fake_spectra")

tester.main(sys.argv[1:])

Add import back to test script

Add import back to test script

Response:
from runtests import Tester
import os.path
import sys

tester = Tester(os.path.abspath(__file__), "fake_spectra")

tester.main(sys.argv[1:])

Prompt:
Add import back to test script

from runtests import Tester
import os.path

tester = Tester(os.path.abspath(__file__), "fake_spectra")

tester.main(sys.argv[1:])


import pytest

from typing import Tuple

from .pells_equation import solve_pells_equation
from ..sqrt import is_square

PELLS_SOLUTIONS = [
    (
        2,
        [
            3,
            2
        ]
    ),
    (
        3,
        [
            2,
            1
        ]
    ),
    (
        5,
        [
            9,
            4
        ]
    ),
    (
        6,
        [
            5,
            2
        ]
    ),
    (
        7,
        [
            8,
            3
        ]
    ),
]

RANGE = [n for n in range(1, 20) if not is_square(n)]
DEPTH = 100

@pytest.mark.parametrize('n,expected_output', PELLS_SOLUTIONS)
def test_first_solution_pells_equation(n: int,
                                       expected_output: Tuple[int, int]) -> \
        None:
    assert tuple(expected_output) == next(solve_pells_equation(n))

@pytest.mark.parametrize('n', RANGE)
def test_further_solutions_pells_equation(n: int,
                                          number: int=DEPTH) -> None:
    solutions = solve_pells_equation(n)

    for (x, y), i in zip(solutions, range(number)):
        assert x ** 2 - n * y ** 2 == 1

Add testing for Pells equation

Add testing for Pells equation

Response:
import pytest

from typing import Tuple

from .pells_equation import solve_pells_equation
from ..sqrt import is_square

PELLS_SOLUTIONS = [
    (
        2,
        [
            3,
            2
        ]
    ),
    (
        3,
        [
            2,
            1
        ]
    ),
    (
        5,
        [
            9,
            4
        ]
    ),
    (
        6,
        [
            5,
            2
        ]
    ),
    (
        7,
        [
            8,
            3
        ]
    ),
]

RANGE = [n for n in range(1, 20) if not is_square(n)]
DEPTH = 100

@pytest.mark.parametrize('n,expected_output', PELLS_SOLUTIONS)
def test_first_solution_pells_equation(n: int,
                                       expected_output: Tuple[int, int]) -> \
        None:
    assert tuple(expected_output) == next(solve_pells_equation(n))

@pytest.mark.parametrize('n', RANGE)
def test_further_solutions_pells_equation(n: int,
                                          number: int=DEPTH) -> None:
    solutions = solve_pells_equation(n)

    for (x, y), i in zip(solutions, range(number)):
        assert x ** 2 - n * y ** 2 == 1

Prompt: Add testing for Pells equation


import binascii

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes

from knox.settings import knox_settings, CONSTANTS

sha = knox_settings.SECURE_HASH_ALGORITHM

def create_token_string():
    return binascii.hexlify(
        generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
    ).decode()

def create_salt_string():
    return binascii.hexlify(
        generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()

def hash_token(token, salt):
    '''
    Calculates the hash of a token and salt.
    input is unhexlified
    '''
    digest = hashes.Hash(sha(), backend=default_backend())
    digest.update(binascii.unhexlify(token))
    digest.update(binascii.unhexlify(salt))
    return binascii.hexlify(digest.finalize()).decode()

Response:
import binascii

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from os import urandom as generate_bytes

from knox.settings import knox_settings, CONSTANTS

sha = knox_settings.SECURE_HASH_ALGORITHM

def create_token_string():
    return binascii.hexlify(
        generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
    ).decode()

def create_salt_string():
    return binascii.hexlify(
        generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()

def hash_token(token, salt):
    '''
    Calculates the hash of a token and salt.
    input is unhexlified
    '''
    digest = hashes.Hash(sha(), backend=default_backend())
    digest.update(binascii.unhexlify(token))
    digest.update(binascii.unhexlify(salt))
    return binascii.hexlify(digest.finalize()).decode()

Prompt:
Use os.urandom instead of OpenSSL.rand.bytes

Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1
import binascii

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from OpenSSL.rand import bytes as generate_bytes

from knox.settings import knox_settings, CONSTANTS

sha = knox_settings.SECURE_HASH_ALGORITHM

def create_token_string():
    return binascii.hexlify(
        generate_bytes(int(knox_settings.AUTH_TOKEN_CHARACTER_LENGTH / 2))
    ).decode()

def create_salt_string():
    return binascii.hexlify(
        generate_bytes(int(CONSTANTS.SALT_LENGTH / 2))).decode()

def hash_token(token, salt):
    '''
    Calculates the hash of a token and salt.
    input is unhexlified
    '''
    digest = hashes.Hash(sha(), backend=default_backend())
    digest.update(binascii.unhexlify(token))
    digest.update(binascii.unhexlify(salt))
    return binascii.hexlify(digest.finalize()).decode()


import math
import numpy
import pyaudio

def sine(frequency, length, rate):
    length = int(length * rate)
    factor = float(frequency) * (math.pi * 2) / rate
    return numpy.sin(numpy.arange(length) * factor)

def play_tone(stream, frequency=440, length=1, rate=44100):
    chunks = []
    chunks.append(sine(frequency, length, rate))

    chunk = numpy.concatenate(chunks) * 0.25

    stream.write(chunk.astype(numpy.float32).tostring())

if __name__ == '__main__':
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                    channels=1, rate=44100, output=1)

    play_tone(stream, frequency=750, length=10)

    stream.close()
    p.terminate()

Test codie to get sound duration right

Test codie to get sound duration right

Response:
import math
import numpy
import pyaudio

def sine(frequency, length, rate):
    length = int(length * rate)
    factor = float(frequency) * (math.pi * 2) / rate
    return numpy.sin(numpy.arange(length) * factor)

def play_tone(stream, frequency=440, length=1, rate=44100):
    chunks = []
    chunks.append(sine(frequency, length, rate))

    chunk = numpy.concatenate(chunks) * 0.25

    stream.write(chunk.astype(numpy.float32).tostring())

if __name__ == '__main__':
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                    channels=1, rate=44100, output=1)

    play_tone(stream, frequency=750, length=10)

    stream.close()
    p.terminate()

Prompt: Test codie to get sound duration right


from django.contrib import admin

from registration.models import RegistrationProfile

class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'activation_key_expired')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)

Response:
from django.contrib import admin

from registration.models import RegistrationProfile

class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'activation_key_expired')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)

Prompt:
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.

from django.contrib import admin

from registration.models import RegistrationProfile

class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'activation_key_expired')
    search_fields = ('user__username', 'user__first_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)


"""suorganizer URL Configuration

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

from organizer.views import homepage, tag_detail

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', homepage),
    url(r'^tag/(?P<slug>[\w\-]+)/$',
        tag_detail,
        ),
]

Create URL pattern for Tag Detail.

Response:
"""suorganizer URL Configuration

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

from organizer.views import homepage, tag_detail

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', homepage),
    url(r'^tag/(?P<slug>[\w\-]+)/$',
        tag_detail,
        ),
]

Prompt:
Ch05: Create URL pattern for Tag Detail.

"""suorganizer URL Configuration

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

from organizer.views import homepage

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


#!/usr/bin/env python

import base64
import rsa
import six

from st2common.runners.base_action import Action

class AwsDecryptPassworData(Action):

    def run(self, keyfile, password_data):
        # copied from:
        # https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122

        self.logger.debug("Decrypting password data using: %s", keyfile)
        value = password_data

        if not value:
            return ''

        # Hack because somewhere in the Mistral parameter "publish" pipeline, we
        # strip trailing and leading whitespace from a string which results in
        # an invalid base64 string
        if not value.startswith('\r\n'):
            value = '\r\n' + value

        if not value.endswith('\r\n'):
            value = value + '\r\n'

        value = base64.b64decode(value)

        try:
            with open(keyfile) as pk_file:
                pk_contents = pk_file.read()
                private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                value = rsa.decrypt(value, private_key)
                return value.decode('utf-8')
        except Exception:
            msg = ('Unable to decrypt password data using '
                   'provided private key file: {}').format(keyfile)
            self.logger.debug(msg, exc_info=True)
            raise ValueError(msg)

Response:
#!/usr/bin/env python

import base64
import rsa
import six

from st2common.runners.base_action import Action

class AwsDecryptPassworData(Action):

    def run(self, keyfile, password_data):
        # copied from:
        # https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122

        self.logger.debug("Decrypting password data using: %s", keyfile)
        value = password_data

        if not value:
            return ''

        # Hack because somewhere in the Mistral parameter "publish" pipeline, we
        # strip trailing and leading whitespace from a string which results in
        # an invalid base64 string
        if not value.startswith('\r\n'):
            value = '\r\n' + value

        if not value.endswith('\r\n'):
            value = value + '\r\n'

        value = base64.b64decode(value)

        try:
            with open(keyfile) as pk_file:
                pk_contents = pk_file.read()
                private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                value = rsa.decrypt(value, private_key)
                return value.decode('utf-8')
        except Exception:
            msg = ('Unable to decrypt password data using '
                   'provided private key file: {}').format(keyfile)
            self.logger.debug(msg, exc_info=True)
            raise ValueError(msg)

Prompt:
Add a workaround since somewhere in the Mistral "publish variable"
pipeline, trealing and leading whitespace is removed.

#!/usr/bin/env python

import base64
import rsa
import six

from st2common.runners.base_action import Action

class AwsDecryptPassworData(Action):

    def run(self, keyfile, password_data):
        # copied from:
        # https://github.com/aws/aws-cli/blob/master/awscli/customizations/ec2/decryptpassword.py#L96-L122

        self.logger.debug("Decrypting password data using: %s", keyfile)
        value = password_data
        if not value:
            return ''

        try:
            with open(keyfile) as pk_file:
                pk_contents = pk_file.read()
                private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents))
                value = base64.b64decode(value)
                value = rsa.decrypt(value, private_key)
                return value.decode('utf-8')
        except Exception:
            msg = ('Unable to decrypt password data using '
                   'provided private key file: {}').format(keyfile)
            self.logger.debug(msg, exc_info=True)
            raise ValueError(msg)


"""Collection of HTTP helpers."""

from functools import partial, wraps
from inspect import iscoroutine

from aiohttp.web import json_response

def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
    """Turn dict output of an HTTP handler into JSON response.

    Decorates aiohttp request handlers.
    """
    if orig_method is None:
        return partial(async_json_out, status=200, content_type='application/json', **kwargs)

    @wraps(orig_method)
    async def wrapper(*args, **kwargs):
        dict_resp = orig_method(*args, **kwargs)

        if iscoroutine(dict_resp):
            dict_resp = await dict_resp

        return json_response(
            dict_resp,
            status=status,
            content_type=content_type,
            **kwargs
        )
    return wrapper

Response:
"""Collection of HTTP helpers."""

from functools import partial, wraps
from inspect import iscoroutine

from aiohttp.web import json_response

def async_json_out(orig_method=None, *, status=200, content_type='application/json', **kwargs):
    """Turn dict output of an HTTP handler into JSON response.

    Decorates aiohttp request handlers.
    """
    if orig_method is None:
        return partial(async_json_out, status=200, content_type='application/json', **kwargs)

    @wraps(orig_method)
    async def wrapper(*args, **kwargs):
        dict_resp = orig_method(*args, **kwargs)

        if iscoroutine(dict_resp):
            dict_resp = await dict_resp

        return json_response(
            dict_resp,
            status=status,
            content_type=content_type,
            **kwargs
        )
    return wrapper

Prompt:
Add default status=200 to async_json_out decorator

"""Collection of HTTP helpers."""

from functools import partial, wraps
from inspect import iscoroutine

from aiohttp.web import json_response

def async_json_out(orig_method=None, *, content_type='application/json', **kwargs):
    """Turn dict output of an HTTP handler into JSON response.

    Decorates aiohttp request handlers.
    """
    if orig_method is None:
        return partial(async_json_out, content_type='application/json', **kwargs)

    @wraps(orig_method)
    async def wrapper(*args, **kwargs):
        dict_resp = orig_method(*args, **kwargs)

        if iscoroutine(dict_resp):
            dict_resp = await dict_resp

        return json_response(
            dict_resp,
            content_type=content_type,
            **kwargs
        )
    return wrapper


from nameko.rpc import rpc, RpcProxy

class ScoreService(object):
    name = 'score_service'

    player_rpc = RpcProxy('players_service')

    @rpc
    def leaderboard(self):
        players = self.player_rpc.get_players()
        sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
        return [(p.name, p.score) for p in players]

    @rpc
    def update_player_score(self, player_id, score):
        player = self.player_rpc.get_player(player_id)
        player.add_score(score)

Add method to update a player's score

Add method to update a player's score

Response:
from nameko.rpc import rpc, RpcProxy

class ScoreService(object):
    name = 'score_service'

    player_rpc = RpcProxy('players_service')

    @rpc
    def leaderboard(self):
        players = self.player_rpc.get_players()
        sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
        return [(p.name, p.score) for p in players]

    @rpc
    def update_player_score(self, player_id, score):
        player = self.player_rpc.get_player(player_id)
        player.add_score(score)

Prompt:
Add method to update a player's score

from nameko.rpc import rpc, RpcProxy

class ScoreService(object):
    name = 'score_service'

    player_service = RpcProxy('players_service')

    @rpc
    def leaderboard(self):
        players = self.player_service.get_players()
        return sorted(players, key=lambda player: player.score, reverse=True)


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

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

import unittest

# To test this module:
# python -m unittest -v nested

def string_maxlen(txt,max_len=12):
    n = len(txt)
    if n <= max_len:
        return txt
    elif n > max_len-3:
        return txt[:(max_len-3)] + '...'

# python -m unittest -v nested.TestStringMaxLength
class TestStringMaxLength(unittest.TestCase):
    def test_short_strings(self):
        self.assertEqual(string_maxlen('abcdefghij'),     'abcdefghij')
        self.assertEqual(string_maxlen('abcdefghijk'),    'abcdefghijk')
        self.assertEqual(string_maxlen('abcdefghijkl'),   'abcdefghijkl')

    def test_long_strings(self):
        self.assertEqual(string_maxlen('abcdefghijklm'),  'abcdefghi...')
        self.assertEqual(string_maxlen('abcdefghijklmn'), 'abcdefghi...')

def print_structure(elmt,level=0,max_level=5):
    txt=''
    if level > max_level:
        return txt

    whitespace = " " * (level * 2)
    if isinstance(elmt, (dict)) is True:
        for k in elmt.keys():
            if type(elmt[k])==int:
                txt += whitespace + "+'{0}': {1}\n".format(k,elmt[k])
            elif type(elmt[k])==str:
                my_str=elmt[k][:40]
                txt += whitespace + "+'{0}': '{1}'\n".format(k,my_str)
            else:
                txt += whitespace + "+'{0}': {1}\n".format(k,type(elmt[k]))
                txt += print_structure(elmt[k],level+1,max_level=max_level)
    elif isinstance(elmt, (list)) is True:
        txt += whitespace + "+[list]\n"
        if len(elmt) > 0:
            txt += print_structure(elmt[0],level+1,max_level=max_level)
    else:
        pass
    return txt

# python -m unittest -v nested.TestPrintStructure
class TestPrintStructure(unittest.TestCase):
    def test_dict_int(self):
        d = {'integer': 123}
        self.assertEqual(print_structure(d),"+'integer': 123\n")

    def test_dict_string(self):
        d = {'string': 'abc'}
        self.assertEqual(print_structure(d),"+'string': 'abc'\n")

    def test_dict_list(self):
        d = {'list': [1,2,3]}
        self.assertEqual(print_structure(d),"+'list': <class 'list'>\n  +[list]\n")

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

Add subroutine to print a dictionary tree

Response:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

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

import unittest

# To test this module:
# python -m unittest -v nested

def string_maxlen(txt,max_len=12):
    n = len(txt)
    if n <= max_len:
        return txt
    elif n > max_len-3:
        return txt[:(max_len-3)] + '...'

# python -m unittest -v nested.TestStringMaxLength
class TestStringMaxLength(unittest.TestCase):
    def test_short_strings(self):
        self.assertEqual(string_maxlen('abcdefghij'),     'abcdefghij')
        self.assertEqual(string_maxlen('abcdefghijk'),    'abcdefghijk')
        self.assertEqual(string_maxlen('abcdefghijkl'),   'abcdefghijkl')

    def test_long_strings(self):
        self.assertEqual(string_maxlen('abcdefghijklm'),  'abcdefghi...')
        self.assertEqual(string_maxlen('abcdefghijklmn'), 'abcdefghi...')

def print_structure(elmt,level=0,max_level=5):
    txt=''
    if level > max_level:
        return txt

    whitespace = " " * (level * 2)
    if isinstance(elmt, (dict)) is True:
        for k in elmt.keys():
            if type(elmt[k])==int:
                txt += whitespace + "+'{0}': {1}\n".format(k,elmt[k])
            elif type(elmt[k])==str:
                my_str=elmt[k][:40]
                txt += whitespace + "+'{0}': '{1}'\n".format(k,my_str)
            else:
                txt += whitespace + "+'{0}': {1}\n".format(k,type(elmt[k]))
                txt += print_structure(elmt[k],level+1,max_level=max_level)
    elif isinstance(elmt, (list)) is True:
        txt += whitespace + "+[list]\n"
        if len(elmt) > 0:
            txt += print_structure(elmt[0],level+1,max_level=max_level)
    else:
        pass
    return txt

# python -m unittest -v nested.TestPrintStructure
class TestPrintStructure(unittest.TestCase):
    def test_dict_int(self):
        d = {'integer': 123}
        self.assertEqual(print_structure(d),"+'integer': 123\n")

    def test_dict_string(self):
        d = {'string': 'abc'}
        self.assertEqual(print_structure(d),"+'string': 'abc'\n")

    def test_dict_list(self):
        d = {'list': [1,2,3]}
        self.assertEqual(print_structure(d),"+'list': <class 'list'>\n  +[list]\n")

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

Prompt: Add subroutine to print a dictionary tree


import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-nexmo',
    version='1.0.1',
    packages=['nexmo'],
    include_package_data=True,
    license='WTFPL',
    description='A simple Django app to send text messages using the Nexmo api.',
    long_description=README,
    url='https://github.com/thibault/django-nexmo',
    author='Thibault Jouannic',
    author_email='thibault@miximum.fr',
    setup_requires=('setuptools'),
    install_requires=[
        'libnexmo',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Add libnexmo as a dependency

Add libnexmo as a dependency

Response:
import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-nexmo',
    version='1.0.1',
    packages=['nexmo'],
    include_package_data=True,
    license='WTFPL',
    description='A simple Django app to send text messages using the Nexmo api.',
    long_description=README,
    url='https://github.com/thibault/django-nexmo',
    author='Thibault Jouannic',
    author_email='thibault@miximum.fr',
    setup_requires=('setuptools'),
    install_requires=[
        'libnexmo',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Prompt:
Add libnexmo as a dependency

import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-nexmo',
    version='1.0.1',
    packages=['nexmo'],
    include_package_data=True,
    license='WTFPL',
    description='A simple Django app to send text messages using the Nexmo api.',
    long_description=README,
    url='https://github.com/thibault/django-nexmo',
    author='Thibault Jouannic',
    author_email='thibault@miximum.fr',
    setup_requires=('setuptools'),
    requires=(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requires = [
    'requests',
    'rauth'
]

setup(
    name='fatsecret',
    version='0.2.1',
    description='Python wrapper for FatSecret REST API',
    url='github.com/walexnelson/pyfatsecret',
    license='MIT',
    author='Alex Nelson',
    author_email='w.alexnelson@gmail.com',
    install_requires=requires,
    packages=["fatsecret"],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ]
)

Use packaging instead of a module

Use packaging instead of a module

Response:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requires = [
    'requests',
    'rauth'
]

setup(
    name='fatsecret',
    version='0.2.1',
    description='Python wrapper for FatSecret REST API',
    url='github.com/walexnelson/pyfatsecret',
    license='MIT',
    author='Alex Nelson',
    author_email='w.alexnelson@gmail.com',
    install_requires=requires,
    packages=["fatsecret"],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ]
)

Prompt:
Use packaging instead of a module
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requires = [
    'requests',
    'rauth'
]

setup(
    name='fatsecret',
    version='0.2.1',
    description='Python wrapper for FatSecret REST API',
    url='github.com/walexnelson/pyfatsecret',
    license='MIT',
    author='Alex Nelson',
    author_email='w.alexnelson@gmail.com',
    install_requires=requires,
    py_modules=("fatsecret",),
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3'
    ]
)


""" Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse

def create_output_timing(f_out, args):
    print(
        """
source {util_tcl}
write_timing_info timing_{name}.json5

report_timing_summary
""".format(name=args.name, util_tcl=args.util_tcl),
        file=f_out
    )

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--name', required=True)
    parser.add_argument('--util_tcl', required=True)
    parser.add_argument('--output_tcl', required=True)

    args = parser.parse_args()
    with open(args.output_tcl, 'w') as f:
        create_output_timing(f, args)

if __name__ == "__main__":
    main()

Response:
""" Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse

def create_output_timing(f_out, args):
    print(
        """
source {util_tcl}
write_timing_info timing_{name}.json5

report_timing_summary
""".format(name=args.name, util_tcl=args.util_tcl),
        file=f_out
    )

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--name', required=True)
    parser.add_argument('--util_tcl', required=True)
    parser.add_argument('--output_tcl', required=True)

    args = parser.parse_args()
    with open(args.output_tcl, 'w') as f:
        create_output_timing(f, args)

if __name__ == "__main__":
    main()

Prompt:
Correct function name and put report_timing_summary at end of script.

Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>

""" Utility for generating TCL script to output timing information from a
design checkpoint.
"""
import argparse

def create_runme(f_out, args):
    print(
        """
report_timing_summary

source {util_tcl}
write_timing_info timing_{name}.json5
""".format(name=args.name, util_tcl=args.util_tcl),
        file=f_out
    )

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--name', required=True)
    parser.add_argument('--util_tcl', required=True)
    parser.add_argument('--output_tcl', required=True)

    args = parser.parse_args()
    with open(args.output_tcl, 'w') as f:
        create_runme(f, args)

if __name__ == "__main__":
    main()


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

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, i))
    return prime

Prompt:
Switch to more optimal non-generator solution

def sieve(n):
    return list(primes(n))

def primes(n):
    if n < 2:
        raise StopIteration
    yield 2
    not_prime = set()
    for i in range(3, n+1, 2):
        if i not in not_prime:
            yield i
        not_prime.update(range(i*i, n, i))


import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')

# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""

    result = []

    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)

    return unicode(delim.join(result))

Response:
import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')

# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""

    result = []

    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)

    return unicode(delim.join(result))

Prompt:
Change ":" in titles to "-" for better SEO

import re
from unicodedata import normalize

_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')

# From http://flask.pocoo.org/snippets/5/
def slugify(text, delim=u'-'):
    """Generates an slightly worse ASCII-only slug."""

    result = []

    for word in _punct_re.split(text.lower()):
        word = normalize('NFKD', word).encode('ascii', 'ignore')
        if word:
            result.append(word)

    return unicode(delim.join(result))