from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
                       exp, as_vector, Constant, acos)
import numpy as np

class Gaussian(object):

    def __init__(self,
                 mesh,
                 dir_from_center,
                 radial_dist,
                 sigma_theta,
                 sigma_r,
                 amplitude=1):

        self._mesh = mesh
        self._n0 = dir_from_center
        self._r0 = radial_dist
        self._sigma_theta = sigma_theta
        self._sigma_r = sigma_r
        self._amp = amplitude

        self.x = SpatialCoordinate(mesh)

    @property
    def r(self):
        x = self.x
        return sqrt(x[0]**2 + x[1]**2 + x[2]**2)

    @property
    def theta(self):
        x = self.x
        n0 = self._n0
        return acos(dot(x, n0) / abs(dot(x, n0)))

    @property
    def r_expr(self):
        r = self.r
        r0 = self._r0
        return r - r0

    @property
    def expression(self):
        A = self._amp
        theta = self.theta
        R = self.r_expr
        sigma_theta = self._sigma_theta
        sigma_r = self._sigma_r
        return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))

class MultipleGaussians(object):

    def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):

        self._N = n_gaussians
        self._R = r_earth
        self._H = thickness
        self._seed = seed
        self._generate_random_vars()

    def _generate_random_vars(self):
        np.random.rand(self._seed)
        ns = []
        rs = []
        for i in range(self._N):
            nrm = 0.0

            while (nrm < 0.5) or (nrm > 1.0):
                n = 2*np.random.rand(3) - 1.0
                nrm = np.linalg.norm(n)

            ns.append(as_vector(list(n)))
            rs.append(Constant(self._R + self._H * np.random.rand()))

        self._random_Ns = ns
        self._random_Rs = rs

    def expression(self, mesh):

        gs = []
        for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
            sigma_theta = 1.0 - 0.5 * (i / self._N)
            sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
            amplitude = 1.0
            g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
            gs.append(g.expression)

        return sum(gs)

Set up object to create random pressure field

Response:
from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
                       exp, as_vector, Constant, acos)
import numpy as np

class Gaussian(object):

    def __init__(self,
                 mesh,
                 dir_from_center,
                 radial_dist,
                 sigma_theta,
                 sigma_r,
                 amplitude=1):

        self._mesh = mesh
        self._n0 = dir_from_center
        self._r0 = radial_dist
        self._sigma_theta = sigma_theta
        self._sigma_r = sigma_r
        self._amp = amplitude

        self.x = SpatialCoordinate(mesh)

    @property
    def r(self):
        x = self.x
        return sqrt(x[0]**2 + x[1]**2 + x[2]**2)

    @property
    def theta(self):
        x = self.x
        n0 = self._n0
        return acos(dot(x, n0) / abs(dot(x, n0)))

    @property
    def r_expr(self):
        r = self.r
        r0 = self._r0
        return r - r0

    @property
    def expression(self):
        A = self._amp
        theta = self.theta
        R = self.r_expr
        sigma_theta = self._sigma_theta
        sigma_r = self._sigma_r
        return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))

class MultipleGaussians(object):

    def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):

        self._N = n_gaussians
        self._R = r_earth
        self._H = thickness
        self._seed = seed
        self._generate_random_vars()

    def _generate_random_vars(self):
        np.random.rand(self._seed)
        ns = []
        rs = []
        for i in range(self._N):
            nrm = 0.0

            while (nrm < 0.5) or (nrm > 1.0):
                n = 2*np.random.rand(3) - 1.0
                nrm = np.linalg.norm(n)

            ns.append(as_vector(list(n)))
            rs.append(Constant(self._R + self._H * np.random.rand()))

        self._random_Ns = ns
        self._random_Rs = rs

    def expression(self, mesh):

        gs = []
        for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
            sigma_theta = 1.0 - 0.5 * (i / self._N)
            sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
            amplitude = 1.0
            g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
            gs.append(g.expression)

        return sum(gs)

Prompt: Set up object to create random pressure field


from setuptools import setup
import os

#Function to read README
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='clipboard_memo',
    version='0.1',
    description='A command-line clipboard manager',
    long_description=read('README.rst'),
    url='http://github.com/arafsheikh/clipboard-memo',
    author='Sheikh Araf',
    author_email='arafsheikh@rocketmail.com',
    license='MIT',
    keywords='clipboard memo manager command-line CLI',
    include_package_data=True,
    entry_points='''
        [console_scripts]
        cmemo=clipboard_memo:main
        cmemo_direct=clipboard_memo:direct_save
    ''',
    py_modules=['clipboard_memo'],
    install_requires=[
        'pyperclip',
    ],
)

Use README.rst for long description

Use README.rst for long description

Response:
from setuptools import setup
import os

#Function to read README
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='clipboard_memo',
    version='0.1',
    description='A command-line clipboard manager',
    long_description=read('README.rst'),
    url='http://github.com/arafsheikh/clipboard-memo',
    author='Sheikh Araf',
    author_email='arafsheikh@rocketmail.com',
    license='MIT',
    keywords='clipboard memo manager command-line CLI',
    include_package_data=True,
    entry_points='''
        [console_scripts]
        cmemo=clipboard_memo:main
        cmemo_direct=clipboard_memo:direct_save
    ''',
    py_modules=['clipboard_memo'],
    install_requires=[
        'pyperclip',
    ],
)

Prompt:
Use README.rst for long description

from setuptools import setup
import os

#Function to read README
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='clipboard_memo',
    version='0.1',
    description='A command-line clipboard manager',
    long_description=read('README.md'),
    url='http://github.com/arafsheikh/clipboard-memo',
    author='Sheikh Araf',
    author_email='arafsheikh@rocketmail.com',
    license='MIT',
    keywords='clipboard memo manager command-line CLI',
    include_package_data=True,
    entry_points='''
        [console_scripts]
        cmemo=clipboard_memo:main
        cmemo_direct=clipboard_memo:direct_save
    ''',
    py_modules=['clipboard_memo'],
    install_requires=[
        'pyperclip',
    ],
)


from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
                                    image_and_scalar)
from metadatastore.api import Document

def run_example(example):
    events = example.run()
    assert_true(isinstance(events, list))
    assert_true(isinstance(events[0], Document))

def test_examples():
    for example in [temperature_ramp, multisource_event, image_and_scalar]:
        yield run_example, example

Use generator test for examples.

REF: Use generator test for examples.

Response:
from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
                                    image_and_scalar)
from metadatastore.api import Document

def run_example(example):
    events = example.run()
    assert_true(isinstance(events, list))
    assert_true(isinstance(events[0], Document))

def test_examples():
    for example in [temperature_ramp, multisource_event, image_and_scalar]:
        yield run_example, example

Prompt:
REF: Use generator test for examples.

import unittest
from ..examples.sample_data import (temperature_ramp, multisource_event,
                                    image_and_scalar)
from metadatastore.api import Document

class CommonSampleDataTests(object):
    def setUp(self):
        pass

    def test_basic_usage(self):
        events = self.example.run()

        # check expected types
        self.assertTrue(isinstance(events, list))
        self.assertTrue(isinstance(events[0], Document))

class TestTemperatureRamp(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = temperature_ramp

class TestMultisourceEvent(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = multisource_event

class TestImageAndScalar(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = image_and_scalar


# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('data_interfaces', '0018_check_for_rule_migration'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='automaticupdateaction',
            name='rule',
        ),
        migrations.RemoveField(
            model_name='automaticupdaterulecriteria',
            name='rule',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateAction',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateRuleCriteria',
        ),
    ]

Add migration to remove old rule models

Add migration to remove old rule models

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('data_interfaces', '0018_check_for_rule_migration'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='automaticupdateaction',
            name='rule',
        ),
        migrations.RemoveField(
            model_name='automaticupdaterulecriteria',
            name='rule',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateAction',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateRuleCriteria',
        ),
    ]

Prompt: Add migration to remove old rule models


# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest

from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager

if __name__ == '__main__':
    all_test_suites = []
    all_test_suites.append(testpost.get_test_suites())
    all_test_suites.append(testpage.get_test_suites())
    all_test_suites.append(testutility.get_test_suites())
    all_test_suites.append(testconfig.get_test_suites())
    all_test_suites.append(testgenerator.get_test_suites())
    all_test_suites.append(testpostmanager.get_test_suites())

    alltests = unittest.TestSuite(all_test_suites)

    status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
    sys.exit(status)

Response:
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest

from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager

if __name__ == '__main__':
    all_test_suites = []
    all_test_suites.append(testpost.get_test_suites())
    all_test_suites.append(testpage.get_test_suites())
    all_test_suites.append(testutility.get_test_suites())
    all_test_suites.append(testconfig.get_test_suites())
    all_test_suites.append(testgenerator.get_test_suites())
    all_test_suites.append(testpostmanager.get_test_suites())

    alltests = unittest.TestSuite(all_test_suites)

    status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
    sys.exit(status)

Prompt:
Add test cases for module post_manager, refactor part of class PostManager and update TODO list.

# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest

from yatest import testpost, testpage, testutility, testconfig

if __name__ == '__main__':
    all_test_suites = []
    all_test_suites.append(testpost.get_test_suites())
    all_test_suites.append(testpage.get_test_suites())
    all_test_suites.append(testutility.get_test_suites())
    all_test_suites.append(testconfig.get_test_suites())

    alltests = unittest.TestSuite(all_test_suites)

    status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
    sys.exit(status)


VERSION = (1, 4, 6, 'alpha', 0)

def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_svn_revision
        svn_revision = get_svn_revision()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub

Response:
VERSION = (1, 4, 6, 'alpha', 0)

def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_svn_revision
        svn_revision = get_svn_revision()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub

Prompt:
[1.4.x] Bump version to no longer claim to be 1.4.5 final.

VERSION = (1, 4, 5, 'final', 0)

def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_svn_revision
        svn_revision = get_svn_revision()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub


#!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/

"""Test tvnamer's filename parser
"""

import os
import sys
from copy import copy
import unittest

sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser

from test_files import files

def check_case(curtest):
    """Runs test case, used by test_generator
    """
    parser = FileParser(curtest['input'])
    theep = parser.parse()
    assert(theep.seriesname.lower() == curtest['seriesname'].lower(),
        "%s == %s" % (theep.seriesname.lower(), curtest['seriesname'].lower()))

    assert (theep.seasonnumber == curtest['seasonnumber'],
        "%s == %s" % (theep.seasonnumber, curtest['seasonnumber']))

    assert (theep.episodenumber == curtest['episodenumber'],
        "%s == %s" % (theep.episodenumber, curtest['episodenumber']))

def test_generator():
    """Generates test for each test case in test_files.py
    """
    for category, testcases in files.items():
        for testindex, curtest in enumerate(testcases):
            cur_tester = lambda x: check_case(x)
            cur_tester.description = '%s_%d' % (category, testindex)
            yield (cur_tester, curtest)

if __name__ == '__main__':
    import nose
    nose.main()

Response:
#!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/

"""Test tvnamer's filename parser
"""

import os
import sys
from copy import copy
import unittest

sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser

from test_files import files

def check_case(curtest):
    """Runs test case, used by test_generator
    """
    parser = FileParser(curtest['input'])
    theep = parser.parse()
    assert(theep.seriesname.lower() == curtest['seriesname'].lower(),
        "%s == %s" % (theep.seriesname.lower(), curtest['seriesname'].lower()))

    assert (theep.seasonnumber == curtest['seasonnumber'],
        "%s == %s" % (theep.seasonnumber, curtest['seasonnumber']))

    assert (theep.episodenumber == curtest['episodenumber'],
        "%s == %s" % (theep.episodenumber, curtest['episodenumber']))

def test_generator():
    """Generates test for each test case in test_files.py
    """
    for category, testcases in files.items():
        for testindex, curtest in enumerate(testcases):
            cur_tester = lambda x: check_case(x)
            cur_tester.description = '%s_%d' % (category, testindex)
            yield (cur_tester, curtest)

if __name__ == '__main__':
    import nose
    nose.main()

Prompt:
Fix utility being picked up as test, display expected-and-got values in assertion error
#!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/

"""Test tvnamer's filename parser
"""

import os
import sys
from copy import copy
import unittest

sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser

from test_files import files

def check_test(curtest):
    """Runs test case, used by test_generator
    """
    parser = FileParser(curtest['input'])
    theep = parser.parse()
    assert theep.seriesname.lower() == curtest['seriesname'].lower()
    assert theep.seasonnumber == curtest['seasonnumber']
    assert theep.episodenumber == curtest['episodenumber']

def test_generator():
    """Generates test for each test case in test_files.py
    """
    for category, testcases in files.items():
        for testindex, curtest in enumerate(testcases):
            cur_tester = lambda x: check_test(x)
            cur_tester.description = '%s_%d' % (category, testindex)
            yield (cur_tester, curtest)

if __name__ == '__main__':
    import nose
    nose.main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '__first__'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='GenericLink',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('object_id', models.PositiveIntegerField(db_index=True)),
                ('url', models.URLField()),
                ('title', models.CharField(max_length=200)),
                ('description', models.TextField(max_length=1000, null=True, blank=True)),
                ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('is_external', models.BooleanField(default=True, db_index=True)),
                ('content_type', models.ForeignKey(to='contenttypes.ContentType')),
                ('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
            ],
            options={
                'ordering': ('-created_at',),
                'verbose_name': 'Generic Link',
                'verbose_name_plural': 'Generic Links',
            },
        ),
    ]

Response:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '__first__'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='GenericLink',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('object_id', models.PositiveIntegerField(db_index=True)),
                ('url', models.URLField()),
                ('title', models.CharField(max_length=200)),
                ('description', models.TextField(max_length=1000, null=True, blank=True)),
                ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('is_external', models.BooleanField(default=True, db_index=True)),
                ('content_type', models.ForeignKey(to='contenttypes.ContentType')),
                ('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
            ],
            options={
                'ordering': ('-created_at',),
                'verbose_name': 'Generic Link',
                'verbose_name_plural': 'Generic Links',
            },
        ),
    ]

Prompt:
Remove Django 1.8 dependency in initial migration

The ('contenttypes', '0002_remove_content_type_name') migration was part of Django 1.8, replacing it with '__first__' allows the use of Django 1.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='GenericLink',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('object_id', models.PositiveIntegerField(db_index=True)),
                ('url', models.URLField()),
                ('title', models.CharField(max_length=200)),
                ('description', models.TextField(max_length=1000, null=True, blank=True)),
                ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('is_external', models.BooleanField(default=True, db_index=True)),
                ('content_type', models.ForeignKey(to='contenttypes.ContentType')),
                ('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
            ],
            options={
                'ordering': ('-created_at',),
                'verbose_name': 'Generic Link',
                'verbose_name_plural': 'Generic Links',
            },
        ),
    ]


import asyncio

import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger

EXCEPTIONS = (
    aiohttp.client_exceptions.ClientConnectionError,
    aiohttp.client_exceptions.InvalidURL,
    aiohttp.client_exceptions.TooManyRedirects,
    AssertionError,
    asyncio.TimeoutError,
    UnicodeError,
)

async def download(url: str, path: AsyncPath) -> bool:
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url, timeout=10) as response:

                if response.status == 200:
                    f = await aiofiles.open(path, mode="wb")  # type: ignore
                    await f.write(await response.read())
                    await f.close()
                    return True

                logger.error(f"{response.status} response from {url}")

        except EXCEPTIONS as e:
            message = str(e).strip("() ") or e.__class__.__name__
            logger.error(f"Invalid response from {url}: {message}")

    return False

Response:
import asyncio

import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger

EXCEPTIONS = (
    aiohttp.client_exceptions.ClientConnectionError,
    aiohttp.client_exceptions.InvalidURL,
    aiohttp.client_exceptions.TooManyRedirects,
    AssertionError,
    asyncio.TimeoutError,
    UnicodeError,
)

async def download(url: str, path: AsyncPath) -> bool:
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url, timeout=10) as response:

                if response.status == 200:
                    f = await aiofiles.open(path, mode="wb")  # type: ignore
                    await f.write(await response.read())
                    await f.close()
                    return True

                logger.error(f"{response.status} response from {url}")

        except EXCEPTIONS as e:
            message = str(e).strip("() ") or e.__class__.__name__
            logger.error(f"Invalid response from {url}: {message}")

    return False

Prompt:
Add timeout to downloading custom background images

import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger

EXCEPTIONS = (
    aiohttp.client_exceptions.ClientConnectionError,
    aiohttp.client_exceptions.InvalidURL,
    aiohttp.client_exceptions.TooManyRedirects,
    AssertionError,
    UnicodeError,
)

async def download(url: str, path: AsyncPath) -> bool:
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(url) as response:

                if response.status == 200:
                    f = await aiofiles.open(path, mode="wb")  # type: ignore
                    await f.write(await response.read())
                    await f.close()
                    return True

                logger.error(f"{response.status} response from {url}")

        except EXCEPTIONS as e:
            message = str(e).strip("() ")
            logger.error(f"Invalid response from {url}: {message}")

    return False


#!/usr/bin/python

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

import unittest
from selenium.webdriver.common.proxy import Proxy

class ProxyTests(unittest.TestCase):

    def testCanAddToDesiredCapabilities(self):
        desired_capabilities = {}
        proxy = Proxy()
        proxy.http_proxy = 'some.url:1234'

        proxy.add_to_capabilities(desired_capabilities)

        expected_capabilities = {
            'proxy': {
                'proxyType': 'MANUAL',
                'httpProxy': 'some.url:1234'
            }
        }

        self.assertEqual(expected_capabilities, desired_capabilities)

Fix test as well :)

Response:
#!/usr/bin/python

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

import unittest
from selenium.webdriver.common.proxy import Proxy

class ProxyTests(unittest.TestCase):

    def testCanAddToDesiredCapabilities(self):
        desired_capabilities = {}
        proxy = Proxy()
        proxy.http_proxy = 'some.url:1234'

        proxy.add_to_capabilities(desired_capabilities)

        expected_capabilities = {
            'proxy': {
                'proxyType': 'MANUAL',
                'httpProxy': 'some.url:1234'
            }
        }

        self.assertEqual(expected_capabilities, desired_capabilities)

Prompt:
DanielWagnerHall: Fix test as well :)

r17825

#!/usr/bin/python

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

import unittest
from selenium.webdriver.common.proxy import Proxy

class ProxyTests(unittest.TestCase):

    def testCanAddToDesiredCapabilities(self):
        desired_capabilities = {}
        proxy = Proxy()
        proxy.http_proxy = 'some.url:1234'

        proxy.add_to_capabilities(desired_capabilities)

        expected_capabilities = {
            'proxy': {
                'proxyType': 'manual',
                'httpProxy': 'some.url:1234'
            }
        }

        self.assertEqual(expected_capabilities, desired_capabilities)


from abc import (
    ABCMeta,
    abstractmethod,
)
from impact.v1.helpers import (
    STRING_FIELD,
)

class BaseHistoryEvent(object):
    __metaclass__ = ABCMeta

    CLASS_FIELDS = {
        "event_type": STRING_FIELD,
        "datetime": STRING_FIELD,
        "latest_datetime": STRING_FIELD,
        "description": STRING_FIELD,
    }

    def __init__(self):
        self.earliest = None
        self.latest = None

    @classmethod
    def all_fields(cls):
        result = {}
        for base_class in cls.__bases__:
            if hasattr(base_class, "all_fields"):
                result.update(base_class.all_fields())
        if hasattr(cls, "CLASS_FIELDS"):
            result.update(cls.CLASS_FIELDS)
        return result

    @classmethod
    def event_type(cls):
        return cls.EVENT_TYPE

    @abstractmethod
    def calc_datetimes(self):
        pass  # pragma: no cover

    def datetime(self):
        self._check_date_cache()
        return self.earliest

    def latest_datetime(self):
        self._check_date_cache()
        return self.latest

    def _check_date_cache(self):
        if not self.earliest and hasattr(self, "calc_datetimes"):
            self.calc_datetimes()

    def description(self):
        return None  # pragma: no cover

    def serialize(self):
        result = {}
        for key in self.all_fields().keys():
            value = getattr(self, key).__call__()
            if value is not None:
                result[key] = value
        return result

Switch from () to __call__()

[AC-4857] Switch from () to __call__()

Response:
from abc import (
    ABCMeta,
    abstractmethod,
)
from impact.v1.helpers import (
    STRING_FIELD,
)

class BaseHistoryEvent(object):
    __metaclass__ = ABCMeta

    CLASS_FIELDS = {
        "event_type": STRING_FIELD,
        "datetime": STRING_FIELD,
        "latest_datetime": STRING_FIELD,
        "description": STRING_FIELD,
    }

    def __init__(self):
        self.earliest = None
        self.latest = None

    @classmethod
    def all_fields(cls):
        result = {}
        for base_class in cls.__bases__:
            if hasattr(base_class, "all_fields"):
                result.update(base_class.all_fields())
        if hasattr(cls, "CLASS_FIELDS"):
            result.update(cls.CLASS_FIELDS)
        return result

    @classmethod
    def event_type(cls):
        return cls.EVENT_TYPE

    @abstractmethod
    def calc_datetimes(self):
        pass  # pragma: no cover

    def datetime(self):
        self._check_date_cache()
        return self.earliest

    def latest_datetime(self):
        self._check_date_cache()
        return self.latest

    def _check_date_cache(self):
        if not self.earliest and hasattr(self, "calc_datetimes"):
            self.calc_datetimes()

    def description(self):
        return None  # pragma: no cover

    def serialize(self):
        result = {}
        for key in self.all_fields().keys():
            value = getattr(self, key).__call__()
            if value is not None:
                result[key] = value
        return result

Prompt:
[AC-4857] Switch from () to __call__()

from abc import (
    ABCMeta,
    abstractmethod,
)
from impact.v1.helpers import (
    STRING_FIELD,
)

class BaseHistoryEvent(object):
    __metaclass__ = ABCMeta

    CLASS_FIELDS = {
        "event_type": STRING_FIELD,
        "datetime": STRING_FIELD,
        "latest_datetime": STRING_FIELD,
        "description": STRING_FIELD,
    }

    def __init__(self):
        self.earliest = None
        self.latest = None

    @classmethod
    def all_fields(cls):
        result = {}
        for base_class in cls.__bases__:
            if hasattr(base_class, "all_fields"):
                result.update(base_class.all_fields())
        if hasattr(cls, "CLASS_FIELDS"):
            result.update(cls.CLASS_FIELDS)
        return result

    @classmethod
    def event_type(cls):
        return cls.EVENT_TYPE

    @abstractmethod
    def calc_datetimes(self):
        pass  # pragma: no cover

    def datetime(self):
        self._check_date_cache()
        return self.earliest

    def latest_datetime(self):
        self._check_date_cache()
        return self.latest

    def _check_date_cache(self):
        if not self.earliest and hasattr(self, "calc_datetimes"):
            self.calc_datetimes()

    def description(self):
        return None  # pragma: no cover

    def serialize(self):
        result = {}
        for key in self.all_fields().keys():
            value = getattr(self, key)()
            if value is not None:
                result[key] = value
        return result


from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker

from imager_profile.models import ImagerProfile
from .models import Album, Pho

# Create your tests here.
fake = Faker()

class UserFactory(factory.Factory):
    """Create a fake user."""
    class Meta:
        model = User

    username = factory.Sequence(lambda n: 'user{}'.format(n))
    first_name = fake.first_name()
    last_name = fake.last_name()
    email = fake.email()

Add a UserFactory for images test

Add a UserFactory for images test

Response:
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker

from imager_profile.models import ImagerProfile
from .models import Album, Pho

# Create your tests here.
fake = Faker()

class UserFactory(factory.Factory):
    """Create a fake user."""
    class Meta:
        model = User

    username = factory.Sequence(lambda n: 'user{}'.format(n))
    first_name = fake.first_name()
    last_name = fake.last_name()
    email = fake.email()

Prompt:
Add a UserFactory for images test

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker

from imager_profile.models import ImagerProfile
from .models import Album, Photo

# Create your tests here.


"""Tests for vumi.scripts.db_backup."""

from twisted.trial.unittest import TestCase

from vumi.tests.utils import PersistenceMixin

from vumi.scripts.db_backup import ConfigHolder, Options

class TestConfigHolder(ConfigHolder):
    def __init__(self, *args, **kwargs):
        self.output = []
        super(TestConfigHolder, self).__init__(*args, **kwargs)

    def emit(self, s):
        self.output.append(s)

def make_cfg(args):
    options = Options()
    options.parseOptions(args)
    return TestConfigHolder(options)

class DbBackupBaseTestCase(TestCase, PersistenceMixin):
    sync_persistence = True

    def setUp(self):
        self._persist_setUp()
        # Make sure we start fresh.
        self.get_redis_manager()._purge_all()

    def tearDown(self):
        return self._persist_tearDown()

class BackupDbCmdTestCase(DbBackupBaseTestCase):
    def test_backup_db(self):
        cfg = make_cfg(["backup", "db_config.yaml"])
        cfg.run()
        self.assertEqual(cfg.output, [
            'Backing up dbs ...',
        ])

class RestoreDbCmdTestCase(DbBackupBaseTestCase):
    def test_create_pool_range_tags(self):
        cfg = make_cfg(["restore", "db_backup.json"])
        cfg.run()
        self.assertEqual(cfg.output, [
            'Restoring dbs ...',
        ])

Test skeleton for db backup scripts.

Test skeleton for db backup scripts.

Response:
"""Tests for vumi.scripts.db_backup."""

from twisted.trial.unittest import TestCase

from vumi.tests.utils import PersistenceMixin

from vumi.scripts.db_backup import ConfigHolder, Options

class TestConfigHolder(ConfigHolder):
    def __init__(self, *args, **kwargs):
        self.output = []
        super(TestConfigHolder, self).__init__(*args, **kwargs)

    def emit(self, s):
        self.output.append(s)

def make_cfg(args):
    options = Options()
    options.parseOptions(args)
    return TestConfigHolder(options)

class DbBackupBaseTestCase(TestCase, PersistenceMixin):
    sync_persistence = True

    def setUp(self):
        self._persist_setUp()
        # Make sure we start fresh.
        self.get_redis_manager()._purge_all()

    def tearDown(self):
        return self._persist_tearDown()

class BackupDbCmdTestCase(DbBackupBaseTestCase):
    def test_backup_db(self):
        cfg = make_cfg(["backup", "db_config.yaml"])
        cfg.run()
        self.assertEqual(cfg.output, [
            'Backing up dbs ...',
        ])

class RestoreDbCmdTestCase(DbBackupBaseTestCase):
    def test_create_pool_range_tags(self):
        cfg = make_cfg(["restore", "db_backup.json"])
        cfg.run()
        self.assertEqual(cfg.output, [
            'Restoring dbs ...',
        ])

Prompt: Test skeleton for db backup scripts.


from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone

def process_queue():
    filtered = Query.objects.filter(is_finished=False)

    try:
        oldest_query = filtered.order_by('id')[:1].get()
    except Query.DoesNotExist:
        return

    backend = get_backend()
    try:
        res = backend.run_query(oldest_query.sql, oldest_query.owner)
    except Exception as ex:
        oldest_query.has_error = True
        oldest_query.error = str(ex)

    oldest_query.is_finished = True
    oldest_query.date_finished = timezone.now()
    oldest_query.save()

Response:
from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone

def process_queue():
    filtered = Query.objects.filter(is_finished=False)

    try:
        oldest_query = filtered.order_by('id')[:1].get()
    except Query.DoesNotExist:
        return

    backend = get_backend()
    try:
        res = backend.run_query(oldest_query.sql, oldest_query.owner)
    except Exception as ex:
        oldest_query.has_error = True
        oldest_query.error = str(ex)

    oldest_query.is_finished = True
    oldest_query.date_finished = timezone.now()
    oldest_query.save()

Prompt:
Remove a print statement that was dumb and breaking python3

from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone

def process_queue():
    filtered = Query.objects.filter(is_finished=False)

    try:
        oldest_query = filtered.order_by('id')[:1].get()
    except Query.DoesNotExist:
        return

    backend = get_backend()
    try:
        res = backend.run_query(oldest_query.sql, oldest_query.owner)
    except Exception as ex:
        oldest_query.has_error = True
        oldest_query.error = str(ex)

    oldest_query.is_finished = True
    oldest_query.date_finished = timezone.now()
    print "Finished: ", oldest_query.date_finished
    oldest_query.save()


from django.db import models
from datetime import datetime
import settings

class Email(models.Model):
    ''' Monitor emails sent '''
    to      = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emails')
    subject = models.CharField(max_length=150)
    body    = models.TextField()
    at      = models.DateTimeField(default=datetime.now)

    prefetch = ['to']

    def __str__(self):
        return 'TO: %s, %s' % (self.to, self.subject)

    @models.permalink
    def get_absolute_url(self):
        if self.body:
            return 'email', [self.pk]
        return ''

    class Meta:
        db_table = 'emails'

class UserSubscription(models.Model):
    ''' Abstract subscription model to subclass.
    Add boolean fields to your subclass to make your own subscriptions
    named recieve_x; e.g.: receive_newsletter, receive_alerts etc.
    This will allow users to subscribe to different types of non-transactional emails.
    '''
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
    receive_email = models.BooleanField('E-mail', default=True)

    def __str__(self):
        return str(self.pk)

    class Meta:
        abstract = True

Add a django model to save emails and specify subscriptions.

Response:
from django.db import models
from datetime import datetime
import settings

class Email(models.Model):
    ''' Monitor emails sent '''
    to      = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emails')
    subject = models.CharField(max_length=150)
    body    = models.TextField()
    at      = models.DateTimeField(default=datetime.now)

    prefetch = ['to']

    def __str__(self):
        return 'TO: %s, %s' % (self.to, self.subject)

    @models.permalink
    def get_absolute_url(self):
        if self.body:
            return 'email', [self.pk]
        return ''

    class Meta:
        db_table = 'emails'

class UserSubscription(models.Model):
    ''' Abstract subscription model to subclass.
    Add boolean fields to your subclass to make your own subscriptions
    named recieve_x; e.g.: receive_newsletter, receive_alerts etc.
    This will allow users to subscribe to different types of non-transactional emails.
    '''
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
    receive_email = models.BooleanField('E-mail', default=True)

    def __str__(self):
        return str(self.pk)

    class Meta:
        abstract = True

Prompt: Add a django model to save emails and specify subscriptions.


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.test import TestCase

from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (build_localized_fieldname,
                              split_translated_fieldname)
from tests.app.models import Blog

class UtilsTest(TestCase):
    def test_split_translated_fieldname(self):

        self.assertEquals(
            split_translated_fieldname('title_nl'),
            ('title', 'nl')
        )

        self.assertEquals(
            split_translated_fieldname('full_name_nl'),
            ('full_name', 'nl')
        )

    def test_transform_translatable_fields(self):
        self.assertEquals(
            transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
            {
                'i18n': {
                    'title_nl': 'foo'
                },
                'title': 'bar'
            }
        )

    def test_build_localized_fieldname(self):
        self.assertEquals(
            build_localized_fieldname('title', 'nl'),
            'title_nl'
        )
        self.assertEquals(
            build_localized_fieldname('category__name', 'nl'),
            'category__name_nl'
        )

Use proper import from utils

Use proper import from utils

Response:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.test import TestCase

from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (build_localized_fieldname,
                              split_translated_fieldname)
from tests.app.models import Blog

class UtilsTest(TestCase):
    def test_split_translated_fieldname(self):

        self.assertEquals(
            split_translated_fieldname('title_nl'),
            ('title', 'nl')
        )

        self.assertEquals(
            split_translated_fieldname('full_name_nl'),
            ('full_name', 'nl')
        )

    def test_transform_translatable_fields(self):
        self.assertEquals(
            transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
            {
                'i18n': {
                    'title_nl': 'foo'
                },
                'title': 'bar'
            }
        )

    def test_build_localized_fieldname(self):
        self.assertEquals(
            build_localized_fieldname('title', 'nl'),
            'title_nl'
        )
        self.assertEquals(
            build_localized_fieldname('category__name', 'nl'),
            'category__name_nl'
        )

Prompt:
Use proper import from utils

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.test import TestCase

from modeltrans.manager import (split_translated_fieldname,
                                transform_translatable_fields)
from modeltrans.utils import build_localized_fieldname
from tests.app.models import Blog

class UtilsTest(TestCase):
    def test_split_translated_fieldname(self):

        self.assertEquals(
            split_translated_fieldname('title_nl'),
            ('title', 'nl')
        )

        self.assertEquals(
            split_translated_fieldname('full_name_nl'),
            ('full_name', 'nl')
        )

    def test_transform_translatable_fields(self):
        self.assertEquals(
            transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
            {
                'i18n': {
                    'title_nl': 'foo'
                },
                'title': 'bar'
            }
        )

    def test_build_localized_fieldname(self):
        self.assertEquals(
            build_localized_fieldname('title', 'nl'),
            'title_nl'
        )
        self.assertEquals(
            build_localized_fieldname('category__name', 'nl'),
            'category__name_nl'
        )


from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

import base64
import unittest
import sys
import os

sys.path.append(os.path.abspath('../server.py'))

import server

class TestPosieService(unittest.TestCase):

    def test_key_generation(self):
        # Load public der key from http endpoint

        key_string = base64.b64decode(server.key())

        public_key = serialization.load_der_public_key(
            key_string,
            backend=default_backend()
        )

        self.assertIsNotNone(public_key)

Response:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

import base64
import unittest
import sys
import os

sys.path.append(os.path.abspath('../server.py'))

import server

class TestPosieService(unittest.TestCase):

    def test_key_generation(self):
        # Load public der key from http endpoint

        key_string = base64.b64decode(server.key())

        public_key = serialization.load_der_public_key(
            key_string,
            backend=default_backend()
        )

        self.assertIsNotNone(public_key)

Prompt:
Remove requests and drop external tests (now in integration)

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization, hashes

import requests
import base64
import unittest
import os

class TestPosieService(unittest.TestCase):

    POSIE_URL = os.getenv('POSIE_URL', 'http://127.0.0.1:5000')

    key_url = "{}/key".format(POSIE_URL)
    import_url = "{}/decrypt".format(POSIE_URL)
    public_key = ""

    def setUp(self):
        # Load public der key from http endpoint

        r = requests.get(self.key_url)

        key_string = base64.b64decode(r.text)

        self.public_key = serialization.load_der_public_key(
            key_string,
            backend=default_backend()
        )

    def send_message(self, message):

        ciphertext = self.public_key.encrypt(
            message,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )

        # Ask posie to decode message
        r = requests.post(self.import_url, data=base64.b64encode(ciphertext))

        return r

    def test_decrypt_fail_sends_400(self):

        # Ask posie to decode message
        r = requests.post(self.import_url, data='rubbish')

        self.assertEqual(r.status_code, 400)

    def test_no_content_sends_400(self):

        # Ask posie to decode message
        r = requests.post(self.import_url, data='')

        self.assertEqual(r.status_code, 400)

    def test_decrypts_message(self):
        # Encrypt a message with the key
        message = b"Some encrypted message"

        # Ask posie to decode message
        r = self.send_message(message)

        # Compare to bytestring version of decrypted data
        self.assertEqual(str.encode(r.text), message)


import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G, M_sun, au
from astropy.units.core import UnitConversionError

def keplerian_binary(givenquant):
    '''Return equivalency for Keplerian binary orbit.

    Parameters
    ----------
    givenquant : `~astropy.units.Quantity`
        `astropy.units.Quantity` associated with the parameter of the orbit
        that is fixed for this conversion (e.g. to convert between period and
        semimajor axis, this should be a mass quanitity).
    '''
    # Finding a pythonic way to to cycle through the three potential choices
    # for givenquant has been difficult. This seems to follow the rule of EAFP
    # best. First I will assume that givenquant is a mass, then a semimajor
    # axis, then a period.
    try:
        fixedmass = givenquant.to(u.solMass)
    except UnitConversionError:
        try:
            fixedsemimajor = givenquant.to(u.AU)
        except UnitConversionError:
            try:
                fixedperiod = givenquant.to(u.year).value
            except UnitConversionError:
                # If it's neither a mass, length, or year, then the wrong
                # quantity was given.
                raise ValueError(
                    "The fixed quantity must be either a mass, time interval, "
                    "or length.")
            else:
                # givenquant is a time
                fromunit = u.solMass
                tounit = u.AU
                def fromfunction(M):
                    return (M * fixedperiod**2)**(1/3)
                def tofunction(a):
                    return a**3 / fixedperiod**2
        else:
            # givenquant is a length
            fromunit = u.solMass
            tounit = u.year
            def fromfunction(M):
                return (fixedsemimajor**3 / M)**(1/2)
            def tofunction(P):
                return fixedsemimajor**3 / P**2
    else:
        # givenquant is a mass
        fromunit = u.year
        tounit = u.AU
        def fromfunction(P):
            return (P**2 * fixedmass)**(1/3)
        def tofunction(a):
            return (a**3 / fixedmass)**(1/2)

    equiv = [
        (fromunit, tounit, fromfunction, tofunction)]
    return equiv

def calc_velocity_of_binary(masses, period, mass_ratio):
    '''Returns the orbital velocity of a binary specified by mass and period.

    The masses should be the total mass of the system and the period should be
    the orbital period of the system.
    '''
    vel = ((2 * np.pi * G * masses / period)**(1/3) * mass_ratio /
           (1 + mass_ratio))
    try:
        return vel.to(u.km/u.s)
    except u.UnitConversionError as e:
        raise TypeError("Arguments should be Astropy Quantities with "
                        "appropriate units")

Convert between period, semimajor axis, and total mass for Keplerian orbit.

For cases where a quick and easy conversion between period and semimajor axis
is needed for some sort of binary system, this function will be able to do the
conversion relatively quickly by taking one aspect to be fixed, and doing the
rest of the conversions through the Astropy Quantitity framework.

What needs to be added now is testing guidelines.

Response:
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G, M_sun, au
from astropy.units.core import UnitConversionError

def keplerian_binary(givenquant):
    '''Return equivalency for Keplerian binary orbit.

    Parameters
    ----------
    givenquant : `~astropy.units.Quantity`
        `astropy.units.Quantity` associated with the parameter of the orbit
        that is fixed for this conversion (e.g. to convert between period and
        semimajor axis, this should be a mass quanitity).
    '''
    # Finding a pythonic way to to cycle through the three potential choices
    # for givenquant has been difficult. This seems to follow the rule of EAFP
    # best. First I will assume that givenquant is a mass, then a semimajor
    # axis, then a period.
    try:
        fixedmass = givenquant.to(u.solMass)
    except UnitConversionError:
        try:
            fixedsemimajor = givenquant.to(u.AU)
        except UnitConversionError:
            try:
                fixedperiod = givenquant.to(u.year).value
            except UnitConversionError:
                # If it's neither a mass, length, or year, then the wrong
                # quantity was given.
                raise ValueError(
                    "The fixed quantity must be either a mass, time interval, "
                    "or length.")
            else:
                # givenquant is a time
                fromunit = u.solMass
                tounit = u.AU
                def fromfunction(M):
                    return (M * fixedperiod**2)**(1/3)
                def tofunction(a):
                    return a**3 / fixedperiod**2
        else:
            # givenquant is a length
            fromunit = u.solMass
            tounit = u.year
            def fromfunction(M):
                return (fixedsemimajor**3 / M)**(1/2)
            def tofunction(P):
                return fixedsemimajor**3 / P**2
    else:
        # givenquant is a mass
        fromunit = u.year
        tounit = u.AU
        def fromfunction(P):
            return (P**2 * fixedmass)**(1/3)
        def tofunction(a):
            return (a**3 / fixedmass)**(1/2)

    equiv = [
        (fromunit, tounit, fromfunction, tofunction)]
    return equiv

def calc_velocity_of_binary(masses, period, mass_ratio):
    '''Returns the orbital velocity of a binary specified by mass and period.

    The masses should be the total mass of the system and the period should be
    the orbital period of the system.
    '''
    vel = ((2 * np.pi * G * masses / period)**(1/3) * mass_ratio /
           (1 + mass_ratio))
    try:
        return vel.to(u.km/u.s)
    except u.UnitConversionError as e:
        raise TypeError("Arguments should be Astropy Quantities with "
                        "appropriate units")

Prompt:
Convert between period, semimajor axis, and total mass for Keplerian orbit.

For cases where a quick and easy conversion between period and semimajor axis
is needed for some sort of binary system, this function will be able to do the
conversion relatively quickly by taking one aspect to be fixed, and doing the
rest of the conversions through the Astropy Quantitity framework.

What needs to be added now is testing guidelines.


import pytest

@pytest.mark.usefixtures('tmpdir')
class TestMove:
    config = """
        tasks:
          test_move:
            mock:
            - title: a movie
              location: __tmp__/movie.mkv
            accept_all: yes
            move:
              # Take advantage that path validation allows non-existent dirs if they are jinja
              to: __tmp__/{{ 'newdir' }}/
    """

    @pytest.mark.filecopy('movie.mkv', '__tmp__/movie.mkv')
    def test_move(self, execute_task, tmpdir):
        assert (tmpdir / 'movie.mkv').exists()
        task = execute_task('test_move')
        assert not (tmpdir / 'movie.mkv').exists()
        assert (tmpdir / 'newdir/movie.mkv').exists()

Add very basic move plugin test

Add very basic move plugin test

Response:
import pytest

@pytest.mark.usefixtures('tmpdir')
class TestMove:
    config = """
        tasks:
          test_move:
            mock:
            - title: a movie
              location: __tmp__/movie.mkv
            accept_all: yes
            move:
              # Take advantage that path validation allows non-existent dirs if they are jinja
              to: __tmp__/{{ 'newdir' }}/
    """

    @pytest.mark.filecopy('movie.mkv', '__tmp__/movie.mkv')
    def test_move(self, execute_task, tmpdir):
        assert (tmpdir / 'movie.mkv').exists()
        task = execute_task('test_move')
        assert not (tmpdir / 'movie.mkv').exists()
        assert (tmpdir / 'newdir/movie.mkv').exists()

Prompt: Add very basic move plugin test


from setuptools import setup, find_packages

import re

with open("README.rst", mode='r') as readme_file:
    text=readme_file.read()

#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
    version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
                               fd.read(), re.MULTILINE).group(1)
if not version_number:
    raise RuntimeError('Cannot find version information')

setup(
    name='pyautoupdate',
    version=version_number,
    packages=find_packages(),
    description='Interface to allow python programs to automatically update',
    long_description=text,
    url='https://github.com/rlee287/pyautoupdate',
    install_requires=['requests'],
    extras_require={
        'testing': ['pytest','coverage']
    },
    package_data={
        'testing':['*.rst']},
    license="LGPL 2.1"
)

Response:
from setuptools import setup, find_packages

import re

with open("README.rst", mode='r') as readme_file:
    text=readme_file.read()

#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
    version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
                               fd.read(), re.MULTILINE).group(1)
if not version_number:
    raise RuntimeError('Cannot find version information')

setup(
    name='pyautoupdate',
    version=version_number,
    packages=find_packages(),
    description='Interface to allow python programs to automatically update',
    long_description=text,
    url='https://github.com/rlee287/pyautoupdate',
    install_requires=['requests'],
    extras_require={
        'testing': ['pytest','coverage']
    },
    package_data={
        'testing':['*.rst']},
    license="LGPL 2.1"
)

Prompt:
Fix continuation whitespace and add extras_require

from setuptools import setup, find_packages

import re

with open("README.rst", mode='r') as readme_file:
    text=readme_file.read()

#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
    version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
                        fd.read(), re.MULTILINE).group(1)
if not version_number:
    raise RuntimeError('Cannot find version information')

setup(
    name='pyautoupdate',
    version=version_number,
    packages=find_packages(),
    description='Interface to allow python programs to automatically update',
    long_description=text,
    url='https://github.com/rlee287/pyautoupdate',
    install_requires=['requests>=2.6'],
    package_data={
        'testing':['*.rst']},
    license="LGPL 2.1"
)


from setuptools import setup

setup(name='pygraphc',
      version='0.0.1',
      description='Event log clustering in Python',
      long_description='This package contains event log clustering method including non-graph and '
                       'graph-based approaches.',
      classifiers=[
            'Development Status :: 2 - Pre-Alpha',
            'License :: OSI Approved :: MIT License',
            'Programming Language :: Python :: 2.7',
            'Topic :: Security',
      ],
      keywords='log clustering graph anomaly',
      url='http://github.com/studiawan/pygraphc/',
      author='Hudan Studiawan',
      author_email='studiawan@gmail.com',
      license='MIT',
      packages=['pygraphc'],
      scripts=['scripts/pygraphc'],
      entry_points={
          'console_scripts': ['pygraphc=scripts.pygraphc:main']
      },
      install_requires=[
            'networkx',
            'scikit-learn',
            'nltk',
            'Sphinx',
            'numpydoc',
            'TextBlob',
      ],
      include_package_data=True,
      zip_safe=False)

Response:
from setuptools import setup

setup(name='pygraphc',
      version='0.0.1',
      description='Event log clustering in Python',
      long_description='This package contains event log clustering method including non-graph and '
                       'graph-based approaches.',
      classifiers=[
            'Development Status :: 2 - Pre-Alpha',
            'License :: OSI Approved :: MIT License',
            'Programming Language :: Python :: 2.7',
            'Topic :: Security',
      ],
      keywords='log clustering graph anomaly',
      url='http://github.com/studiawan/pygraphc/',
      author='Hudan Studiawan',
      author_email='studiawan@gmail.com',
      license='MIT',
      packages=['pygraphc'],
      scripts=['scripts/pygraphc'],
      entry_points={
          'console_scripts': ['pygraphc=scripts.pygraphc:main']
      },
      install_requires=[
            'networkx',
            'scikit-learn',
            'nltk',
            'Sphinx',
            'numpydoc',
            'TextBlob',
      ],
      include_package_data=True,
      zip_safe=False)

Prompt:
Add entry_points to run executable pygraphc

from setuptools import setup

setup(name='pygraphc',
      version='0.0.1',
      description='Event log clustering in Python',
      long_description='This package contains event log clustering method including non-graph and '
                       'graph-based approaches.',
      classifiers=[
            'Development Status :: 2 - Pre-Alpha',
            'License :: OSI Approved :: MIT License',
            'Programming Language :: Python :: 2.7',
            'Topic :: Security',
      ],
      keywords='log clustering graph anomaly',
      url='http://github.com/studiawan/pygraphc/',
      author='Hudan Studiawan',
      author_email='studiawan@gmail.com',
      license='MIT',
      packages=['pygraphc'],
      scripts=['scripts/pygraphc'],
      install_requires=[
            'networkx',
            'numpy',
            'scipy',
            'scikit-learn',
            'nltk',
            'Sphinx',
            'numpydoc',
            'TextBlob',
      ],
      include_package_data=True,
      zip_safe=False)


# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 22:09:10 2013

@author: Jeff
"""
import logging
try: print('Logger already instantiated, named: ', logger.name)
except:
    # create logger
    logger = logging.getLogger()
    logger.setLevel(logging.CRITICAL)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    # add the handlers to the logger
    logger.addHandler(ch)

class foo:
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)
        self.test()
    def test(self):
        self._logger.debug('test4_debug')
        self._logger.info('test4_info')
        self._logger.warning('test4_warning')
        self._logger.error('test4_error')
        self._logger.critical('test4_critical')

class spam:
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)
        self.test()
    def test(self):
        self._logger.debug('test5_debug')
        self._logger.info('test5_info')
        self._logger.warning('test5_warning')
        self._logger.error('test5_error')
        self._logger.critical('test5_critical')
if __name__ =="__main__":
    y = foo()
    x = spam()

Test script show how we might use the Python logger more effectively

Former-commit-id: cc69a6ab3b6c61fd2f3e60bd16085b81cda84e42
Former-commit-id: 28ba0ba57de3379bd99b9f508972cd0520c04fcb

Response:
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 22:09:10 2013

@author: Jeff
"""
import logging
try: print('Logger already instantiated, named: ', logger.name)
except:
    # create logger
    logger = logging.getLogger()
    logger.setLevel(logging.CRITICAL)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    # add the handlers to the logger
    logger.addHandler(ch)

class foo:
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)
        self.test()
    def test(self):
        self._logger.debug('test4_debug')
        self._logger.info('test4_info')
        self._logger.warning('test4_warning')
        self._logger.error('test4_error')
        self._logger.critical('test4_critical')

class spam:
    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)
        self.test()
    def test(self):
        self._logger.debug('test5_debug')
        self._logger.info('test5_info')
        self._logger.warning('test5_warning')
        self._logger.error('test5_error')
        self._logger.critical('test5_critical')
if __name__ =="__main__":
    y = foo()
    x = spam()

Prompt:
Test script show how we might use the Python logger more effectively

Former-commit-id: cc69a6ab3b6c61fd2f3e60bd16085b81cda84e42
Former-commit-id: 28ba0ba57de3379bd99b9f508972cd0520c04fcb


from math import floor
from collections import Counter

def floored_percentage(val, digits):
    """
    Return string of floored value with given digits after period

    :param val:
    :param digits:
    :return:
    """
    val *= 10 ** (digits + 2)
    return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

def pref_encoding(data, encoding_transform=None):
    """
    Return string with unique words in list with percentage of they frequency

    :param data:
    :param encoding_transform:
    :return str:
    """
    encoding_counted = Counter(data)
    total = sum(encoding_counted.values())
    sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)

    return ' / '.join(
            ["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])

def make_total_row(source, agg):
    """
    Execute agg column based function for source columns. For example if you need `total` in table data:

    Examples:
        src = [[1,1],[1,2],[1,3]]
        print(make_total_row(src, [sum, min]))
        >>> [3, 1]

    :param source:
    :param agg:
    :return:
    """
    return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]

Response:
from math import floor
from collections import Counter

def floored_percentage(val, digits):
    """
    Return string of floored value with given digits after period

    :param val:
    :param digits:
    :return:
    """
    val *= 10 ** (digits + 2)
    return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

def pref_encoding(data, encoding_transform=None):
    """
    Return string with unique words in list with percentage of they frequency

    :param data:
    :param encoding_transform:
    :return str:
    """
    encoding_counted = Counter(data)
    total = sum(encoding_counted.values())
    sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)

    return ' / '.join(
            ["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])

def make_total_row(source, agg):
    """
    Execute agg column based function for source columns. For example if you need `total` in table data:

    Examples:
        src = [[1,1],[1,2],[1,3]]
        print(make_total_row(src, [sum, min]))
        >>> [3, 1]

    :param source:
    :param agg:
    :return:
    """
    return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]

Prompt:
Add transforming function to pref_encodings

from math import floor
from collections import Counter

def floored_percentage(val, digits):
    """
    Return string of floored value with given digits after period

    :param val:
    :param digits:
    :return:
    """
    val *= 10 ** (digits + 2)
    return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

def pref_encoding(data):
    """
    Return string with unique words in list with percentage of they frequency

    :param data:
    :return str:
    """
    encoding_counted = Counter(data)
    total = sum(encoding_counted.values())
    sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)

    return ' / '.join(
            ["{:<1} [{:<4}]".format(k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])

def make_total_row(source, agg):
    """
    Execute agg column based function for source columns. For example if you need `total` in table data:

    Examples:
        src = [[1,1],[1,2],[1,3]]
        print(make_total_row(src, [sum, min]))
        >>> [3, 1]

    :param source:
    :param agg:
    :return:
    """
    return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]


from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
                          save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image

def test_extension_to_format():
    eq_(extension_to_format('.jpeg'), 'JPEG')
    eq_(extension_to_format('.rgba'), 'SGI')

def test_format_to_extension_no_init():
    eq_(format_to_extension('PNG'), '.png')
    eq_(format_to_extension('ICO'), '.ico')

@raises(UnknownFormat)
def test_unknown_format():
    format_to_extension('TXT')

@raises(UnknownExtension)
def test_unknown_extension():
    extension_to_format('.txt')

def test_default_extension():
    """
    Ensure default extensions are honored.

    Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
    JPEG extensions, it would normally be the extension we'd get for that
    format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
    extensions we'd prefer, and this tests to make sure it's working.

    """
    eq_(format_to_extension('JPEG'), '.jpg')

@raises(AttributeError)
def test_filewrapper():

    class K(object):
        def fileno(self):
            raise UnsupportedOperation

    FileWrapper(K()).fileno()

def test_save_with_filename():
    """
    Test that ``save_image`` accepts filename strings (not just file objects).
    This is a test for GH-8.

    """
    im = create_image()
    outfile = NamedTemporaryFile()
    save_image(im, outfile.name, 'JPEG')
    outfile.close()

Response:
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
                          save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image

def test_extension_to_format():
    eq_(extension_to_format('.jpeg'), 'JPEG')
    eq_(extension_to_format('.rgba'), 'SGI')

def test_format_to_extension_no_init():
    eq_(format_to_extension('PNG'), '.png')
    eq_(format_to_extension('ICO'), '.ico')

@raises(UnknownFormat)
def test_unknown_format():
    format_to_extension('TXT')

@raises(UnknownExtension)
def test_unknown_extension():
    extension_to_format('.txt')

def test_default_extension():
    """
    Ensure default extensions are honored.

    Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
    JPEG extensions, it would normally be the extension we'd get for that
    format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
    extensions we'd prefer, and this tests to make sure it's working.

    """
    eq_(format_to_extension('JPEG'), '.jpg')

@raises(AttributeError)
def test_filewrapper():

    class K(object):
        def fileno(self):
            raise UnsupportedOperation

    FileWrapper(K()).fileno()

def test_save_with_filename():
    """
    Test that ``save_image`` accepts filename strings (not just file objects).
    This is a test for GH-8.

    """
    im = create_image()
    outfile = NamedTemporaryFile()
    save_image(im, outfile.name, 'JPEG')
    outfile.close()

Prompt:
Test that filename string can be used with save_image

from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises

def test_extension_to_format():
    eq_(extension_to_format('.jpeg'), 'JPEG')
    eq_(extension_to_format('.rgba'), 'SGI')

def test_format_to_extension_no_init():
    eq_(format_to_extension('PNG'), '.png')
    eq_(format_to_extension('ICO'), '.ico')

@raises(UnknownFormat)
def test_unknown_format():
    format_to_extension('TXT')

@raises(UnknownExtension)
def test_unknown_extension():
    extension_to_format('.txt')

def test_default_extension():
    """
    Ensure default extensions are honored.

    Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
    JPEG extensions, it would normally be the extension we'd get for that
    format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
    extensions we'd prefer, and this tests to make sure it's working.

    """
    eq_(format_to_extension('JPEG'), '.jpg')

@raises(AttributeError)
def test_filewrapper():

    class K(object):
        def fileno(self):
            raise UnsupportedOperation

    FileWrapper(K()).fileno()


from django.core.management import call_command
try:
    from django.shortcuts import resolve_url
except ImportError:
    import warnings
    warnings.warn("URL path supported only in get_url() with Django < 1.5")
    resolve_url = lambda to, *args, **kwargs: to

from behave_django.testcase import BehaveDjangoTestCase

def before_scenario(context, scenario):
    # This is probably a hacky method of setting up the test case
    # outside of a test runner. Suggestions are welcome. :)

    context.test = BehaveDjangoTestCase()
    context.test.setUpClass()
    context.test()

    # Load fixtures
    if getattr(context, 'fixtures', None):
        call_command('loaddata', *context.fixtures, verbosity=0)

    context.base_url = context.test.live_server_url

    def get_url(to=None, *args, **kwargs):
        """
        URL helper attached to context with built-in reverse resolution as a
        handy shortcut.  Takes an absolute path, a view name, or a model
        instance as an argument (as django.shortcuts.resolve_url).  Examples::

            context.get_url()
            context.get_url('/absolute/url/here')
            context.get_url('view-name')
            context.get_url('view-name', 'with args', and='kwargs')
            context.get_url(model_instance)
        """
        return context.base_url + (
            resolve_url(to, *args, **kwargs) if to else '')

    context.get_url = get_url

def after_scenario(context, scenario):
    context.test.tearDownClass()
    del context.test

Response:
from django.core.management import call_command
try:
    from django.shortcuts import resolve_url
except ImportError:
    import warnings
    warnings.warn("URL path supported only in get_url() with Django < 1.5")
    resolve_url = lambda to, *args, **kwargs: to

from behave_django.testcase import BehaveDjangoTestCase

def before_scenario(context, scenario):
    # This is probably a hacky method of setting up the test case
    # outside of a test runner. Suggestions are welcome. :)

    context.test = BehaveDjangoTestCase()
    context.test.setUpClass()
    context.test()

    # Load fixtures
    if getattr(context, 'fixtures', None):
        call_command('loaddata', *context.fixtures, verbosity=0)

    context.base_url = context.test.live_server_url

    def get_url(to=None, *args, **kwargs):
        """
        URL helper attached to context with built-in reverse resolution as a
        handy shortcut.  Takes an absolute path, a view name, or a model
        instance as an argument (as django.shortcuts.resolve_url).  Examples::

            context.get_url()
            context.get_url('/absolute/url/here')
            context.get_url('view-name')
            context.get_url('view-name', 'with args', and='kwargs')
            context.get_url(model_instance)
        """
        return context.base_url + (
            resolve_url(to, *args, **kwargs) if to else '')

    context.get_url = get_url

def after_scenario(context, scenario):
    context.test.tearDownClass()
    del context.test

Prompt:
Support Django < 1.5 with a simplified version of `get_url()`

from django.core.management import call_command
from django.shortcuts import resolve_url

from behave_django.testcase import BehaveDjangoTestCase

def before_scenario(context, scenario):
    # This is probably a hacky method of setting up the test case
    # outside of a test runner. Suggestions are welcome. :)

    context.test = BehaveDjangoTestCase()
    context.test.setUpClass()
    context.test()

    # Load fixtures
    if getattr(context, 'fixtures', None):
        call_command('loaddata', *context.fixtures, verbosity=0)

    context.base_url = context.test.live_server_url

    def get_url(to=None, *args, **kwargs):
        """
        URL helper attached to context with built-in reverse resolution as a
        handy shortcut.  Takes an absolute path, a view name, or a model
        instance as an argument (as django.shortcuts.resolve_url).  Examples::

            context.get_url()
            context.get_url('/absolute/url/here')
            context.get_url('view-name')
            context.get_url('view-name', 'with args', and='kwargs')
            context.get_url(model_instance)
        """
        return context.base_url + (
            resolve_url(to, *args, **kwargs) if to else '')

    context.get_url = get_url

def after_scenario(context, scenario):
    context.test.tearDownClass()
    del context.test


# vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003  Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
           'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
           'application', 'proxy']

Add proxy module to __all__.

Response:
# vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003  Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
           'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
           'application', 'proxy']

Prompt:
Add proxy module to __all__.

git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@248 5646265b-94b7-0310-9681-9501d24b2df7

# vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003  Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
           'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
           'application']


#!/usr/bin/env python2.6

#
# This file is used to test reading and processing of config files
#

import os

#It's ugly I know....
from shinken_test import *
from shinken.action import Action

class TestConfig(ShinkenTest):
    #setUp is in shinken_test

    #Change ME :)
    def test_action(self):
        a = Action()
        a.timeout = 10

        if os.name == 'nt':
            a.command = "./dummy_command.cmd"
        else:
            a.command = "./dummy_command.sh"
        self.assert_(a.got_shell_caracters() == False)
        a.execute()
        self.assert_(a.status == 'launched')
        #Give also the max output we want for the command
        for i in xrange(1, 100):
            if a.status == 'launched':
                a.check_finished(8012)
        self.assert_(a.exit_status == 0)
        self.assert_(a.status == 'done')
        self.assert_(a.output == "Hi, I'm for testing only. Please do not use me directly, really ")
        self.assert_(a.perf_data == " Hip=99% Bob=34mm")

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

Add a test for actions.

Add a test for actions.

Response:
#!/usr/bin/env python2.6

#
# This file is used to test reading and processing of config files
#

import os

#It's ugly I know....
from shinken_test import *
from shinken.action import Action

class TestConfig(ShinkenTest):
    #setUp is in shinken_test

    #Change ME :)
    def test_action(self):
        a = Action()
        a.timeout = 10

        if os.name == 'nt':
            a.command = "./dummy_command.cmd"
        else:
            a.command = "./dummy_command.sh"
        self.assert_(a.got_shell_caracters() == False)
        a.execute()
        self.assert_(a.status == 'launched')
        #Give also the max output we want for the command
        for i in xrange(1, 100):
            if a.status == 'launched':
                a.check_finished(8012)
        self.assert_(a.exit_status == 0)
        self.assert_(a.status == 'done')
        self.assert_(a.output == "Hi, I'm for testing only. Please do not use me directly, really ")
        self.assert_(a.perf_data == " Hip=99% Bob=34mm")

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

Prompt: Add a test for actions.


import csv

def test():
    with open("CVfolds_2.txt", newline='') as id2set, open("rec_id2filename.txt", newline='') as id2file, open("rec_labels_test_hidden.txt", newline='') as id2label:
        with open("file2label.csv", 'w', newline='') as file2label:
            readId2Label = csv.reader(id2label)
            readId2Set = csv.reader(id2set)
            readId2File = csv.reader(id2file)
            file2labelwriter = csv.writer(file2label)

            id2file = {}
            for r in readId2File:
                if r[0] == 'rec_id':
                    print("Reading id to file...")
                else:
                    id2file[r[0]] = r[1]

            print("Done reading id to file.")

            nb_samples = 0
            nb_bird_present = 0

            print("Creating file to labels csv...")
            for (id2label, id2set) in zip(readId2Label, readId2Set):
                if(id2set[0] != id2label[0]):
                    raise ValueError
                iden = id2set[0]
                if(id2set[1] == '0'):
                    nb_samples += 1
                    if(len(id2label) > 1):
                        labels = id2label[1:]
                        nb_bird_present += 1
                        f = id2file[iden]
                        file2labelwriter.writerow([f] + labels)
                    else:
                        file2labelwriter.writerow([f])

            print("Number of training samples: ", nb_samples)
            print("Number of training samples with birds present: ", nb_bird_present)

Add a script which structures the mlsp2013 data

  - creates a csv file which maps a file name to a label set

Response:
import csv

def test():
    with open("CVfolds_2.txt", newline='') as id2set, open("rec_id2filename.txt", newline='') as id2file, open("rec_labels_test_hidden.txt", newline='') as id2label:
        with open("file2label.csv", 'w', newline='') as file2label:
            readId2Label = csv.reader(id2label)
            readId2Set = csv.reader(id2set)
            readId2File = csv.reader(id2file)
            file2labelwriter = csv.writer(file2label)

            id2file = {}
            for r in readId2File:
                if r[0] == 'rec_id':
                    print("Reading id to file...")
                else:
                    id2file[r[0]] = r[1]

            print("Done reading id to file.")

            nb_samples = 0
            nb_bird_present = 0

            print("Creating file to labels csv...")
            for (id2label, id2set) in zip(readId2Label, readId2Set):
                if(id2set[0] != id2label[0]):
                    raise ValueError
                iden = id2set[0]
                if(id2set[1] == '0'):
                    nb_samples += 1
                    if(len(id2label) > 1):
                        labels = id2label[1:]
                        nb_bird_present += 1
                        f = id2file[iden]
                        file2labelwriter.writerow([f] + labels)
                    else:
                        file2labelwriter.writerow([f])

            print("Number of training samples: ", nb_samples)
            print("Number of training samples with birds present: ", nb_bird_present)

Prompt:
Add a script which structures the mlsp2013 data

  - creates a csv file which maps a file name to a label set


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

'''
Internal library for the fresque application.

This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''

import sqlalchemy as sa
import fresque.lib.database as db

from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import SQLAlchemyError

def create_session(db_url, debug=False, pool_recycle=3600):
    """ Create the Session object to use to query the database.

    :arg db_url: URL used to connect to the database. The URL contains
    information with regards to the database engine, the host to connect
    to, the user and password and the database name.
      ie: <engine>://<user>:<password>@<host>/<dbname>
    :kwarg debug: a boolean specifying wether we should have the verbose
        output of sqlalchemy or not.
    :return a Session that can be used to query the database.

    """
    engine = sa.create_engine(
        db_url,
        echo=debug,
        pool_recycle=pool_recycle)
    scopedsession = scoped_session(sessionmaker(bind=engine))
    return scopedsession

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

'''
Internal library for the fresque application.

This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''

import sqlalchemy as sa
import fresque.lib.database as db

from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import SQLAlchemyError

def create_session(db_url, debug=False, pool_recycle=3600):
    """ Create the Session object to use to query the database.

    :arg db_url: URL used to connect to the database. The URL contains
    information with regards to the database engine, the host to connect
    to, the user and password and the database name.
      ie: <engine>://<user>:<password>@<host>/<dbname>
    :kwarg debug: a boolean specifying wether we should have the verbose
        output of sqlalchemy or not.
    :return a Session that can be used to query the database.

    """
    engine = sa.create_engine(
        db_url,
        echo=debug,
        pool_recycle=pool_recycle)
    scopedsession = scoped_session(sessionmaker(bind=engine))
    return scopedsession

Prompt:
Add method to create a database session in the internal library

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

'''
Internal library for the fresque application.

This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''

import sqlalchemy as sa
import fresque.lib.database as db


from nose.tools import *
from webtest.app import AppError
from webtest_plus import TestApp

from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code

app = init_app(
    routes=True,
    set_backends=False,
    settings_module='website.settings',
)

class TestViews(OsfTestCase):
    def setUp(self):
        super(TestViews, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('twofactor')
        self.user_settings = self.user.get_addon('twofactor')

        self.app = TestApp(app)

    def test_confirm_code(self):
        # Send a valid code to the API endpoint for the user settings.
        res = self.app.post_json(
            '/api/v1/settings/twofactor/',
            {'code': _valid_code(self.user_settings.totp_secret)},
            auth=self.user.auth
        )

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_true(self.user_settings.is_confirmed)
        assert_equal(res.status_code, 200)

    def test_confirm_code_failure(self):
        with assert_raises(AppError) as error:
            res = self.app.post_json(
                '/api/v1/settings/twofactor/',
                {'code': '000000'},
                auth=self.user.auth
            )

            assert_in('403 FORBIDDEN', error.message)

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_false(self.user_settings.is_confirmed)

Response:
from nose.tools import *
from webtest.app import AppError
from webtest_plus import TestApp

from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code

app = init_app(
    routes=True,
    set_backends=False,
    settings_module='website.settings',
)

class TestViews(OsfTestCase):
    def setUp(self):
        super(TestViews, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('twofactor')
        self.user_settings = self.user.get_addon('twofactor')

        self.app = TestApp(app)

    def test_confirm_code(self):
        # Send a valid code to the API endpoint for the user settings.
        res = self.app.post_json(
            '/api/v1/settings/twofactor/',
            {'code': _valid_code(self.user_settings.totp_secret)},
            auth=self.user.auth
        )

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_true(self.user_settings.is_confirmed)
        assert_equal(res.status_code, 200)

    def test_confirm_code_failure(self):
        with assert_raises(AppError) as error:
            res = self.app.post_json(
                '/api/v1/settings/twofactor/',
                {'code': '000000'},
                auth=self.user.auth
            )

            assert_in('403 FORBIDDEN', error.message)

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_false(self.user_settings.is_confirmed)

Prompt:
Add test for failure to confirm 2FA code

from nose.tools import *
from webtest_plus import TestApp

from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code

app = init_app(
    routes=True,
    set_backends=False,
    settings_module='website.settings',
)

class TestViews(OsfTestCase):
    def setUp(self):
        super(TestViews, self).setUp()
        self.user = AuthUserFactory()
        self.user.add_addon('twofactor')
        self.user_settings = self.user.get_addon('twofactor')

        self.app = TestApp(app)

    def test_confirm_code(self):
        # Send a valid code to the API endpoint for the user settings.
        res = self.app.post_json(
            '/api/v1/settings/twofactor/',
            {'code': _valid_code(self.user_settings.totp_secret)},
            auth=self.user.auth
        )

        # reload the user settings object from the DB
        self.user_settings.reload()

        assert_true(self.user_settings.is_confirmed)
        assert_equal(res.status_code, 200)