'''Test Span.as_doc() doesn't segfault'''
from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy

def test_issue1537():
    string = 'The sky is blue . The man is pink . The dog is purple .'
    doc = Doc(Vocab(), words=string.split())
    doc[0].sent_start = True
    for word in doc[1:]:
        if word.nbor(-1).text == '.':
            word.sent_start = True
        else:
            word.sent_start = False

    sents = list(doc.sents)
    sent0 = sents[0].as_doc()
    sent1 = sents[1].as_doc()
    assert isinstance(sent0, Doc)
    assert isinstance(sent1, Doc)

# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
#    nlp = load_spacy('en')
#    doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
#    sents = [s.as_doc() for s in doc.sents]
#    print(list(sents[0].noun_chunks))
#    print(list(sents[1].noun_chunks))

Fix unicode error in new test

Fix unicode error in new test

Response:
<INSERT> __future__ import unicode_literals
from <INSERT_END> <|endoftext|> '''Test Span.as_doc() doesn't segfault'''
from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy

def test_issue1537():
    string = 'The sky is blue . The man is pink . The dog is purple .'
    doc = Doc(Vocab(), words=string.split())
    doc[0].sent_start = True
    for word in doc[1:]:
        if word.nbor(-1).text == '.':
            word.sent_start = True
        else:
            word.sent_start = False

    sents = list(doc.sents)
    sent0 = sents[0].as_doc()
    sent1 = sents[1].as_doc()
    assert isinstance(sent0, Doc)
    assert isinstance(sent1, Doc)

# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
#    nlp = load_spacy('en')
#    doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
#    sents = [s.as_doc() for s in doc.sents]
#    print(list(sents[0].noun_chunks))
#    print(list(sents[1].noun_chunks))

Prompt:
Fix unicode error in new test

'''Test Span.as_doc() doesn't segfault'''
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy

def test_issue1537():
    string = 'The sky is blue . The man is pink . The dog is purple .'
    doc = Doc(Vocab(), words=string.split())
    doc[0].sent_start = True
    for word in doc[1:]:
        if word.nbor(-1).text == '.':
            word.sent_start = True
        else:
            word.sent_start = False

    sents = list(doc.sents)
    sent0 = sents[0].as_doc()
    sent1 = sents[1].as_doc()
    assert isinstance(sent0, Doc)
    assert isinstance(sent1, Doc)

# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
#    nlp = load_spacy('en')
#    doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
#    sents = [s.as_doc() for s in doc.sents]
#    print(list(sents[0].noun_chunks))
#    print(list(sents[1].noun_chunks))


from .tabulate import _text_type

def pad(field, total, char=u" "):
    return field + (char * (total - len(field)))

def get_separator(num, header_len, data_len):

    sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
    return sep

def expanded_table(rows, headers):
    header_len = max([len(x) for x in headers])
    max_row_len = 0
    results = []

    padded_headers = [pad(x, header_len) + u" |" for x in headers]
    header_len += 2

    for row in rows:
        row_len = max([len(_text_type(x)) for x in row])
        row_result = []
        if row_len > max_row_len:
            max_row_len = row_len

        for header, value in zip(padded_headers, row):
            if value is None: value = '<null>'
            row_result.append(u"%s %s" % (header, value))

        results.append('\n'.join(row_result))

    output = []
    for i, result in enumerate(results):
        output.append(get_separator(i, header_len, max_row_len))
        output.append(result)
        output.append('\n')

    return ''.join(output)

Response:
<INSERT> if value is None: value = '<null>'
            <INSERT_END> <|endoftext|> from .tabulate import _text_type

def pad(field, total, char=u" "):
    return field + (char * (total - len(field)))

def get_separator(num, header_len, data_len):

    sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
    return sep

def expanded_table(rows, headers):
    header_len = max([len(x) for x in headers])
    max_row_len = 0
    results = []

    padded_headers = [pad(x, header_len) + u" |" for x in headers]
    header_len += 2

    for row in rows:
        row_len = max([len(_text_type(x)) for x in row])
        row_result = []
        if row_len > max_row_len:
            max_row_len = row_len

        for header, value in zip(padded_headers, row):
            if value is None: value = '<null>'
            row_result.append(u"%s %s" % (header, value))

        results.append('\n'.join(row_result))

    output = []
    for i, result in enumerate(results):
        output.append(get_separator(i, header_len, max_row_len))
        output.append(result)
        output.append('\n')

    return ''.join(output)

Prompt:
Make the null value consistent between vertical and tabular output.

from .tabulate import _text_type

def pad(field, total, char=u" "):
    return field + (char * (total - len(field)))

def get_separator(num, header_len, data_len):

    sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
    return sep

def expanded_table(rows, headers):
    header_len = max([len(x) for x in headers])
    max_row_len = 0
    results = []

    padded_headers = [pad(x, header_len) + u" |" for x in headers]
    header_len += 2

    for row in rows:
        row_len = max([len(_text_type(x)) for x in row])
        row_result = []
        if row_len > max_row_len:
            max_row_len = row_len

        for header, value in zip(padded_headers, row):
            row_result.append(u"%s %s" % (header, value))

        results.append('\n'.join(row_result))

    output = []
    for i, result in enumerate(results):
        output.append(get_separator(i, header_len, max_row_len))
        output.append(result)
        output.append('\n')

    return ''.join(output)


from django import template
from django.conf import settings

from .utils import get_menu_from_apps
from .. import defaults
from ..menu import generate_menu

register = template.Library()

@register.simple_tag(takes_context=True)
def get_menu(context, menu_name):
    """
    Returns a consumable menu list for a given menu_name found in settings.py.
    Else it returns an empty list.

    Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the
    menus.py's 'MENUS' dict.
    :param context: Template context
    :param menu_name: String, name of the menu to be found
    :return: Generated menu
    """
    menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND)
    menu_from_apps = get_menu_from_apps(menu_name)
    # If there isn't a menu on settings but there is menu from apps we built menu from apps
    if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list = menu_from_apps
    # It there is a menu on settings and also on apps we merge both menus
    elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list += menu_from_apps
    return generate_menu(context['request'], menu_list)

Response:
<REPLACE_OLD> template.Library()

@register.assignment_tag(takes_context=True)
def <REPLACE_NEW> template.Library()

@register.simple_tag(takes_context=True)
def <REPLACE_END> <|endoftext|> from django import template
from django.conf import settings

from .utils import get_menu_from_apps
from .. import defaults
from ..menu import generate_menu

register = template.Library()

@register.simple_tag(takes_context=True)
def get_menu(context, menu_name):
    """
    Returns a consumable menu list for a given menu_name found in settings.py.
    Else it returns an empty list.

    Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the
    menus.py's 'MENUS' dict.
    :param context: Template context
    :param menu_name: String, name of the menu to be found
    :return: Generated menu
    """
    menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND)
    menu_from_apps = get_menu_from_apps(menu_name)
    # If there isn't a menu on settings but there is menu from apps we built menu from apps
    if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list = menu_from_apps
    # It there is a menu on settings and also on apps we merge both menus
    elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list += menu_from_apps
    return generate_menu(context['request'], menu_list)

Prompt:
Use simple_tag instead of assignment_tag

The assignment_tag is depraceted and in django-2.0 removed.

Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com>

from django import template
from django.conf import settings

from .utils import get_menu_from_apps
from .. import defaults
from ..menu import generate_menu

register = template.Library()

@register.assignment_tag(takes_context=True)
def get_menu(context, menu_name):
    """
    Returns a consumable menu list for a given menu_name found in settings.py.
    Else it returns an empty list.

    Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the
    menus.py's 'MENUS' dict.
    :param context: Template context
    :param menu_name: String, name of the menu to be found
    :return: Generated menu
    """
    menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND)
    menu_from_apps = get_menu_from_apps(menu_name)
    # If there isn't a menu on settings but there is menu from apps we built menu from apps
    if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list = menu_from_apps
    # It there is a menu on settings and also on apps we merge both menus
    elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list += menu_from_apps
    return generate_menu(context['request'], menu_list)


from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter

class GeoCodePipeline(object):

    def open_spider(self, spider):
        geolocator = Photon(timeout=5)
        self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)

    def process_item(self, item, spider):

        for crime in item["crimes"]:
            place = crime["place"]
            latitude, longitude = self.__geocode_address(place)
            crime["latitude"] = latitude
            crime["longitude"] = longitude
        return item

    def __geocode_address(self, place):
        if place is None:
            return None, None

        location = self.__geocodeFunc(place)
        if location is not None:
            return location.latitude, location.longitude
        else:
            return None, None

Response:
<REPLACE_OLD> Nominatim
from <REPLACE_NEW> Nominatim, Photon
from <REPLACE_END> <REPLACE_OLD> Nominatim(timeout=5)
 <REPLACE_NEW> Photon(timeout=5)
 <REPLACE_END> <|endoftext|> from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter

class GeoCodePipeline(object):

    def open_spider(self, spider):
        geolocator = Photon(timeout=5)
        self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)

    def process_item(self, item, spider):

        for crime in item["crimes"]:
            place = crime["place"]
            latitude, longitude = self.__geocode_address(place)
            crime["latitude"] = latitude
            crime["longitude"] = longitude
        return item

    def __geocode_address(self, place):
        if place is None:
            return None, None

        location = self.__geocodeFunc(place)
        if location is not None:
            return location.latitude, location.longitude
        else:
            return None, None

Prompt:
Use Phonon instead of Nominatim for geo coding

Phonon is more fault tolerant to spelling mistakes.

from geopy import Nominatim
from geopy.extra.rate_limiter import RateLimiter

class GeoCodePipeline(object):

    def open_spider(self, spider):
        geolocator = Nominatim(timeout=5)
        self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)

    def process_item(self, item, spider):

        for crime in item["crimes"]:
            place = crime["place"]
            latitude, longitude = self.__geocode_address(place)
            crime["latitude"] = latitude
            crime["longitude"] = longitude
        return item

    def __geocode_address(self, place):
        if place is None:
            return None, None

        location = self.__geocodeFunc(place)
        if location is not None:
            return location.latitude, location.longitude
        else:
            return None, None


import boto3

from bluecanary.exceptions import NamespaceError
from bluecanary.utilities import throttle

@throttle()
def set_cloudwatch_alarm(identifier, **kwargs):
    if not kwargs.get('Dimensions'):
        kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs)

    if not kwargs.get('AlarmName'):
        kwargs['AlarmName'] = '{}_{}'.format(identifier,
                                             kwargs.get('MetricName'))

    if kwargs.get('AlarmNameModifier'):
        kwargs['AlarmName'] = '{}_{}'.format(kwargs.get('AlarmName'),
                                             kwargs.get('AlarmNameModifier'))
        del(kwargs['AlarmNameModifier'])

    cloudwatch_client = boto3.client('cloudwatch')

    return cloudwatch_client.put_metric_alarm(**kwargs)

def _get_dimensions(identifier, **kwargs):

    base_dimensions = {
        'AWS/ELB': [{u'Name': 'LoadBalancerName', u'Value': identifier}],
        'AWS/EC2': [{u'Name': 'InstanceId', u'Value': identifier}],
    }

    try:
        return base_dimensions[kwargs.get('Namespace')]
    except KeyError:
        message = ('Namespace "{}" is not supported by Blue Canary. '
                   'If you are using a plugin that supports this Namespace '
                   'please ensure that the plugin alarm class does not return '
                   'None when calling the "get_dimensions" method.'
                   .format(kwargs.get('Namespace')))
        raise NamespaceError(message)

Response:
<REPLACE_OLD> '{}_{}'.format(identifier, <REPLACE_NEW> '{}_{}'.format(identifier,
                                             <REPLACE_END> <INSERT>    if kwargs.get('AlarmNameModifier'):
        kwargs['AlarmName'] = '{}_{}'.format(kwargs.get('AlarmName'),
                                             kwargs.get('AlarmNameModifier'))
        del(kwargs['AlarmNameModifier'])

 <INSERT_END> <|endoftext|> import boto3

from bluecanary.exceptions import NamespaceError
from bluecanary.utilities import throttle

@throttle()
def set_cloudwatch_alarm(identifier, **kwargs):
    if not kwargs.get('Dimensions'):
        kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs)

    if not kwargs.get('AlarmName'):
        kwargs['AlarmName'] = '{}_{}'.format(identifier,
                                             kwargs.get('MetricName'))

    if kwargs.get('AlarmNameModifier'):
        kwargs['AlarmName'] = '{}_{}'.format(kwargs.get('AlarmName'),
                                             kwargs.get('AlarmNameModifier'))
        del(kwargs['AlarmNameModifier'])

    cloudwatch_client = boto3.client('cloudwatch')

    return cloudwatch_client.put_metric_alarm(**kwargs)

def _get_dimensions(identifier, **kwargs):

    base_dimensions = {
        'AWS/ELB': [{u'Name': 'LoadBalancerName', u'Value': identifier}],
        'AWS/EC2': [{u'Name': 'InstanceId', u'Value': identifier}],
    }

    try:
        return base_dimensions[kwargs.get('Namespace')]
    except KeyError:
        message = ('Namespace "{}" is not supported by Blue Canary. '
                   'If you are using a plugin that supports this Namespace '
                   'please ensure that the plugin alarm class does not return '
                   'None when calling the "get_dimensions" method.'
                   .format(kwargs.get('Namespace')))
        raise NamespaceError(message)

Prompt:
Allow multiple alarms for same metric type

import boto3

from bluecanary.exceptions import NamespaceError
from bluecanary.utilities import throttle

@throttle()
def set_cloudwatch_alarm(identifier, **kwargs):
    if not kwargs.get('Dimensions'):
        kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs)

    if not kwargs.get('AlarmName'):
        kwargs['AlarmName'] = '{}_{}'.format(identifier, kwargs.get('MetricName'))

    cloudwatch_client = boto3.client('cloudwatch')

    return cloudwatch_client.put_metric_alarm(**kwargs)

def _get_dimensions(identifier, **kwargs):

    base_dimensions = {
        'AWS/ELB': [{u'Name': 'LoadBalancerName', u'Value': identifier}],
        'AWS/EC2': [{u'Name': 'InstanceId', u'Value': identifier}],
    }

    try:
        return base_dimensions[kwargs.get('Namespace')]
    except KeyError:
        message = ('Namespace "{}" is not supported by Blue Canary. '
                   'If you are using a plugin that supports this Namespace '
                   'please ensure that the plugin alarm class does not return '
                   'None when calling the "get_dimensions" method.'
                   .format(kwargs.get('Namespace')))
        raise NamespaceError(message)


"""
For examples of dadi's usage, see the examples directory in the source
distribution.

Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()

import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
import Numerics
import PhiManip
# Protect import of Plotting in case matplotlib not installed.
try:
    import Plotting
except ImportError:
    pass

# We do it this way so it's easier to reload.
import Spectrum_mod
Spectrum = Spectrum_mod.Spectrum

try:
    # This is to try and ensure we have a nice __SVNVERSION__ attribute, so
    # when we get bug reports, we know what version they were using. The
    # svnversion file is created by setup.py.
    import os
    _directory = os.path.dirname(Integration.__file__)
    _svn_file = os.path.join(_directory, 'svnversion')
    __SVNVERSION__ = file(_svn_file).read().strip()
except:
    __SVNVERSION__ = 'Unknown'

# When doing arithmetic with Spectrum objects (which are masked arrays), we
# often have masked values which generate annoying arithmetic warnings. Here
# we tell numpy to ignore such warnings. This puts greater onus on the user to
# check results, but for our use case I think it's the better default.
import numpy
numpy.seterr(all='ignore')

Response:
<REPLACE_OLD> 'Unknown'
 <REPLACE_NEW> 'Unknown'

# When doing arithmetic with Spectrum objects (which are masked arrays), we
# often have masked values which generate annoying arithmetic warnings. Here
# we tell numpy to ignore such warnings. This puts greater onus on the user to
# check results, but for our use case I think it's the better default.
import numpy
numpy.seterr(all='ignore')
 <REPLACE_END> <|endoftext|> """
For examples of dadi's usage, see the examples directory in the source
distribution.

Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()

import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
import Numerics
import PhiManip
# Protect import of Plotting in case matplotlib not installed.
try:
    import Plotting
except ImportError:
    pass

# We do it this way so it's easier to reload.
import Spectrum_mod
Spectrum = Spectrum_mod.Spectrum

try:
    # This is to try and ensure we have a nice __SVNVERSION__ attribute, so
    # when we get bug reports, we know what version they were using. The
    # svnversion file is created by setup.py.
    import os
    _directory = os.path.dirname(Integration.__file__)
    _svn_file = os.path.join(_directory, 'svnversion')
    __SVNVERSION__ = file(_svn_file).read().strip()
except:
    __SVNVERSION__ = 'Unknown'

# When doing arithmetic with Spectrum objects (which are masked arrays), we
# often have masked values which generate annoying arithmetic warnings. Here
# we tell numpy to ignore such warnings. This puts greater onus on the user to
# check results, but for our use case I think it's the better default.
import numpy
numpy.seterr(all='ignore')

Prompt:
Hide spurious numpy warnings about divide by zeros and nans.

git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@429 979d6bd5-6d4d-0410-bece-f567c23bd345

"""
For examples of dadi's usage, see the examples directory in the source
distribution.

Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()

import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
import Numerics
import PhiManip
# Protect import of Plotting in case matplotlib not installed.
try:
    import Plotting
except ImportError:
    pass

# We do it this way so it's easier to reload.
import Spectrum_mod
Spectrum = Spectrum_mod.Spectrum

try:
    # This is to try and ensure we have a nice __SVNVERSION__ attribute, so
    # when we get bug reports, we know what version they were using. The
    # svnversion file is created by setup.py.
    import os
    _directory = os.path.dirname(Integration.__file__)
    _svn_file = os.path.join(_directory, 'svnversion')
    __SVNVERSION__ = file(_svn_file).read().strip()
except:
    __SVNVERSION__ = 'Unknown'


import discord
import duckbot_settings
import random
from discord.ext import commands

_DESCRIPTION = '''quack'''

bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()

@bot.event
async def on_ready():
	print('logged in: %s (%s)' % (bot.user.name, bot.user.id))

	oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
	print('invite me: %s' % oauth_url)

	print('Channels:')

	channels = bot.get_all_channels()
	for channel in channels:
		print('%s (%s)' % (channel.name, channel.id))
		if channel.name == 'botspam':
			await bot.send_message(channel, 'quack!! (ready to roll)')

@bot.command()
async def roll():
	lower_bound = 1
	upper_boundb = 6
	await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))

bot.run(duckbot_settings.TOKEN)

Add a real roll command

Add a real roll command

Response:
<REPLACE_OLD> description=_DESCRIPTION)

@bot.event
async <REPLACE_NEW> description=_DESCRIPTION)
rand = random.SystemRandom()

@bot.event
async <REPLACE_END> <REPLACE_OLD> roll():
	await bot.say('pretending to roll')

bot.run(duckbot_settings.TOKEN)
 <REPLACE_NEW> roll():
	lower_bound = 1
	upper_boundb = 6
	await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))

bot.run(duckbot_settings.TOKEN)
 <REPLACE_END> <|endoftext|> import discord
import duckbot_settings
import random
from discord.ext import commands

_DESCRIPTION = '''quack'''

bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()

@bot.event
async def on_ready():
	print('logged in: %s (%s)' % (bot.user.name, bot.user.id))

	oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
	print('invite me: %s' % oauth_url)

	print('Channels:')

	channels = bot.get_all_channels()
	for channel in channels:
		print('%s (%s)' % (channel.name, channel.id))
		if channel.name == 'botspam':
			await bot.send_message(channel, 'quack!! (ready to roll)')

@bot.command()
async def roll():
	lower_bound = 1
	upper_boundb = 6
	await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))

bot.run(duckbot_settings.TOKEN)

Prompt:
Add a real roll command

import discord
import duckbot_settings
import random
from discord.ext import commands

_DESCRIPTION = '''quack'''

bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)

@bot.event
async def on_ready():
	print('logged in: %s (%s)' % (bot.user.name, bot.user.id))

	oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
	print('invite me: %s' % oauth_url)

	print('Channels:')

	channels = bot.get_all_channels()
	for channel in channels:
		print('%s (%s)' % (channel.name, channel.id))
		if channel.name == 'botspam':
			await bot.send_message(channel, 'quack!! (ready to roll)')

@bot.command()
async def roll():
	await bot.say('pretending to roll')

bot.run(duckbot_settings.TOKEN)


from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil

from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile

class Command(BaseCommand):
    help = 'Construct web export of an annotated volume'

    def add_arguments(self, parser):
        parser.add_argument('pid', nargs='+', type=str)
        parser.add_argument('--static', action='store_true', default=False,
            help='Generate built (static) site instead of jekyll site')
        parser.add_argument('--tei',
            help='Use the specified TEI file instead of generating it')

    def handle(self, *args, **options):
        print args
        repo = Repository()
        for pid in options['pid']:
            vol = repo.get_object(pid, type=Volume)
            if options['tei']:
                tei = load_xmlobject_from_file(options['tei'], Facsimile)
            else:
                tei = annotate.annotated_tei(vol.generate_volume_tei(),
                    vol.annotations())
            zipfile = export.website(vol, tei, static=options['static'])
            zipfilename = '%s-annotated-site.zip' % vol.noid
            shutil.copyfile(zipfile.name, zipfilename)

            print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)

Response:
<INSERT> eulxml.xmlmap import load_xmlobject_from_file
from <INSERT_END> <REPLACE_OLD> Volume

class <REPLACE_NEW> Volume
from readux.books.tei import Facsimile

class <REPLACE_END> <REPLACE_OLD> site')

 <REPLACE_NEW> site')
        parser.add_argument('--tei',
            help='Use the specified TEI file instead of generating it')

 <REPLACE_END> <INSERT> if options['tei']:
                <INSERT_END> <INSERT> load_xmlobject_from_file(options['tei'], Facsimile)
            else:
                tei = <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> pid
 <REPLACE_NEW> vol.noid
 <REPLACE_END> <|endoftext|> from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil

from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile

class Command(BaseCommand):
    help = 'Construct web export of an annotated volume'

    def add_arguments(self, parser):
        parser.add_argument('pid', nargs='+', type=str)
        parser.add_argument('--static', action='store_true', default=False,
            help='Generate built (static) site instead of jekyll site')
        parser.add_argument('--tei',
            help='Use the specified TEI file instead of generating it')

    def handle(self, *args, **options):
        print args
        repo = Repository()
        for pid in options['pid']:
            vol = repo.get_object(pid, type=Volume)
            if options['tei']:
                tei = load_xmlobject_from_file(options['tei'], Facsimile)
            else:
                tei = annotate.annotated_tei(vol.generate_volume_tei(),
                    vol.annotations())
            zipfile = export.website(vol, tei, static=options['static'])
            zipfilename = '%s-annotated-site.zip' % vol.noid
            shutil.copyfile(zipfile.name, zipfilename)

            print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)

Prompt:
Add an option to pass in generated TEI, for speed & troubleshooting

from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil

from readux.books import annotate, export
from readux.books.models import Volume

class Command(BaseCommand):
    help = 'Construct web export of an annotated volume'

    def add_arguments(self, parser):
        parser.add_argument('pid', nargs='+', type=str)
        parser.add_argument('--static', action='store_true', default=False,
            help='Generate built (static) site instead of jekyll site')

    def handle(self, *args, **options):
        print args
        repo = Repository()
        for pid in options['pid']:
            vol = repo.get_object(pid, type=Volume)
            tei = annotate.annotated_tei(vol.generate_volume_tei(),
                vol.annotations())
            zipfile = export.website(vol, tei, static=options['static'])
            zipfilename = '%s-annotated-site.zip' % pid
            shutil.copyfile(zipfile.name, zipfilename)

            print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)


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

from fedora import _

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

Correct minor typo in a string.

Correct minor typo in a string.

Response:
<REPLACE_OLD> services')
LONG_DESCRIPTION <REPLACE_NEW> Services')
LONG_DESCRIPTION <REPLACE_END> <|endoftext|> '''
Information about this python-fedora release
'''

from fedora import _

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

Prompt:
Correct minor typo in a string.

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

from fedora import _

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


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

from neutron_lib._i18n import _
from neutron_lib import exceptions

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

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

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

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

Add address group in use exception

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

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

from neutron_lib._i18n import _
from neutron_lib import exceptions

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

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

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

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

Prompt:
Add address group in use exception

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

Change-Id: I2a9872890ca4d5e59a9e266c1dcacd3488a3265c

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

from neutron_lib._i18n import _
from neutron_lib import exceptions

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

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

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


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

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

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

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

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

        return data

    class Media:
        js = (JS_URL,)

Use version 1 of Filepicker.js

Use version 1 of Filepicker.js

Response:
<REPLACE_OLD> 0
JS_URL <REPLACE_NEW> 1
JS_URL <REPLACE_END> <|endoftext|> from django.conf import settings
from django.forms import widgets

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

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

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

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

        return data

    class Media:
        js = (JS_URL,)

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

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

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

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

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

        return data

    class Media:
        js = (JS_URL,)


import unittest

from shapely.geometry import LineString, Point

from directions.base import _parse_points

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

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

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

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

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

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

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

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

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

Add tests for the different input variations.

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest

from shapely.geometry import LineString, Point

from directions.base import _parse_points

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

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

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

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

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

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

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

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

    def test_bad_input(self):
        # Test points not length 2
        with self.assertRaises(ValueError):
            _parse_points(self.p[0], (1.0, 2.0, 3.0))
 <REPLACE_END> <|endoftext|> import unittest

from shapely.geometry import LineString, Point

from directions.base import _parse_points

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

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

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

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

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

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

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

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

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

Prompt: Add tests for the different input variations.


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

import os
import subprocess
import sys

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

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

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

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

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

    contents = p.stdout.readlines()

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

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

    fp.close()

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

if __name__ == "__main__":
    main()

Response:
<INSERT> 'htdocs',
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
#
# Utility script to run pyflakes with the modules we care about and
# exclude errors we know to be fine.

import os
import subprocess
import sys

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

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

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

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

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

    contents = p.stdout.readlines()

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

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

    fp.close()

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

if __name__ == "__main__":
    main()

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

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

import os
import subprocess
import sys

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

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

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

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

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

    contents = p.stdout.readlines()

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

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

    fp.close()

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

if __name__ == "__main__":
    main()


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

register = template.Library()

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

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

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

    return context

Remove last_page not needed anymore.

Remove last_page not needed anymore.

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

 <DELETE_END> <|endoftext|> import math
from django import template
from ..conf import settings

register = template.Library()

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

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

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

    return context

Prompt:
Remove last_page not needed anymore.

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

register = template.Library()

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

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

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

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

    return context


from spicedham.basewrapper import BaseWrapper

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

Fix inheritence error and return value

Response:
<REPLACE_OLD> DigitDestroyer(BaseWrapper):
 <REPLACE_NEW> DigitDestroyer(object):
 <REPLACE_END> <REPLACE_OLD> 0.5
 <REPLACE_NEW> None
 <REPLACE_END> <|endoftext|> from spicedham.basewrapper import BaseWrapper

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

Prompt:
Fix inheritence error and return value

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

from spicedham.basewrapper import BaseWrapper

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


# -*- encoding: utf-8

import pytest

from reports import NGINX_LOG_REGEX

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

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

Add a few tests for the analytics code

Add a few tests for the analytics code

Response:
<INSERT> # -*- encoding: utf-8

import pytest

from reports import NGINX_LOG_REGEX

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

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

import pytest

from reports import NGINX_LOG_REGEX

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

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

Prompt: Add a few tests for the analytics code


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

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

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

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


from setuptools import setup, find_packages

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

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

Allow version to have subrevision.

Allow version to have subrevision.

Response:
<INSERT>    if type(version_tuple[2]) == int:
        version = "%d.%d.%s" % version_tuple
    else:
     <INSERT_END> <|endoftext|> from setuptools import setup, find_packages

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

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

Prompt:
Allow version to have subrevision.

from setuptools import setup, find_packages

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

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


import os

import pytest
import requests

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

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

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

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

Add test for custom images

Add test for custom images

Response:
<REPLACE_OLD> "image/jpeg"
 <REPLACE_NEW> "image/jpeg"

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

import pytest
import requests

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

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

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

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

Prompt:
Add test for custom images

import os

import pytest
import requests

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

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

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


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

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

MAX_FOLDERS = 1000

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

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

        url = FOLDERS_URL.format(folder_id)

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

                'offset': offset+count,
            }

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

            json_data = response.json()

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

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

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

Response:
<REPLACE_OLD> params=params)

 <REPLACE_NEW> params=params)
            response.raise_for_status()

 <REPLACE_END> <|endoftext|> BASE_URL = 'https://api.box.com/2.0'

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

MAX_FOLDERS = 1000

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

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

        url = FOLDERS_URL.format(folder_id)

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

                'offset': offset+count,
            }

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

            json_data = response.json()

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

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

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

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

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

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

MAX_FOLDERS = 1000

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

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

        url = FOLDERS_URL.format(folder_id)

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

                'offset': offset+count,
            }

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

            json_data = response.json()

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

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

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


from tools import add_constant, categorical

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

Remove import of moved file

REF: Remove import of moved file

Response:
<REPLACE_OLD> categorical
from datautils import Dataset

from <REPLACE_NEW> categorical

from <REPLACE_END> <|endoftext|> from tools import add_constant, categorical

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

Prompt:
REF: Remove import of moved file

from tools import add_constant, categorical
from datautils import Dataset

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


from setuptools import setup, find_packages

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

Remove Python 3 only classifier

Remove Python 3 only classifier

Response:
<REPLACE_OLD> Python :: 3 :: Only'],
 <REPLACE_NEW> Python'],
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

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

Prompt:
Remove Python 3 only classifier

from setuptools import setup, find_packages

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


import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

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

Response:
<REPLACE_OLD> vision):
 <REPLACE_NEW> vision_on):
 <REPLACE_END> <REPLACE_OLD> (3, 64, 64) <REPLACE_NEW> (64*64, 3) = (4096, 3) <REPLACE_END> <REPLACE_OLD> vision <REPLACE_NEW> vision_on <REPLACE_END> <INSERT> print(vision.shape)
            <INSERT_END> <REPLACE_OLD> vision[i]

 <REPLACE_NEW> vision[:, i].reshape((64, 64))

 <REPLACE_END> <|endoftext|> import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

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

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

import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

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


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

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

from canaryd_packages import six

from canaryd.plugin import get_plugin_by_name

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

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

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

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

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

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

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

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

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

        yield

        check_output_patch.stop()

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

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

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

Response:
<DELETE> canaryd_packages import six
from <DELETE_END> <INSERT> canaryd_packages import six

from <INSERT_END> <REPLACE_OLD> get_plugin_by_name

@six.add_metaclass(JsonTest)
class <REPLACE_NEW> get_plugin_by_name

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

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

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

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

@six.add_metaclass(JsonTest)
class <REPLACE_END> <REPLACE_OLD> ValueError(
                    'Broken <REPLACE_NEW> ValueError('Broken <REPLACE_END> <REPLACE_OLD> commands'.format(command),
                )

 <REPLACE_NEW> commands: {1}'.format(
                    command, commands.keys(),
                ))

 <REPLACE_END> <|endoftext|> from contextlib import contextmanager
from os import path
from unittest import TestCase

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

from canaryd_packages import six

from canaryd.plugin import get_plugin_by_name

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

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

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

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

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

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

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

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

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

        yield

        check_output_patch.stop()

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

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

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

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

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

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

from canaryd.plugin import get_plugin_by_name

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

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

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

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

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

        yield

        check_output_patch.stop()

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

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

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


#!/usr/bin/env python

import os
import random
import string
import sys

from django.utils.crypto import get_random_string

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

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

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

import django
django.setup()

from django.contrib.auth.models import User

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

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

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

Response:
<REPLACE_OLD> range(20))

User.objects.create_superuser('admin', <REPLACE_NEW> range(20))

if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', <REPLACE_END> <REPLACE_OLD> password)
print <REPLACE_NEW> password)
    print <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os
import random
import string
import sys

from django.utils.crypto import get_random_string

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

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

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

import django
django.setup()

from django.contrib.auth.models import User

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

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

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

Prompt:
Check if admin user exists before creating one

#!/usr/bin/env python

import os
import random
import string
import sys

from django.utils.crypto import get_random_string

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

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

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

import django
django.setup()

from django.contrib.auth.models import User

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

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

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


import argparse

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

Add cmd for getting version

Add cmd for getting version

Response:
<REPLACE_OLD>  <REPLACE_NEW> import argparse

parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis')
parser.add_argument('-v', '--version', action='version', version='0.1.0')
parser.parse_args()
 <REPLACE_END> <|endoftext|> import argparse

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

Prompt: Add cmd for getting version


import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY

log = logging.getLogger(__name__)

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

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

Response:
<REPLACE_OLD> '\\dt', <REPLACE_NEW> '\\dt [table]', <REPLACE_END> <|endoftext|> import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY

log = logging.getLogger(__name__)

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

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

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

import logging
from .main import special_command, RAW_QUERY, PARSED_QUERY

log = logging.getLogger(__name__)

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

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


import pytest
from nose.tools import assert_raises

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

class TestCeleryHandlers:

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

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

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

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

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

Add tests for new get_task_from_queue celery helper

Response:
<REPLACE_OLD>  <REPLACE_NEW> import pytest
from nose.tools import assert_raises

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

class TestCeleryHandlers:

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

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

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

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

        with assert_raises(ValueError):
            handlers.get_task_from_queue(
                'website.project.tasks.on_node_updated',
                predicate=lambda task: task.kwargs['node_id'] == 'woop'
            )
 <REPLACE_END> <|endoftext|> import pytest
from nose.tools import assert_raises

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

class TestCeleryHandlers:

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

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

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

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

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

Prompt: Add tests for new get_task_from_queue celery helper


import numpy as np

from eigen3 import toEigenX
import rbdyn as rbd

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

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

    return t

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

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

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

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

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

Fix a bad eigen vector cast.

Fix a bad eigen vector cast.

Response:
<REPLACE_OLD> toEigen
import <REPLACE_NEW> toEigenX
import <REPLACE_END> <REPLACE_OLD> toEigen(alpha2))

 <REPLACE_NEW> toEigenX(alpha2))

 <REPLACE_END> <|endoftext|> import numpy as np

from eigen3 import toEigenX
import rbdyn as rbd

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

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

    return t

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

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

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

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

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

Prompt:
Fix a bad eigen vector cast.

import numpy as np

from eigen3 import toEigen
import rbdyn as rbd

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

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

    return t

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

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

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

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

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


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

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

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

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

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

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

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

        self.User = User
        self.Group = Group

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

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

Add tests for many to many aggregates

Add tests for many to many aggregates

Response:
<REPLACE_OLD>  <REPLACE_NEW> import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
from tests import TestCase

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

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

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

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

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

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

        self.User = User
        self.Group = Group

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

    def test_updates_aggregates_on_delete(self):
        user = self.User(
            name=u'John Matrix'
        )
        self.session.add(user)
        self.session.commit()
        group = self.Group(
            name=u'Some group',
            users=[user]
        )
        self.session.add(group)
        self.session.commit()
        self.session.refresh(user)
        user.groups = []
        self.session.commit()
        self.session.refresh(user)
        assert user.group_count == 0
 <REPLACE_END> <|endoftext|> import sqlalchemy as sa
from sqlalchemy_utils.aggregates import aggregated
from tests import TestCase

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

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

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

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

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

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

        self.User = User
        self.Group = Group

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

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

Prompt: Add tests for many to many aggregates