import os
from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

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

setup(
    name='django-argcache',
    version='0.1',
    license='AGPLv3',
    description='A function-level caching and invalidaton framework for Django.',
    long_description=README,
    url='https://github.com/luac/django-argcache/',
    author='Anthony Lu',
    author_email='lua@mit.edu',
    packages=[
        'argcache',
        'argcache.extras',
    ],
    package_dir={
        'argcache': 'src'
    },
    include_package_data=True,
    install_requires=[
        'django>=1.7',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: License :: OSI Approved :: GNU Affero General Public License v3',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)

Fix typo in package description

Fix typo in package description

Response:
import os
from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

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

setup(
    name='django-argcache',
    version='0.1',
    license='AGPLv3',
    description='A function-level caching and invalidaton framework for Django.',
    long_description=README,
    url='https://github.com/luac/django-argcache/',
    author='Anthony Lu',
    author_email='lua@mit.edu',
    packages=[
        'argcache',
        'argcache.extras',
    ],
    package_dir={
        'argcache': 'src'
    },
    include_package_data=True,
    install_requires=[
        'django>=1.7',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: License :: OSI Approved :: GNU Affero General Public License v3',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)

Prompt:
Fix typo in package description

import os
from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

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

setup(
    name='django-argcache',
    version='0.1',
    license='AGPLv3',
    description='A function-level caching and invalidaton fraemwork for Django.',
    long_description=README,
    url='https://github.com/luac/django-argcache/',
    author='Anthony Lu',
    author_email='lua@mit.edu',
    packages=[
        'argcache',
        'argcache.extras',
    ],
    package_dir={
        'argcache': 'src'
    },
    include_package_data=True,
    install_requires=[
        'django>=1.7',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: License :: OSI Approved :: GNU Affero General Public License v3',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
)


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0030_realm_org_type'),
    ]

    operations = [
        migrations.AlterField(
            model_name='userprofile',
            name='avatar_source',
            field=models.CharField(choices=[('G', 'Hosted by Gravatar'), ('U', 'Uploaded by user')], max_length=1, default='G'),
        ),
    ]

Add migration to remove system avatar source.

Fixes the last commit having broken master.

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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0030_realm_org_type'),
    ]

    operations = [
        migrations.AlterField(
            model_name='userprofile',
            name='avatar_source',
            field=models.CharField(choices=[('G', 'Hosted by Gravatar'), ('U', 'Uploaded by user')], max_length=1, default='G'),
        ),
    ]

Prompt:
Add migration to remove system avatar source.

Fixes the last commit having broken master.


# -*- coding: utf-8 -*-
"""
h2/frame_buffer
~~~~~~~~~~~~~~~

A data structure that provides a way to iterate over a byte buffer in terms of
frames.
"""
from hyperframe.frame import Frame

class FrameBuffer(object):
    """
    This is a data structure that expects to act as a buffer for HTTP/2 data
    that allows iteraton in terms of H2 frames.
    """
    def __init__(self, server=False):
        self.data = b''
        self.preamble_len = (
            len(b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n') if server else 0
        )

    def add_data(self, data):
        """
        Add more data to the frame buffer.

        :param data: A bytestring containing the byte buffer.
        """
        if self.preamble_len:
            data_len = len(data)
            data = data[self.preamble_len:]
            self.preamble_len -= min(data_len, self.preamble_len)

        self.data += data

    def __iter__(self):
        return self

    def next(self):
        if len(self.data) < 9:
            raise StopIteration()

        f, length = Frame.parse_frame_header(self.data[:9])
        if len(self.data) < length + 9:
            raise StopIteration()

        f.parse_body(memoryview(self.data[9:9+length]))
        self.data = self.data[9+length:]
        return f

Define an iterable frame buffer.

Define an iterable frame buffer.

Response:
# -*- coding: utf-8 -*-
"""
h2/frame_buffer
~~~~~~~~~~~~~~~

A data structure that provides a way to iterate over a byte buffer in terms of
frames.
"""
from hyperframe.frame import Frame

class FrameBuffer(object):
    """
    This is a data structure that expects to act as a buffer for HTTP/2 data
    that allows iteraton in terms of H2 frames.
    """
    def __init__(self, server=False):
        self.data = b''
        self.preamble_len = (
            len(b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n') if server else 0
        )

    def add_data(self, data):
        """
        Add more data to the frame buffer.

        :param data: A bytestring containing the byte buffer.
        """
        if self.preamble_len:
            data_len = len(data)
            data = data[self.preamble_len:]
            self.preamble_len -= min(data_len, self.preamble_len)

        self.data += data

    def __iter__(self):
        return self

    def next(self):
        if len(self.data) < 9:
            raise StopIteration()

        f, length = Frame.parse_frame_header(self.data[:9])
        if len(self.data) < length + 9:
            raise StopIteration()

        f.parse_body(memoryview(self.data[9:9+length]))
        self.data = self.data[9+length:]
        return f

Prompt: Define an iterable frame buffer.


#!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Member(Base):
    __tablename__ = 'member'

    id = Column(Integer, primary_key=True)
    globalName = Column(String(250), nullable=True)
    nickname = Column(String(250), nullable=True)
    role = Column(String(250), nullable=True)
    points = Column(Integer, nullable=True)

    def __init__(self,id,globalAccountName,serverNickname,role,points):
        self.id = id
        self.globalAccountName = globalAccountName
        self.serverNickname = serverNickname
        self.role = role
        self.points = points

#Display member method.
    def displayMember(self):
        print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points)

#Example of creating one object, changing value of an object and displaying an object using a method.
'''mem1 = Member(43344454,"larry","doessuck","officer",150)

mem1.globalAccountName="Jack"

mem1.displayMember()'''

engine = create_engine('sqlite:///bayohwoolph.db')

Base.metadata.create_all(engine)

Make globalName nullable for now.

Make globalName nullable for now.

Response:
#!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Member(Base):
    __tablename__ = 'member'

    id = Column(Integer, primary_key=True)
    globalName = Column(String(250), nullable=True)
    nickname = Column(String(250), nullable=True)
    role = Column(String(250), nullable=True)
    points = Column(Integer, nullable=True)

    def __init__(self,id,globalAccountName,serverNickname,role,points):
        self.id = id
        self.globalAccountName = globalAccountName
        self.serverNickname = serverNickname
        self.role = role
        self.points = points

#Display member method.
    def displayMember(self):
        print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points)

#Example of creating one object, changing value of an object and displaying an object using a method.
'''mem1 = Member(43344454,"larry","doessuck","officer",150)

mem1.globalAccountName="Jack"

mem1.displayMember()'''

engine = create_engine('sqlite:///bayohwoolph.db')

Base.metadata.create_all(engine)

Prompt:
Make globalName nullable for now.

#!/usr/bin/python3
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Member(Base):
    __tablename__ = 'member'

    id = Column(Integer, primary_key=True)
    globalName = Column(String(250), nullable=False)
    nickname = Column(String(250), nullable=True)
    role = Column(String(250), nullable=True)
    points = Column(Integer, nullable=True)

    def __init__(self,id,globalAccountName,serverNickname,role,points):
        self.id = id
        self.globalAccountName = globalAccountName
        self.serverNickname = serverNickname
        self.role = role
        self.points = points

#Display member method.
    def displayMember(self):
        print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points)

#Example of creating one object, changing value of an object and displaying an object using a method.
'''mem1 = Member(43344454,"larry","doessuck","officer",150)

mem1.globalAccountName="Jack"

mem1.displayMember()'''

engine = create_engine('sqlite:///bayohwoolph.db')

Base.metadata.create_all(engine)


__doc__ = """
Manipulate audio with an simple and easy high level interface.

See the README file for details, usage info, and a list of gotchas.
"""

from setuptools import setup

setup(
    name='pydub',
    version='0.16.4',
    author='James Robert',
    author_email='jiaaro@gmail.com',
    description='Manipulate audio with an simple and easy high level interface',
    license='MIT',
    keywords='audio sound high-level',
    url='http://pydub.com',
    packages=['pydub'],
    long_description=__doc__,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        "Topic :: Multimedia :: Sound/Audio",
        "Topic :: Multimedia :: Sound/Audio :: Analysis",
        "Topic :: Multimedia :: Sound/Audio :: Conversion",
        "Topic :: Multimedia :: Sound/Audio :: Editors",
        "Topic :: Multimedia :: Sound/Audio :: Mixers",
        "Topic :: Software Development :: Libraries",
        'Topic :: Utilities',
    ]
)

Response:
__doc__ = """
Manipulate audio with an simple and easy high level interface.

See the README file for details, usage info, and a list of gotchas.
"""

from setuptools import setup

setup(
    name='pydub',
    version='0.16.4',
    author='James Robert',
    author_email='jiaaro@gmail.com',
    description='Manipulate audio with an simple and easy high level interface',
    license='MIT',
    keywords='audio sound high-level',
    url='http://pydub.com',
    packages=['pydub'],
    long_description=__doc__,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        "Topic :: Multimedia :: Sound/Audio",
        "Topic :: Multimedia :: Sound/Audio :: Analysis",
        "Topic :: Multimedia :: Sound/Audio :: Conversion",
        "Topic :: Multimedia :: Sound/Audio :: Editors",
        "Topic :: Multimedia :: Sound/Audio :: Mixers",
        "Topic :: Software Development :: Libraries",
        'Topic :: Utilities',
    ]
)

Prompt:
Increment version for 24-bit wav bug fix
__doc__ = """
Manipulate audio with an simple and easy high level interface.

See the README file for details, usage info, and a list of gotchas.
"""

from setuptools import setup

setup(
    name='pydub',
    version='0.16.3',
    author='James Robert',
    author_email='jiaaro@gmail.com',
    description='Manipulate audio with an simple and easy high level interface',
    license='MIT',
    keywords='audio sound high-level',
    url='http://pydub.com',
    packages=['pydub'],
    long_description=__doc__,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        "Topic :: Multimedia :: Sound/Audio",
        "Topic :: Multimedia :: Sound/Audio :: Analysis",
        "Topic :: Multimedia :: Sound/Audio :: Conversion",
        "Topic :: Multimedia :: Sound/Audio :: Editors",
        "Topic :: Multimedia :: Sound/Audio :: Mixers",
        "Topic :: Software Development :: Libraries",
        'Topic :: Utilities',
    ]
)


"""
Project

:Authors:
	Berend Klein Haneveld
"""

class Project(object):
	"""
	Project holds the basic information of a project for RegistrationShop
	"""

	def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
		super(Project, self).__init__()

		self.title = title
		self.fixedData = fixedData
		self.movingData = movingData
		self.isReference = isReference
		self.folder = None
		self.resultData = None
		self.fixedSettings = None
		self.movingSettings = None
		self.multiSettings = None
		self.transformations = None

	def __eq__(self, other):
		if not isinstance(other, Project):
			return False
		return (self.title == other.title
			and self.fixedData == other.fixedData
			and self.movingData == other.movingData
			and self.isReference == other.isReference)

	def __ne__(self, other):
		return not self.__eq__(other)

Response:
"""
Project

:Authors:
	Berend Klein Haneveld
"""

class Project(object):
	"""
	Project holds the basic information of a project for RegistrationShop
	"""

	def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
		super(Project, self).__init__()

		self.title = title
		self.fixedData = fixedData
		self.movingData = movingData
		self.isReference = isReference
		self.folder = None
		self.resultData = None
		self.fixedSettings = None
		self.movingSettings = None
		self.multiSettings = None
		self.transformations = None

	def __eq__(self, other):
		if not isinstance(other, Project):
			return False
		return (self.title == other.title
			and self.fixedData == other.fixedData
			and self.movingData == other.movingData
			and self.isReference == other.isReference)

	def __ne__(self, other):
		return not self.__eq__(other)

Prompt:
Add transformations property to projects.

"""
Project

:Authors:
	Berend Klein Haneveld
"""

class Project(object):
	"""
	Project holds the basic information of a project for RegistrationShop
	"""

	def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
		super(Project, self).__init__()

		self.title = title
		self.fixedData = fixedData
		self.movingData = movingData
		self.isReference = isReference
		self.folder = None
		self.resultData = None
		self.fixedSettings = None
		self.movingSettings = None
		self.multiSettings = None

	def __eq__(self, other):
		if not isinstance(other, Project):
			return False
		return (self.title == other.title
			and self.fixedData == other.fixedData
			and self.movingData == other.movingData
			and self.isReference == other.isReference)

	def __ne__(self, other):
		return not self.__eq__(other)


class APIObject(object):

    def __init__(self, client, json_data):
        super(APIObject, self).__init__()
        self.client = client
        self._data = json_data

    def __eq__(self, other):
        if not isinstance(other, APIObject):
            return NotImplemented
        return self.client is other.client and self._data == other._data

    def __ne__(self, other):
        return not (self == other)

    def __getattr__(self, name):
        try:
            return self.__dict__['_data'][name]
        except KeyError:
            raise AttributeError(name)

    def refresh(self):
        self._data = self._fetch()
        return self

    def _fetch(self):
        return self.client.api.get(self.api_path, raw=True)[self._data['type']]

    def __repr__(self):
        return '<API:{data[type]}:{data[id]}>'.format(data=self._data)

Response:
class APIObject(object):

    def __init__(self, client, json_data):
        super(APIObject, self).__init__()
        self.client = client
        self._data = json_data

    def __eq__(self, other):
        if not isinstance(other, APIObject):
            return NotImplemented
        return self.client is other.client and self._data == other._data

    def __ne__(self, other):
        return not (self == other)

    def __getattr__(self, name):
        try:
            return self.__dict__['_data'][name]
        except KeyError:
            raise AttributeError(name)

    def refresh(self):
        self._data = self._fetch()
        return self

    def _fetch(self):
        return self.client.api.get(self.api_path, raw=True)[self._data['type']]

    def __repr__(self):
        return '<API:{data[type]}:{data[id]}>'.format(data=self._data)

Prompt:
Make `refresh` return self for chaining actions

class APIObject(object):

    def __init__(self, client, json_data):
        super(APIObject, self).__init__()
        self.client = client
        self._data = json_data

    def __eq__(self, other):
        if not isinstance(other, APIObject):
            return NotImplemented
        return self.client is other.client and self._data == other._data

    def __ne__(self, other):
        return not (self == other)

    def __getattr__(self, name):
        try:
            return self.__dict__['_data'][name]
        except KeyError:
            raise AttributeError(name)

    def refresh(self):
        self._data = self._fetch()

    def _fetch(self):
        return self.client.api.get(self.api_path, raw=True)[self._data['type']]

    def __repr__(self):
        return '<API:{data[type]}:{data[id]}>'.format(data=self._data)


#
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
from selenium import webdriver

def before_feature(context, feature):
    #context.browser = webdriver.Firefox()
    context.browser = webdriver.PhantomJS()
    context.browser.set_window_size(1280, 1024)
    context.browser.implicitly_wait(5)
    context.browser.set_page_load_timeout(60) # wait for data
    context.browser.get('http://localhost:4567/')

def after_feature(context, feature):
    context.browser.quit()

def take_screenshot(context):
    context.browser.save_screenshot('/tmp/screenshot.jpeg')

def save_source(context):
    with open('/tmp/source.html', 'w') as out:
        out.write(context.browser.page_source.encode('utf8'))

Response:
#
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
from selenium import webdriver

def before_feature(context, feature):
    #context.browser = webdriver.Firefox()
    context.browser = webdriver.PhantomJS()
    context.browser.set_window_size(1280, 1024)
    context.browser.implicitly_wait(5)
    context.browser.set_page_load_timeout(60) # wait for data
    context.browser.get('http://localhost:4567/')

def after_feature(context, feature):
    context.browser.quit()

def take_screenshot(context):
    context.browser.save_screenshot('/tmp/screenshot.jpeg')

def save_source(context):
    with open('/tmp/source.html', 'w') as out:
        out.write(context.browser.page_source.encode('utf8'))

Prompt:
Revert "increasing webdriver timeout on fake-service"

This reverts commit a39a4b40a947db655c84af6eb62d5870cfd8b32c.

#
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
from selenium import webdriver

def before_feature(context, feature):
    #context.browser = webdriver.Firefox()
    context.browser = webdriver.PhantomJS()
    context.browser.set_window_size(1280, 1024)
    context.browser.implicitly_wait(10)
    context.browser.set_page_load_timeout(120) # wait for data
    context.browser.get('http://localhost:4567/')

def after_feature(context, feature):
    context.browser.quit()

def take_screenshot(context):
    context.browser.save_screenshot('/tmp/screenshot.jpeg')

def save_source(context):
    with open('/tmp/source.html', 'w') as out:
        out.write(context.browser.page_source.encode('utf8'))


from collections import deque
from peewee import *

db = SqliteDatabase(':memory:')

class TreeNode(Model):
    parent = ForeignKeyField('self', backref='children', null=True)
    name = TextField()

    class Meta:
        database = db

    def __str__(self):
        return 'name=%s' % self.name

    def dump(self, _indent=0):
        return ('  ' * _indent + repr(self) + '\n' +
                ''.join(c.dump(_indent + 1) for c in self.children))

if __name__ == '__main__':
    db.create_tables([TreeNode])
    tree = (
        'root', (
            ('node-1', (
                ('sub-1-1', ()),
                ('sub-1-2', ()))),
            ('node-2', (
                ('sub-2-1', (
                    ('sub-sub-2-1-1', ()),
                    ('sub-sub-2-1-2', ()))),
                ('sub-2-2', (
                    ('sub-sub-2-2-1', ()),
                    ('sub-sub-2-2-2', ()))))),
            ('node-3', ()),
            ('node-4', (
                ('sub-4-1', ()),
                ('sub-4-2', ()),
                ('sub-4-3', ()),
                ('sub-4-4', ())))))

    with db.atomic():
        stack = deque([(None, tree)])
        while stack:
            parent, t = stack.pop()
            name, children = t
            node = TreeNode.create(name=name, parent=parent)
            for childdef in children:
                stack.appendleft((node, childdef))

    root = TreeNode.get(name='root')
    print(root.dump())

Add adjacency list example. Compare to SQA's.

[skip ci]

Response:
from collections import deque
from peewee import *

db = SqliteDatabase(':memory:')

class TreeNode(Model):
    parent = ForeignKeyField('self', backref='children', null=True)
    name = TextField()

    class Meta:
        database = db

    def __str__(self):
        return 'name=%s' % self.name

    def dump(self, _indent=0):
        return ('  ' * _indent + repr(self) + '\n' +
                ''.join(c.dump(_indent + 1) for c in self.children))

if __name__ == '__main__':
    db.create_tables([TreeNode])
    tree = (
        'root', (
            ('node-1', (
                ('sub-1-1', ()),
                ('sub-1-2', ()))),
            ('node-2', (
                ('sub-2-1', (
                    ('sub-sub-2-1-1', ()),
                    ('sub-sub-2-1-2', ()))),
                ('sub-2-2', (
                    ('sub-sub-2-2-1', ()),
                    ('sub-sub-2-2-2', ()))))),
            ('node-3', ()),
            ('node-4', (
                ('sub-4-1', ()),
                ('sub-4-2', ()),
                ('sub-4-3', ()),
                ('sub-4-4', ())))))

    with db.atomic():
        stack = deque([(None, tree)])
        while stack:
            parent, t = stack.pop()
            name, children = t
            node = TreeNode.create(name=name, parent=parent)
            for childdef in children:
                stack.appendleft((node, childdef))

    root = TreeNode.get(name='root')
    print(root.dump())

Prompt:
Add adjacency list example. Compare to SQA's.

[skip ci]


#!/usr/bin/env python

import multiprocessing
import optparse

from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

from hurricane.utils import run_until_stopped

class ApplicationManager(object):
    @run_until_stopped
    def run(self):
        parser = optparse.OptionParser()
        parser.add_option('--settings', dest='settings')

        options, args = parser.parse_args()
        if not options.settings:
            raise ImproperlyConfigured("You didn't provide a settings module.")
        settings = import_module(options.settings)
        django_settings.configure(settings)

        self.producer_queue = multiprocessing.Queue()

        for producer in settings.PRODUCERS:
            ProducerClass = import_module(producer).Producer
            producer = ProducerClass(settings, self.producer_queue)
            multiprocessing.Process(target=producer.run).start()

        self.receiver_queues = []

        for consumer in settings.CONSUMERS:
            ConsumerClass = import_module(consumer).Consumer
            recv_queue = multiprocessing.Queue()
            consumer = ConsumerClass(settings, recv_queue)
            self.receiver_queues.append(recv_queue)
            multiprocessing.Process(target=consumer.run).start()

        while True:
            item = self.producer_queue.get()
            for recv_queue in self.receiver_queues:
                recv_queue.put(item)

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

Response:
#!/usr/bin/env python

import multiprocessing
import optparse

from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

from hurricane.utils import run_until_stopped

class ApplicationManager(object):
    @run_until_stopped
    def run(self):
        parser = optparse.OptionParser()
        parser.add_option('--settings', dest='settings')

        options, args = parser.parse_args()
        if not options.settings:
            raise ImproperlyConfigured("You didn't provide a settings module.")
        settings = import_module(options.settings)
        django_settings.configure(settings)

        self.producer_queue = multiprocessing.Queue()

        for producer in settings.PRODUCERS:
            ProducerClass = import_module(producer).Producer
            producer = ProducerClass(settings, self.producer_queue)
            multiprocessing.Process(target=producer.run).start()

        self.receiver_queues = []

        for consumer in settings.CONSUMERS:
            ConsumerClass = import_module(consumer).Consumer
            recv_queue = multiprocessing.Queue()
            consumer = ConsumerClass(settings, recv_queue)
            self.receiver_queues.append(recv_queue)
            multiprocessing.Process(target=consumer.run).start()

        while True:
            item = self.producer_queue.get()
            for recv_queue in self.receiver_queues:
                recv_queue.put(item)

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

Prompt:
Configure django correctly when we setup our env

#!/usr/bin/env python

import multiprocessing
import optparse

from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

from hurricane.utils import run_until_stopped

class ApplicationManager(object):
    @run_until_stopped
    def run(self):
        parser = optparse.OptionParser()
        parser.add_option('--settings', dest='settings')

        options, args = parser.parse_args()
        if not options.settings:
            raise ImproperlyConfigured("You didn't provide a settings module.")
        settings = import_module(options.settings)

        self.producer_queue = multiprocessing.Queue()

        for producer in settings.PRODUCERS:
            ProducerClass = import_module(producer).Producer
            producer = ProducerClass(settings, self.producer_queue)
            multiprocessing.Process(target=producer.run).start()

        self.receiver_queues = []

        for consumer in settings.CONSUMERS:
            ConsumerClass = import_module(consumer).Consumer
            recv_queue = multiprocessing.Queue()
            consumer = ConsumerClass(settings, recv_queue)
            self.receiver_queues.append(recv_queue)
            multiprocessing.Process(target=consumer.run).start()

        while True:
            item = self.producer_queue.get()
            for recv_queue in self.receiver_queues:
                recv_queue.put(item)

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


from scriptcwl import WorkflowGenerator as WFGenerator

from .utils import CWL_PATH

class WorkflowGenerator(WFGenerator):
    def __init__(self, working_dir=None):
        WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir)

    def save(self, fname, validate=True, wd=True, inline=False, relative=False,
             pack=False, encoding='utf-8'):
        """Save workflow to file

        For nlppln, the default is to use a working directory (and save steps
        using the ``wd`` option).
        """
        super(WorkflowGenerator, self).save(fname,
                                            validate=validate,
                                            wd=wd,
                                            inline=inline,
                                            relative=relative,
                                            pack=pack,
                                            encoding=encoding)

Response:
from scriptcwl import WorkflowGenerator as WFGenerator

from .utils import CWL_PATH

class WorkflowGenerator(WFGenerator):
    def __init__(self, working_dir=None):
        WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir)

    def save(self, fname, validate=True, wd=True, inline=False, relative=False,
             pack=False, encoding='utf-8'):
        """Save workflow to file

        For nlppln, the default is to use a working directory (and save steps
        using the ``wd`` option).
        """
        super(WorkflowGenerator, self).save(fname,
                                            validate=validate,
                                            wd=wd,
                                            inline=inline,
                                            relative=relative,
                                            pack=pack,
                                            encoding=encoding)

Prompt:
Update to use newest (unreleased) scriptcwl options

from scriptcwl import WorkflowGenerator as WFGenerator

from .utils import CWL_PATH

class WorkflowGenerator(WFGenerator):
    def __init__(self, working_dir=None, copy_steps=True):
        WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
                             copy_steps=copy_steps)

    def save(self, fname, inline=True, relative=False, validate=True,
             encoding='utf-8'):
        """Save workflow to file

        For nlppln, the default is to save steps inline.
        """
        super(WorkflowGenerator, self).save(fname,
                                            inline=inline,
                                            relative=relative,
                                            validate=validate,
                                            encoding=encoding)


from pkg_resources import iter_entry_points

from spicedham.config import load_config

_plugins = None

def load_plugins():
    """
    If not already loaded, load plugins.
    """
    if _plugins == None
        load_config()
        _plugins = []
        for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
            pluginClass = plugin.load()
            _plugins.append(pluginClass())

def train(tag, training_data, is_spam):
    """
    Calls each plugin's train function.
    """
    for plugin in _plugins:
        plugin.train(tag, training_data, is_spam)

def classify(tag, classification_data):
    """
    Calls each plugin's classify function and averages the results.
    """
    average_score = 0
    total = 0
    for plugin in _plugins:
        value = plugin.classify(tag, classification_data)
        # Skip _plugins which give a score of None
        if value != None:
            total += 1
            average_score += value
    # On rare occasions no _plugins will give scores. If so, return 0
    if total > 0:
        return average_score / total
    else:
        return 0

Fix code which executes on module load.

Fix code which executes on module load.

Response:
from pkg_resources import iter_entry_points

from spicedham.config import load_config

_plugins = None

def load_plugins():
    """
    If not already loaded, load plugins.
    """
    if _plugins == None
        load_config()
        _plugins = []
        for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
            pluginClass = plugin.load()
            _plugins.append(pluginClass())

def train(tag, training_data, is_spam):
    """
    Calls each plugin's train function.
    """
    for plugin in _plugins:
        plugin.train(tag, training_data, is_spam)

def classify(tag, classification_data):
    """
    Calls each plugin's classify function and averages the results.
    """
    average_score = 0
    total = 0
    for plugin in _plugins:
        value = plugin.classify(tag, classification_data)
        # Skip _plugins which give a score of None
        if value != None:
            total += 1
            average_score += value
    # On rare occasions no _plugins will give scores. If so, return 0
    if total > 0:
        return average_score / total
    else:
        return 0

Prompt:
Fix code which executes on module load.

from pkg_resources import iter_entry_points

from spicedham.config import config

# TODO: Wrap all of this in an object with this in an __init__ function
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
    pluginClass = plugin.load()
    plugins.append(pluginClass())

def train(tag, training_data, is_spam):
    """
    Calls each plugin's train function.
    """
    for plugin in plugins:
        plugin.train(tag, training_data, is_spam)

def classify(tag, classification_data):
    """
    Calls each plugin's classify function and averages the results.
    """
    average_score = 0
    total = 0
    for plugin in plugins:
        value = plugin.classify(tag, classification_data)
        # Skip plugins which give a score of None
        if value != None:
            total += 1
            average_score += value
    # On rare occasions no plugins will give scores. If so, return 0
    if total > 0:
        return average_score / total
    else:
        return 0


import json
import logging

if __name__ == "__main__":
    input = sys.argv[1]
    output = sys.argv[2]
    processor = fix_changeline_budget_titles().process(input,output,[])

class fix_changeline_budget_titles(object):

    def process(self,inputs,output):

        out = []

        budgets = {}

        changes_jsons, budget_jsons = inputs

        for line in file(budget_jsons):
            line = json.loads(line.strip())
            budgets["%(year)s/%(code)s" % line] = line['title']

        outfile = file(output,"w")
        changed_num = 0
        for line in file(changes_jsons):
            line = json.loads(line.strip())
            key = "%(year)s/%(budget_code)s" % line
            title = budgets.get(key)
            if title != None and title != line['budget_title']:
                line['budget_title'] = title
                changed_num += 1
            else:
                logging.error("Failed to find title for change with key %s" % key)
            outfile.write(json.dumps(line,sort_keys=True)+"\n")
        print "updated %d entries" % changed_num

Response:
import json
import logging

if __name__ == "__main__":
    input = sys.argv[1]
    output = sys.argv[2]
    processor = fix_changeline_budget_titles().process(input,output,[])

class fix_changeline_budget_titles(object):

    def process(self,inputs,output):

        out = []

        budgets = {}

        changes_jsons, budget_jsons = inputs

        for line in file(budget_jsons):
            line = json.loads(line.strip())
            budgets["%(year)s/%(code)s" % line] = line['title']

        outfile = file(output,"w")
        changed_num = 0
        for line in file(changes_jsons):
            line = json.loads(line.strip())
            key = "%(year)s/%(budget_code)s" % line
            title = budgets.get(key)
            if title != None and title != line['budget_title']:
                line['budget_title'] = title
                changed_num += 1
            else:
                logging.error("Failed to find title for change with key %s" % key)
            outfile.write(json.dumps(line,sort_keys=True)+"\n")
        print "updated %d entries" % changed_num

Prompt:
Fix bug in changeling title fix - it used to remove some lines on the way...

import json

if __name__ == "__main__":
    input = sys.argv[1]
    output = sys.argv[2]
    processor = fix_changeline_budget_titles().process(input,output,[])

class fix_changeline_budget_titles(object):

    def process(self,inputs,output):

        out = []

        budgets = {}

        changes_jsons, budget_jsons = inputs

        for line in file(budget_jsons):
            line = json.loads(line.strip())
            budgets["%(year)s/%(code)s" % line] = line['title']

        outfile = file(output,"w")
        changed_num = 0
        for line in file(changes_jsons):
            line = json.loads(line.strip())
            title = budgets.get("%(year)s/%(budget_code)s" % line)
            if title != None and title != line['budget_title']:
                line['budget_title'] = title
                changed_num += 1
                outfile.write(json.dumps(line,sort_keys=True)+"\n")
        print "updated %d entries" % changed_num


#! /usr/bin/python

from __future__ import print_function
import sys
import photo.index

idx = photo.index.Index(idxfile=sys.argv[1])
for i in idx:
    print("%s  %s" % (i.md5, i.filename))

Add a script to convert an index to a md5 file.

Response:
#! /usr/bin/python

from __future__ import print_function
import sys
import photo.index

idx = photo.index.Index(idxfile=sys.argv[1])
for i in idx:
    print("%s  %s" % (i.md5, i.filename))

Prompt: Add a script to convert an index to a md5 file.


#!/usr/bin/env python
import os
import socket
import subprocess
import telnetlib

def can_connect(host, port):
    """Check that we can make a connection to Memcached."""
    try:
        c = telnetlib.Telnet(host, port)
    except socket.error:
        return False
    c.close()
    return True

def main():
    if not os.path.exists('/etc/init.d/memcached'):
        return

    hostname = subprocess.check_output('hostname').strip()
    localhost = '127.0.0.1'

    if can_connect(hostname, '11211') or can_connect(localhost, '11211'):
        print 'status ok memcached is reachable'
    else:
        print 'status err memcached is unreachable'

Add rudimentary status check for memcached

Response:
#!/usr/bin/env python
import os
import socket
import subprocess
import telnetlib

def can_connect(host, port):
    """Check that we can make a connection to Memcached."""
    try:
        c = telnetlib.Telnet(host, port)
    except socket.error:
        return False
    c.close()
    return True

def main():
    if not os.path.exists('/etc/init.d/memcached'):
        return

    hostname = subprocess.check_output('hostname').strip()
    localhost = '127.0.0.1'

    if can_connect(hostname, '11211') or can_connect(localhost, '11211'):
        print 'status ok memcached is reachable'
    else:
        print 'status err memcached is unreachable'

Prompt: Add rudimentary status check for memcached


import json

from django.test import TestCase, Client

class MemeTests(TestCase):

    def test_can_post_to_db(self):
        response = json.loads(self.client.post('/', {'url':'https://foo.bar/baz.gif', 'keywords':'omg, this, is, great'}).content)
        self.assertTrue(response['success'])

Response:
import json

from django.test import TestCase, Client

class MemeTests(TestCase):

    def test_can_post_to_db(self):
        response = json.loads(self.client.post('/', {'url':'https://foo.bar/baz.gif', 'keywords':'omg, this, is, great'}).content)
        self.assertTrue(response['success'])

Prompt:
Add test for posting content to the server

from django.test import TestCase

# Create your tests here.


import os
import pytest
import yaml

from photoshell.selection import Selection

@pytest.fixture
def sidecar(tmpdir):
    tmpdir.join("test.sidecar").write(yaml.dump({
        'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
        'datetime': '2014-10-10 00:00'
    }, default_flow_style=False))
    return os.path.join(tmpdir.strpath, "test.sidecar")

@pytest.fixture
def empty_selection():
    s = Selection('', '')
    return s

@pytest.fixture
def selection(empty_selection):
    empty_selection.images.append('image')
    empty_selection.photos.append('image')
    return empty_selection

def test_current_default_selection(selection):
    assert selection.current()

def test_current_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current() is None

def test_current_photo_default_selection(selection):
    assert selection.current_photo()

def test_current_photo_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current_photo() is None

def test_next_prev_does_nothing_single_photo(selection):
    assert selection.current() == selection.next()
    assert selection.current() == selection.prev()

def test_next_prev_wrap_around(selection):
    selection.photos.append('photo2')
    selection.images.append('image2')

    assert selection.next() == 'image2'
    assert selection.next() == 'image'
    assert selection.prev() == 'image2'
    assert selection.prev() == 'image'

Add a few behavior tests for selection

Add a few behavior tests for selection

Response:
import os
import pytest
import yaml

from photoshell.selection import Selection

@pytest.fixture
def sidecar(tmpdir):
    tmpdir.join("test.sidecar").write(yaml.dump({
        'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
        'datetime': '2014-10-10 00:00'
    }, default_flow_style=False))
    return os.path.join(tmpdir.strpath, "test.sidecar")

@pytest.fixture
def empty_selection():
    s = Selection('', '')
    return s

@pytest.fixture
def selection(empty_selection):
    empty_selection.images.append('image')
    empty_selection.photos.append('image')
    return empty_selection

def test_current_default_selection(selection):
    assert selection.current()

def test_current_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current() is None

def test_current_photo_default_selection(selection):
    assert selection.current_photo()

def test_current_photo_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current_photo() is None

def test_next_prev_does_nothing_single_photo(selection):
    assert selection.current() == selection.next()
    assert selection.current() == selection.prev()

def test_next_prev_wrap_around(selection):
    selection.photos.append('photo2')
    selection.images.append('image2')

    assert selection.next() == 'image2'
    assert selection.next() == 'image'
    assert selection.prev() == 'image2'
    assert selection.prev() == 'image'

Prompt: Add a few behavior tests for selection


import pytz
from datetime import datetime, timedelta
from django.test import TestCase

from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet

class TopicAPITest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.active_view = TopicViewSet.as_view({'get': 'active'})
        self.inactive_view = TopicViewSet.as_view({'get': 'inactive'})
        self.user = UserFactory()

        self.active_topics_count = 5
        self.inactive_topics_count = 5

        TopicFactory.create_batch(self.active_topics_count, start=datetime.now(pytz.utc) - timedelta(days=3),
                                  end=datetime.now(pytz.utc) + timedelta(days=4))
        TopicFactory.create_batch(self.inactive_topics_count, start=datetime.now(pytz.utc) + timedelta(weeks=1),
                                  end=datetime.now(pytz.utc) + timedelta(weeks=2))

    def test_active_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/active")
        force_authenticate(request, user=self.user)
        response = self.active_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.active_topics_count, len(topics))

        for topic in topics:
            self.assertTrue(topic.is_active())

    def test_inactive_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/inactive")
        force_authenticate(request, user=self.user)
        response = self.inactive_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.inactive_topics_count, len(topics))

        for topic in topics:
            self.assertFalse(topic.is_active())

Write tests for active and inactive list routes

Response:
import pytz
from datetime import datetime, timedelta
from django.test import TestCase

from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet

class TopicAPITest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.active_view = TopicViewSet.as_view({'get': 'active'})
        self.inactive_view = TopicViewSet.as_view({'get': 'inactive'})
        self.user = UserFactory()

        self.active_topics_count = 5
        self.inactive_topics_count = 5

        TopicFactory.create_batch(self.active_topics_count, start=datetime.now(pytz.utc) - timedelta(days=3),
                                  end=datetime.now(pytz.utc) + timedelta(days=4))
        TopicFactory.create_batch(self.inactive_topics_count, start=datetime.now(pytz.utc) + timedelta(weeks=1),
                                  end=datetime.now(pytz.utc) + timedelta(weeks=2))

    def test_active_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/active")
        force_authenticate(request, user=self.user)
        response = self.active_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.active_topics_count, len(topics))

        for topic in topics:
            self.assertTrue(topic.is_active())

    def test_inactive_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/inactive")
        force_authenticate(request, user=self.user)
        response = self.inactive_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.inactive_topics_count, len(topics))

        for topic in topics:
            self.assertFalse(topic.is_active())

Prompt: Write tests for active and inactive list routes


from unittest import TestCase

from pydatajson.threading_helper import apply_threading

class ThreadingTests(TestCase):

    def test_threading(self):
        elements = [1, 2, 3, 4]

        def function(x):
            return x ** 2

        result = apply_threading(elements, function, 3)

        self.assertEqual(result, [1, 4, 9, 16])

Test case que pase por threading

Test case que pase por threading

Response:
from unittest import TestCase

from pydatajson.threading_helper import apply_threading

class ThreadingTests(TestCase):

    def test_threading(self):
        elements = [1, 2, 3, 4]

        def function(x):
            return x ** 2

        result = apply_threading(elements, function, 3)

        self.assertEqual(result, [1, 4, 9, 16])

Prompt: Test case que pase por threading


"""
Implementation of Thompson sampling for continuous spaces.
"""

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

from collections import deque
from ..utils import params

__all__ = ['Thompson']

@params('n')
def Thompson(model, n=100, rng=None):
    """
    Implementation of Thompson sampling for continuous models using a finite
    approximation to the kernel matrix with `n` Fourier components.
    """
    if hasattr(model, '__iter__'):
        model = deque(model, maxlen=1).pop()
    return model.sample_fourier(n, rng).get

Response:
"""
Implementation of Thompson sampling for continuous spaces.
"""

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

from collections import deque
from ..utils import params

__all__ = ['Thompson']

@params('n')
def Thompson(model, n=100, rng=None):
    """
    Implementation of Thompson sampling for continuous models using a finite
    approximation to the kernel matrix with `n` Fourier components.
    """
    if hasattr(model, '__iter__'):
        model = deque(model, maxlen=1).pop()
    return model.sample_fourier(n, rng).get

Prompt:
Fix Thompson to pay attention to the RNG.

"""
Acquisition functions based on (GP) UCB.
"""

# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from collections import deque

# local imports
from ..utils import params

# exported symbols
__all__ = ['Thompson']

@params('n')
def Thompson(model, n=100):
    """
    Implementation of Thompson sampling for continuous models using a finite
    approximation to the kernel matrix with `n` Fourier components.
    """
    if hasattr(model, '__iter__'):
        model = deque(model, maxlen=1).pop()
    return model.sample_fourier(n).get


from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os

def play_sound_file(path):
    fp = open(path, 'r')
    data = fp.read()
    fp.close()
    try:
        a = linuxaudiodev.open('w')
    except linuxaudiodev.error, msg:
	if msg[0] in (errno.EACCES, errno.ENODEV):
		raise TestSkipped, msg
        raise TestFailed, msg
    else:
        a.write(data)
        a.close()

def test():
    play_sound_file(findfile('audiotest.au'))

test()

Response:
from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os

def play_sound_file(path):
    fp = open(path, 'r')
    data = fp.read()
    fp.close()
    try:
        a = linuxaudiodev.open('w')
    except linuxaudiodev.error, msg:
	if msg[0] in (errno.EACCES, errno.ENODEV):
		raise TestSkipped, msg
        raise TestFailed, msg
    else:
        a.write(data)
        a.close()

def test():
    play_sound_file(findfile('audiotest.au'))

test()

Prompt:
Raise TestSkipped, not ImportError.
Honesty's the best policy.

from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os

def play_sound_file(path):
    fp = open(path, 'r')
    data = fp.read()
    fp.close()
    try:
        a = linuxaudiodev.open('w')
    except linuxaudiodev.error, msg:
	if msg[0] in (errno.EACCES, errno.ENODEV):
		raise ImportError, msg
        raise TestFailed, msg
    else:
        a.write(data)
        a.close()

def test():
    play_sound_file(findfile('audiotest.au'))

test()


# Generated by Django 4.0.5 on 2022-06-22 05:40

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("services", "0096_create_syllables_fi_columns"),
    ]

    operations = [
        migrations.AlterField(
            model_name="unitconnection",
            name="section_type",
            field=models.PositiveSmallIntegerField(
                choices=[
                    (1, "PHONE_OR_EMAIL"),
                    (2, "LINK"),
                    (3, "TOPICAL"),
                    (4, "OTHER_INFO"),
                    (5, "OPENING_HOURS"),
                    (6, "SOCIAL_MEDIA_LINK"),
                    (7, "OTHER_ADDRESS"),
                    (8, "HIGHLIGHT"),
                    (9, "ESERVICE_LINK"),
                    (10, "PRICE"),
                    (11, "SUBGROUP"),
                ],
                null=True,
            ),
        ),
    ]

Add migration for unitconnection section types

Response:
# Generated by Django 4.0.5 on 2022-06-22 05:40

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("services", "0096_create_syllables_fi_columns"),
    ]

    operations = [
        migrations.AlterField(
            model_name="unitconnection",
            name="section_type",
            field=models.PositiveSmallIntegerField(
                choices=[
                    (1, "PHONE_OR_EMAIL"),
                    (2, "LINK"),
                    (3, "TOPICAL"),
                    (4, "OTHER_INFO"),
                    (5, "OPENING_HOURS"),
                    (6, "SOCIAL_MEDIA_LINK"),
                    (7, "OTHER_ADDRESS"),
                    (8, "HIGHLIGHT"),
                    (9, "ESERVICE_LINK"),
                    (10, "PRICE"),
                    (11, "SUBGROUP"),
                ],
                null=True,
            ),
        ),
    ]

Prompt: Add migration for unitconnection section types


import tomviz.operators

NUMBER_OF_CHUNKS = 10

class InvertOperator(tomviz.operators.CancelableOperator):

    def transform_scalars(self, dataset):
        from tomviz import utils
        import numpy as np
        self.progress.maximum = NUMBER_OF_CHUNKS

        scalars = utils.get_scalars(dataset)
        if scalars is None:
            raise RuntimeError("No scalars found!")

        result = np.float32(scalars)
        min = np.amin(scalars)
        max = np.amax(scalars)
        step = 0
        for chunk in np.array_split(result, NUMBER_OF_CHUNKS):
            if self.canceled:
                return
            chunk[:] = max - chunk + min
            step += 1
            self.progress.value = step

        utils.set_scalars(dataset, result)

Response:
import tomviz.operators

NUMBER_OF_CHUNKS = 10

class InvertOperator(tomviz.operators.CancelableOperator):

    def transform_scalars(self, dataset):
        from tomviz import utils
        import numpy as np
        self.progress.maximum = NUMBER_OF_CHUNKS

        scalars = utils.get_scalars(dataset)
        if scalars is None:
            raise RuntimeError("No scalars found!")

        result = np.float32(scalars)
        min = np.amin(scalars)
        max = np.amax(scalars)
        step = 0
        for chunk in np.array_split(result, NUMBER_OF_CHUNKS):
            if self.canceled:
                return
            chunk[:] = max - chunk + min
            step += 1
            self.progress.value = step

        utils.set_scalars(dataset, result)

Prompt:
Add the minimum scalar value to the result of the InvertOperator

Without it, all results would be shifted so the minimum was 0.

import tomviz.operators

NUMBER_OF_CHUNKS = 10

class InvertOperator(tomviz.operators.CancelableOperator):

    def transform_scalars(self, dataset):
        from tomviz import utils
        import numpy as np
        self.progress.maximum = NUMBER_OF_CHUNKS

        scalars = utils.get_scalars(dataset)
        if scalars is None:
            raise RuntimeError("No scalars found!")

        result = np.float32(scalars)
        max = np.amax(scalars)
        step = 0
        for chunk in np.array_split(result, NUMBER_OF_CHUNKS):
            if self.canceled:
                return
            chunk[:] = max - chunk
            step += 1
            self.progress.value = step

        utils.set_scalars(dataset, result)


Add a missing line between imports

Add a missing line between imports

Response:
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic

from . import views

urlpatterns = (
    url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)

if getattr(settings, 'LOADERIO_TOKEN', None):
    loaderio_token = settings.LOADERIO_TOKEN

    class LoaderioTokenView(generic.View):
        def get(self, request, *args, **kwargs):
            return HttpResponse('{}'.format(loaderio_token))

    urlpatterns += (
        url(r'^{}/$'.format(loaderio_token), LoaderioTokenView.as_view()),
    )

Prompt:
Add a missing line between imports

from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic

from . import views

urlpatterns = (
    url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)

if getattr(settings, 'LOADERIO_TOKEN', None):
    loaderio_token = settings.LOADERIO_TOKEN

    class LoaderioTokenView(generic.View):
        def get(self, request, *args, **kwargs):
            return HttpResponse('{}'.format(loaderio_token))

    urlpatterns += (
        url(r'^{}/$'.format(loaderio_token), LoaderioTokenView.as_view()),
    )


import math

def line_magnitude (x1, y1, x2, y2):
    return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))

#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
    #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
    LineMag = line_magnitude(x1, y1, x2, y2)

    if LineMag < 0.00000001:
        dpl = 9999
        return dpl

    u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
    u = u1 / (LineMag * LineMag)

    if (u < 0.00001) or (u > 1):
        #// closest point does not fall within the line segment, take the shorter distance
        #// to an endpoint
        ix = line_magnitude(px, py, x1, y1)
        iy = line_magnitude(px, py, x2, y2)
        if ix > iy:
            dpl = iy
        else:
            dpl = ix
    else:
        # Intersecting point is on the line, use the formula
        ix = x1 + u * (x2 - x1)
        iy = y1 + u * (y2 - y1)
        dpl = line_magnitude(px, py, ix, iy)

    return dpl

Move geometric functions into a separate file

Response:
import math

def line_magnitude (x1, y1, x2, y2):
    return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))

#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
    #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
    LineMag = line_magnitude(x1, y1, x2, y2)

    if LineMag < 0.00000001:
        dpl = 9999
        return dpl

    u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
    u = u1 / (LineMag * LineMag)

    if (u < 0.00001) or (u > 1):
        #// closest point does not fall within the line segment, take the shorter distance
        #// to an endpoint
        ix = line_magnitude(px, py, x1, y1)
        iy = line_magnitude(px, py, x2, y2)
        if ix > iy:
            dpl = iy
        else:
            dpl = ix
    else:
        # Intersecting point is on the line, use the formula
        ix = x1 + u * (x2 - x1)
        iy = y1 + u * (y2 - y1)
        dpl = line_magnitude(px, py, ix, iy)

    return dpl

Prompt: Move geometric functions into a separate file


"""
=============
LineAnimator
=============

This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt

from sunpy.visualization.animator import LineAnimator

###############################################################################
# Animate a 2D cube of random data as a line plot along an
# axis where the x-axis drifts with time.

# Define some random data
data_shape0 = (10, 20)
data0 = np.random.rand(*data_shape0)

###############################################################################
# Define the axis that will make up the line plot
plot_axis0 = 1
slider_axis0 = 0

###############################################################################
# Define value along x axis which drift with time.  To do this, define
# xdata to be the same shape as the data where each row/column
# (depending on axis to be animated) represents the x-axis values for
# a single frame of the animations.
xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1))

###############################################################################
# Generate animation object with variable x-axis data.
ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata])

###############################################################################
# Show plot
plt.show()

Response:
"""
=============
LineAnimator
=============

This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt

from sunpy.visualization.animator import LineAnimator

###############################################################################
# Animate a 2D cube of random data as a line plot along an
# axis where the x-axis drifts with time.

# Define some random data
data_shape0 = (10, 20)
data0 = np.random.rand(*data_shape0)

###############################################################################
# Define the axis that will make up the line plot
plot_axis0 = 1
slider_axis0 = 0

###############################################################################
# Define value along x axis which drift with time.  To do this, define
# xdata to be the same shape as the data where each row/column
# (depending on axis to be animated) represents the x-axis values for
# a single frame of the animations.
xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1))

###############################################################################
# Generate animation object with variable x-axis data.
ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata])

###############################################################################
# Show plot
plt.show()

Prompt:
Fix LineAnimator example to adhere to new pixel edges axis_ranges API.

"""
=============
LineAnimator
=============

This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt

from sunpy.visualization.animator import LineAnimator

###############################################################################
# Animate a 2D cube of random data as a line plot along an
# axis where the x-axis drifts with time.

# Define some random data
data_shape0 = (10, 20)
data0 = np.random.rand(*data_shape0)

###############################################################################
# Define the axis that will make up the line plot
plot_axis0 = 1
slider_axis0 = 0

###############################################################################
# Define value along x axis which drift with time.  To do this, define
# xdata to be the same shape as the data where each row/column
# (depending on axis to be animated) represents the x-axis values for
# a single frame of the animations.
xdata = np.tile(np.linspace(0, 100, data_shape0[plot_axis0]), (data_shape0[slider_axis0], 1))

###############################################################################
# Generate animation object with variable x-axis data.
ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata])

###############################################################################
# Show plot
plt.show()


#!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
    print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
    sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
    print >>f, '; Automatically generated by "win.py"'
    VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
    for line in open(sys.argv[1], 'r'):
        m = VK.match(line)
        if m:
            n, i = m.groups()
            i = int(i, 0)
            print >>f, '%d\t%s' % (i, n)
    f.close()
    os.rename(TMP, OUT)
except:
    try:
        os.unlink(TMP)
    except OSError:
        pass
    raise

Add keycode table generator for Windows

Add keycode table generator for Windows

Response:
#!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
    print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
    sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
    print >>f, '; Automatically generated by "win.py"'
    VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
    for line in open(sys.argv[1], 'r'):
        m = VK.match(line)
        if m:
            n, i = m.groups()
            i = int(i, 0)
            print >>f, '%d\t%s' % (i, n)
    f.close()
    os.rename(TMP, OUT)
except:
    try:
        os.unlink(TMP)
    except OSError:
        pass
    raise

Prompt: Add keycode table generator for Windows


#!/usr/bin/env python3

import ftplib
import gzip
import os
import sys

host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3

ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
    (year, filename) = line.strip().split()
    for i in range(retries):
        sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
            filename, i + 1, retries))
        try:
            ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
        except ftplib.all_errors as error:
            sys.stderr.write('%s\n' % error)
            continue
        count = 0
        for record in gzip.open(filename, 'rb'):
            print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
            count += 1
        sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
        os.remove(filename)
        break
    else:
        ftp.quit()
        sys.exit(1)
ftp.quit()

Response:
#!/usr/bin/env python3

import ftplib
import gzip
import os
import sys

host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3

ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
    (year, filename) = line.strip().split()
    for i in range(retries):
        sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
            filename, i + 1, retries))
        try:
            ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
        except ftplib.all_errors as error:
            sys.stderr.write('%s\n' % error)
            continue
        count = 0
        for record in gzip.open(filename, 'rb'):
            print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
            count += 1
        sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
        os.remove(filename)
        break
    else:
        ftp.quit()
        sys.exit(1)
ftp.quit()

Prompt:
Decompress downloaded files from disk, not in memory

#!/usr/bin/env python3

import ftplib
import gzip
import sys

host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3

ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
    (year, filename) = line.strip().split()
    for i in range(retries):
        sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries))
        data = bytearray()
        try:
            ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), data.extend)
        except ftplib.all_errors as error:
            sys.stderr.write('%s\n' % error)
            continue
        records = gzip.decompress(data).decode('ISO-8859-1').split('\n')[0:-1]
        for record in records:
            print('%s\t%s' % (year, record))
        sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, len(records)))
        break
    else:
        ftp.quit()
        sys.exit(1)
ftp.quit()


# Configuration file for ipython-notebook.

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

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

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
    'X-Frame-Options': 'ALLOW FROM nature.com',
    'Content-Security-Policy': "frame-ancestors 'self' *.nature.com",
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}

Set the content security policy

Set the content security policy

Response:
# Configuration file for ipython-notebook.

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

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

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
    'X-Frame-Options': 'ALLOW FROM nature.com',
    'Content-Security-Policy': "frame-ancestors 'self' *.nature.com",
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}

Prompt:
Set the content security policy

# Configuration file for ipython-notebook.

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

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

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
    'X-Frame-Options': 'ALLOW FROM nature.com',
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}


from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from .timing import Timing

Add timing in devices init

DEV.ENH: Add timing in devices init

Response:
from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from .timing import Timing

Prompt:
DEV.ENH: Add timing in devices init

from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS


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

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

class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0045_populate_responded'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='responded',
            field=models.BooleanField(default=False, help_text='Whether contact has responded in this run'),
        ),
    ]

Set FlowRun.respnoded to be non-nullable

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

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

class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0045_populate_responded'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='responded',
            field=models.BooleanField(default=False, help_text='Whether contact has responded in this run'),
        ),
    ]

Prompt: Set FlowRun.respnoded to be non-nullable


from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
    (r'^ticket/', include('ticketus.ui.urls')),
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include(admin.site.urls)),
)

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

    # Serve media files in development. Note Django automatically serves
    # static files as the staticfiles app is active in settings.py.
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Add CBV for redirecting / to /ticket

Add CBV for redirecting / to /ticket

Response:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
    (r'^ticket/', include('ticketus.ui.urls')),
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include(admin.site.urls)),
)

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

    # Serve media files in development. Note Django automatically serves
    # static files as the staticfiles app is active in settings.py.
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Prompt:
Add CBV for redirecting / to /ticket

from django.conf import settings
from django.conf.urls import patterns, include
from django.contrib import admin

urlpatterns = patterns('',
    (r'^ticket/', include('ticketus.ui.urls')),
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include(admin.site.urls)),
)

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

    # Serve media files in development. Note Django automatically serves
    # static files as the staticfiles app is active in settings.py.
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from hypothesis_auto import auto_pytest_magic

from isort import parse
from isort.settings import Config

TEST_CONTENTS = """
import xyz
import abc

def function():
    pass
"""

def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        place_imports,
        import_placements,
        as_map,
        imports,
        categorized_comments,
        first_comment_index_start,
        first_comment_index_end,
        change_count,
        original_line_count,
        line_separator,
        sections,
        section_comments,
    ) = parse.file_contents(TEST_CONTENTS, config=Config())
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -2
    assert original_line_count == len(in_lines)

auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)

Response:
from hypothesis_auto import auto_pytest_magic

from isort import parse
from isort.settings import Config

TEST_CONTENTS = """
import xyz
import abc

def function():
    pass
"""

def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        place_imports,
        import_placements,
        as_map,
        imports,
        categorized_comments,
        first_comment_index_start,
        first_comment_index_end,
        change_count,
        original_line_count,
        line_separator,
        sections,
        section_comments,
    ) = parse.file_contents(TEST_CONTENTS, config=Config())
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -2
    assert original_line_count == len(in_lines)

auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)

Prompt:
Fix use of default config to match new refactor

from hypothesis_auto import auto_pytest_magic

from isort import parse
from isort.settings import default

TEST_CONTENTS = """
import xyz
import abc

def function():
    pass
"""

def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        place_imports,
        import_placements,
        as_map,
        imports,
        categorized_comments,
        first_comment_index_start,
        first_comment_index_end,
        change_count,
        original_line_count,
        line_separator,
        sections,
        section_comments,
    ) = parse.file_contents(TEST_CONTENTS, config=default)
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -2
    assert original_line_count == len(in_lines)

auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)


"""Prints the current view hierarchy.

Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
  debugger.GetCommandInterpreter().HandleCommand('po [[UIWindow keyWindow] recursiveDescription]', result)

def __lldb_init_module(debugger, internal_dict):
  debugger.HandleCommand('command script add -f print_view_hierarchy.print_view_hierarchy pv')

Response:
"""Prints the current view hierarchy.

Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
  debugger.GetCommandInterpreter().HandleCommand('po [[UIWindow keyWindow] recursiveDescription]', result)

def __lldb_init_module(debugger, internal_dict):
  debugger.HandleCommand('command script add -f print_view_hierarchy.print_view_hierarchy pv')

Prompt:
Update view hierarchy script to use the interpreter as needed for tests.

"""Prints the current view hierarchy.

Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
  debugger.HandleCommand('po [[UIWindow keyWindow] recursiveDescription]')

def __lldb_init_module(debugger, internal_dict):
  debugger.HandleCommand('command script add -f print_view_hierarchy.print_view_hierarchy pv')


import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError

from django.conf import settings
from django.http import HttpResponse, Http404

log = logging.getLogger(__name__)

class ControllerQueryService(GradingService):
    """
    Interface to staff grading backend.
    """
    def __init__(self, config):
        super(ControllerQuery, self).__init__(config)
        self.check_eta_url = self.url + '/get_submission_eta/'
        self.is_unique_url = self.url + '/is_name_unique/'
        self.combined_notifications_url = self.url + '/combined_notifications/'

    def check_if_name_is_unique(self, location, problem_id, course_id):
        params = {
            'course_id': course_id,
            'location' : location,
            'problem_id' : problem_id
        }
        response = self.get(self.is_unique_url, params)
        return response

    def check_for_eta(self, location):
        params = {
            'location' : location,
        }
        response = self.get(self.check_eta_url, params)
        return response

    def check_combined_notifications(self, course_id, student_id):
        params= {
            'student_id' : student_id,
            'course_id' : course_id,
        }
        response = self.get(self.combined_notifications_url,params)
        return response

Response:
import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError

from django.conf import settings
from django.http import HttpResponse, Http404

log = logging.getLogger(__name__)

class ControllerQueryService(GradingService):
    """
    Interface to staff grading backend.
    """
    def __init__(self, config):
        super(ControllerQuery, self).__init__(config)
        self.check_eta_url = self.url + '/get_submission_eta/'
        self.is_unique_url = self.url + '/is_name_unique/'
        self.combined_notifications_url = self.url + '/combined_notifications/'

    def check_if_name_is_unique(self, location, problem_id, course_id):
        params = {
            'course_id': course_id,
            'location' : location,
            'problem_id' : problem_id
        }
        response = self.get(self.is_unique_url, params)
        return response

    def check_for_eta(self, location):
        params = {
            'location' : location,
        }
        response = self.get(self.check_eta_url, params)
        return response

    def check_combined_notifications(self, course_id, student_id):
        params= {
            'student_id' : student_id,
            'course_id' : course_id,
        }
        response = self.get(self.combined_notifications_url,params)
        return response

Prompt:
Add in an item to check for combined notifications

import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError

from django.conf import settings
from django.http import HttpResponse, Http404

log = logging.getLogger(__name__)

class ControllerQueryService(GradingService):
    """
    Interface to staff grading backend.
    """
    def __init__(self, config):
        super(ControllerQuery, self).__init__(config)
        self.check_eta_url = self.url + '/get_submission_eta/'
        self.is_unique_url = self.url + '/is_name_unique/'

    def check_if_name_is_unique(self, location, problem_id, course_id):
        params = {
            'course_id': course_id,
            'location' : location,
            'problem_id' : problem_id
        }
        response = self.get(self.is_unique_url, params)
        return response

    def check_for_eta(self, location):
        params = {
            'location' : location,
        }
        response = self.get(self.check_eta_url, params)
        return response


import glob
import unittest
import os, sys

if __name__ == '__main__':
    PROJECT_ROOT = os.path.dirname(__file__)
    test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
    module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
    suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings]
    testSuite = unittest.TestSuite(suites)
    text_runner = unittest.TextTestRunner().run(testSuite)

Add all test runner for command line. Now every test can be run for commandline

Response:
import glob
import unittest
import os, sys

if __name__ == '__main__':
    PROJECT_ROOT = os.path.dirname(__file__)
    test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
    module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
    suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings]
    testSuite = unittest.TestSuite(suites)
    text_runner = unittest.TextTestRunner().run(testSuite)

Prompt: Add all test runner for command line. Now every test can be run for commandline


# -*- coding: utf-8 -*-
"""Asynchronous task queue module."""

from celery import Celery
from celery.utils.log import get_task_logger

from raven import Client
from raven.contrib.celery import register_signal

from website import settings

app = Celery()

# TODO: Hardcoded settings module. Should be set using framework's config handler
app.config_from_object('website.settings')

if settings.SENTRY_DSN:
    client = Client(settings.SENTRY_DSN)
    register_signal(client)

@app.task
def error_handler(task_id, task_name):
    """logs detailed message about tasks that raise exceptions

    :param task_id: TaskID of the failed task
    :param task_name: name of task that failed
    """
    # get the current logger
    logger = get_task_logger(__name__)
    # query the broker for the AsyncResult
    result = app.AsyncResult(task_id)
    excep = result.get(propagate=False)
    # log detailed error mesage in error log
    logger.error('#####FAILURE LOG BEGIN#####\n'
                'Task {0} raised exception: {0}\n\{0}\n'
                '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))

Use auto generated celery queues

Use auto generated celery queues

Response:
# -*- coding: utf-8 -*-
"""Asynchronous task queue module."""

from celery import Celery
from celery.utils.log import get_task_logger

from raven import Client
from raven.contrib.celery import register_signal

from website import settings

app = Celery()

# TODO: Hardcoded settings module. Should be set using framework's config handler
app.config_from_object('website.settings')

if settings.SENTRY_DSN:
    client = Client(settings.SENTRY_DSN)
    register_signal(client)

@app.task
def error_handler(task_id, task_name):
    """logs detailed message about tasks that raise exceptions

    :param task_id: TaskID of the failed task
    :param task_name: name of task that failed
    """
    # get the current logger
    logger = get_task_logger(__name__)
    # query the broker for the AsyncResult
    result = app.AsyncResult(task_id)
    excep = result.get(propagate=False)
    # log detailed error mesage in error log
    logger.error('#####FAILURE LOG BEGIN#####\n'
                'Task {0} raised exception: {0}\n\{0}\n'
                '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))

Prompt:
Use auto generated celery queues

# -*- coding: utf-8 -*-
"""Asynchronous task queue module."""

from celery import Celery
from celery.utils.log import get_task_logger
from kombu import Exchange, Queue

from raven import Client
from raven.contrib.celery import register_signal

from website import settings

app = Celery()

# TODO: Hardcoded settings module. Should be set using framework's config handler
app.config_from_object('website.settings')

app.conf.CELERY_QUEUES = (
    Queue(
        settings.CELERY_DEFAULT_QUEUE,
        Exchange(settings.CELERY_DEFAULT_QUEUE),
        routing_key=settings.CELERY_DEFAULT_QUEUE),
)

if settings.SENTRY_DSN:
    client = Client(settings.SENTRY_DSN)
    register_signal(client)

@app.task
def error_handler(task_id, task_name):
    """logs detailed message about tasks that raise exceptions

    :param task_id: TaskID of the failed task
    :param task_name: name of task that failed
    """
    # get the current logger
    logger = get_task_logger(__name__)
    # query the broker for the AsyncResult
    result = app.AsyncResult(task_id)
    excep = result.get(propagate=False)
    # log detailed error mesage in error log
    logger.error('#####FAILURE LOG BEGIN#####\n'
                'Task {0} raised exception: {0}\n\{0}\n'
                '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))


# -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.

.. code-block::

    # -- FILE: features/steps/use_substep_dirs.py
    # REQUIRES: path.py
    from behave.runner_util import load_step_modules
    from path import Path

    HERE = Path(__file__).dirname()
    SUBSTEP_DIRS = list(HERE.walkdirs())
    load_step_modules(SUBSTEP_DIRS)
"""

FIX TYPO: Uncovered by NaveenKVN

FIX TYPO: Uncovered by NaveenKVN

Response:
# -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.

.. code-block::

    # -- FILE: features/steps/use_substep_dirs.py
    # REQUIRES: path.py
    from behave.runner_util import load_step_modules
    from path import Path

    HERE = Path(__file__).dirname()
    SUBSTEP_DIRS = list(HERE.walkdirs())
    load_step_modules(SUBSTEP_DIRS)
"""

Prompt:
FIX TYPO: Uncovered by NaveenKVN

# -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.

.. code-block::

    # -- FILE: features/steps/use_substep_dirs.py
    # REQUIRES: path.py
    from behave.runner_util import load_step_modules
    from path import Path

    HERE = Path(__file__).dirname
    SUBSTEP_DIRS = list(HERE.walkdirs())
    load_step_modules(SUBSTEP_DIRS)
"""


#!/usr/bin/env python

import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError

def main(args):
    log = lutils.setupLog('bioinfologger', args.logfile)
    lims = Lims(BASEURI, USERNAME, PASSWORD)
    with open(args.conf) as conf_file:
        conf = yaml.safe_load(conf_file)
    bioinfodb = lutils.setupServer(conf)['bioinfo_analysis']
    open_projects = bioinfodb.view('latest_data/sample_id_open')

    for row in open_projects.rows:
        project_id = row.key[0]
        sample_id = row.key[3]
        close_date = None
        try:
            close_date = Project(lims=lims, id=project_id).close_date
        except HTTPError as e:
            if '404: Project not found' in e.message:
                log.error('Project '+project_id+' not found in LIMS')
                continue
        if close_date is not None:
            try:
                doc = bioinfodb.get(row.id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while accessing doc from statusdb')
            doc['project_closed'] = True
            try:
                bioinfodb.save(doc)
                log.info('Updated Project '+project_id+ ' Sample '+sample_id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while saving to statusdb')

if __name__ == '__main__':
    usage = "Usage:       python bioinfo_project_status_update.py [options]"
    parser = argparse.ArgumentParser(description=usage)

    parser.add_argument("-c", "--conf", dest="conf",
    default=os.path.join(os.environ['HOME'],'opt/config/post_process.yaml'),
    help = "Config file.  Default: ~/opt/config/post_process.yaml")

    parser.add_argument("-l", "--log", dest="logfile",
    default=os.path.join(os.environ['HOME'],'statusdb_bioinfo_closed.log'),
    help = "log file.  Default: ~/statusdb_bioinfo_closed.log")
    args = parser.parse_args()

    main(args)

Add script to update project closure in bioinfo_analysis db

Response:
#!/usr/bin/env python

import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError

def main(args):
    log = lutils.setupLog('bioinfologger', args.logfile)
    lims = Lims(BASEURI, USERNAME, PASSWORD)
    with open(args.conf) as conf_file:
        conf = yaml.safe_load(conf_file)
    bioinfodb = lutils.setupServer(conf)['bioinfo_analysis']
    open_projects = bioinfodb.view('latest_data/sample_id_open')

    for row in open_projects.rows:
        project_id = row.key[0]
        sample_id = row.key[3]
        close_date = None
        try:
            close_date = Project(lims=lims, id=project_id).close_date
        except HTTPError as e:
            if '404: Project not found' in e.message:
                log.error('Project '+project_id+' not found in LIMS')
                continue
        if close_date is not None:
            try:
                doc = bioinfodb.get(row.id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while accessing doc from statusdb')
            doc['project_closed'] = True
            try:
                bioinfodb.save(doc)
                log.info('Updated Project '+project_id+ ' Sample '+sample_id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while saving to statusdb')

if __name__ == '__main__':
    usage = "Usage:       python bioinfo_project_status_update.py [options]"
    parser = argparse.ArgumentParser(description=usage)

    parser.add_argument("-c", "--conf", dest="conf",
    default=os.path.join(os.environ['HOME'],'opt/config/post_process.yaml'),
    help = "Config file.  Default: ~/opt/config/post_process.yaml")

    parser.add_argument("-l", "--log", dest="logfile",
    default=os.path.join(os.environ['HOME'],'statusdb_bioinfo_closed.log'),
    help = "log file.  Default: ~/statusdb_bioinfo_closed.log")
    args = parser.parse_args()

    main(args)

Prompt: Add script to update project closure in bioinfo_analysis db