from django.db.models import Model, CharField, Field

class MaxLengthCharField(CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        super().__init__(*args, **kwargs)

class BaseModel(Model):
    class Meta:
        abstract = True

    def _get_explicit_field_names(self):
        return [field.name for field in self._meta.get_fields()
                if isinstance(field, Field) and field.name != 'id']

    def to_dict(self):
        fields = self._get_explicit_field_names()
        return {field: getattr(self, field) for field in fields}

    def __repr__(self):
        model = str(self.__class__.__name__)
        columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
        return '{}({})'.format(model, columns)

Add columns and values to repr

Add columns and values to repr

Response:
from django.db.models import Model, CharField, Field

class MaxLengthCharField(CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        super().__init__(*args, **kwargs)

class BaseModel(Model):
    class Meta:
        abstract = True

    def _get_explicit_field_names(self):
        return [field.name for field in self._meta.get_fields()
                if isinstance(field, Field) and field.name != 'id']

    def to_dict(self):
        fields = self._get_explicit_field_names()
        return {field: getattr(self, field) for field in fields}

    def __repr__(self):
        model = str(self.__class__.__name__)
        columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
        return '{}({})'.format(model, columns)

Prompt:
Add columns and values to repr

from django.db.models import Model, CharField, Field

class MaxLengthCharField(CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        super().__init__(*args, **kwargs)

class BaseModel(Model):
    class Meta:
        abstract = True

    def _get_explicit_field_names(self):
        return [field.name for field in self._meta.get_fields()
                if isinstance(field, Field) and field.name != 'id']

    def to_dict(self):
        fields = self._get_explicit_field_names()
        return {field: getattr(self, field) for field in fields}

    def __repr__(self):
        return 'Model({})'.format(repr(self.to_dict()))


# This module contains built-in introspector plugins for various common
# Django apps.

# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions
import south.introspection_plugins.annoying_autoonetoone

Add import of django-annoying patch

Add import of django-annoying patch

Response:
# This module contains built-in introspector plugins for various common
# Django apps.

# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions
import south.introspection_plugins.annoying_autoonetoone

Prompt:
Add import of django-annoying patch

# This module contains built-in introspector plugins for various common
# Django apps.

# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions


def bot_says(channel, text, slack_client):
    return slack_client.api_call("chat.postMessage",
                                 channel=channel,
                                 text=text,
                                 as_user=True)

def compose_explanation(url):
    return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)

def ask_confirmation(message, slack_client):
    bot_says(message['channel'],
             compose_explanation(message['url']),
             slack_client)

def compose_url_list(url_cache_list):
    if len(url_cache_list) == 0:
        return "The list is empty"

    intro = "The list of urls to be confirmed is: \n"
    options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)]

    return intro + "\n".join(options)

def list_cached_urls(url_cache_list, channel, slack_client):
    bot_says(channel,
             compose_url_list(url_cache_list),
             slack_client)

Response:
def bot_says(channel, text, slack_client):
    return slack_client.api_call("chat.postMessage",
                                 channel=channel,
                                 text=text,
                                 as_user=True)

def compose_explanation(url):
    return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)

def ask_confirmation(message, slack_client):
    bot_says(message['channel'],
             compose_explanation(message['url']),
             slack_client)

def compose_url_list(url_cache_list):
    if len(url_cache_list) == 0:
        return "The list is empty"

    intro = "The list of urls to be confirmed is: \n"
    options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)]

    return intro + "\n".join(options)

def list_cached_urls(url_cache_list, channel, slack_client):
    bot_says(channel,
             compose_url_list(url_cache_list),
             slack_client)

Prompt:
refactor: Change iteration over a collection based on ags suggestion

def bot_says(channel, text, slack_client):
    return slack_client.api_call("chat.postMessage",
                                 channel=channel,
                                 text=text,
                                 as_user=True)

def compose_explanation(url):
    return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)

def ask_confirmation(message, slack_client):
    bot_says(message['channel'],
             compose_explanation(message['url']),
             slack_client)

def compose_url_list(url_cache_list):
    if len(url_cache_list) == 0:
        return "The list is empty"

    list_message = "The list of urls to be confirmed is: \n"

    for index in range(0, len(url_cache_list)):
        extra = "{} - {} \n".format(index, url_cache_list[index]['url'])
        list_message = list_message + extra

    return list_message

def list_cached_urls(url_cache_list, channel, slack_client):
    bot_says(channel,
             compose_url_list(url_cache_list),
             slack_client)


# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository

class CodeSearchResult(GitHubCore):
    def __init__(self, data, session=None):
        super(CodeSearchResult, self).__init__(data, session)
        self._api = data.get('url')
        #: Filename the match occurs in
        self.name = data.get('name')
        #: Path in the repository to the file
        self.path = data.get('path')
        #: SHA in which the code can be found
        self.sha = data.get('sha')
        #: URL to the Git blob endpoint
        self.git_url = data.get('git_url')
        #: URL to the HTML view of the blob
        self.html_url = data.get('html_url')
        #: Repository the code snippet belongs to
        self.repository = Repository(data.get('repository', {}), self)
        #: Score of the result
        self.score = data.get('score')
        #: Text matches
        self.text_matches = data.get('text_matches', [])

    def __repr__(self):
        return '<CodeSearchResult [{0}]>'.format(self.path)

Add a __repr__ for CodeSearchResult

Add a __repr__ for CodeSearchResult

Response:
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository

class CodeSearchResult(GitHubCore):
    def __init__(self, data, session=None):
        super(CodeSearchResult, self).__init__(data, session)
        self._api = data.get('url')
        #: Filename the match occurs in
        self.name = data.get('name')
        #: Path in the repository to the file
        self.path = data.get('path')
        #: SHA in which the code can be found
        self.sha = data.get('sha')
        #: URL to the Git blob endpoint
        self.git_url = data.get('git_url')
        #: URL to the HTML view of the blob
        self.html_url = data.get('html_url')
        #: Repository the code snippet belongs to
        self.repository = Repository(data.get('repository', {}), self)
        #: Score of the result
        self.score = data.get('score')
        #: Text matches
        self.text_matches = data.get('text_matches', [])

    def __repr__(self):
        return '<CodeSearchResult [{0}]>'.format(self.path)

Prompt:
Add a __repr__ for CodeSearchResult

# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository

class CodeSearchResult(GitHubCore):
    def __init__(self, data, session=None):
        super(CodeSearchResult, self).__init__(data, session)
        self._api = data.get('url')
        #: Filename the match occurs in
        self.name = data.get('name')
        #: Path in the repository to the file
        self.path = data.get('path')
        #: SHA in which the code can be found
        self.sha = data.get('sha')
        #: URL to the Git blob endpoint
        self.git_url = data.get('git_url')
        #: URL to the HTML view of the blob
        self.html_url = data.get('html_url')
        #: Repository the code snippet belongs to
        self.repository = Repository(data.get('repository', {}), self)
        #: Score of the result
        self.score = data.get('score')
        #: Text matches
        self.text_matches = data.get('text_matches', [])


"""A set of utility functions to evaluate expressions.

Sample Usage:
    print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
    print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
    t = tb.SgTable()
    t.SetFields(["a", "bb", "ccc"])
    t.Append([1, 2, 3])
    t.Append([2, 4, 6])
    print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
"""

import table as tb

class SgExpressionEvaluator:
    """A set of utility functions to evaluate expressions."""

    @staticmethod
    def EvaluateExpressionInRow(fields, row, expr):
        """
        Evaluates the results of an expression (presumably a non-terminal field)
        given a list of fields and the values of a row.
        """

        # TODO(lnishan): This works for now, but in the future we might want to implement
        # a proper evaluator (correct tokenization, 2-stack evaluation)
        pairs = zip(fields, row)
        pairs.sort(key=lambda p: len(p[0]), reverse=True)
        for pair in pairs:
            expr = expr.replace(pair[0], str(pair[1]))
        return eval(expr)

    @staticmethod
    def EvaluateExpressionsInRow(fields, row, exprs):
        return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs]

    @staticmethod
    def EvaluateExpressionsInTable(table, exprs):
        ret = tb.SgTable()
        ret.SetFields(exprs)
        for row in table:
            ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs))
        return ret

Add SgExpressionEvaluator - Evaluates expressions given fields and values

Response:
"""A set of utility functions to evaluate expressions.

Sample Usage:
    print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
    print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
    t = tb.SgTable()
    t.SetFields(["a", "bb", "ccc"])
    t.Append([1, 2, 3])
    t.Append([2, 4, 6])
    print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
"""

import table as tb

class SgExpressionEvaluator:
    """A set of utility functions to evaluate expressions."""

    @staticmethod
    def EvaluateExpressionInRow(fields, row, expr):
        """
        Evaluates the results of an expression (presumably a non-terminal field)
        given a list of fields and the values of a row.
        """

        # TODO(lnishan): This works for now, but in the future we might want to implement
        # a proper evaluator (correct tokenization, 2-stack evaluation)
        pairs = zip(fields, row)
        pairs.sort(key=lambda p: len(p[0]), reverse=True)
        for pair in pairs:
            expr = expr.replace(pair[0], str(pair[1]))
        return eval(expr)

    @staticmethod
    def EvaluateExpressionsInRow(fields, row, exprs):
        return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs]

    @staticmethod
    def EvaluateExpressionsInTable(table, exprs):
        ret = tb.SgTable()
        ret.SetFields(exprs)
        for row in table:
            ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs))
        return ret

Prompt: Add SgExpressionEvaluator - Evaluates expressions given fields and values


""" Angr module """
# pylint: disable=wildcard-import

import logging
logging.getLogger("angr").addHandler(logging.NullHandler())

from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service import *
from .analyses import *
from .analysis import *
from .tablespecs import *
from . import surveyors
from .blade import Blade
from .simos import SimOS
from .path_group import PathGroup
from .surveyors.caller import Callable
from .log import Loggers
loggers = Loggers(logging.ERROR)

Make default logging level ERROR

Make default logging level ERROR

Response:
""" Angr module """
# pylint: disable=wildcard-import

import logging
logging.getLogger("angr").addHandler(logging.NullHandler())

from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service import *
from .analyses import *
from .analysis import *
from .tablespecs import *
from . import surveyors
from .blade import Blade
from .simos import SimOS
from .path_group import PathGroup
from .surveyors.caller import Callable
from .log import Loggers
loggers = Loggers(logging.ERROR)

Prompt:
Make default logging level ERROR

""" Angr module """
# pylint: disable=wildcard-import

import logging
logging.getLogger("angr").addHandler(logging.NullHandler())

from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service import *
from .analyses import *
from .analysis import *
from .tablespecs import *
from . import surveyors
from .blade import Blade
from .simos import SimOS
from .path_group import PathGroup
from .surveyors.caller import Callable
from .log import Loggers
loggers = Loggers()


"""
The setup package to install MasterQA requirements
"""

from setuptools import setup, find_packages  # noqa
from os import path

this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
    with open(path.join(this_directory, 'README.md'), 'rb') as f:
        long_description = f.read().decode('utf-8')
except IOError:
    long_description = (
        'Automation-Assisted Manual Testing - http://masterqa.com')

setup(
    name='masterqa',
    version='1.1.5',
    description='Automation-Assisted Manual Testing - http://masterqa.com',
    long_description=long_description,
    long_description_content_type='text/markdown',
    platforms='Mac * Windows * Linux',
    url='http://masterqa.com',
    author='Michael Mintz',
    author_email='mdmintz@gmail.com',
    maintainer='Michael Mintz',
    license='The MIT License',
    install_requires=[
        'seleniumbase',
        ],
    packages=['masterqa'],
    entry_points={
        'nose.plugins': []
        }
    )

Fix description content type for PyPi

Fix description content type for PyPi

Response:
"""
The setup package to install MasterQA requirements
"""

from setuptools import setup, find_packages  # noqa
from os import path

this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
    with open(path.join(this_directory, 'README.md'), 'rb') as f:
        long_description = f.read().decode('utf-8')
except IOError:
    long_description = (
        'Automation-Assisted Manual Testing - http://masterqa.com')

setup(
    name='masterqa',
    version='1.1.5',
    description='Automation-Assisted Manual Testing - http://masterqa.com',
    long_description=long_description,
    long_description_content_type='text/markdown',
    platforms='Mac * Windows * Linux',
    url='http://masterqa.com',
    author='Michael Mintz',
    author_email='mdmintz@gmail.com',
    maintainer='Michael Mintz',
    license='The MIT License',
    install_requires=[
        'seleniumbase',
        ],
    packages=['masterqa'],
    entry_points={
        'nose.plugins': []
        }
    )

Prompt:
Fix description content type for PyPi

"""
The setup package to install MasterQA requirements
"""

from setuptools import setup, find_packages  # noqa
from os import path

this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
    with open(path.join(this_directory, 'README.md'), 'rb') as f:
        long_description = f.read().decode('utf-8')
except IOError:
    long_description = (
        'Automation-Assisted Manual Testing - http://masterqa.com')

setup(
    name='masterqa',
    version='1.1.5',
    description='Automation-Assisted Manual Testing - http://masterqa.com',
    long_description=long_description,
    platforms='Mac * Windows * Linux',
    url='http://masterqa.com',
    author='Michael Mintz',
    author_email='mdmintz@gmail.com',
    maintainer='Michael Mintz',
    license='The MIT License',
    install_requires=[
        'seleniumbase',
        ],
    packages=['masterqa'],
    entry_points={
        'nose.plugins': []
        }
    )


from string import Template
from collections import defaultdict
import os
import yaml

def load_defaults():
    skipper_conf = 'skipper.yaml'
    defaults = {}
    if os.path.exists(skipper_conf):
        with open(skipper_conf) as confile:
            config = yaml.load(confile)
            containers = config.pop('containers', None)
        _normalize_config(config, defaults)
        if containers is not None:
            defaults['containers'] = containers
    return defaults

def _normalize_config(config, normalized_config):
    for key, value in config.iteritems():
        if isinstance(value, dict):
            normalized_config[key] = {}
            _normalize_config(value, normalized_config[key])
        elif isinstance(value, list):
            normalized_config[key] = [_interpolate_env_vars(x) for x in value]
        else:
            normalized_key = key.replace('-', '_')
            normalized_config[normalized_key] = _interpolate_env_vars(value)

def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))

Handle env vars in volumes

Handle env vars in volumes

Response:
from string import Template
from collections import defaultdict
import os
import yaml

def load_defaults():
    skipper_conf = 'skipper.yaml'
    defaults = {}
    if os.path.exists(skipper_conf):
        with open(skipper_conf) as confile:
            config = yaml.load(confile)
            containers = config.pop('containers', None)
        _normalize_config(config, defaults)
        if containers is not None:
            defaults['containers'] = containers
    return defaults

def _normalize_config(config, normalized_config):
    for key, value in config.iteritems():
        if isinstance(value, dict):
            normalized_config[key] = {}
            _normalize_config(value, normalized_config[key])
        elif isinstance(value, list):
            normalized_config[key] = [_interpolate_env_vars(x) for x in value]
        else:
            normalized_key = key.replace('-', '_')
            normalized_config[normalized_key] = _interpolate_env_vars(value)

def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))

Prompt:
Handle env vars in volumes

from string import Template
from collections import defaultdict
import os
import yaml

def load_defaults():
    skipper_conf = 'skipper.yaml'
    defaults = {}
    if os.path.exists(skipper_conf):
        with open(skipper_conf) as confile:
            config = yaml.load(confile)
            containers = config.pop('containers', None)
        _normalize_config(config, defaults)
        if containers is not None:
            defaults['containers'] = containers
    return defaults

def _normalize_config(config, normalized_config):
    for key, value in config.iteritems():
        if isinstance(value, dict):
            normalized_config[key] = {}
            _normalize_config(value, normalized_config[key])
        elif isinstance(value, list):
            normalized_config[key] = value
        else:
            normalized_key = key.replace('-', '_')
            normalized_config[normalized_key] = _interpolate_env_vars(value)

def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))


#import pygame.midi.Output
from pygame.midi import Output

class Output(Output):#pygame.midi.Output):

    def set_pan(self, pan, channel):
        assert (0 <= channel <= 15)
        assert pan <= 127

        self.write_short(0xB0 + channel, 0x0A, pan)

    def set_volume(self, volume, channel):
        assert (0 <= channel <= 15)
        assert volume <= 127

        self.write_short(0xB0 + channel, 0x07, volume)

    def set_pitch(self, pitch, channel):
        assert (0 <= channel <= 15)
        assert pitch <= (2**14-1)

        # the 7 least significant bits come into the first data byte,
        # the 7 most significant bits come into the second data byte
        pitch_lsb = (pitch >> 7) & 127
        pitch_msb = pitch & 127

        self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)

Add Volume and Pitch methods

Add Volume and Pitch methods

Response:
#import pygame.midi.Output
from pygame.midi import Output

class Output(Output):#pygame.midi.Output):

    def set_pan(self, pan, channel):
        assert (0 <= channel <= 15)
        assert pan <= 127

        self.write_short(0xB0 + channel, 0x0A, pan)

    def set_volume(self, volume, channel):
        assert (0 <= channel <= 15)
        assert volume <= 127

        self.write_short(0xB0 + channel, 0x07, volume)

    def set_pitch(self, pitch, channel):
        assert (0 <= channel <= 15)
        assert pitch <= (2**14-1)

        # the 7 least significant bits come into the first data byte,
        # the 7 most significant bits come into the second data byte
        pitch_lsb = (pitch >> 7) & 127
        pitch_msb = pitch & 127

        self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)

Prompt:
Add Volume and Pitch methods

#import pygame.midi.Output
from pygame.midi import Output

class Output(Output):#pygame.midi.Output):
    def set_pan(self, pan, channel):
        assert (0 <= channel <= 15)
        assert pan <= 127

        self.write_short(0xB0 + channel, 0x0A, pan)


import htmlmin
from markupsafe import Markup

from qxlc import app

@app.template_filter("minify")
def minify_filter(s):
    return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))

Response:
import htmlmin
from markupsafe import Markup

from qxlc import app

@app.template_filter("minify")
def minify_filter(s):
    return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))

Prompt:
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)

import htmlmin
from markupsafe import Markup

from qxlc import app

@app.template_filter("minify")
def minify_filter(text):
    return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True))


from django.conf import settings

import factory

from ..models import Document

class EmptyFileField(factory.django.FileField):
    DEFAULT_FILENAME = None

class DocumentFactory(factory.django.DjangoModelFactory):
    title = factory.Sequence(lambda n: "Test document {0}".format(n))
    summary = "This is a test summary"
    lang = settings.LANGUAGE_CODE
    original = factory.django.FileField()
    preview = EmptyFileField()
    credits = "Document credits"
    package_id = ""

    @factory.post_generation
    def tags(self, create, extracted, **kwargs):
        if extracted:
            self.tags.add(*extracted)

    class Meta:
        model = Document

Response:
from django.conf import settings

import factory

from ..models import Document

class EmptyFileField(factory.django.FileField):
    DEFAULT_FILENAME = None

class DocumentFactory(factory.django.DjangoModelFactory):
    title = factory.Sequence(lambda n: "Test document {0}".format(n))
    summary = "This is a test summary"
    lang = settings.LANGUAGE_CODE
    original = factory.django.FileField()
    preview = EmptyFileField()
    credits = "Document credits"
    package_id = ""

    @factory.post_generation
    def tags(self, create, extracted, **kwargs):
        if extracted:
            self.tags.add(*extracted)

    class Meta:
        model = Document

Prompt:
Allow DocumentFactory to handle preview field.

The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'.
It means that by default a FileField created by factoryboy is considered as a
True value.
Before this commit, we were not defining a Document.preview field in the
factory so factoryboy created a empty FileField.
To not break the API for other tests, we need to create a "False" FileField by
default.
To do so, we need to change the DEFAULT_FILENAME to None.

from django.conf import settings

import factory

from ..models import Document

class DocumentFactory(factory.django.DjangoModelFactory):
    title = factory.Sequence(lambda n: "Test document {0}".format(n))
    summary = "This is a test summary"
    lang = settings.LANGUAGE_CODE
    original = factory.django.FileField()
    credits = "Document credits"
    package_id = ""

    @factory.post_generation
    def tags(self, create, extracted, **kwargs):
        if extracted:
            self.tags.add(*extracted)

    class Meta:
        model = Document


from django.shortcuts import get_object_or_404
import jingo

from challenges.models import Submission, Category
from projects.models import Project

def splash(request, project, slug, template_name='challenges/show.html'):
    """Show an individual project challenge."""
    project = get_object_or_404(Project, slug=project)
    challenge = get_object_or_404(project.challenge_set, slug=slug)
    entries = (Submission.objects.visible()
                                 .filter(phase__challenge=challenge)
                                 .order_by("?"))

    return jingo.render(request, 'ignite/splash.html', {
        'challenge': challenge,
        'project': project,
        'phases': list(enumerate(challenge.phases.all(), start=1)),
        'entries': entries[:10],
        'categories': Category.objects.get_active_categories(),
    })

Response:
from django.shortcuts import get_object_or_404
import jingo

from challenges.models import Submission, Category
from projects.models import Project

def splash(request, project, slug, template_name='challenges/show.html'):
    """Show an individual project challenge."""
    project = get_object_or_404(Project, slug=project)
    challenge = get_object_or_404(project.challenge_set, slug=slug)
    entries = (Submission.objects.visible()
                                 .filter(phase__challenge=challenge)
                                 .order_by("?"))

    return jingo.render(request, 'ignite/splash.html', {
        'challenge': challenge,
        'project': project,
        'phases': list(enumerate(challenge.phases.all(), start=1)),
        'entries': entries[:10],
        'categories': Category.objects.get_active_categories(),
    })

Prompt:
Update splash view to use visible() method.

from django.shortcuts import get_object_or_404
import jingo

from challenges.models import Submission, Category
from projects.models import Project

def splash(request, project, slug, template_name='challenges/show.html'):
    """Show an individual project challenge."""
    project = get_object_or_404(Project, slug=project)
    challenge = get_object_or_404(project.challenge_set, slug=slug)
    entries = Submission.objects.filter(
        phase__challenge=challenge
    ).exclude(
        is_draft=True
    ).extra(
        order_by="?"
    )
    return jingo.render(request, 'ignite/splash.html', {
        'challenge': challenge,
        'project': project,
        'phases': list(enumerate(challenge.phases.all(), start=1)),
        'entries': entries[:10],
        'categories': Category.objects.get_active_categories(),
    })


from setuptools import setup, find_packages

setup(name='coinop',
      version='0.1.0',
      description='Crypto-currency conveniences',
      url='http://github.com/BitVault/coinop-py',
      author='Matthew King',
      author_email='matthew@bitvault.io',
      license='MIT',
      packages=find_packages(exclude=[
          u'*.tests', u'*.tests.*', u'tests.*', u'tests']),
      install_requires=[
          # Not listed explicitly to ensure you install PyNaCl by hand--
          # see README
          #'PyNaCl',
          'cffi',
          'pytest',
          'pycrypto',
          'python-bitcoinlib',
          'pycoin',
          'PyYAML',
          'ecdsa'
      ],
      zip_safe=False)

Response:
from setuptools import setup, find_packages

setup(name='coinop',
      version='0.1.0',
      description='Crypto-currency conveniences',
      url='http://github.com/BitVault/coinop-py',
      author='Matthew King',
      author_email='matthew@bitvault.io',
      license='MIT',
      packages=find_packages(exclude=[
          u'*.tests', u'*.tests.*', u'tests.*', u'tests']),
      install_requires=[
          # Not listed explicitly to ensure you install PyNaCl by hand--
          # see README
          #'PyNaCl',
          'cffi',
          'pytest',
          'pycrypto',
          'python-bitcoinlib',
          'pycoin',
          'PyYAML',
          'ecdsa'
      ],
      zip_safe=False)

Prompt:
Make version number match patchboard, bitvault

from setuptools import setup, find_packages

setup(name='coinop',
      version='0.0.3',
      description='Crypto-currency conveniences',
      url='http://github.com/BitVault/coinop-py',
      author='Matthew King',
      author_email='matthew@bitvault.io',
      license='MIT',
      packages=find_packages(exclude=[
          u'*.tests', u'*.tests.*', u'tests.*', u'tests']),
      install_requires=[
          # Not listed explicitly to ensure you install PyNaCl by hand--
          # see README
          #'PyNaCl',
          'cffi',
          'pytest',
          'pycrypto',
          'python-bitcoinlib',
          'pycoin',
          'PyYAML',
          'ecdsa'
      ],
      zip_safe=False)


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

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from .staff_student import StaffStudentBase
from .postsecondary_readiness import PostSecondaryReadinessBase

@python_2_unicode_compatible
class SchoolYear(models.Model):
    name = models.CharField(max_length=9)

    def __str__(self):
        return self.name

class StatsBase(StaffStudentBase, PostSecondaryReadinessBase):
    """
    An abstract model representing stats commonly tracked across all entities
    in TEA data. Meant to be the base used by other apps for establishing
    their stats models.

    Example:

    class CampusStats(StatsBase):
        ...

    """

    class Meta:
        abstract = True

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

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from .staff_student import StaffStudentBase
from .postsecondary_readiness import PostSecondaryReadinessBase

@python_2_unicode_compatible
class SchoolYear(models.Model):
    name = models.CharField(max_length=9)

    def __str__(self):
        return self.name

class StatsBase(StaffStudentBase, PostSecondaryReadinessBase):
    """
    An abstract model representing stats commonly tracked across all entities
    in TEA data. Meant to be the base used by other apps for establishing
    their stats models.

    Example:

    class CampusStats(StatsBase):
        ...

    """

    class Meta:
        abstract = True

Prompt:
Add postsecondary stats to the StatsBase model

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

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from .staff_student import StaffStudentBase

@python_2_unicode_compatible
class SchoolYear(models.Model):
    name = models.CharField(max_length=9)

    def __str__(self):
        return self.name

class StatsBase(StaffStudentBase):
    """
    An abstract model representing stats commonly tracked across all entities
    in TEA data. Meant to be the base used by other apps for establishing
    their stats models.

    Example:

    class CampusStats(StatsBase):
        ...

    """

    class Meta:
        abstract = True


import os
from setuptools import setup, find_packages

ROOT = os.path.abspath(os.path.dirname(__file__))

setup(
    name='django-nose',
    version='0.2',
    description='Django test runner that uses nose.',
    long_description=open(os.path.join(ROOT, 'README.rst')).read(),
    author='Jeff Balogh',
    author_email='me@jeffbalogh.org',
    url='http://github.com/jbalogh/django-nose',
    license='BSD',
    packages=find_packages(exclude=['testapp','testapp/*']),
    include_package_data=True,
    zip_safe=False,
    install_requires=['nose'],
    tests_require=['Django', 'south'],
    # This blows up tox runs that install django-nose into a virtualenv,
    # because it causes Nose to import django_nose.runner before the Django
    # settings are initialized, leading to a mess of errors. There's no reason
    # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you
    # need to be using django-nose to find the it useful, and django-nose knows
    # about it intrinsically.
    #entry_points="""
    #    [nose.plugins.0.10]
    #    fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin
    #    """,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)

Response:
import os
from setuptools import setup, find_packages

ROOT = os.path.abspath(os.path.dirname(__file__))

setup(
    name='django-nose',
    version='0.2',
    description='Django test runner that uses nose.',
    long_description=open(os.path.join(ROOT, 'README.rst')).read(),
    author='Jeff Balogh',
    author_email='me@jeffbalogh.org',
    url='http://github.com/jbalogh/django-nose',
    license='BSD',
    packages=find_packages(exclude=['testapp','testapp/*']),
    include_package_data=True,
    zip_safe=False,
    install_requires=['nose'],
    tests_require=['Django', 'south'],
    # This blows up tox runs that install django-nose into a virtualenv,
    # because it causes Nose to import django_nose.runner before the Django
    # settings are initialized, leading to a mess of errors. There's no reason
    # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you
    # need to be using django-nose to find the it useful, and django-nose knows
    # about it intrinsically.
    #entry_points="""
    #    [nose.plugins.0.10]
    #    fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin
    #    """,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)

Prompt:
Comment out entrypoint because it blows up django-nose in connection with tox. Ouch.

import os
from setuptools import setup, find_packages

ROOT = os.path.abspath(os.path.dirname(__file__))

setup(
    name='django-nose',
    version='0.2',
    description='Django test runner that uses nose.',
    long_description=open(os.path.join(ROOT, 'README.rst')).read(),
    author='Jeff Balogh',
    author_email='me@jeffbalogh.org',
    url='http://github.com/jbalogh/django-nose',
    license='BSD',
    packages=find_packages(exclude=['testapp','testapp/*']),
    include_package_data=True,
    zip_safe=False,
    install_requires=['nose'],
    tests_require=['Django', 'south'],
    entry_points="""
        [nose.plugins.0.10]
        fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin
        """,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
)


import importlib
import importlib.util
import sys
import types

import pytest

def load_script(example: str) -> types.ModuleType:
    file_path = f"examples/{example}.py"
    module_name = "run"

    spec = importlib.util.spec_from_file_location(module_name, file_path)
    assert spec is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module

    assert spec.loader is not None
    spec.loader.exec_module(module)

    return module

def test_dataset(unihan_options):
    example = load_script("dataset")
    example.run()

def test_variants(unihan_options):
    example = load_script("variants")
    example.run()

def test_ts_difficulties(unihan_options):
    example = load_script("variant_ts_difficulties")
    example.run(unihan_options=unihan_options)

def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]):
    example = load_script("basic_usage")
    example.run(unihan_options=unihan_options)

    captured = capsys.readouterr()

    assert "lookup for 好: good" in captured.out
    assert 'matches for "good": 好' in captured.out

def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]):
    example = load_script("basic_usage_manual")
    example.run(unihan_options=unihan_options)

    captured = capsys.readouterr()

    assert "lookup for 好: good" in captured.out
    assert 'matches for "good": 好' in captured.out

Rework for handling of examples/

Response:
import importlib
import importlib.util
import sys
import types

import pytest

def load_script(example: str) -> types.ModuleType:
    file_path = f"examples/{example}.py"
    module_name = "run"

    spec = importlib.util.spec_from_file_location(module_name, file_path)
    assert spec is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module

    assert spec.loader is not None
    spec.loader.exec_module(module)

    return module

def test_dataset(unihan_options):
    example = load_script("dataset")
    example.run()

def test_variants(unihan_options):
    example = load_script("variants")
    example.run()

def test_ts_difficulties(unihan_options):
    example = load_script("variant_ts_difficulties")
    example.run(unihan_options=unihan_options)

def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]):
    example = load_script("basic_usage")
    example.run(unihan_options=unihan_options)

    captured = capsys.readouterr()

    assert "lookup for 好: good" in captured.out
    assert 'matches for "good": 好' in captured.out

def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]):
    example = load_script("basic_usage_manual")
    example.run(unihan_options=unihan_options)

    captured = capsys.readouterr()

    assert "lookup for 好: good" in captured.out
    assert 'matches for "good": 好' in captured.out

Prompt:
refactor(tests): Rework for handling of examples/

import pytest

import examples.basic_usage
import examples.basic_usage_manual
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants

def test_dataset(unihan_options):
    examples.dataset.run()

def test_variants(unihan_options):
    examples.variants.run(unihan_options=unihan_options)

def test_ts_difficulties(unihan_options):
    examples.variant_ts_difficulties.run(unihan_options=unihan_options)

def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]):
    examples.basic_usage.run(unihan_options=unihan_options)

    captured = capsys.readouterr()

    assert "lookup for 好: good" in captured.out
    assert 'matches for "good": 好' in captured.out

def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]):
    examples.basic_usage_manual.run(unihan_options=unihan_options)

    captured = capsys.readouterr()

    assert "lookup for 好: good" in captured.out
    assert 'matches for "good": 好' in captured.out


'''
In this example we use Q-learning via self-play to learn
the value function of all Tic-Tac-Toe positions.
'''
from capstone.environment import Environment
from capstone.game import TicTacToe
from capstone.mdp import GameMDP
from capstone.rl import QLearningSelfPlay
from capstone.rl.tabularf import TabularF
from capstone.util import tic2pdf

game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=1000)
qlearning.learn()

for move in game.legal_moves():
    print('-' * 80)
    value = qlearning.qf[(game, move)]
    new_game = game.copy().make_move(move)
    print(value)
    print(new_game)

Use Q-learning to learn all state-action values via self-play

Response:
'''
In this example we use Q-learning via self-play to learn
the value function of all Tic-Tac-Toe positions.
'''
from capstone.environment import Environment
from capstone.game import TicTacToe
from capstone.mdp import GameMDP
from capstone.rl import QLearningSelfPlay
from capstone.rl.tabularf import TabularF
from capstone.util import tic2pdf

game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=1000)
qlearning.learn()

for move in game.legal_moves():
    print('-' * 80)
    value = qlearning.qf[(game, move)]
    new_game = game.copy().make_move(move)
    print(value)
    print(new_game)

Prompt: Use Q-learning to learn all state-action values via self-play


import os
from setuptools import setup, find_packages

from taggit import VERSION

f = open(os.path.join(os.path.dirname(__file__), 'README.txt'))
readme = f.read()
f.close()

setup(
    name='django-taggit',
    version=".".join(VERSION),
    description='django-taggit is a reusable Django application for simple tagging.',
    long_description=readme,
    author='Alex Gaynor',
    author_email='alex.gaynor@gmail.com',
    url='http://github.com/alex/django-taggit/tree/master',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
)

Update on suggestion of jezdez.

Update on suggestion of jezdez.

Response:
import os
from setuptools import setup, find_packages

from taggit import VERSION

f = open(os.path.join(os.path.dirname(__file__), 'README.txt'))
readme = f.read()
f.close()

setup(
    name='django-taggit',
    version=".".join(VERSION),
    description='django-taggit is a reusable Django application for simple tagging.',
    long_description=readme,
    author='Alex Gaynor',
    author_email='alex.gaynor@gmail.com',
    url='http://github.com/alex/django-taggit/tree/master',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
)

Prompt:
Update on suggestion of jezdez.

from setuptools import setup, find_packages

from taggit import VERSION

f = open('README.txt')
readme = f.read()
f.close()

setup(
    name='django-taggit',
    version=".".join(VERSION),
    description='django-taggit is a reusable Django application for simple tagging.',
    long_description=readme,
    author='Alex Gaynor',
    author_email='alex.gaynor@gmail.com',
    url='http://github.com/alex/django-taggit/tree/master',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
)


import tkFileDialog
import joincsv
import os.path
import sys

if __name__ == '__main__':
    filetypes=[("Spreadsheets", "*.csv"),
               ("Spreadsheets", "*.xls"),
               ("Spreadsheets", "*.xlsx")]

    if len(sys.argv) == 2:
        input_filename = sys.argv[1]
    else:
        input_filename = tkFileDialog.askopenfilename(filetypes=filetypes)

    if not os.path.isfile(input_filename):
        exit(0)

    output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv")

    if output_filename:
        joiner = joincsv.RecordJoiner(input_filename)
        joiner.save(output_filename)

Response:
import tkFileDialog
import joincsv
import os.path
import sys

if __name__ == '__main__':
    filetypes=[("Spreadsheets", "*.csv"),
               ("Spreadsheets", "*.xls"),
               ("Spreadsheets", "*.xlsx")]

    if len(sys.argv) == 2:
        input_filename = sys.argv[1]
    else:
        input_filename = tkFileDialog.askopenfilename(filetypes=filetypes)

    if not os.path.isfile(input_filename):
        exit(0)

    output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv")

    if output_filename:
        joiner = joincsv.RecordJoiner(input_filename)
        joiner.save(output_filename)

Prompt:
Allow saving to a file that does not already exist again.

import tkFileDialog
import joincsv
import os.path
import sys

if __name__ == '__main__':
    filetypes=[("Spreadsheets", "*.csv"),
               ("Spreadsheets", "*.xls"),
               ("Spreadsheets", "*.xlsx")]

    if len(sys.argv) == 2:
        input_filename = sys.argv[1]
    else:
        input_filename = tkFileDialog.askopenfilename(filetypes=filetypes)

    if not os.path.isfile(input_filename):
        exit(0)

    output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv")
    if not os.path.isfile(output_filename):
        exit(0)

    joiner = joincsv.RecordJoiner(input_filename)
    joiner.save(output_filename)


import re
from django import forms
from fluent_contents.forms import ContentItemForm
from icekit.plugins.twitter_embed.models import TwitterEmbedItem

class TwitterEmbedAdminForm(ContentItemForm):
    class Meta:
        model = TwitterEmbedItem
        fields = '__all__'

    def clean_twitter_url(self):
        """
        Make sure the URL provided matches the twitter URL format.
        """
        url = self.cleaned_data['twitter_url']

        if url:
            pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+')
            if not pattern.match(url):
                raise forms.ValidationError('Please provide a valid twitter link.')

        return url

Response:
import re
from django import forms
from fluent_contents.forms import ContentItemForm
from icekit.plugins.twitter_embed.models import TwitterEmbedItem

class TwitterEmbedAdminForm(ContentItemForm):
    class Meta:
        model = TwitterEmbedItem
        fields = '__all__'

    def clean_twitter_url(self):
        """
        Make sure the URL provided matches the twitter URL format.
        """
        url = self.cleaned_data['twitter_url']

        if url:
            pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+')
            if not pattern.match(url):
                raise forms.ValidationError('Please provide a valid twitter link.')

        return url

Prompt:
Add model and firld information to form.

import re
from django import forms
from fluent_contents.forms import ContentItemForm

class TwitterEmbedAdminForm(ContentItemForm):
    def clean_twitter_url(self):
        """
        Make sure the URL provided matches the twitter URL format.
        """
        url = self.cleaned_data['twitter_url']

        if url:
            pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+')
            if not pattern.match(url):
                raise forms.ValidationError('Please provide a valid twitter link.')

        return url


# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
#    This program 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.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv

class analytic_code(osv.Model):
    _name = "analytic.code"

    _columns = dict(
        name=fields.char("Name", size=128, translate=True, required=True),
        nd_id=fields.many2one(
            "analytic.dimension", "Dimensions", ondelete="restrict"),
        active=fields.boolean('Active'),
        nd_name=fields.related('nd_id', 'name', type="char",
                               string="Dimension Name", store=False),
        description=fields.char('Description', size=512),
    )
    _defaults = {
        'active': 1,
    }

Response:
# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
#    This program 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.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv

class analytic_code(osv.Model):
    _name = "analytic.code"

    _columns = dict(
        name=fields.char("Name", size=128, translate=True, required=True),
        nd_id=fields.many2one(
            "analytic.dimension", "Dimensions", ondelete="restrict"),
        active=fields.boolean('Active'),
        nd_name=fields.related('nd_id', 'name', type="char",
                               string="Dimension Name", store=False),
        description=fields.char('Description', size=512),
    )
    _defaults = {
        'active': 1,
    }

Prompt:
Add string to display the name of the field Dimension during the import

# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
#    This program 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.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv

class analytic_code(osv.Model):
    _name = "analytic.code"

    _columns = dict(
        name=fields.char("Name", size=128, translate=True, required=True),
        nd_id=fields.many2one(
            "analytic.dimension", ondelete="restrict"),
        active=fields.boolean('Active'),
        nd_name=fields.related('nd_id', 'name', type="char",
                               string="Dimension Name", store=False),
        description=fields.char('Description', size=512),
    )
    _defaults = {
        'active': 1,
    }


from hoomd.update.box_resize import BoxResize

# TODO remove when no longer necessary
class _updater:
    pass

__all__ = ['BoxResize']

Response:
from hoomd.update.box_resize import BoxResize

# TODO remove when no longer necessary
class _updater:
    pass

__all__ = ['BoxResize']

Prompt:
Fix typo in hoomd.update.__all__ quote class name

from hoomd.update.box_resize import BoxResize

# TODO remove when no longer necessary
class _updater:
    pass

__all__ = [BoxResize]


from django import forms
from django.utils.translation import ugettext_lazy as _

from tagging.forms import TagField

from bookmarks.models import Bookmark, BookmarkInstance

class BookmarkInstanceForm(forms.ModelForm):

    url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
    description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
    redirect = forms.BooleanField(label="Redirect", required=False)
    tags = TagField(label="Tags", required=False)

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
        # hack to order fields
        self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']

    def clean(self):
        if 'url' not in self.cleaned_data:
            return
        if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
            raise forms.ValidationError(_("You have already bookmarked this link."))
        return self.cleaned_data

    def should_redirect(self):
        if self.cleaned_data["redirect"]:
            return True
        else:
            return False

    def save(self, commit=True):
        self.instance.url = self.cleaned_data['url']
        return super(BookmarkInstanceForm, self).save(commit)

    class Meta:
        model = BookmarkInstance
        #fields = ('url', 'description', 'note', 'redirect')

Response:
from django import forms
from django.utils.translation import ugettext_lazy as _

from tagging.forms import TagField

from bookmarks.models import Bookmark, BookmarkInstance

class BookmarkInstanceForm(forms.ModelForm):

    url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
    description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
    redirect = forms.BooleanField(label="Redirect", required=False)
    tags = TagField(label="Tags", required=False)

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
        # hack to order fields
        self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']

    def clean(self):
        if 'url' not in self.cleaned_data:
            return
        if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
            raise forms.ValidationError(_("You have already bookmarked this link."))
        return self.cleaned_data

    def should_redirect(self):
        if self.cleaned_data["redirect"]:
            return True
        else:
            return False

    def save(self, commit=True):
        self.instance.url = self.cleaned_data['url']
        return super(BookmarkInstanceForm, self).save(commit)

    class Meta:
        model = BookmarkInstance
        #fields = ('url', 'description', 'note', 'redirect')

Prompt:
Make URLField compatible with Django 1.4 and remove verify_exists attribute

from django import forms
from django.utils.translation import ugettext_lazy as _

from tagging.forms import TagField

from bookmarks.models import Bookmark, BookmarkInstance

class BookmarkInstanceForm(forms.ModelForm):

    url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40}))
    description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40}))
    redirect = forms.BooleanField(label="Redirect", required=False)
    tags = TagField(label="Tags", required=False)

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(BookmarkInstanceForm, self).__init__(*args, **kwargs)
        # hack to order fields
        self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect']

    def clean(self):
        if 'url' not in self.cleaned_data:
            return
        if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0:
            raise forms.ValidationError(_("You have already bookmarked this link."))
        return self.cleaned_data

    def should_redirect(self):
        if self.cleaned_data["redirect"]:
            return True
        else:
            return False

    def save(self, commit=True):
        self.instance.url = self.cleaned_data['url']
        return super(BookmarkInstanceForm, self).save(commit)

    class Meta:
        model = BookmarkInstance
        #fields = ('url', 'description', 'note', 'redirect')


from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors

import cv2
import numpy as np

class CharacteristicIdentifier:
    """
    Identify target characteristics
    """

    def __init__(self, **kwargs):
        pass

    def identify_characteristics(self, target):
        """
        Identifies the characteristics of the target "target" and returns
        them as a dictionary object
        """
        # My thoughts so far to accomplish this is to break the problem down
        #   into the following tasks:
        #   1) Segmentation
        #   2) OCR
        # I'm not really sure how to implement this process, which is why I am
        #   leaving it in this comment as a "stub" which needs to be resolved.

        # Returning the characteristics for each target
        return {}

    def segment(self, target):
        """
        Separate different important aspects of the image out. This is
        to extract the letter within the image
        """
        # @TODO: Implement segmentation here

        return target

    def OCR(self, target):
        """
        Use OCR to identify the character within the image "target"
        """
        # @TODO: Implement OCR here

        return ""

Remove mention of Log parser

Remove mention of Log parser

Response:
from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors

import cv2
import numpy as np

class CharacteristicIdentifier:
    """
    Identify target characteristics
    """

    def __init__(self, **kwargs):
        pass

    def identify_characteristics(self, target):
        """
        Identifies the characteristics of the target "target" and returns
        them as a dictionary object
        """
        # My thoughts so far to accomplish this is to break the problem down
        #   into the following tasks:
        #   1) Segmentation
        #   2) OCR
        # I'm not really sure how to implement this process, which is why I am
        #   leaving it in this comment as a "stub" which needs to be resolved.

        # Returning the characteristics for each target
        return {}

    def segment(self, target):
        """
        Separate different important aspects of the image out. This is
        to extract the letter within the image
        """
        # @TODO: Implement segmentation here

        return target

    def OCR(self, target):
        """
        Use OCR to identify the character within the image "target"
        """
        # @TODO: Implement OCR here

        return ""

Prompt:
Remove mention of Log parser

from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors

import cv2
import numpy as np

class CharacteristicIdentifier:
    """
    Identify target characteristics
    """

    def __init__(self, **kwargs):
        pass

    def identify_characteristics(self, target):
        """
        Identifies the characteristics of the target "target" and returns
        them as a dictionary object
        """
        # My thoughts so far to accomplish this is to break the problem down
        #   into the following tasks:
        #   1) Segmentation
        #   2) OCR
        #   3) Pixhawk log parse to gather data about
        #       3a) GPS
        #       3b) Heading
        # I'm not really sure how to implement this process, which is why I am
        #   leaving it in this comment as a "stub" which needs to be resolved.

        # Returning the characteristics for each target
        return {}

    def segment(self, target):
        """
        Separate different important aspects of the image out. This is
        to extract the letter within the image
        """
        # @TODO: Implement segmentation here

        return target

    def OCR(self, target):
        """
        Use OCR to identify the character within the image "target"
        """
        # @TODO: Implement OCR here

        return ""


from datetime import datetime

from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user

from . import admin
from .forms import ProfileForm, PostForm

from .. import db
from ..models import User

@admin.route('/')
@login_required
def index():
  return render_template('admin/user.html', user=current_user)

@admin.route('/edit_user', methods=['GET', 'POST'])
@login_required
def edit_user():
  form = ProfileForm()

  if form.validate_on_submit():
    current_user.name = form.name.data
    current_user.location = form.location.data
    current_user.bio = form.bio.data

    db.session.add(current_user._get_current_object())
    db.session.commit()

    flash("Síðan hefur verið uppfærð")

    return redirect(url_for('admin.index'))

  form.name.data = current_user.name
  form.location.data = current_user.location
  form.bio.data = current_user.bio

  return render_template('admin/edit_user.html', form=form)

@admin.route('/news')
@login_required
def news():
  return render_template('admin/news.html')

@admin.route('/news/post', methods=['GET', 'POST'])
@login_required
def post():
  form = PostForm()
  form.category.choices = [(0, 'Almenn frétt')]

  if form.validate_on_submit():
    flash("Fréttin hefur verið vistuð!")
    return redirect(url_for('admin.news'))

  return render_template('admin/post.html', form=form)

Response:
from datetime import datetime

from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user

from . import admin
from .forms import ProfileForm, PostForm

from .. import db
from ..models import User

@admin.route('/')
@login_required
def index():
  return render_template('admin/user.html', user=current_user)

@admin.route('/edit_user', methods=['GET', 'POST'])
@login_required
def edit_user():
  form = ProfileForm()

  if form.validate_on_submit():
    current_user.name = form.name.data
    current_user.location = form.location.data
    current_user.bio = form.bio.data

    db.session.add(current_user._get_current_object())
    db.session.commit()

    flash("Síðan hefur verið uppfærð")

    return redirect(url_for('admin.index'))

  form.name.data = current_user.name
  form.location.data = current_user.location
  form.bio.data = current_user.bio

  return render_template('admin/edit_user.html', form=form)

@admin.route('/news')
@login_required
def news():
  return render_template('admin/news.html')

@admin.route('/news/post', methods=['GET', 'POST'])
@login_required
def post():
  form = PostForm()
  form.category.choices = [(0, 'Almenn frétt')]

  if form.validate_on_submit():
    flash("Fréttin hefur verið vistuð!")
    return redirect(url_for('admin.news'))

  return render_template('admin/post.html', form=form)

Prompt:
Add a route to admin/news/post to post a news story. Uses the PostForm for forms

from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user

from . import admin
from .forms import ProfileForm

from .. import db
from ..models import User

@admin.route('/')
@login_required
def index():
  return render_template('admin/user.html', user=current_user)

@admin.route('/edit_user', methods=['GET', 'POST'])
@login_required
def edit_user():
  form = ProfileForm()

  if form.validate_on_submit():
    current_user.name = form.name.data
    current_user.location = form.location.data
    current_user.bio = form.bio.data

    db.session.add(current_user._get_current_object())
    db.session.commit()

    flash("Síðan hefur verið uppfærð")

    return redirect(url_for('admin.index'))

  form.name.data = current_user.name
  form.location.data = current_user.location
  form.bio.data = current_user.bio

  return render_template('admin/edit_user.html', form=form)

@admin.route('/news')
@login_required
def news():
  return render_template('admin/news.html')


from orbit import satellite

from django.core.management.base import BaseCommand

from base.utils import update_all_satellites
from base.models import Satellite

class Command(BaseCommand):
    help = 'Create initial fixtures'

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

        satellites = Satellite.objets.all()

        for obj in satellites:
            try:
                sat = satellite(obj.norad_cat_id)
            except:
                self.stdout.write(('Satellite {} with Identifier {} does '
                                  'not exist').format(obj.name, obj.norad_cat_id))
                continue

            obj.name = sat.name()
            tle = sat.tle()
            obj.tle0 = tle[0]
            obj.tle1 = tle[1]
            obj.tle2 = tle[2]
            obj.save()
            self.stdout.write(('Satellite {} with Identifier {} '
                              'found [updated]').format(obj.norad_cat_id, obj.name))

Add management command to update all existing satellite tle data

Response:
from orbit import satellite

from django.core.management.base import BaseCommand

from base.utils import update_all_satellites
from base.models import Satellite

class Command(BaseCommand):
    help = 'Create initial fixtures'

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

        satellites = Satellite.objets.all()

        for obj in satellites:
            try:
                sat = satellite(obj.norad_cat_id)
            except:
                self.stdout.write(('Satellite {} with Identifier {} does '
                                  'not exist').format(obj.name, obj.norad_cat_id))
                continue

            obj.name = sat.name()
            tle = sat.tle()
            obj.tle0 = tle[0]
            obj.tle1 = tle[1]
            obj.tle2 = tle[2]
            obj.save()
            self.stdout.write(('Satellite {} with Identifier {} '
                              'found [updated]').format(obj.norad_cat_id, obj.name))

Prompt: Add management command to update all existing satellite tle data


#!/usr/bin/env python

"""
This module sets up a video stream from internal or connected webcam using Gstreamer.
You can then take snapshots.

import qrtools
qr = qrtools.QR()
qr.decode("cam.jpg")
print qr.data

"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gtk as gtk
from gi.repository import Gdk
from gi.repository import Gst as gst
from gi.repository import GdkPixbuf

from avocado import Test
from os.path import exists, relpath
import qrtools
import time

#import pyqrcode

class WebcamReadQR(Test):
    def setUp(self):
        # if not exists('/dev/video0'):
            # self.skip("No webcam detected: /dev/video0 cannot be found");
        self.device = '/dev/video0'

        Gdk.threads_init()
        gtk.main()
        self.take_snapshot()

    def test(self):
        self.create_video_pipeline()

    def create_video_pipeline(self):
        gst.init([])
        #v4l2src
        self.video_player = gst.parse_launch("videotestsrc ! jpegenc ! filesink location=cam.jpg")
        self.video_player.set_state(gst.State.PLAYING)

        bus = self.video_player.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.on_message)
        bus.enable_sync_message_emission()
        bus.connect("sync-message::element", self.on_sync_message)

    def on_message(self, bus, message):
        t = message.type
        if t == gst.MessageType.EOS:
            self.exit()
        elif t == gst.MessageType.ERROR:
            self.exit()
            self.fail("Error {0}".format(message.parse_error()))

    def on_sync_message(self, bus, message):
        if message.structure is None:
            return
        message_name = message.structure.get_name()

    def exit(self):
        self.video_player.set_state(gst.State.NULL)
        gtk.main_quit()

    def take_snapshot(self):
        #TODO:fill this in

Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.

Response:
#!/usr/bin/env python

"""
This module sets up a video stream from internal or connected webcam using Gstreamer.
You can then take snapshots.

import qrtools
qr = qrtools.QR()
qr.decode("cam.jpg")
print qr.data

"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gtk as gtk
from gi.repository import Gdk
from gi.repository import Gst as gst
from gi.repository import GdkPixbuf

from avocado import Test
from os.path import exists, relpath
import qrtools
import time

#import pyqrcode

class WebcamReadQR(Test):
    def setUp(self):
        # if not exists('/dev/video0'):
            # self.skip("No webcam detected: /dev/video0 cannot be found");
        self.device = '/dev/video0'

        Gdk.threads_init()
        gtk.main()
        self.take_snapshot()

    def test(self):
        self.create_video_pipeline()

    def create_video_pipeline(self):
        gst.init([])
        #v4l2src
        self.video_player = gst.parse_launch("videotestsrc ! jpegenc ! filesink location=cam.jpg")
        self.video_player.set_state(gst.State.PLAYING)

        bus = self.video_player.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.on_message)
        bus.enable_sync_message_emission()
        bus.connect("sync-message::element", self.on_sync_message)

    def on_message(self, bus, message):
        t = message.type
        if t == gst.MessageType.EOS:
            self.exit()
        elif t == gst.MessageType.ERROR:
            self.exit()
            self.fail("Error {0}".format(message.parse_error()))

    def on_sync_message(self, bus, message):
        if message.structure is None:
            return
        message_name = message.structure.get_name()

    def exit(self):
        self.video_player.set_state(gst.State.NULL)
        gtk.main_quit()

    def take_snapshot(self):
        #TODO:fill this in

Prompt: Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.


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

from setuptools import setup, find_packages

import materializecssform

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(

    name='django-materializecss-form',

    version=materializecssform.__version__,

    packages=find_packages(),

    author="Kal Walkden",

    author_email="kal@walkden.us",

    description="A simple Django form template tag to work with Materializecss",
    long_description=long_description,
    long_description_content_type="text/markdown",

    include_package_data=True,

    url='https://github.com/kalwalkden/django-materializecss-form',
    classifiers=[
        "Programming Language :: Python",
        "Development Status :: 4 - Beta",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3.6",
    ],

    license="MIT",

    zip_safe=False
)

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

from setuptools import setup, find_packages

import materializecssform

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(

    name='django-materializecss-form',

    version=materializecssform.__version__,

    packages=find_packages(),

    author="Kal Walkden",

    author_email="kal@walkden.us",

    description="A simple Django form template tag to work with Materializecss",
    long_description=long_description,
    long_description_content_type="text/markdown",

    include_package_data=True,

    url='https://github.com/kalwalkden/django-materializecss-form',
    classifiers=[
        "Programming Language :: Python",
        "Development Status :: 4 - Beta",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3.6",
    ],

    license="MIT",

    zip_safe=False
)

Prompt:
Update meta version so that documentation looks good in pypi

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

from setuptools import setup, find_packages

import materializecssform

setup(

    name='django-materializecss-form',

    version=materializecssform.__version__,

    packages=find_packages(),

    author="Kal Walkden",

    author_email="kal@walkden.us",

    description="A simple Django form template tag to work with Materializecss",
    long_description=open('README.md').read(),
    long_description_content_type="text/markdown",

    include_package_data=True,

    url='https://github.com/kalwalkden/django-materializecss-form',
    classifiers=[
        "Programming Language :: Python",
        "Development Status :: 4 - Beta",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3.6",
        "Topic :: Documentation :: Sphinx",
    ],

    license="MIT",

    zip_safe=False
)


from simplesqlite.model import Integer, Model, Text

from .._const import Tc

class Filter(Model):
    device = Text(attr_name=Tc.Param.DEVICE, not_null=True)
    filter_id = Text(attr_name=Tc.Param.FILTER_ID)
    flowid = Text(attr_name=Tc.Param.FLOW_ID)
    protocol = Text(attr_name=Tc.Param.PROTOCOL)
    priority = Integer(attr_name=Tc.Param.PRIORITY)
    src_network = Text(attr_name=Tc.Param.SRC_NETWORK)
    dst_network = Text(attr_name=Tc.Param.DST_NETWORK)
    src_port = Integer(attr_name=Tc.Param.SRC_PORT)
    dst_port = Integer(attr_name=Tc.Param.DST_PORT)

    classid = Text(attr_name=Tc.Param.CLASS_ID)
    handle = Integer(attr_name=Tc.Param.HANDLE)

class Qdisc(Model):
    device = Text(attr_name=Tc.Param.DEVICE, not_null=True)
    direct_qlen = Integer()
    parent = Text(attr_name=Tc.Param.PARENT, not_null=True)
    handle = Text(attr_name=Tc.Param.HANDLE, not_null=True)
    delay = Text()
    delay_distro = Text(attr_name="delay-distro")
    loss = Text()
    duplicate = Text()
    corrupt = Text()
    reorder = Text()
    rate = Text()

Add ORM models for filter/qdisc

Add ORM models for filter/qdisc

Response:
from simplesqlite.model import Integer, Model, Text

from .._const import Tc

class Filter(Model):
    device = Text(attr_name=Tc.Param.DEVICE, not_null=True)
    filter_id = Text(attr_name=Tc.Param.FILTER_ID)
    flowid = Text(attr_name=Tc.Param.FLOW_ID)
    protocol = Text(attr_name=Tc.Param.PROTOCOL)
    priority = Integer(attr_name=Tc.Param.PRIORITY)
    src_network = Text(attr_name=Tc.Param.SRC_NETWORK)
    dst_network = Text(attr_name=Tc.Param.DST_NETWORK)
    src_port = Integer(attr_name=Tc.Param.SRC_PORT)
    dst_port = Integer(attr_name=Tc.Param.DST_PORT)

    classid = Text(attr_name=Tc.Param.CLASS_ID)
    handle = Integer(attr_name=Tc.Param.HANDLE)

class Qdisc(Model):
    device = Text(attr_name=Tc.Param.DEVICE, not_null=True)
    direct_qlen = Integer()
    parent = Text(attr_name=Tc.Param.PARENT, not_null=True)
    handle = Text(attr_name=Tc.Param.HANDLE, not_null=True)
    delay = Text()
    delay_distro = Text(attr_name="delay-distro")
    loss = Text()
    duplicate = Text()
    corrupt = Text()
    reorder = Text()
    rate = Text()

Prompt: Add ORM models for filter/qdisc


from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT

def setUpModule():
    call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
                 verbosity=0)

def tearDownModule():
    call_command('flush', verbosity=0, interactive=False)

class CommandsTestCase(TestCase):

    def test_import_ccg_boundaries(self):
        args = []
        opts = {
            'filename': ('frontend/tests/fixtures/commands/'
                         'CCG_BSC_Apr2015.TAB')
        }
        call_command('import_ccg_boundaries', *args, **opts)

        pct = PCT.objects.get(code='03Q')
        self.assertAlmostEqual(pct.boundary.centroid.x, -1.0307530606980588)

Response:
from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT

def setUpModule():
    call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
                 verbosity=0)

def tearDownModule():
    call_command('flush', verbosity=0, interactive=False)

class CommandsTestCase(TestCase):

    def test_import_ccg_boundaries(self):
        args = []
        opts = {
            'filename': ('frontend/tests/fixtures/commands/'
                         'CCG_BSC_Apr2015.TAB')
        }
        call_command('import_ccg_boundaries', *args, **opts)

        pct = PCT.objects.get(code='03Q')
        self.assertAlmostEqual(pct.boundary.centroid.x, -1.0307530606980588)

Prompt:
Use almostEqual for comparing geo coordinates

An upgrade in one of the underlying libraries has shifted the numbers
very slightly.

from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT

def setUpModule():
    call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
                 verbosity=0)

def tearDownModule():
    call_command('flush', verbosity=0, interactive=False)

class CommandsTestCase(TestCase):

    def test_import_ccg_boundaries(self):
        args = []
        opts = {
            'filename': ('frontend/tests/fixtures/commands/'
                         'CCG_BSC_Apr2015.TAB')
        }
        call_command('import_ccg_boundaries', *args, **opts)

        pct = PCT.objects.get(code='03Q')
        self.assertEqual(pct.boundary.centroid.x, -1.0307530606980588)


# coding: utf-8

__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=13, patch=0)

Bump fireant version to 0.13.0

Bump fireant version to 0.13.0

Response:
# coding: utf-8

__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=13, patch=0)

Prompt:
Bump fireant version to 0.13.0

# coding: utf-8

__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=12, patch=0)


import pytest
import warnings

from .. import (PlasmaPyError,
                PhysicsError,
                RelativityError,
                AtomicError)

from .. import (PlasmaPyWarning,
                PhysicsWarning,
                RelativityWarning,
                AtomicWarning)

plasmapy_exceptions = [
    PlasmaPyError,
    PhysicsError,
    RelativityError,
    AtomicError,
]

plasmapy_warnings = [
    PlasmaPyWarning,
    PhysicsWarning,
    RelativityWarning,
    AtomicWarning,
]

@pytest.mark.parametrize("exception", plasmapy_exceptions)
def test_exceptions(exception):
    r"""Test that custom PlasmaPy exceptions can be raised with an
    error message."""
    with pytest.raises(exception):
        raise exception("What an exceptionally exceptional exception!")

@pytest.mark.parametrize("warning", plasmapy_warnings)
def test_warnings(warning):
    r"""Test that custom PlasmaPy warnings can be issued with a
    warning message."""
    with pytest.warns(warning):
        warnings.warn("Coverage decreased (-0.00002%)", warning)

@pytest.mark.parametrize("exception", plasmapy_exceptions)
def test_PlasmaPyError_subclassing(exception):
    r"""Test that each custom PlasmaPy exception can be caught
    as a PlasmaPyError."""
    with pytest.raises(PlasmaPyError):
        raise exception("I'm sorry, Dave.  I'm afraid I can't do that.")

@pytest.mark.parametrize("warning", plasmapy_warnings)
def test_PlasmaPyWarning_subclassing(warning):
    r"""Test that custom PlasmaPy warnings can all be caught
    as a PlasmaPyWarning."""
    with pytest.warns(PlasmaPyWarning):
        warnings.warn("Electrons are WEIRD.", warning)

Create tests for custom exceptions and warnings

Response:
import pytest
import warnings

from .. import (PlasmaPyError,
                PhysicsError,
                RelativityError,
                AtomicError)

from .. import (PlasmaPyWarning,
                PhysicsWarning,
                RelativityWarning,
                AtomicWarning)

plasmapy_exceptions = [
    PlasmaPyError,
    PhysicsError,
    RelativityError,
    AtomicError,
]

plasmapy_warnings = [
    PlasmaPyWarning,
    PhysicsWarning,
    RelativityWarning,
    AtomicWarning,
]

@pytest.mark.parametrize("exception", plasmapy_exceptions)
def test_exceptions(exception):
    r"""Test that custom PlasmaPy exceptions can be raised with an
    error message."""
    with pytest.raises(exception):
        raise exception("What an exceptionally exceptional exception!")

@pytest.mark.parametrize("warning", plasmapy_warnings)
def test_warnings(warning):
    r"""Test that custom PlasmaPy warnings can be issued with a
    warning message."""
    with pytest.warns(warning):
        warnings.warn("Coverage decreased (-0.00002%)", warning)

@pytest.mark.parametrize("exception", plasmapy_exceptions)
def test_PlasmaPyError_subclassing(exception):
    r"""Test that each custom PlasmaPy exception can be caught
    as a PlasmaPyError."""
    with pytest.raises(PlasmaPyError):
        raise exception("I'm sorry, Dave.  I'm afraid I can't do that.")

@pytest.mark.parametrize("warning", plasmapy_warnings)
def test_PlasmaPyWarning_subclassing(warning):
    r"""Test that custom PlasmaPy warnings can all be caught
    as a PlasmaPyWarning."""
    with pytest.warns(PlasmaPyWarning):
        warnings.warn("Electrons are WEIRD.", warning)

Prompt: Create tests for custom exceptions and warnings


#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar as Grammar
from grammpy import Nonterminal
from grammpy.exceptions import NotNonterminalException

class TempClass(Nonterminal):
    pass

class NonterminalsInvalidTest(TestCase):
    def test_invalidAddNumber(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm(0)

    def test_invalidAddString(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm("string")

    def test_invalidAddAfterCorrectAdd(self):
        gr = Grammar()
        gr.add_nonterm(TempClass)
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm("asdf")

    def test_invalidAddInArray(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm([TempClass, "asdf"])

    def test_invalidHaveNumber(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm(0)

    def test_invalidHaveString(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm("string")

    def test_invalidHaveAfterCorrectAdd(self):
        gr = Grammar()
        gr.add_nonterm(TempClass)
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm("asdf")

    def test_invalidHaveInArray(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm([TempClass, "asdf"])

if __name__ == '__main__':
    main()

Response:
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar as Grammar
from grammpy import Nonterminal
from grammpy.exceptions import NotNonterminalException

class TempClass(Nonterminal):
    pass

class NonterminalsInvalidTest(TestCase):
    def test_invalidAddNumber(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm(0)

    def test_invalidAddString(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm("string")

    def test_invalidAddAfterCorrectAdd(self):
        gr = Grammar()
        gr.add_nonterm(TempClass)
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm("asdf")

    def test_invalidAddInArray(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.add_nonterm([TempClass, "asdf"])

    def test_invalidHaveNumber(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm(0)

    def test_invalidHaveString(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm("string")

    def test_invalidHaveAfterCorrectAdd(self):
        gr = Grammar()
        gr.add_nonterm(TempClass)
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm("asdf")

    def test_invalidHaveInArray(self):
        gr = Grammar()
        with self.assertRaises(NotNonterminalException):
            gr.have_nonterm([TempClass, "asdf"])

if __name__ == '__main__':
    main()

Prompt:
Add tests that have and get of nonterms raise exceptions

#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar

class NonterminalsInvalidTest(TestCase):
    pass

if __name__ == '__main__':
    main()


"""
    pyexcel.internal
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Pyexcel internals that subjected to change

    :copyright: (c) 2015-2017 by Onni Software Ltd.
    :license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER  # noqa
from pyexcel.internal.source_plugin import SOURCE  # noqa
from pyexcel.internal.generators import SheetStream, BookStream  # noqa

BLACK_LIST = [
    "pyexcel_io",
    "pyexcel_webio",
    "pyexcel_xlsx",
    "pyexcel_xls",
    "pyexcel_ods3",
    "pyexcel_ods",
    "pyexcel_odsr",
    "pyexcel_xlsxw",
]
WHITE_LIST = [
    "pyexcel.plugins.parsers",
    "pyexcel.plugins.renderers",
    "pyexcel.plugins.sources",
]

scan_plugins_regex("^pyexcel_.+$", "pyexcel", BLACK_LIST, WHITE_LIST)

Response:
"""
    pyexcel.internal
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Pyexcel internals that subjected to change

    :copyright: (c) 2015-2017 by Onni Software Ltd.
    :license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER  # noqa
from pyexcel.internal.source_plugin import SOURCE  # noqa
from pyexcel.internal.generators import SheetStream, BookStream  # noqa

BLACK_LIST = [
    "pyexcel_io",
    "pyexcel_webio",
    "pyexcel_xlsx",
    "pyexcel_xls",
    "pyexcel_ods3",
    "pyexcel_ods",
    "pyexcel_odsr",
    "pyexcel_xlsxw",
]
WHITE_LIST = [
    "pyexcel.plugins.parsers",
    "pyexcel.plugins.renderers",
    "pyexcel.plugins.sources",
]

scan_plugins_regex("^pyexcel_.+$", "pyexcel", BLACK_LIST, WHITE_LIST)

Prompt:
Remove use of deprecated `scan_plugins` method

`scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This
is causing warnings to be logged.

The new method takes a regular expression as its first argument, rather than a
simple prefix string. This commit adds a regular expression which does the same
thing as the prefix argument used to do.

For source code see: https://lml.readthedocs.io/en/latest/_modules/lml/loader.html
"""
    pyexcel.internal
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Pyexcel internals that subjected to change

    :copyright: (c) 2015-2017 by Onni Software Ltd.
    :license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER  # noqa
from pyexcel.internal.source_plugin import SOURCE  # noqa
from pyexcel.internal.generators import SheetStream, BookStream  # noqa

BLACK_LIST = [
    "pyexcel_io",
    "pyexcel_webio",
    "pyexcel_xlsx",
    "pyexcel_xls",
    "pyexcel_ods3",
    "pyexcel_ods",
    "pyexcel_odsr",
    "pyexcel_xlsxw",
]
WHITE_LIST = [
    "pyexcel.plugins.parsers",
    "pyexcel.plugins.renderers",
    "pyexcel.plugins.sources",
]

scan_plugins("pyexcel_", "pyexcel", BLACK_LIST, WHITE_LIST)


from wolis.test_case import WolisTestCase
from wolis import utils

class SearchBackendMysqlTest(WolisTestCase):
    @utils.restrict_database('mysql*')
    @utils.restrict_phpbb_version('>=3.1.0')
    def test_set_search_backend(self):
        self.login('morpheus', 'morpheus')
        self.acp_login('morpheus', 'morpheus')

        self.change_acp_knob(
            link_text='Search settings',
            check_page_text='Here you can define what search backend will be used',
            name='config[search_type]',
            value='phpbb_search_fulltext_mysql',
            confirm=True,
        )

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

Test for selecting mysql search backend

Test for selecting mysql search backend

Response:
from wolis.test_case import WolisTestCase
from wolis import utils

class SearchBackendMysqlTest(WolisTestCase):
    @utils.restrict_database('mysql*')
    @utils.restrict_phpbb_version('>=3.1.0')
    def test_set_search_backend(self):
        self.login('morpheus', 'morpheus')
        self.acp_login('morpheus', 'morpheus')

        self.change_acp_knob(
            link_text='Search settings',
            check_page_text='Here you can define what search backend will be used',
            name='config[search_type]',
            value='phpbb_search_fulltext_mysql',
            confirm=True,
        )

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

Prompt: Test for selecting mysql search backend


import NDIR
import time

sensor = NDIR.Sensor(0x4D)

if sensor.begin() == False:
    print("Adaptor initialization FAILED!")
    exit()

while True:
    if sensor.measure():
        print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
    else:
        print("Sensor communication ERROR.")

    time.sleep(1)

Response:
import NDIR
import time

sensor = NDIR.Sensor(0x4D)

if sensor.begin() == False:
    print("Adaptor initialization FAILED!")
    exit()

while True:
    if sensor.measure():
        print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
    else:
        print("Sensor communication ERROR.")

    time.sleep(1)

Prompt:
Make use of the return value of begin() and measure()
import NDIR
import time

sensor = NDIR.Sensor(0x4D)
sensor.begin()

while True:
    sensor.measure()
    print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
    time.sleep(1)


import importlib
from cx_Freeze import setup, Executable

backend_path = importlib.import_module("bcrypt").__path__[0]

backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")

# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
    "include_files": [
        ("client/dist", "client"),
        "LICENSE",
        "templates",
        "readme.md",
        (backend_path, "lib/.libs_cffi_backend")
    ],
    "includes": [
        "cffi",
        "numpy",
        "numpy.core._methods",
        "numpy.lib",
        "numpy.lib.format",
        "raven.processors"
    ],
    "packages": [
        "_cffi_backend",
        "appdirs",
        "asyncio",
        "bcrypt",
        "cffi",
        "gzip",
        "idna",
        "motor",
        "packaging",
        "ssl",
        "uvloop"
    ]
}

options = {
    "build_exe": build_exe_options
}

executables = [
    Executable('run.py', base="Console")
]

classifiers=[
    "Programming Language :: Python :: 3.7"
]

importlib.import_module("virtool")

setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")

Add gzip to cx-freeze packages

Add gzip to cx-freeze packages

Response:
import importlib
from cx_Freeze import setup, Executable

backend_path = importlib.import_module("bcrypt").__path__[0]

backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")

# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
    "include_files": [
        ("client/dist", "client"),
        "LICENSE",
        "templates",
        "readme.md",
        (backend_path, "lib/.libs_cffi_backend")
    ],
    "includes": [
        "cffi",
        "numpy",
        "numpy.core._methods",
        "numpy.lib",
        "numpy.lib.format",
        "raven.processors"
    ],
    "packages": [
        "_cffi_backend",
        "appdirs",
        "asyncio",
        "bcrypt",
        "cffi",
        "gzip",
        "idna",
        "motor",
        "packaging",
        "ssl",
        "uvloop"
    ]
}

options = {
    "build_exe": build_exe_options
}

executables = [
    Executable('run.py', base="Console")
]

classifiers=[
    "Programming Language :: Python :: 3.7"
]

importlib.import_module("virtool")

setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")

Prompt:
Add gzip to cx-freeze packages

import importlib
from cx_Freeze import setup, Executable

backend_path = importlib.import_module("bcrypt").__path__[0]

backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")

# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
    "include_files": [
        ("client/dist", "client"),
        "LICENSE",
        "templates",
        "readme.md",
        (backend_path, "lib/.libs_cffi_backend")
    ],
    "includes": [
        "cffi",
        "numpy",
        "numpy.core._methods",
        "numpy.lib",
        "numpy.lib.format",
        "raven.processors"
    ],
    "packages": [
        "_cffi_backend",
        "appdirs",
        "asyncio",
        "bcrypt",
        "cffi",
        "idna",
        "motor",
        "packaging",
        "ssl",
        "uvloop"
    ]
}

options = {
    "build_exe": build_exe_options
}

executables = [
    Executable('run.py', base="Console")
]

classifiers=[
    "Programming Language :: Python :: 3.7"
]

importlib.import_module("virtool")

setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")