from django.conf import settings
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView

class MozilliansGraphQLView(GraphQLView):
    """Class Based View to handle GraphQL requests."""

    @method_decorator(csrf_exempt)
    @method_decorator(csp_exempt)
    def dispatch(self, *args, **kwargs):
        """Override dispatch method to allow the use of multiple decorators."""

        if not settings.DINO_PARK_ACTIVE:
            raise Http404()

        return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)

Use the same setting for DinoPark.

Use the same setting for DinoPark.

Response:
<INSERT> django.conf import settings
from <INSERT_END> <REPLACE_OLD> method_decorator

import waffle
from <REPLACE_NEW> method_decorator

from <REPLACE_END> <REPLACE_OLD> waffle.flag_is_active(self.request, 'enable_graphql'):
 <REPLACE_NEW> settings.DINO_PARK_ACTIVE:
 <REPLACE_END> <|endoftext|> from django.conf import settings
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView

class MozilliansGraphQLView(GraphQLView):
    """Class Based View to handle GraphQL requests."""

    @method_decorator(csrf_exempt)
    @method_decorator(csp_exempt)
    def dispatch(self, *args, **kwargs):
        """Override dispatch method to allow the use of multiple decorators."""

        if not settings.DINO_PARK_ACTIVE:
            raise Http404()

        return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)

Prompt:
Use the same setting for DinoPark.

from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

import waffle
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView

class MozilliansGraphQLView(GraphQLView):
    """Class Based View to handle GraphQL requests."""

    @method_decorator(csrf_exempt)
    @method_decorator(csp_exempt)
    def dispatch(self, *args, **kwargs):
        """Override dispatch method to allow the use of multiple decorators."""

        if not waffle.flag_is_active(self.request, 'enable_graphql'):
            raise Http404()

        return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)


from matplotlib import pyplot as plt
import numpy as np
from cobs import cobs
from cobs import cobsr

def cobsr_overhead_calc(num_bytes):
    return 257./256 - (255./256)**num_bytes

def cobsr_overhead_measure(num_bytes):
    # TODO: review value
    NUM_TESTS = 10000
    overhead = 0
    for _i in xrange(NUM_TESTS):
        output = cobsr.encode(np.random.bytes(num_bytes))
        overhead += (len(output) - num_bytes)
    return overhead / float(NUM_TESTS)

def cobs_overhead_measure(num_bytes):
    # TODO: review value
    NUM_TESTS = 10000
    overhead = 0
    for _i in xrange(NUM_TESTS):
        output = cobs.encode(np.random.bytes(num_bytes))
        overhead += (len(output) - num_bytes)
    return overhead / float(NUM_TESTS)

fig = plt.figure()
ax1 = fig.add_subplot(111)

# x-range for plot
num_bytes_list = np.arange(1, 30)

# Calculate values and plot

# Measured values for COBS
#cobs_measured_overhead = [ cobs_overhead_measure(num_bytes) for num_bytes in num_bytes_list ]
#ax1.plot(num_bytes_list, cobs_measured_overhead, 'g.')

# Measured values for COBS/R
cobsr_measured_overhead = [ cobsr_overhead_measure(num_bytes) for num_bytes in num_bytes_list ]
ax1.plot(num_bytes_list, cobsr_measured_overhead, 'r.')

# Calculated values for COBS/R
cobsr_calc_overhead = [ cobsr_overhead_calc(num_bytes) for num_bytes in num_bytes_list ]
ax1.plot(num_bytes_list, cobsr_calc_overhead, 'b.')

ax1.set_xlabel('message length (bytes)')
ax1.set_xlim(min(num_bytes_list), max(num_bytes_list))

# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('encoding overhead (bytes)')
if 0:
    ax1.set_ylabel('encoding overhead (bytes)', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')

plt.show()

Add program to graph theoretical vs experimental COBS/R overhead

I wrote this a long time ago, but didn't put it into version control
until now.

Response:
<REPLACE_OLD>  <REPLACE_NEW>
from matplotlib import pyplot as plt
import numpy as np
from cobs import cobs
from cobs import cobsr

def cobsr_overhead_calc(num_bytes):
    return 257./256 - (255./256)**num_bytes

def cobsr_overhead_measure(num_bytes):
    # TODO: review value
    NUM_TESTS = 10000
    overhead = 0
    for _i in xrange(NUM_TESTS):
        output = cobsr.encode(np.random.bytes(num_bytes))
        overhead += (len(output) - num_bytes)
    return overhead / float(NUM_TESTS)

def cobs_overhead_measure(num_bytes):
    # TODO: review value
    NUM_TESTS = 10000
    overhead = 0
    for _i in xrange(NUM_TESTS):
        output = cobs.encode(np.random.bytes(num_bytes))
        overhead += (len(output) - num_bytes)
    return overhead / float(NUM_TESTS)

fig = plt.figure()
ax1 = fig.add_subplot(111)

# x-range for plot
num_bytes_list = np.arange(1, 30)

# Calculate values and plot

# Measured values for COBS
#cobs_measured_overhead = [ cobs_overhead_measure(num_bytes) for num_bytes in num_bytes_list ]
#ax1.plot(num_bytes_list, cobs_measured_overhead, 'g.')

# Measured values for COBS/R
cobsr_measured_overhead = [ cobsr_overhead_measure(num_bytes) for num_bytes in num_bytes_list ]
ax1.plot(num_bytes_list, cobsr_measured_overhead, 'r.')

# Calculated values for COBS/R
cobsr_calc_overhead = [ cobsr_overhead_calc(num_bytes) for num_bytes in num_bytes_list ]
ax1.plot(num_bytes_list, cobsr_calc_overhead, 'b.')

ax1.set_xlabel('message length (bytes)')
ax1.set_xlim(min(num_bytes_list), max(num_bytes_list))

# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('encoding overhead (bytes)')
if 0:
    ax1.set_ylabel('encoding overhead (bytes)', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')

plt.show()
 <REPLACE_END> <|endoftext|>
from matplotlib import pyplot as plt
import numpy as np
from cobs import cobs
from cobs import cobsr

def cobsr_overhead_calc(num_bytes):
    return 257./256 - (255./256)**num_bytes

def cobsr_overhead_measure(num_bytes):
    # TODO: review value
    NUM_TESTS = 10000
    overhead = 0
    for _i in xrange(NUM_TESTS):
        output = cobsr.encode(np.random.bytes(num_bytes))
        overhead += (len(output) - num_bytes)
    return overhead / float(NUM_TESTS)

def cobs_overhead_measure(num_bytes):
    # TODO: review value
    NUM_TESTS = 10000
    overhead = 0
    for _i in xrange(NUM_TESTS):
        output = cobs.encode(np.random.bytes(num_bytes))
        overhead += (len(output) - num_bytes)
    return overhead / float(NUM_TESTS)

fig = plt.figure()
ax1 = fig.add_subplot(111)

# x-range for plot
num_bytes_list = np.arange(1, 30)

# Calculate values and plot

# Measured values for COBS
#cobs_measured_overhead = [ cobs_overhead_measure(num_bytes) for num_bytes in num_bytes_list ]
#ax1.plot(num_bytes_list, cobs_measured_overhead, 'g.')

# Measured values for COBS/R
cobsr_measured_overhead = [ cobsr_overhead_measure(num_bytes) for num_bytes in num_bytes_list ]
ax1.plot(num_bytes_list, cobsr_measured_overhead, 'r.')

# Calculated values for COBS/R
cobsr_calc_overhead = [ cobsr_overhead_calc(num_bytes) for num_bytes in num_bytes_list ]
ax1.plot(num_bytes_list, cobsr_calc_overhead, 'b.')

ax1.set_xlabel('message length (bytes)')
ax1.set_xlim(min(num_bytes_list), max(num_bytes_list))

# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('encoding overhead (bytes)')
if 0:
    ax1.set_ylabel('encoding overhead (bytes)', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')

plt.show()

Prompt:
Add program to graph theoretical vs experimental COBS/R overhead

I wrote this a long time ago, but didn't put it into version control
until now.


# Web server
DEBUG = True
HOST = '127.0.0.1'
PORT = 5000
TEMPLATE = 'flot.html'

SITE_TITLE = "UA Sensors Visualization"

# Database location
SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3'

# Sensor type mapping
#
# - First parameter is the identifier sent from sensors in the wild
# - Second parameter is the readable name of the sensor type
# - Third parameter is the types of readings returned
#   - Semi-colon separates different sensor reading types
#   - Each reading type needs to specify type and unit of measurement
#   - For, example TYPE UNITS; TYPE UNITS -> distance meters; temperature celsius
SENSOR_TYPES = (
    ("d", "Water", "distance meters; temperature celsius"),
    ("g", "Gate", "distance meters"),
    ("s", "Soil", "moisture percent; temperature celsius"),
)

# Maps sensor ids to more informative name.
#
# Not all sensors need to be named. Can be adjusted later, just remember to
# restart server on config file updates
#
# For instance, +12223334444 is not as informative as Campbell Creek Water Sensor
#
# Example format:
#
# SENSOR_NAMES = {
#   '+12223334444': 'Yosemite Distance Sensor',
#   '+01234567890': 'Siberia Gate Sensor',
#   'moteino_1': 'Arctic Ocean Moisture Sensor',
# }
SENSOR_NAMES = {}

# Data logger error logging
DATA_LOGGER_ERROR_FILE = 'log/ua_sensor.log'
DATA_LOGGER_ERROR_LEVEL = 'INFO'
DATA_LOGGER_ERROR_FORMAT = '%(levelname)s - %(message)s'

Add some new default settings

Add some new default settings

Response:
<REPLACE_OLD> 'flot.html'

# <REPLACE_NEW> 'flot.html'

SITE_TITLE = "UA Sensors Visualization"

# <REPLACE_END> <REPLACE_OLD> 'data/ua_sensors.sqlite3'

# <REPLACE_NEW> 'data/ua_sensors.sqlite3'

# <REPLACE_END> <REPLACE_OLD> celsius"),
)

# <REPLACE_NEW> celsius"),
)

# Maps sensor ids to more informative name.
#
# Not all sensors need to be named. Can be adjusted later, just remember to
# restart server on config file updates
#
# For instance, +12223334444 is not as informative as Campbell Creek Water Sensor
#
# Example format:
#
# SENSOR_NAMES = {
#   '+12223334444': 'Yosemite Distance Sensor',
#   '+01234567890': 'Siberia Gate Sensor',
#   'moteino_1': 'Arctic Ocean Moisture Sensor',
# }
SENSOR_NAMES = {}

# <REPLACE_END> <|endoftext|> # Web server
DEBUG = True
HOST = '127.0.0.1'
PORT = 5000
TEMPLATE = 'flot.html'

SITE_TITLE = "UA Sensors Visualization"

# Database location
SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3'

# Sensor type mapping
#
# - First parameter is the identifier sent from sensors in the wild
# - Second parameter is the readable name of the sensor type
# - Third parameter is the types of readings returned
#   - Semi-colon separates different sensor reading types
#   - Each reading type needs to specify type and unit of measurement
#   - For, example TYPE UNITS; TYPE UNITS -> distance meters; temperature celsius
SENSOR_TYPES = (
    ("d", "Water", "distance meters; temperature celsius"),
    ("g", "Gate", "distance meters"),
    ("s", "Soil", "moisture percent; temperature celsius"),
)

# Maps sensor ids to more informative name.
#
# Not all sensors need to be named. Can be adjusted later, just remember to
# restart server on config file updates
#
# For instance, +12223334444 is not as informative as Campbell Creek Water Sensor
#
# Example format:
#
# SENSOR_NAMES = {
#   '+12223334444': 'Yosemite Distance Sensor',
#   '+01234567890': 'Siberia Gate Sensor',
#   'moteino_1': 'Arctic Ocean Moisture Sensor',
# }
SENSOR_NAMES = {}

# Data logger error logging
DATA_LOGGER_ERROR_FILE = 'log/ua_sensor.log'
DATA_LOGGER_ERROR_LEVEL = 'INFO'
DATA_LOGGER_ERROR_FORMAT = '%(levelname)s - %(message)s'

Prompt:
Add some new default settings

# Web server
DEBUG = True
HOST = '127.0.0.1'
PORT = 5000
TEMPLATE = 'flot.html'

# Database location
SQLITE3_DB_PATH = 'data/ua_sensors.sqlite3'

# Sensor type mapping
#
# - First parameter is the identifier sent from sensors in the wild
# - Second parameter is the readable name of the sensor type
# - Third parameter is the types of readings returned
#   - Semi-colon separates different sensor reading types
#   - Each reading type needs to specify type and unit of measurement
#   - For, example TYPE UNITS; TYPE UNITS -> distance meters; temperature celsius
SENSOR_TYPES = (
    ("d", "Water", "distance meters; temperature celsius"),
    ("g", "Gate", "distance meters"),
    ("s", "Soil", "moisture percent; temperature celsius"),
)

# Data logger error logging
DATA_LOGGER_ERROR_FILE = 'log/ua_sensor.log'
DATA_LOGGER_ERROR_LEVEL = 'INFO'
DATA_LOGGER_ERROR_FORMAT = '%(levelname)s - %(message)s'


import numpy as np

def main():
    np.random.seed(0)
    bins = 50
    X = np.random.zipf(1.2, 1000)
    y = np.histogram(X[X<bins], bins, normed=True)[0]
    fn = np.polyfit(np.arange(bins), y, 3)
    print(fn)

    np.random.seed(0)
    bins = 50
    samples = 1000
    X = [np.random.zipf(1.2, samples),
         np.random.zipf(1.3, samples),
         np.random.zipf(1.5, samples)]
    y = np.array([np.histogram(x[x<b], bins, normed=True)[0] for x in X])
    fn = np.polyfit(np.arange(bins), y.T, 3)
    print(fn)

if __name__ == '__main__':
    main()

Build curves for a single zipfian distribution and then 3 combined

Response:
<INSERT> import numpy as np

def main():
 <INSERT_END> <INSERT>   np.random.seed(0)
    bins = 50
    X = np.random.zipf(1.2, 1000)
    y = np.histogram(X[X<bins], bins, normed=True)[0]
    fn = np.polyfit(np.arange(bins), y, 3)
    print(fn)

    np.random.seed(0)
    bins = 50
    samples = 1000
    X = [np.random.zipf(1.2, samples),
         np.random.zipf(1.3, samples),
         np.random.zipf(1.5, samples)]
    y = np.array([np.histogram(x[x<b], bins, normed=True)[0] for x in X])
    fn = np.polyfit(np.arange(bins), y.T, 3)
    print(fn)

if __name__ == '__main__':
    main()
 <INSERT_END> <|endoftext|> import numpy as np

def main():
    np.random.seed(0)
    bins = 50
    X = np.random.zipf(1.2, 1000)
    y = np.histogram(X[X<bins], bins, normed=True)[0]
    fn = np.polyfit(np.arange(bins), y, 3)
    print(fn)

    np.random.seed(0)
    bins = 50
    samples = 1000
    X = [np.random.zipf(1.2, samples),
         np.random.zipf(1.3, samples),
         np.random.zipf(1.5, samples)]
    y = np.array([np.histogram(x[x<b], bins, normed=True)[0] for x in X])
    fn = np.polyfit(np.arange(bins), y.T, 3)
    print(fn)

if __name__ == '__main__':
    main()

Prompt: Build curves for a single zipfian distribution and then 3 combined


class TestUserThermal:
    def test_can_download_recording(self, helper):
        device = helper.given_new_device(self, 'cacophonator-download')
        recording = device.has_recording()

        print("\nA user should be able to download the recording")
        helper.admin_user().can_download_correct_recording(recording)

    def test_can_delete_recording(self, helper):
        device = helper.given_new_device(self, 'cacophonator-delete')
        recording = device.has_recording()

        print("\nA user should be able to see the recording")
        user = helper.admin_user()
        user.can_see_recordings(recording)

        print("And when they delete it ... ", end='')
        user.delete_recording(recording)

        print("they can no longer see it.")
        user.cannot_see_recordings(recording)

Response:
<REPLACE_OLD> test_can_download_audio(self, <REPLACE_NEW> test_can_download_recording(self, <REPLACE_END> <REPLACE_OLD> 'cacophonator')
 <REPLACE_NEW> 'cacophonator-download')
 <REPLACE_END> <REPLACE_OLD> 'cacophonator')
 <REPLACE_NEW> 'cacophonator-delete')
 <REPLACE_END> <|endoftext|> class TestUserThermal:
    def test_can_download_recording(self, helper):
        device = helper.given_new_device(self, 'cacophonator-download')
        recording = device.has_recording()

        print("\nA user should be able to download the recording")
        helper.admin_user().can_download_correct_recording(recording)

    def test_can_delete_recording(self, helper):
        device = helper.given_new_device(self, 'cacophonator-delete')
        recording = device.has_recording()

        print("\nA user should be able to see the recording")
        user = helper.admin_user()
        user.can_see_recordings(recording)

        print("And when they delete it ... ", end='')
        user.delete_recording(recording)

        print("they can no longer see it.")
        user.cannot_see_recordings(recording)

Prompt:
Use unique device names in tests & correct a test name

class TestUserThermal:
    def test_can_download_audio(self, helper):
        device = helper.given_new_device(self, 'cacophonator')
        recording = device.has_recording()

        print("\nA user should be able to download the recording")
        helper.admin_user().can_download_correct_recording(recording)

    def test_can_delete_recording(self, helper):
        device = helper.given_new_device(self, 'cacophonator')
        recording = device.has_recording()

        print("\nA user should be able to see the recording")
        user = helper.admin_user()
        user.can_see_recordings(recording)

        print("And when they delete it ... ", end='')
        user.delete_recording(recording)

        print("they can no longer see it.")
        user.cannot_see_recordings(recording)


DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''

TWILIO_NUMBERS = ['']

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

TWILIO_NUMBERS = ['']
 <REPLACE_END> <|endoftext|> DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''

TWILIO_NUMBERS = ['']

Prompt:
Allow for representative view display with sample configuration

DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''


from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend

@extend(User)
class Profile(object):
    """Add shortcuts to user"""

    @property
    def github(self):
        """Github api instance with access from user"""
        return Github(self.github_token)

    @property
    def github_token(self):
        """Get github api token"""
        return self.social_auth.get().extra_data['access_token']

Response:
<REPLACE_OLD> token = self.social_auth.get().extra_data['access_token']
 <REPLACE_NEW> return Github(self.github_token)

    @property
    def github_token(self):
        """Get github api token"""
 <REPLACE_END> <REPLACE_OLD> Github(token)
 <REPLACE_NEW> self.social_auth.get().extra_data['access_token']
 <REPLACE_END> <|endoftext|> from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend

@extend(User)
class Profile(object):
    """Add shortcuts to user"""

    @property
    def github(self):
        """Github api instance with access from user"""
        return Github(self.github_token)

    @property
    def github_token(self):
        """Get github api token"""
        return self.social_auth.get().extra_data['access_token']

Prompt:
Add ability to get github token from user model

from github import Github
from django.contrib.auth.models import User
from tools.decorators import extend

@extend(User)
class Profile(object):
    """Add shortcuts to user"""

    @property
    def github(self):
        """Github api instance with access from user"""
        token = self.social_auth.get().extra_data['access_token']
        return Github(token)


from werkzeug.urls import url_decode

import foauth.providers

class Rdio(foauth.providers.OAuth1):
    # General info about the provider
    provider_url = 'http://www.rdio.com/'
    docs_url = 'http://developer.rdio.com/docs/REST/'
    category = 'Music'

    # URLs to interact with the API
    request_token_url = 'http://api.rdio.com/oauth/request_token'
    authorize_url = None  # Provided when the request token is granted
    access_token_url = 'http://api.rdio.com/oauth/access_token'
    api_domain = 'api.rdio.com'

    available_permissions = [
        (None, 'access and manage your music'),
    ]

    https = False

    def parse_token(self, content):
        # Override standard token request to also get the authorization URL
        data = url_decode(content)
        if 'login_url' in data:
            self.authorize_url = data['login_url']
        return super(Rdio, self).parse_token(content)

    def get_user_id(self, key):
        r = self.api(key, self.api_domain, u'/1/', method='POST', data={
            'method': 'currentUser',
        })
        return unicode(r.json[u'result'][u'key'])

Response:
<REPLACE_OLD> url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY

import <REPLACE_NEW> url_decode

import <REPLACE_END> <REPLACE_OLD> False
    signature_type = SIGNATURE_TYPE_BODY

 <REPLACE_NEW> False

 <REPLACE_END> <|endoftext|> from werkzeug.urls import url_decode

import foauth.providers

class Rdio(foauth.providers.OAuth1):
    # General info about the provider
    provider_url = 'http://www.rdio.com/'
    docs_url = 'http://developer.rdio.com/docs/REST/'
    category = 'Music'

    # URLs to interact with the API
    request_token_url = 'http://api.rdio.com/oauth/request_token'
    authorize_url = None  # Provided when the request token is granted
    access_token_url = 'http://api.rdio.com/oauth/access_token'
    api_domain = 'api.rdio.com'

    available_permissions = [
        (None, 'access and manage your music'),
    ]

    https = False

    def parse_token(self, content):
        # Override standard token request to also get the authorization URL
        data = url_decode(content)
        if 'login_url' in data:
            self.authorize_url = data['login_url']
        return super(Rdio, self).parse_token(content)

    def get_user_id(self, key):
        r = self.api(key, self.api_domain, u'/1/', method='POST', data={
            'method': 'currentUser',
        })
        return unicode(r.json[u'result'][u'key'])

Prompt:
Allow Rdio to use default signature handling

from werkzeug.urls import url_decode
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_BODY

import foauth.providers

class Rdio(foauth.providers.OAuth1):
    # General info about the provider
    provider_url = 'http://www.rdio.com/'
    docs_url = 'http://developer.rdio.com/docs/REST/'
    category = 'Music'

    # URLs to interact with the API
    request_token_url = 'http://api.rdio.com/oauth/request_token'
    authorize_url = None  # Provided when the request token is granted
    access_token_url = 'http://api.rdio.com/oauth/access_token'
    api_domain = 'api.rdio.com'

    available_permissions = [
        (None, 'access and manage your music'),
    ]

    https = False
    signature_type = SIGNATURE_TYPE_BODY

    def parse_token(self, content):
        # Override standard token request to also get the authorization URL
        data = url_decode(content)
        if 'login_url' in data:
            self.authorize_url = data['login_url']
        return super(Rdio, self).parse_token(content)

    def get_user_id(self, key):
        r = self.api(key, self.api_domain, u'/1/', method='POST', data={
            'method': 'currentUser',
        })
        return unicode(r.json[u'result'][u'key'])


"""calc.py: A simple Python calculator."""
import sys

def add_all(nums):
    return sum(nums)

def multiply_all(nums):
    return reduce(lambda a, b: a * b, nums)

if __name__ == '__main__':
    command = sys.argv[1]
    nums = map(float, sys.argv[2:])
    if command == 'add':
        print(add_all(nums))
    elif command == 'multiply':
        print(multiply_all(nums))
    elif command == 'min':
        print(min(nums))

Add support to min command

Add support to min command

Response:
<REPLACE_OLD> python calculator."""

import <REPLACE_NEW> Python calculator."""
import <REPLACE_END> <INSERT>    elif command == 'min':
        print(min(nums))
 <INSERT_END> <|endoftext|> """calc.py: A simple Python calculator."""
import sys

def add_all(nums):
    return sum(nums)

def multiply_all(nums):
    return reduce(lambda a, b: a * b, nums)

if __name__ == '__main__':
    command = sys.argv[1]
    nums = map(float, sys.argv[2:])
    if command == 'add':
        print(add_all(nums))
    elif command == 'multiply':
        print(multiply_all(nums))
    elif command == 'min':
        print(min(nums))

Prompt:
Add support to min command

"""calc.py: A simple python calculator."""

import sys

def add_all(nums):
    return sum(nums)

def multiply_all(nums):
    return reduce(lambda a, b: a * b, nums)

if __name__ == '__main__':
    command = sys.argv[1]
    nums = map(float, sys.argv[2:])
    if command == 'add':
        print(add_all(nums))
    elif command == 'multiply':
        print(multiply_all(nums))


import logging
import sys

from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib

VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')

logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ and environ.get(VEXT_DEBUG_LOG, "0") == "1":
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
else:
    logger.addHandler(logging.NullHandler())

def install_importer():
    # This is here so that older versions of vext don't break.
    logger.warning("install_importer has been moved to gatekeeper module")
    from vext import gatekeeper
    gatekeeper.install_importer()

Change how logging works again :)

Change how logging works again :)

Response:
<REPLACE_OLD> logging

from <REPLACE_NEW> logging
import sys

from <REPLACE_END> <REPLACE_OLD> environ:
    if <REPLACE_NEW> environ and <REPLACE_END> <DELETE>     <DELETE_END> <REPLACE_OLD> else:
     <REPLACE_NEW> logger.addHandler(logging.StreamHandler())
else:
 <REPLACE_END> <REPLACE_OLD> logger.debug("install_importer <REPLACE_NEW> # This is here so that older versions of vext don't break.
    logger.warning("install_importer <REPLACE_END> <|endoftext|> import logging
import sys

from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib

VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')

logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ and environ.get(VEXT_DEBUG_LOG, "0") == "1":
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
else:
    logger.addHandler(logging.NullHandler())

def install_importer():
    # This is here so that older versions of vext don't break.
    logger.warning("install_importer has been moved to gatekeeper module")
    from vext import gatekeeper
    gatekeeper.install_importer()

Prompt:
Change how logging works again :)

import logging

from os import environ
from os.path import join
from distutils.sysconfig import get_python_lib

VEXT_DEBUG_LOG = "VEXT_DEBUG_LOG"
vext_pth = join(get_python_lib(), 'vext_importer.pth')

logger = logging.getLogger("vext")
if VEXT_DEBUG_LOG in environ:
    if environ.get(VEXT_DEBUG_LOG, "0") == "1":
        logger.setLevel(logging.DEBUG)
    else:
        logger.addHandler(logging.NullHandler())

def install_importer():
    logger.debug("install_importer has been moved to gatekeeper module")
    from vext import gatekeeper
    gatekeeper.install_importer()


import unittest

import requests

class TestCase(object):
    """
    Add assetion methods for HTTP Requests to TestCase
    """
    hosts = []

    def assertGet(self, endpoint="", status_code=200, body=""):
        """
        Asserts GET requests on a given endpoint
        """
        for host in self.hosts:
            response = requests.get(host+endpoint)
            self.assertEqual(response.status_code, status_code)
            if isinstance(body, str):
                self.assertIn(body, response.content)
            elif isinstance(body, list):
                for content in body:
                    self.assertIn(content, response.content)

Response:
<DELETE> types
import <DELETE_END> <REPLACE_OLD> types.StringType):
 <REPLACE_NEW> str):
 <REPLACE_END> <|endoftext|> import unittest

import requests

class TestCase(object):
    """
    Add assetion methods for HTTP Requests to TestCase
    """
    hosts = []

    def assertGet(self, endpoint="", status_code=200, body=""):
        """
        Asserts GET requests on a given endpoint
        """
        for host in self.hosts:
            response = requests.get(host+endpoint)
            self.assertEqual(response.status_code, status_code)
            if isinstance(body, str):
                self.assertIn(body, response.content)
            elif isinstance(body, list):
                for content in body:
                    self.assertIn(content, response.content)

Prompt:
Change assertGet body check from StringType to str

import types
import unittest

import requests

class TestCase(object):
    """
    Add assetion methods for HTTP Requests to TestCase
    """
    hosts = []

    def assertGet(self, endpoint="", status_code=200, body=""):
        """
        Asserts GET requests on a given endpoint
        """
        for host in self.hosts:
            response = requests.get(host+endpoint)
            self.assertEqual(response.status_code, status_code)
            if isinstance(body, types.StringType):
                self.assertIn(body, response.content)
            elif isinstance(body, list):
                for content in body:
                    self.assertIn(content, response.content)


#!/usr/bin/env python

import os
import subprocess

from lib import functional

from util import find_all

def coverage_module(package, module):
    command = (
        'coverage run --branch'
        ' --source=%s.%s tests/%s/%s_test.py')
    print subprocess.check_output(
        command % (package, module, package, module),
        stderr=subprocess.STDOUT,
        shell=True)
    print subprocess.check_output(
        'coverage report --fail-under=100 -m',
        stderr=subprocess.STDOUT,
        shell=True)
    subprocess.check_output(
        'coverage erase',
        shell=True)

def coverage_test_package(package):
    def path_to_name(name):
        return os.path.split(name)[1].split('.')[0]

    for module in functional.removed(
            map(path_to_name, find_all(
                os.path.join('src', package), '.py')), '__init__'):
        print package, module
        coverage_module(package, module)

def coverage_test_all():
    os.chdir(os.environ['PORTER'])
    for package in os.listdir('src/'):
        coverage_test_package(package)

if __name__ == '__main__':
    coverage_test_all()

Response:
<REPLACE_OLD> ['lib', 'engine']:
 <REPLACE_NEW> os.listdir('src/'):
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os
import subprocess

from lib import functional

from util import find_all

def coverage_module(package, module):
    command = (
        'coverage run --branch'
        ' --source=%s.%s tests/%s/%s_test.py')
    print subprocess.check_output(
        command % (package, module, package, module),
        stderr=subprocess.STDOUT,
        shell=True)
    print subprocess.check_output(
        'coverage report --fail-under=100 -m',
        stderr=subprocess.STDOUT,
        shell=True)
    subprocess.check_output(
        'coverage erase',
        shell=True)

def coverage_test_package(package):
    def path_to_name(name):
        return os.path.split(name)[1].split('.')[0]

    for module in functional.removed(
            map(path_to_name, find_all(
                os.path.join('src', package), '.py')), '__init__'):
        print package, module
        coverage_module(package, module)

def coverage_test_all():
    os.chdir(os.environ['PORTER'])
    for package in os.listdir('src/'):
        coverage_test_package(package)

if __name__ == '__main__':
    coverage_test_all()

Prompt:
Remove hard coded 'engine' and 'lib' in coverage testing

#!/usr/bin/env python

import os
import subprocess

from lib import functional

from util import find_all

def coverage_module(package, module):
    command = (
        'coverage run --branch'
        ' --source=%s.%s tests/%s/%s_test.py')
    print subprocess.check_output(
        command % (package, module, package, module),
        stderr=subprocess.STDOUT,
        shell=True)
    print subprocess.check_output(
        'coverage report --fail-under=100 -m',
        stderr=subprocess.STDOUT,
        shell=True)
    subprocess.check_output(
        'coverage erase',
        shell=True)

def coverage_test_package(package):
    def path_to_name(name):
        return os.path.split(name)[1].split('.')[0]

    for module in functional.removed(
            map(path_to_name, find_all(
                os.path.join('src', package), '.py')), '__init__'):
        print package, module
        coverage_module(package, module)

def coverage_test_all():
    os.chdir(os.environ['PORTER'])
    for package in ['lib', 'engine']:
        coverage_test_package(package)

if __name__ == '__main__':
    coverage_test_all()


from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm

class GraphSeriesSerializer(serializers.ModelSerializer):
    x = serializers.SerializerMethodField('get_time')
    y = serializers.SerializerMethodField('get_value')

    class Meta:
        fields = ['x', 'y']

    def get_time(self, obj):
        return int(timegm(obj.time.utctimetuple())) * 1000  # Milliseconds since epoch, UTC

    def get_value(self, obj):
        return obj.value

class MeasurementGraphSeriesSerializer(GraphSeriesSerializer):
    alarm = serializers.SerializerMethodField('get_alarm')

    def __init__(self, *args, **kwargs):
        self.alarm_dict = kwargs.pop('alarm_dict', None)
        super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs)
        if not self.alarm_dict:
            self.fields.pop('alarm')

    def get_alarm(self, obj):
        if obj.id in self.alarm_dict:
            alarm = self.alarm_dict[obj.id]
            serializer = SimpleAlarmSerializer(alarm)
            return serializer.data
        return None

    class Meta(GraphSeriesSerializer.Meta):
        model = Measurement
        fields = GraphSeriesSerializer.Meta.fields + ['alarm']

class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer):
    class Meta(GraphSeriesSerializer.Meta):
        model = ThresholdValue

class SimpleAlarmSerializer(serializers.ModelSerializer):
    class Meta:
        model = Alarm
        fields = ['is_treated']

Response:
<REPLACE_OLD> ('id', 'time_created', 'is_treated', 'treated_text')
 <REPLACE_NEW> ['is_treated']
 <REPLACE_END> <|endoftext|> from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm

class GraphSeriesSerializer(serializers.ModelSerializer):
    x = serializers.SerializerMethodField('get_time')
    y = serializers.SerializerMethodField('get_value')

    class Meta:
        fields = ['x', 'y']

    def get_time(self, obj):
        return int(timegm(obj.time.utctimetuple())) * 1000  # Milliseconds since epoch, UTC

    def get_value(self, obj):
        return obj.value

class MeasurementGraphSeriesSerializer(GraphSeriesSerializer):
    alarm = serializers.SerializerMethodField('get_alarm')

    def __init__(self, *args, **kwargs):
        self.alarm_dict = kwargs.pop('alarm_dict', None)
        super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs)
        if not self.alarm_dict:
            self.fields.pop('alarm')

    def get_alarm(self, obj):
        if obj.id in self.alarm_dict:
            alarm = self.alarm_dict[obj.id]
            serializer = SimpleAlarmSerializer(alarm)
            return serializer.data
        return None

    class Meta(GraphSeriesSerializer.Meta):
        model = Measurement
        fields = GraphSeriesSerializer.Meta.fields + ['alarm']

class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer):
    class Meta(GraphSeriesSerializer.Meta):
        model = ThresholdValue

class SimpleAlarmSerializer(serializers.ModelSerializer):
    class Meta:
        model = Alarm
        fields = ['is_treated']

Prompt:
Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint

from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm

class GraphSeriesSerializer(serializers.ModelSerializer):
    x = serializers.SerializerMethodField('get_time')
    y = serializers.SerializerMethodField('get_value')

    class Meta:
        fields = ['x', 'y']

    def get_time(self, obj):
        return int(timegm(obj.time.utctimetuple())) * 1000  # Milliseconds since epoch, UTC

    def get_value(self, obj):
        return obj.value

class MeasurementGraphSeriesSerializer(GraphSeriesSerializer):
    alarm = serializers.SerializerMethodField('get_alarm')

    def __init__(self, *args, **kwargs):
        self.alarm_dict = kwargs.pop('alarm_dict', None)
        super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs)
        if not self.alarm_dict:
            self.fields.pop('alarm')

    def get_alarm(self, obj):
        if obj.id in self.alarm_dict:
            alarm = self.alarm_dict[obj.id]
            serializer = SimpleAlarmSerializer(alarm)
            return serializer.data
        return None

    class Meta(GraphSeriesSerializer.Meta):
        model = Measurement
        fields = GraphSeriesSerializer.Meta.fields + ['alarm']

class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer):
    class Meta(GraphSeriesSerializer.Meta):
        model = ThresholdValue

class SimpleAlarmSerializer(serializers.ModelSerializer):
    class Meta:
        model = Alarm
        fields = ('id', 'time_created', 'is_treated', 'treated_text')


import platform

import pytest

from hypothesis import HealthCheck, settings

from cattr import Converter

@pytest.fixture()
def converter():
    return Converter()

if platform.python_implementation() == 'PyPy':
    settings.default.suppress_health_check.append(HealthCheck.too_slow)

Response:
<INSERT> platform

import <INSERT_END> <INSERT> hypothesis import HealthCheck, settings

from <INSERT_END> <REPLACE_OLD> Converter()
 <REPLACE_NEW> Converter()

if platform.python_implementation() == 'PyPy':
    settings.default.suppress_health_check.append(HealthCheck.too_slow)
 <REPLACE_END> <|endoftext|> import platform

import pytest

from hypothesis import HealthCheck, settings

from cattr import Converter

@pytest.fixture()
def converter():
    return Converter()

if platform.python_implementation() == 'PyPy':
    settings.default.suppress_health_check.append(HealthCheck.too_slow)

Prompt:
Disable Hypothesis health check for PyPy.

import pytest

from cattr import Converter

@pytest.fixture()
def converter():
    return Converter()


"""Tests for gcld3."""

import gcld3
import unittest

class NnetLanguageIdentifierTest(unittest.TestCase):

  def testLangIdentification(self):
    detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
    sample = "This text is written in English."
    result = detector.FindLanguage(text=sample)
    self.assertEqual(result.language, "en")
    self.assertTrue(result.is_reliable)
    self.assertGreater(result.proportion, 0.99)
    self.assertGreater(result.probability, 0.90)

  def testEmptyString(self):
    detector = gcld3.NNetLanguageIdentifier(
        min_num_bytes=10, max_num_bytes=1000)
    sample = ""
    result = detector.FindLanguage(text=sample)
    self.assertEqual(result.language, "und")
    self.assertFalse(result.is_reliable)
    self.assertEqual(result.proportion, 0.0)
    self.assertEqual(result.probability, 0.00)

  def testLangsIdentification(self):
    detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
    sample = ("This piece of text is in English. Този текст е на " "Български.")
    results = detector.FindTopNMostFreqLangs(text=sample, num_langs=2)
    self.assertEqual(results[0].language, "bg")
    self.assertTrue(results[0].is_reliable)
    self.assertLess(results[0].proportion, 0.75)
    self.assertGreater(results[0].probability, 0.90)
    self.assertEqual(results[1].language, "en")
    self.assertTrue(results[1].is_reliable)
    self.assertLess(results[1].proportion, 0.75)
    self.assertGreater(results[1].probability, 0.90)

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

Add a python unit test

Add a python unit test

Response:
<INSERT> """Tests for gcld3."""

import gcld3
import unittest

class NnetLanguageIdentifierTest(unittest.TestCase):

 <INSERT_END> <INSERT> def testLangIdentification(self):
    detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
    sample = "This text is written in English."
    result = detector.FindLanguage(text=sample)
    self.assertEqual(result.language, "en")
    self.assertTrue(result.is_reliable)
    self.assertGreater(result.proportion, 0.99)
    self.assertGreater(result.probability, 0.90)

  def testEmptyString(self):
    detector = gcld3.NNetLanguageIdentifier(
        min_num_bytes=10, max_num_bytes=1000)
    sample = ""
    result = detector.FindLanguage(text=sample)
    self.assertEqual(result.language, "und")
    self.assertFalse(result.is_reliable)
    self.assertEqual(result.proportion, 0.0)
    self.assertEqual(result.probability, 0.00)

  def testLangsIdentification(self):
    detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
    sample = ("This piece of text is in English. Този текст е на " "Български.")
    results = detector.FindTopNMostFreqLangs(text=sample, num_langs=2)
    self.assertEqual(results[0].language, "bg")
    self.assertTrue(results[0].is_reliable)
    self.assertLess(results[0].proportion, 0.75)
    self.assertGreater(results[0].probability, 0.90)
    self.assertEqual(results[1].language, "en")
    self.assertTrue(results[1].is_reliable)
    self.assertLess(results[1].proportion, 0.75)
    self.assertGreater(results[1].probability, 0.90)

if __name__ == "__main__":
  unittest.main()
 <INSERT_END> <|endoftext|> """Tests for gcld3."""

import gcld3
import unittest

class NnetLanguageIdentifierTest(unittest.TestCase):

  def testLangIdentification(self):
    detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
    sample = "This text is written in English."
    result = detector.FindLanguage(text=sample)
    self.assertEqual(result.language, "en")
    self.assertTrue(result.is_reliable)
    self.assertGreater(result.proportion, 0.99)
    self.assertGreater(result.probability, 0.90)

  def testEmptyString(self):
    detector = gcld3.NNetLanguageIdentifier(
        min_num_bytes=10, max_num_bytes=1000)
    sample = ""
    result = detector.FindLanguage(text=sample)
    self.assertEqual(result.language, "und")
    self.assertFalse(result.is_reliable)
    self.assertEqual(result.proportion, 0.0)
    self.assertEqual(result.probability, 0.00)

  def testLangsIdentification(self):
    detector = gcld3.NNetLanguageIdentifier(min_num_bytes=0, max_num_bytes=1000)
    sample = ("This piece of text is in English. Този текст е на " "Български.")
    results = detector.FindTopNMostFreqLangs(text=sample, num_langs=2)
    self.assertEqual(results[0].language, "bg")
    self.assertTrue(results[0].is_reliable)
    self.assertLess(results[0].proportion, 0.75)
    self.assertGreater(results[0].probability, 0.90)
    self.assertEqual(results[1].language, "en")
    self.assertTrue(results[1].is_reliable)
    self.assertLess(results[1].proportion, 0.75)
    self.assertGreater(results[1].probability, 0.90)

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

Prompt: Add a python unit test


"""Test IAM Policies for correctness."""
import json

from foremast.iam.construct_policy import construct_policy

ANSWER1 = {
    'Version': '2012-10-17',
    'Statement': [
        {
            'Effect': 'Allow',
            'Action': [
                's3:GetObject',
                's3:ListObject'
            ],
            'Resource': [
                'arn:aws:s3:::archaius-stage/forrest/unicornforrest',
                'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*'
            ]
        }
    ]
}

def test_main():
    """Check general assemblage."""
    settings = {'services': {'s3': True}}
    policy_json = construct_policy(app='unicornforrest',
                                   env='stage',
                                   group='forrest',
                                   pipeline_settings=settings)

    assert json.loads(policy_json) == ANSWER1

    # TODO: Test other services besides S3
    settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest',
                                               'attendantdevops']}})
    policy_json = construct_policy(pipeline_settings=settings)
    policy = json.loads(policy_json)

Add TODO for more IAM Policy testing

Response:
<INSERT> # TODO: Test other services besides S3
    <INSERT_END> <|endoftext|> """Test IAM Policies for correctness."""
import json

from foremast.iam.construct_policy import construct_policy

ANSWER1 = {
    'Version': '2012-10-17',
    'Statement': [
        {
            'Effect': 'Allow',
            'Action': [
                's3:GetObject',
                's3:ListObject'
            ],
            'Resource': [
                'arn:aws:s3:::archaius-stage/forrest/unicornforrest',
                'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*'
            ]
        }
    ]
}

def test_main():
    """Check general assemblage."""
    settings = {'services': {'s3': True}}
    policy_json = construct_policy(app='unicornforrest',
                                   env='stage',
                                   group='forrest',
                                   pipeline_settings=settings)

    assert json.loads(policy_json) == ANSWER1

    # TODO: Test other services besides S3
    settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest',
                                               'attendantdevops']}})
    policy_json = construct_policy(pipeline_settings=settings)
    policy = json.loads(policy_json)

Prompt:
chore: Add TODO for more IAM Policy testing

See also: PSOBAT-1482

"""Test IAM Policies for correctness."""
import json

from foremast.iam.construct_policy import construct_policy

ANSWER1 = {
    'Version': '2012-10-17',
    'Statement': [
        {
            'Effect': 'Allow',
            'Action': [
                's3:GetObject',
                's3:ListObject'
            ],
            'Resource': [
                'arn:aws:s3:::archaius-stage/forrest/unicornforrest',
                'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*'
            ]
        }
    ]
}

def test_main():
    """Check general assemblage."""
    settings = {'services': {'s3': True}}
    policy_json = construct_policy(app='unicornforrest',
                                   env='stage',
                                   group='forrest',
                                   pipeline_settings=settings)

    assert json.loads(policy_json) == ANSWER1

    settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest',
                                               'attendantdevops']}})
    policy_json = construct_policy(pipeline_settings=settings)
    policy = json.loads(policy_json)


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

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

# Create your tests here.

Add imports to imager_images test

Add imports to imager_images test

Response:
<INSERT> __future__ import unicode_literals
from django.contrib.auth.models import User
from <INSERT_END> <REPLACE_OLD> TestCase

# <REPLACE_NEW> TestCase
import factory
from faker import Faker

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

# <REPLACE_END> <|endoftext|> from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker

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

# Create your tests here.

Prompt:
Add imports to imager_images test

from django.test import TestCase

# Create your tests here.


'''
Create a cube that is spatially-matched and convolved to the IRAM 30-m
CO(2-1) cube.
'''

import os
from os.path import join as osjoin

from cube_analysis.reprojection import reproject_cube
from cube_analysis.run_pipe import run_pipeline

from paths import (seventeenB_HI_data_1kms_wGBT_path,
                   seventeenB_1kms_wGBT_HI_file_dict, iram_co21_data_path)

out_folder = seventeenB_HI_data_1kms_wGBT_path("iram_co21_match",
                                               no_check=True)

if not os.path.exists(out_folder):
    os.mkdir(out_folder)

out_name = seventeenB_1kms_wGBT_HI_file_dict['Cube'].split("/")[-1].rstrip(".fits") + \
    ".iram30m_spatialmatch.fits"

reproject_cube(seventeenB_1kms_wGBT_HI_file_dict['Cube'],
               iram_co21_data_path("m33.co21_iram.fits"),
               out_name,
               output_folder=out_folder,
               save_spectral=False,
               is_huge=True,
               reproject_type='spatial',
               common_beam=True,
               verbose=True,
               chunk=40)

run_pipeline(osjoin(out_folder, out_name),
             out_folder,
             masking_kwargs={"method": "ppv_connectivity",
                             "save_cube": True,
                             "is_huge": True,
                             "smooth_chans": 6,
                             "min_chan": 4,
                             "peak_snr": 4.,
                             "min_snr": 2,
                             "edge_thresh": 1,
                             "verbose": True,
                             },
             moment_kwargs={"num_cores": 1,
                            "verbose": False,
                            "chunk_size": 1e5,
                            "make_peakvels": False},)

Make a 17B HI cube matched to the 30-m IRAM cube

Response:
<REPLACE_OLD>  <REPLACE_NEW>
'''
Create a cube that is spatially-matched and convolved to the IRAM 30-m
CO(2-1) cube.
'''

import os
from os.path import join as osjoin

from cube_analysis.reprojection import reproject_cube
from cube_analysis.run_pipe import run_pipeline

from paths import (seventeenB_HI_data_1kms_wGBT_path,
                   seventeenB_1kms_wGBT_HI_file_dict, iram_co21_data_path)

out_folder = seventeenB_HI_data_1kms_wGBT_path("iram_co21_match",
                                               no_check=True)

if not os.path.exists(out_folder):
    os.mkdir(out_folder)

out_name = seventeenB_1kms_wGBT_HI_file_dict['Cube'].split("/")[-1].rstrip(".fits") + \
    ".iram30m_spatialmatch.fits"

reproject_cube(seventeenB_1kms_wGBT_HI_file_dict['Cube'],
               iram_co21_data_path("m33.co21_iram.fits"),
               out_name,
               output_folder=out_folder,
               save_spectral=False,
               is_huge=True,
               reproject_type='spatial',
               common_beam=True,
               verbose=True,
               chunk=40)

run_pipeline(osjoin(out_folder, out_name),
             out_folder,
             masking_kwargs={"method": "ppv_connectivity",
                             "save_cube": True,
                             "is_huge": True,
                             "smooth_chans": 6,
                             "min_chan": 4,
                             "peak_snr": 4.,
                             "min_snr": 2,
                             "edge_thresh": 1,
                             "verbose": True,
                             },
             moment_kwargs={"num_cores": 1,
                            "verbose": False,
                            "chunk_size": 1e5,
                            "make_peakvels": False},)
 <REPLACE_END> <|endoftext|>
'''
Create a cube that is spatially-matched and convolved to the IRAM 30-m
CO(2-1) cube.
'''

import os
from os.path import join as osjoin

from cube_analysis.reprojection import reproject_cube
from cube_analysis.run_pipe import run_pipeline

from paths import (seventeenB_HI_data_1kms_wGBT_path,
                   seventeenB_1kms_wGBT_HI_file_dict, iram_co21_data_path)

out_folder = seventeenB_HI_data_1kms_wGBT_path("iram_co21_match",
                                               no_check=True)

if not os.path.exists(out_folder):
    os.mkdir(out_folder)

out_name = seventeenB_1kms_wGBT_HI_file_dict['Cube'].split("/")[-1].rstrip(".fits") + \
    ".iram30m_spatialmatch.fits"

reproject_cube(seventeenB_1kms_wGBT_HI_file_dict['Cube'],
               iram_co21_data_path("m33.co21_iram.fits"),
               out_name,
               output_folder=out_folder,
               save_spectral=False,
               is_huge=True,
               reproject_type='spatial',
               common_beam=True,
               verbose=True,
               chunk=40)

run_pipeline(osjoin(out_folder, out_name),
             out_folder,
             masking_kwargs={"method": "ppv_connectivity",
                             "save_cube": True,
                             "is_huge": True,
                             "smooth_chans": 6,
                             "min_chan": 4,
                             "peak_snr": 4.,
                             "min_snr": 2,
                             "edge_thresh": 1,
                             "verbose": True,
                             },
             moment_kwargs={"num_cores": 1,
                            "verbose": False,
                            "chunk_size": 1e5,
                            "make_peakvels": False},)

Prompt: Make a 17B HI cube matched to the 30-m IRAM cube


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015  Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.

"""
import rospy
from sensor_msgs.msg import Image

class ImageFeature(object):
    """
    A ROS image Publisher/Subscriber.

    """
    def __init__(self):
        self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
                                                 Image, self.frame_callback,
                                                 queue_size=1)
        self.image_publisher = rospy.Publisher("/output/slow_image_raw",
                                               Image, queue_size=1)
        rospy.logdebug("Subscribed to /ardrone/image_raw")
        self.count = 0

    def frame_callback(self, frame):
        """
        Callback function of subscribed topic.

        """
        # Publish every fifteenth frame
        if not self.count % 15:
            self.image_publisher.publish(frame)
        self.count += 1

def main():
    """Initialize ROS node."""
    rospy.init_node("framerate_reducer", anonymous=True)
    ImageFeature()
    rospy.loginfo("Reducing framerate")
    rospy.spin()

if __name__ == "__main__":
    main()

Response:
<REPLACE_OLD> self.image_callback,
 <REPLACE_NEW> self.frame_callback,
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015  Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.

"""
import rospy
from sensor_msgs.msg import Image

class ImageFeature(object):
    """
    A ROS image Publisher/Subscriber.

    """
    def __init__(self):
        self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
                                                 Image, self.frame_callback,
                                                 queue_size=1)
        self.image_publisher = rospy.Publisher("/output/slow_image_raw",
                                               Image, queue_size=1)
        rospy.logdebug("Subscribed to /ardrone/image_raw")
        self.count = 0

    def frame_callback(self, frame):
        """
        Callback function of subscribed topic.

        """
        # Publish every fifteenth frame
        if not self.count % 15:
            self.image_publisher.publish(frame)
        self.count += 1

def main():
    """Initialize ROS node."""
    rospy.init_node("framerate_reducer", anonymous=True)
    ImageFeature()
    rospy.loginfo("Reducing framerate")
    rospy.spin()

if __name__ == "__main__":
    main()

Prompt:
Fix mistaken reference to image_callback.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015  Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.

"""
import rospy
from sensor_msgs.msg import Image

class ImageFeature(object):
    """
    A ROS image Publisher/Subscriber.

    """
    def __init__(self):
        self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
                                                 Image, self.image_callback,
                                                 queue_size=1)
        self.image_publisher = rospy.Publisher("/output/slow_image_raw",
                                               Image, queue_size=1)
        rospy.logdebug("Subscribed to /ardrone/image_raw")
        self.count = 0

    def frame_callback(self, frame):
        """
        Callback function of subscribed topic.

        """
        # Publish every fifteenth frame
        if not self.count % 15:
            self.image_publisher.publish(frame)
        self.count += 1

def main():
    """Initialize ROS node."""
    rospy.init_node("framerate_reducer", anonymous=True)
    ImageFeature()
    rospy.loginfo("Reducing framerate")
    rospy.spin()

if __name__ == "__main__":
    main()


# coding: utf-8
"""
Unit tests for essential functions in postgresql backup.
"""
from unittest.mock import MagicMock, mock_open, patch
import pytest
import smdba.postgresqlgate

class TestPgBackup:
    """
    Test suite for postgresql backup.
    """
    @patch("smdba.postgresqlgate.os.path.exists", MagicMock(return_value=False))
    def test_init_pkbackup_checks_archivecleaup(self):
        """
        Test constructor of pkgbackup pg_archivecleanup installed

        :return:
        """

        with pytest.raises(Exception) as exc:
            smdba.postgresqlgate.PgBackup("/target")
        assert "The utility pg_archivecleanup was not found on the path." in str(exc)

Add unit test suite for PgBackup

Add unit test suite for PgBackup

Response:
<INSERT> # coding: utf-8
"""
Unit tests for essential functions in postgresql backup.
"""
from unittest.mock import MagicMock, mock_open, patch
import pytest
import smdba.postgresqlgate

class TestPgBackup:
 <INSERT_END> <INSERT>   """
    Test suite for postgresql backup.
    """
    @patch("smdba.postgresqlgate.os.path.exists", MagicMock(return_value=False))
    def test_init_pkbackup_checks_archivecleaup(self):
        """
        Test constructor of pkgbackup pg_archivecleanup installed

        :return:
        """

        with pytest.raises(Exception) as exc:
            smdba.postgresqlgate.PgBackup("/target")
        assert "The utility pg_archivecleanup was not found on the path." in str(exc)
 <INSERT_END> <|endoftext|> # coding: utf-8
"""
Unit tests for essential functions in postgresql backup.
"""
from unittest.mock import MagicMock, mock_open, patch
import pytest
import smdba.postgresqlgate

class TestPgBackup:
    """
    Test suite for postgresql backup.
    """
    @patch("smdba.postgresqlgate.os.path.exists", MagicMock(return_value=False))
    def test_init_pkbackup_checks_archivecleaup(self):
        """
        Test constructor of pkgbackup pg_archivecleanup installed

        :return:
        """

        with pytest.raises(Exception) as exc:
            smdba.postgresqlgate.PgBackup("/target")
        assert "The utility pg_archivecleanup was not found on the path." in str(exc)

Prompt: Add unit test suite for PgBackup


import sys

IS_PY3K = False

try:
    if sys.version_info[0] >= 3:
        IS_PY3K = True
except AttributeError:
    pass  #Not all versions have sys.version_info

if IS_PY3K:
    # noinspection PyUnresolvedReferences
    from thriftpy3 import TSerialization
    # noinspection PyUnresolvedReferences
    from thriftpy3.protocol import TBinaryProtocol
    # noinspection PyUnresolvedReferences
    from profilerpy3.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
else:
    # noinspection PyUnresolvedReferences
    from thrift import TSerialization
    # noinspection PyUnresolvedReferences
    from thrift.protocol import TBinaryProtocol
    # noinspection PyUnresolvedReferences
    from profiler.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function

Response:
<DELETE> TJSONProtocol, <DELETE_END> <DELETE> TJSONProtocol, <DELETE_END> <|endoftext|> import sys

IS_PY3K = False

try:
    if sys.version_info[0] >= 3:
        IS_PY3K = True
except AttributeError:
    pass  #Not all versions have sys.version_info

if IS_PY3K:
    # noinspection PyUnresolvedReferences
    from thriftpy3 import TSerialization
    # noinspection PyUnresolvedReferences
    from thriftpy3.protocol import TBinaryProtocol
    # noinspection PyUnresolvedReferences
    from profilerpy3.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
else:
    # noinspection PyUnresolvedReferences
    from thrift import TSerialization
    # noinspection PyUnresolvedReferences
    from thrift.protocol import TBinaryProtocol
    # noinspection PyUnresolvedReferences
    from profiler.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function

Prompt:
Remove JSON serialization usages (PY-16388, PY-16389)

import sys

IS_PY3K = False

try:
    if sys.version_info[0] >= 3:
        IS_PY3K = True
except AttributeError:
    pass  #Not all versions have sys.version_info

if IS_PY3K:
    # noinspection PyUnresolvedReferences
    from thriftpy3 import TSerialization
    # noinspection PyUnresolvedReferences
    from thriftpy3.protocol import TJSONProtocol, TBinaryProtocol
    # noinspection PyUnresolvedReferences
    from profilerpy3.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
else:
    # noinspection PyUnresolvedReferences
    from thrift import TSerialization
    # noinspection PyUnresolvedReferences
    from thrift.protocol import TJSONProtocol, TBinaryProtocol
    # noinspection PyUnresolvedReferences
    from profiler.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function


#!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Upgrade a bot via apt-get, then reboot. Aborts on error."""

import subprocess

# Copied from
# https://skia.googlesource.com/buildbot/+/d864d83d992f2968cf4d229cebf2d3104ee11ebf/go/gce/swarming/base-image/setup-script.sh#20
base_cmd = ['sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt',
            '-o', 'quiet=2', '--assume-yes',
            '-o', 'Dpkg::Options::=--force-confdef',
            '-o', 'Dpkg::Options::=--force-confold']

subprocess.check_call(base_cmd + ['update'])
subprocess.check_call(base_cmd + ['full-upgrade'])
subprocess.check_call(base_cmd + ['autoremove'])

subprocess.check_call(['sudo', 'reboot'])

Add script to upgrade Debian/Ubuntu bots.

Bug: skia:6890
Change-Id: I30eea5d64c502ac7ef51cf2d8f6ef3c583e60b3e
Reviewed-on: https://skia-review.googlesource.com/28840
Commit-Queue: Ben Wagner <3ef7217be91069877d94f7907ce5479000772cd3@google.com>
Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com>

Response:
<INSERT> #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Upgrade a bot via apt-get, then reboot. Aborts on error."""

import subprocess

# Copied from
# https://skia.googlesource.com/buildbot/+/d864d83d992f2968cf4d229cebf2d3104ee11ebf/go/gce/swarming/base-image/setup-script.sh#20
base_cmd = ['sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt',
 <INSERT_END> <INSERT>           '-o', 'quiet=2', '--assume-yes',
            '-o', 'Dpkg::Options::=--force-confdef',
            '-o', 'Dpkg::Options::=--force-confold']

subprocess.check_call(base_cmd + ['update'])
subprocess.check_call(base_cmd + ['full-upgrade'])
subprocess.check_call(base_cmd + ['autoremove'])

subprocess.check_call(['sudo', 'reboot'])
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Upgrade a bot via apt-get, then reboot. Aborts on error."""

import subprocess

# Copied from
# https://skia.googlesource.com/buildbot/+/d864d83d992f2968cf4d229cebf2d3104ee11ebf/go/gce/swarming/base-image/setup-script.sh#20
base_cmd = ['sudo', 'DEBIAN_FRONTEND=noninteractive', 'apt',
            '-o', 'quiet=2', '--assume-yes',
            '-o', 'Dpkg::Options::=--force-confdef',
            '-o', 'Dpkg::Options::=--force-confold']

subprocess.check_call(base_cmd + ['update'])
subprocess.check_call(base_cmd + ['full-upgrade'])
subprocess.check_call(base_cmd + ['autoremove'])

subprocess.check_call(['sudo', 'reboot'])

Prompt:
Add script to upgrade Debian/Ubuntu bots.

Bug: skia:6890
Change-Id: I30eea5d64c502ac7ef51cf2d8f6ef3c583e60b3e
Reviewed-on: https://skia-review.googlesource.com/28840
Commit-Queue: Ben Wagner <3ef7217be91069877d94f7907ce5479000772cd3@google.com>
Reviewed-by: Eric Boren <0e499112533c8544f0505ea0d08394fb5ad7d8fa@google.com>


#!/usr/bin/env python3
# encoding: utf-8

from setuptools import setup, find_packages

setup(
    name='pyatv',
    version='0.1.5.dev1',
    license='MIT',
    url='https://github.com/postlund/pyatv',
    author='Pierre Ståhl',
    author_email='pierre.staahl@gmail.com',
    description='Library for controlling an Apple TV',
    packages=find_packages(exclude=['tests', 'tests.*']),
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=[
        'aiohttp==1.3.1',
        'zeroconf==0.18.0',
    ],
    test_suite='tests',
    keywords=['apple', 'tv'],
    tests_require=['tox'],
    entry_points={
        'console_scripts': [
            'atvremote = pyatv.__main__:main'
        ]
    },
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Libraries',
        'Topic :: Home Automation',
    ],
)

Bump to next dev 0.1.5.dev1

Bump to next dev 0.1.5.dev1

Response:
<REPLACE_OLD> version='0.1.4',
 <REPLACE_NEW> version='0.1.5.dev1',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
# encoding: utf-8

from setuptools import setup, find_packages

setup(
    name='pyatv',
    version='0.1.5.dev1',
    license='MIT',
    url='https://github.com/postlund/pyatv',
    author='Pierre Ståhl',
    author_email='pierre.staahl@gmail.com',
    description='Library for controlling an Apple TV',
    packages=find_packages(exclude=['tests', 'tests.*']),
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=[
        'aiohttp==1.3.1',
        'zeroconf==0.18.0',
    ],
    test_suite='tests',
    keywords=['apple', 'tv'],
    tests_require=['tox'],
    entry_points={
        'console_scripts': [
            'atvremote = pyatv.__main__:main'
        ]
    },
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Libraries',
        'Topic :: Home Automation',
    ],
)

Prompt:
Bump to next dev 0.1.5.dev1

#!/usr/bin/env python3
# encoding: utf-8

from setuptools import setup, find_packages

setup(
    name='pyatv',
    version='0.1.4',
    license='MIT',
    url='https://github.com/postlund/pyatv',
    author='Pierre Ståhl',
    author_email='pierre.staahl@gmail.com',
    description='Library for controlling an Apple TV',
    packages=find_packages(exclude=['tests', 'tests.*']),
    include_package_data=True,
    zip_safe=False,
    platforms='any',
    install_requires=[
        'aiohttp==1.3.1',
        'zeroconf==0.18.0',
    ],
    test_suite='tests',
    keywords=['apple', 'tv'],
    tests_require=['tox'],
    entry_points={
        'console_scripts': [
            'atvremote = pyatv.__main__:main'
        ]
    },
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Libraries',
        'Topic :: Home Automation',
    ],
)


#!/usr/bin/env python
import sys
import os
from coverage import coverage
from optparse import OptionParser

# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner  # noqa: E402

def run_tests(*test_args):
    if not test_args:
        test_args = ['tests']

    # Add Open edX common and LMS Django apps to PYTHONPATH
    sys.path.append(os.path.join(os.path.dirname(__file__),
                                 'edx-platform'))
    for directory in ['common', 'lms']:
        sys.path.append(os.path.join(os.path.dirname(__file__),
                                     'edx-platform',
                                     directory,
                                     'djangoapps'))
    for lib in ['xmodule', 'dogstats', 'capa', 'calc', 'chem']:
        sys.path.append(os.path.join(os.path.dirname(__file__),
                                     'edx-platform',
                                     'common',
                                     'lib',
                                     lib))

    # Run tests
    test_runner = NoseTestSuiteRunner(verbosity=1)

    c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
                 auto_data=True)
    c.start()
    num_failures = test_runner.run_tests(test_args)
    c.stop()

    if num_failures > 0:
        sys.exit(num_failures)

if __name__ == '__main__':
    parser = OptionParser()
    (options, args) = parser.parse_args()
    run_tests(*args)

Response:
<INSERT> Add Open edX common and LMS Django apps to PYTHONPATH
    sys.path.append(os.path.join(os.path.dirname(__file__),
                                 'edx-platform'))
    for directory in ['common', 'lms']:
        sys.path.append(os.path.join(os.path.dirname(__file__),
                                     'edx-platform',
                                     directory,
                                     'djangoapps'))
    for lib in ['xmodule', 'dogstats', 'capa', 'calc', 'chem']:
        sys.path.append(os.path.join(os.path.dirname(__file__),
                                     'edx-platform',
                                     'common',
                                     'lib',
                                     lib))

    # <INSERT_END> <|endoftext|> #!/usr/bin/env python
import sys
import os
from coverage import coverage
from optparse import OptionParser

# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner  # noqa: E402

def run_tests(*test_args):
    if not test_args:
        test_args = ['tests']

    # Add Open edX common and LMS Django apps to PYTHONPATH
    sys.path.append(os.path.join(os.path.dirname(__file__),
                                 'edx-platform'))
    for directory in ['common', 'lms']:
        sys.path.append(os.path.join(os.path.dirname(__file__),
                                     'edx-platform',
                                     directory,
                                     'djangoapps'))
    for lib in ['xmodule', 'dogstats', 'capa', 'calc', 'chem']:
        sys.path.append(os.path.join(os.path.dirname(__file__),
                                     'edx-platform',
                                     'common',
                                     'lib',
                                     lib))

    # Run tests
    test_runner = NoseTestSuiteRunner(verbosity=1)

    c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
                 auto_data=True)
    c.start()
    num_failures = test_runner.run_tests(test_args)
    c.stop()

    if num_failures > 0:
        sys.exit(num_failures)

if __name__ == '__main__':
    parser = OptionParser()
    (options, args) = parser.parse_args()
    run_tests(*args)

Prompt:
Extend sys.path with required paths from edx-platform submodule

#!/usr/bin/env python
import sys
import os
from coverage import coverage
from optparse import OptionParser

# This envar must be set before importing NoseTestSuiteRunner,
# silence flake8 E402 ("module level import not at top of file").
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
from django_nose import NoseTestSuiteRunner  # noqa: E402

def run_tests(*test_args):
    if not test_args:
        test_args = ['tests']

    # Run tests
    test_runner = NoseTestSuiteRunner(verbosity=1)

    c = coverage(source=['edx_shopify'], omit=['*migrations*', '*tests*'],
                 auto_data=True)
    c.start()
    num_failures = test_runner.run_tests(test_args)
    c.stop()

    if num_failures > 0:
        sys.exit(num_failures)

if __name__ == '__main__':
    parser = OptionParser()
    (options, args) = parser.parse_args()
    run_tests(*args)


from django import template
from copy import copy
from molo.yourwords.models import (YourWordsCompetition, ThankYou,
                                   YourWordsCompetitionIndexPage)
from molo.core.core_tags import get_pages

register = template.Library()

@register.inclusion_tag(
    'yourwords/your_words_competition_tag.html',
    takes_context=True
)
def your_words_competition(context):
    context = copy(context)
    locale_code = context.get('locale_code')
    page = YourWordsCompetitionIndexPage.objects.live().all().first()
    if page:
        competitions = (
            YourWordsCompetition.objects.child_of(page).filter(
                languages__language__is_main_language=True).specific())
    else:
        competitions = []

    context.update({
        'competitions': get_pages(context, competitions, locale_code)
    })
    return context

@register.assignment_tag(takes_context=True)
def load_thank_you_page_for_competition(context, competition):

    page = competition.get_main_language_page()
    locale = context.get('locale_code')

    qs = ThankYou.objects.child_of(page).filter(
        languages__language__is_main_language=True)

    if not locale:
        return qs

    if qs:
        return get_pages(context, qs, locale)
    else:
        return []

Response:
<REPLACE_OLD> YourWordsCompetitionIndexPage)

register <REPLACE_NEW> YourWordsCompetitionIndexPage)
from molo.core.core_tags import get_pages

register <REPLACE_END> <REPLACE_OLD> YourWordsCompetition.objects.live().child_of(page).filter(
 <REPLACE_NEW> YourWordsCompetition.objects.child_of(page).filter(
 <REPLACE_END> <REPLACE_OLD> [
            a.get_translation_for(locale_code) or a for a in competitions]
 <REPLACE_NEW> get_pages(context, competitions, locale_code)
 <REPLACE_END> <REPLACE_OLD> ThankYou.objects.live().child_of(page).filter(
 <REPLACE_NEW> ThankYou.objects.child_of(page).filter(
 <REPLACE_END> <REPLACE_OLD> [a.get_translation_for(locale) or a for a in qs]
 <REPLACE_NEW> get_pages(context, qs, locale)
 <REPLACE_END> <|endoftext|> from django import template
from copy import copy
from molo.yourwords.models import (YourWordsCompetition, ThankYou,
                                   YourWordsCompetitionIndexPage)
from molo.core.core_tags import get_pages

register = template.Library()

@register.inclusion_tag(
    'yourwords/your_words_competition_tag.html',
    takes_context=True
)
def your_words_competition(context):
    context = copy(context)
    locale_code = context.get('locale_code')
    page = YourWordsCompetitionIndexPage.objects.live().all().first()
    if page:
        competitions = (
            YourWordsCompetition.objects.child_of(page).filter(
                languages__language__is_main_language=True).specific())
    else:
        competitions = []

    context.update({
        'competitions': get_pages(context, competitions, locale_code)
    })
    return context

@register.assignment_tag(takes_context=True)
def load_thank_you_page_for_competition(context, competition):

    page = competition.get_main_language_page()
    locale = context.get('locale_code')

    qs = ThankYou.objects.child_of(page).filter(
        languages__language__is_main_language=True)

    if not locale:
        return qs

    if qs:
        return get_pages(context, qs, locale)
    else:
        return []

Prompt:
Add support for hiding untranslated content

from django import template
from copy import copy
from molo.yourwords.models import (YourWordsCompetition, ThankYou,
                                   YourWordsCompetitionIndexPage)

register = template.Library()

@register.inclusion_tag(
    'yourwords/your_words_competition_tag.html',
    takes_context=True
)
def your_words_competition(context):
    context = copy(context)
    locale_code = context.get('locale_code')
    page = YourWordsCompetitionIndexPage.objects.live().all().first()
    if page:
        competitions = (
            YourWordsCompetition.objects.live().child_of(page).filter(
                languages__language__is_main_language=True).specific())
    else:
        competitions = []

    context.update({
        'competitions': [
            a.get_translation_for(locale_code) or a for a in competitions]
    })
    return context

@register.assignment_tag(takes_context=True)
def load_thank_you_page_for_competition(context, competition):

    page = competition.get_main_language_page()
    locale = context.get('locale_code')

    qs = ThankYou.objects.live().child_of(page).filter(
        languages__language__is_main_language=True)

    if not locale:
        return qs

    if qs:
        return [a.get_translation_for(locale) or a for a in qs]
    else:
        return []


"""Utils module."""

from six import class_types

from .errors import Error

def is_provider(instance):
    """Check if instance is provider instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_PROVIDER__'))

def ensure_is_provider(instance):
    """Check if instance is provider instance, otherwise raise and error."""
    if not is_provider(instance):
        raise Error('Expected provider instance, '
                    'got {0}'.format(str(instance)))
    return instance

def is_injection(instance):
    """Check if instance is injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_INJECTION__'))

def is_init_arg_injection(instance):
    """Check if instance is init arg injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_INIT_ARG_INJECTION__'))

def is_attribute_injection(instance):
    """Check if instance is attribute injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_ATTRIBUTE_INJECTION__'))

def is_method_injection(instance):
    """Check if instance is method injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_METHOD_INJECTION__'))

Response:
<REPLACE_OLD> inspect <REPLACE_NEW> six <REPLACE_END> <REPLACE_OLD> isclass

from <REPLACE_NEW> class_types

from <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <REPLACE_OLD> isclass(instance) <REPLACE_NEW> isinstance(instance, class_types) <REPLACE_END> <|endoftext|> """Utils module."""

from six import class_types

from .errors import Error

def is_provider(instance):
    """Check if instance is provider instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_PROVIDER__'))

def ensure_is_provider(instance):
    """Check if instance is provider instance, otherwise raise and error."""
    if not is_provider(instance):
        raise Error('Expected provider instance, '
                    'got {0}'.format(str(instance)))
    return instance

def is_injection(instance):
    """Check if instance is injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_INJECTION__'))

def is_init_arg_injection(instance):
    """Check if instance is init arg injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_INIT_ARG_INJECTION__'))

def is_attribute_injection(instance):
    """Check if instance is attribute injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_ATTRIBUTE_INJECTION__'))

def is_method_injection(instance):
    """Check if instance is method injection instance."""
    return (not isinstance(instance, class_types) and
            hasattr(instance, '__IS_OBJECTS_METHOD_INJECTION__'))

Prompt:
Fix of bug in Python 2.6 with failed isclass check in inspect module

"""Utils module."""

from inspect import isclass

from .errors import Error

def is_provider(instance):
    """Check if instance is provider instance."""
    return (not isclass(instance) and
            hasattr(instance, '__IS_OBJECTS_PROVIDER__'))

def ensure_is_provider(instance):
    """Check if instance is provider instance, otherwise raise and error."""
    if not is_provider(instance):
        raise Error('Expected provider instance, '
                    'got {0}'.format(str(instance)))
    return instance

def is_injection(instance):
    """Check if instance is injection instance."""
    return (not isclass(instance) and
            hasattr(instance, '__IS_OBJECTS_INJECTION__'))

def is_init_arg_injection(instance):
    """Check if instance is init arg injection instance."""
    return (not isclass(instance) and
            hasattr(instance, '__IS_OBJECTS_INIT_ARG_INJECTION__'))

def is_attribute_injection(instance):
    """Check if instance is attribute injection instance."""
    return (not isclass(instance) and
            hasattr(instance, '__IS_OBJECTS_ATTRIBUTE_INJECTION__'))

def is_method_injection(instance):
    """Check if instance is method injection instance."""
    return (not isclass(instance) and
            hasattr(instance, '__IS_OBJECTS_METHOD_INJECTION__'))


from unittest import TestCase

from dusty.preflight import _assert_executable_exists, PreflightException

class PreflightTest(TestCase):
    def test_assert_executable_exists(self):
        _assert_executable_exists('python')

    def test_assert_executable_exists_fails(self):
        with self.assertRaises(PreflightException):
            _assert_executable_exists('somecrazythingwhichforsuredoesnotexist')

Add tests for assert executable

Add tests for assert executable

Response:
<INSERT> from unittest import TestCase

from dusty.preflight import _assert_executable_exists, PreflightException

class PreflightTest(TestCase):
 <INSERT_END> <INSERT>   def test_assert_executable_exists(self):
        _assert_executable_exists('python')

    def test_assert_executable_exists_fails(self):
        with self.assertRaises(PreflightException):
            _assert_executable_exists('somecrazythingwhichforsuredoesnotexist')
 <INSERT_END> <|endoftext|> from unittest import TestCase

from dusty.preflight import _assert_executable_exists, PreflightException

class PreflightTest(TestCase):
    def test_assert_executable_exists(self):
        _assert_executable_exists('python')

    def test_assert_executable_exists_fails(self):
        with self.assertRaises(PreflightException):
            _assert_executable_exists('somecrazythingwhichforsuredoesnotexist')

Prompt: Add tests for assert executable


from os import mkdir
from os.path import join
from shutil import rmtree, copytree

from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish

# Until we move to spec-based testing
@task
def test(ctx, coverage=False, flags=""):
    if "--verbose" not in flags.split():
        flags += " --verbose"
    runner = "python"
    if coverage:
        runner = "coverage run --source=paramiko"
    ctx.run("{0} test.py {1}".format(runner, flags), pty=True)

@task
def coverage(ctx):
    ctx.run("coverage run --source=paramiko test.py --verbose")

# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
    # Build docs first. Use terribad workaround pending invoke #146
    ctx.run("inv docs")
    # Move the built docs into where Epydocs used to live
    target = 'docs'
    rmtree(target, ignore_errors=True)
    # TODO: make it easier to yank out this config val from the docs coll
    copytree('sites/docs/_build', target)
    # Publish
    publish(ctx)
    # Remind
    print("\n\nDon't forget to update RTD's versions page for new minor releases!")

ns = Collection(test, coverage, release, docs, www)

Response:
<REPLACE_OLD> test(ctx):
    ctx.run("python <REPLACE_NEW> test(ctx, coverage=False, flags=""):
    if "--verbose" not in flags.split():
        flags += " --verbose"
    runner = "python"
    if coverage:
        runner = "coverage run --source=paramiko"
    ctx.run("{0} <REPLACE_END> <REPLACE_OLD> --verbose", pty=True)

@task
def <REPLACE_NEW> {1}".format(runner, flags), pty=True)

@task
def <REPLACE_END> <|endoftext|> from os import mkdir
from os.path import join
from shutil import rmtree, copytree

from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish

# Until we move to spec-based testing
@task
def test(ctx, coverage=False, flags=""):
    if "--verbose" not in flags.split():
        flags += " --verbose"
    runner = "python"
    if coverage:
        runner = "coverage run --source=paramiko"
    ctx.run("{0} test.py {1}".format(runner, flags), pty=True)

@task
def coverage(ctx):
    ctx.run("coverage run --source=paramiko test.py --verbose")

# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
    # Build docs first. Use terribad workaround pending invoke #146
    ctx.run("inv docs")
    # Move the built docs into where Epydocs used to live
    target = 'docs'
    rmtree(target, ignore_errors=True)
    # TODO: make it easier to yank out this config val from the docs coll
    copytree('sites/docs/_build', target)
    # Publish
    publish(ctx)
    # Remind
    print("\n\nDon't forget to update RTD's versions page for new minor releases!")

ns = Collection(test, coverage, release, docs, www)

Prompt:
Allow specifying test.py flags in 'inv test'

from os import mkdir
from os.path import join
from shutil import rmtree, copytree

from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish

# Until we move to spec-based testing
@task
def test(ctx):
    ctx.run("python test.py --verbose", pty=True)

@task
def coverage(ctx):
    ctx.run("coverage run --source=paramiko test.py --verbose")

# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
    # Build docs first. Use terribad workaround pending invoke #146
    ctx.run("inv docs")
    # Move the built docs into where Epydocs used to live
    target = 'docs'
    rmtree(target, ignore_errors=True)
    # TODO: make it easier to yank out this config val from the docs coll
    copytree('sites/docs/_build', target)
    # Publish
    publish(ctx)
    # Remind
    print("\n\nDon't forget to update RTD's versions page for new minor releases!")

ns = Collection(test, coverage, release, docs, www)


from .. utils import TranspileTestCase, BuiltinFunctionTestCase

class ListTests(TranspileTestCase):
    pass

class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
    functions = ["list"]

    not_implemented = [
        'test_bytearray',
        'test_bytes',
        'test_class',
        'test_complex',
        'test_dict',
        'test_frozenset',
        'test_str',
    ]

Response:
<DELETE>        'test_bool',
 <DELETE_END> <DELETE> 'test_float',
        <DELETE_END> <DELETE>        'test_int',
 <DELETE_END> <|endoftext|> from .. utils import TranspileTestCase, BuiltinFunctionTestCase

class ListTests(TranspileTestCase):
    pass

class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
    functions = ["list"]

    not_implemented = [
        'test_bytearray',
        'test_bytes',
        'test_class',
        'test_complex',
        'test_dict',
        'test_frozenset',
        'test_str',
    ]

Prompt:
Mark some builtin list() tests as passing

- This is due to the earlier fixed TypeError message.

from .. utils import TranspileTestCase, BuiltinFunctionTestCase

class ListTests(TranspileTestCase):
    pass

class BuiltinListFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
    functions = ["list"]

    not_implemented = [
        'test_bool',
        'test_bytearray',
        'test_bytes',
        'test_class',
        'test_complex',
        'test_dict',
        'test_float',
        'test_frozenset',
        'test_int',
        'test_str',
    ]


import os
import urllib2
import json
import sys
from urlparse import urljoin

from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase

class LookupModule(LookupBase):

    def run(self, terms, variables, **kwargs):
        key = terms[0]

        url = os.getenv('VAULT_ADDR')
        if not url:
            raise AnsibleError('VAULT_ADDR environment variable is missing')

        token = os.getenv('VAULT_TOKEN')
        if not token:
            raise AnsibleError('VAULT_TOKEN environment variable is missing')

        request_url = urljoin(url, "v1/%s" % (key))
        try:
            headers = { 'X-Vault-Token' : token }
            req = urllib2.Request(request_url, None, headers)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError as e:
            raise AnsibleError('Unable to read %s from vault: %s' % (key, e))
        except:
            raise AnsibleError('Unable to read %s from vault' % key)

        result = json.loads(response.read())

        return [result['data']['value']]

Update plugin for ansible 2.0

Update plugin for ansible 2.0

Response:
<REPLACE_OLD> ansible import utils, errors
from ansible.utils import template

class LookupModule(object):

    def __init__(self, basedir=None, **kwargs):
        self.basedir = basedir

 <REPLACE_NEW> ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase

class LookupModule(LookupBase):

 <REPLACE_END> <REPLACE_OLD> inject=None, **kwargs):

        try:
            terms = template.template(self.basedir, terms, inject)
        except Exception, e:
            pass

 <REPLACE_NEW> variables, **kwargs):
        key = terms[0]

 <REPLACE_END> <REPLACE_OLD> errors.AnsibleError('VAULT_ADDR <REPLACE_NEW> AnsibleError('VAULT_ADDR <REPLACE_END> <REPLACE_OLD> errors.AnsibleError('VAULT_TOKEN <REPLACE_NEW> AnsibleError('VAULT_TOKEN <REPLACE_END> <REPLACE_OLD> (terms))
 <REPLACE_NEW> (key))
 <REPLACE_END> <REPLACE_OLD> errors.AnsibleError('Unable <REPLACE_NEW> AnsibleError('Unable <REPLACE_END> <REPLACE_OLD> (terms, <REPLACE_NEW> (key, <REPLACE_END> <REPLACE_OLD> errors.AnsibleError('Unable <REPLACE_NEW> AnsibleError('Unable <REPLACE_END> <REPLACE_OLD> terms)
 <REPLACE_NEW> key)

 <REPLACE_END> <REPLACE_OLD> json.loads(response.read())
 <REPLACE_NEW> json.loads(response.read())

 <REPLACE_END> <|endoftext|> import os
import urllib2
import json
import sys
from urlparse import urljoin

from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase

class LookupModule(LookupBase):

    def run(self, terms, variables, **kwargs):
        key = terms[0]

        url = os.getenv('VAULT_ADDR')
        if not url:
            raise AnsibleError('VAULT_ADDR environment variable is missing')

        token = os.getenv('VAULT_TOKEN')
        if not token:
            raise AnsibleError('VAULT_TOKEN environment variable is missing')

        request_url = urljoin(url, "v1/%s" % (key))
        try:
            headers = { 'X-Vault-Token' : token }
            req = urllib2.Request(request_url, None, headers)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError as e:
            raise AnsibleError('Unable to read %s from vault: %s' % (key, e))
        except:
            raise AnsibleError('Unable to read %s from vault' % key)

        result = json.loads(response.read())

        return [result['data']['value']]

Prompt:
Update plugin for ansible 2.0

import os
import urllib2
import json
import sys
from urlparse import urljoin

from ansible import utils, errors
from ansible.utils import template

class LookupModule(object):

    def __init__(self, basedir=None, **kwargs):
        self.basedir = basedir

    def run(self, terms, inject=None, **kwargs):

        try:
            terms = template.template(self.basedir, terms, inject)
        except Exception, e:
            pass

        url = os.getenv('VAULT_ADDR')
        if not url:
            raise errors.AnsibleError('VAULT_ADDR environment variable is missing')

        token = os.getenv('VAULT_TOKEN')
        if not token:
            raise errors.AnsibleError('VAULT_TOKEN environment variable is missing')

        request_url = urljoin(url, "v1/%s" % (terms))
        try:
            headers = { 'X-Vault-Token' : token }
            req = urllib2.Request(request_url, None, headers)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError as e:
            raise errors.AnsibleError('Unable to read %s from vault: %s' % (terms, e))
        except:
            raise errors.AnsibleError('Unable to read %s from vault' % terms)
        result = json.loads(response.read())
        return [result['data']['value']]


from ..templates import QuandlFT, QuandlSecureFT, GoogleFinanceFT

class TestTemplates(object):

    def test_quandl_ft(self):
        ftemp = QuandlFT("xxx", trim_start="yyyy-mm-dd", authtoken="yyy")
        assert ftemp.sourcing == {'authtoken': 'yyy',
                                  'trim_start': 'yyyy-mm-dd',
                                  'dataset': 'xxx'}

    def test_quandl_secure_ft(self):
        ftemp = QuandlSecureFT("xxx", trim_start="yyyy-mm-dd")
        assert ftemp.sourcing == {'trim_start': 'yyyy-mm-dd',
                                  'dataset': 'xxx'}
        assert ftemp.meta == {'sourcing_key' : 'userone',
                              'stype' : 'Quandl'}

    def test_google_finance_ft(self):
        ftemp = GoogleFinanceFT("xxx")
        assert ftemp.sourcing == {'name': 'xxx',
                                  'start': '2000-01-01,
                                  'end': 'now',
                                  'data_source' : 'google',
                                  'data_column' : 'Close'}
        assert ftemp.meta == {'stype' : 'PyDataDataReaderST'}

Add two tests for templates

Add two tests for templates

Response:
<REPLACE_OLD> QuandlFT

class <REPLACE_NEW> QuandlFT, QuandlSecureFT, GoogleFinanceFT

class <REPLACE_END> <INSERT> 'xxx'}

    def test_quandl_secure_ft(self):
        ftemp = QuandlSecureFT("xxx", trim_start="yyyy-mm-dd")
        assert ftemp.sourcing == {'trim_start': 'yyyy-mm-dd',
                                  'dataset': <INSERT_END> <INSERT>        assert ftemp.meta == {'sourcing_key' : 'userone',
                              'stype' : 'Quandl'}

    def test_google_finance_ft(self):
        ftemp = GoogleFinanceFT("xxx")
        assert ftemp.sourcing == {'name': 'xxx',
                                  'start': '2000-01-01,
                                  'end': 'now',
                                  'data_source' : 'google',
                                  'data_column' : 'Close'}
        assert ftemp.meta == {'stype' : 'PyDataDataReaderST'}
 <INSERT_END> <|endoftext|>
from ..templates import QuandlFT, QuandlSecureFT, GoogleFinanceFT

class TestTemplates(object):

    def test_quandl_ft(self):
        ftemp = QuandlFT("xxx", trim_start="yyyy-mm-dd", authtoken="yyy")
        assert ftemp.sourcing == {'authtoken': 'yyy',
                                  'trim_start': 'yyyy-mm-dd',
                                  'dataset': 'xxx'}

    def test_quandl_secure_ft(self):
        ftemp = QuandlSecureFT("xxx", trim_start="yyyy-mm-dd")
        assert ftemp.sourcing == {'trim_start': 'yyyy-mm-dd',
                                  'dataset': 'xxx'}
        assert ftemp.meta == {'sourcing_key' : 'userone',
                              'stype' : 'Quandl'}

    def test_google_finance_ft(self):
        ftemp = GoogleFinanceFT("xxx")
        assert ftemp.sourcing == {'name': 'xxx',
                                  'start': '2000-01-01,
                                  'end': 'now',
                                  'data_source' : 'google',
                                  'data_column' : 'Close'}
        assert ftemp.meta == {'stype' : 'PyDataDataReaderST'}

Prompt:
Add two tests for templates

from ..templates import QuandlFT

class TestTemplates(object):

    def test_quandl_ft(self):
        ftemp = QuandlFT("xxx", trim_start="yyyy-mm-dd", authtoken="yyy")
        assert ftemp.sourcing == {'authtoken': 'yyy',
                                  'trim_start': 'yyyy-mm-dd',
                                  'dataset': 'xxx'}