'''Sockets that wrap different connection types'''

# Not all platforms support all types of sockets provided here. For those that
# are not available, the corresponding socket wrapper is imported as None.

from .. import logger

# Snappy support
try:
    from .snappy import SnappySocket
except ImportError:  # pragma: no cover
    logger.debug('Snappy compression not supported')
    SnappySocket = None

# Deflate support
try:
    from .deflate import DeflateSocket
except ImportError:  # pragma: no cover
    logger.debug('Deflate compression not supported')
    DeflateSocket = None

# The TLS socket
try:
    from .tls import TLSSocket
except ImportError:  # pragma: no cover
    logger.warn('TLS not supported')
    TLSSocket = None

Response:
<REPLACE_OLD> logger.warn('Snappy <REPLACE_NEW> logger.debug('Snappy <REPLACE_END> <REPLACE_OLD> logger.warn('Deflate <REPLACE_NEW> logger.debug('Deflate <REPLACE_END> <|endoftext|> '''Sockets that wrap different connection types'''

# Not all platforms support all types of sockets provided here. For those that
# are not available, the corresponding socket wrapper is imported as None.

from .. import logger

# Snappy support
try:
    from .snappy import SnappySocket
except ImportError:  # pragma: no cover
    logger.debug('Snappy compression not supported')
    SnappySocket = None

# Deflate support
try:
    from .deflate import DeflateSocket
except ImportError:  # pragma: no cover
    logger.debug('Deflate compression not supported')
    DeflateSocket = None

# The TLS socket
try:
    from .tls import TLSSocket
except ImportError:  # pragma: no cover
    logger.warn('TLS not supported')
    TLSSocket = None

Prompt:
Reduce log severity of socket import messages
'''Sockets that wrap different connection types'''

# Not all platforms support all types of sockets provided here. For those that
# are not available, the corresponding socket wrapper is imported as None.

from .. import logger

# Snappy support
try:
    from .snappy import SnappySocket
except ImportError:  # pragma: no cover
    logger.warn('Snappy compression not supported')
    SnappySocket = None

# Deflate support
try:
    from .deflate import DeflateSocket
except ImportError:  # pragma: no cover
    logger.warn('Deflate compression not supported')
    DeflateSocket = None

# The TLS socket
try:
    from .tls import TLSSocket
except ImportError:  # pragma: no cover
    logger.warn('TLS not supported')
    TLSSocket = None


Fix comment header on init

Fix comment header on init

Response:
<REPLACE_OLD> Emanuel Cino <ecino@compassion.ch>
#
# <REPLACE_NEW> Emmanuel Mathier <emmanuel.mathier@gmail.ch>
#
# <REPLACE_END> <|endoftext|> # -*- encoding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: Emmanuel Mathier <emmanuel.mathier@gmail.ch>
#
#    The licence is in the file __openerp__.py
#
##############################################################################

from . import xmlrpc_helper

Prompt:
Fix comment header on init

# -*- encoding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: Emanuel Cino <ecino@compassion.ch>
#
#    The licence is in the file __openerp__.py
#
##############################################################################

from . import xmlrpc_helper


from flask import Flask, g
from inspect import getmembers, isfunction
from happymongo import HapPyMongo
from config import config
from adminbp import bp as admin_bp
from manage_globals import bp as manage_bp
from engine import bp as engine_bp

import context_functions
import views
import template_filters

def create_app(testing=None):
    app = Flask(__name__)

    if testing:
        config.TESTING = True
        config.MONGO_DATABASE = '%s_test' % config.MONGO_DATABASE
        config.ADMIN = 'rusty.shackelford'

    app.config.from_object(config)
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(manage_bp, url_prefix='/manage')
    app.register_blueprint(engine_bp, url_prefix='/engine')

    mongo, db = HapPyMongo(config)
    views.ProductsView.register(app)
    views.MiscView.register(app)

    custom_filters = {
        name: function for name, function in getmembers(template_filters)
        if isfunction(function)
    }
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(context_functions.utility_processor)

    @app.before_request
    def before_request():
        g.db = db

    return app, db

Add in setup application file to handle the app setup so that it can be used with browser testing as well

Response:
<INSERT> from flask import Flask, g
from inspect import getmembers, isfunction
from happymongo import HapPyMongo
from config import config
from adminbp import bp as admin_bp
from manage_globals import bp as manage_bp
from engine import bp as engine_bp

import context_functions
import views
import template_filters

def create_app(testing=None):
 <INSERT_END> <INSERT>   app = Flask(__name__)

    if testing:
        config.TESTING = True
        config.MONGO_DATABASE = '%s_test' % config.MONGO_DATABASE
        config.ADMIN = 'rusty.shackelford'

    app.config.from_object(config)
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(manage_bp, url_prefix='/manage')
    app.register_blueprint(engine_bp, url_prefix='/engine')

    mongo, db = HapPyMongo(config)
    views.ProductsView.register(app)
    views.MiscView.register(app)

    custom_filters = {
        name: function for name, function in getmembers(template_filters)
        if isfunction(function)
    }
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(context_functions.utility_processor)

    @app.before_request
    def before_request():
        g.db = db

    return app, db
 <INSERT_END> <|endoftext|> from flask import Flask, g
from inspect import getmembers, isfunction
from happymongo import HapPyMongo
from config import config
from adminbp import bp as admin_bp
from manage_globals import bp as manage_bp
from engine import bp as engine_bp

import context_functions
import views
import template_filters

def create_app(testing=None):
    app = Flask(__name__)

    if testing:
        config.TESTING = True
        config.MONGO_DATABASE = '%s_test' % config.MONGO_DATABASE
        config.ADMIN = 'rusty.shackelford'

    app.config.from_object(config)
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(manage_bp, url_prefix='/manage')
    app.register_blueprint(engine_bp, url_prefix='/engine')

    mongo, db = HapPyMongo(config)
    views.ProductsView.register(app)
    views.MiscView.register(app)

    custom_filters = {
        name: function for name, function in getmembers(template_filters)
        if isfunction(function)
    }
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(context_functions.utility_processor)

    @app.before_request
    def before_request():
        g.db = db

    return app, db

Prompt: Add in setup application file to handle the app setup so that it can be used with browser testing as well


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'django_summernote.db',
    }
}

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

STATIC_URL = '/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'test_media'

SECRET_KEY = 'django_summernote'

ROOT_URLCONF = 'django_summernote.urls'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django_summernote',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ]
        },
    },
]

if django.VERSION >= (3, 0):
    X_FRAME_OPTIONS = 'SAMEORIGIN'

Drop old django version support (1.10)

Drop old django version support (1.10)

Response:
<REPLACE_OLD> import django

DATABASES <REPLACE_NEW> DATABASES <REPLACE_END> <REPLACE_OLD> }
}

__MIDDLEWARE__ <REPLACE_NEW> }
}

MIDDLEWARE <REPLACE_END> <REPLACE_OLD> 'django.middleware.locale.LocaleMiddleware',
)

if django.VERSION < (1, 10):
    MIDDLEWARE_CLASSES = __MIDDLEWARE__
else:
    MIDDLEWARE = __MIDDLEWARE__

STATIC_URL <REPLACE_NEW> 'django.middleware.locale.LocaleMiddleware',
)

STATIC_URL <REPLACE_END> <|endoftext|> DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'django_summernote.db',
    }
}

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

STATIC_URL = '/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'test_media'

SECRET_KEY = 'django_summernote'

ROOT_URLCONF = 'django_summernote.urls'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django_summernote',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ]
        },
    },
]

if django.VERSION >= (3, 0):
    X_FRAME_OPTIONS = 'SAMEORIGIN'

Prompt:
Drop old django version support (1.10)

import django

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'django_summernote.db',
    }
}

__MIDDLEWARE__ = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

if django.VERSION < (1, 10):
    MIDDLEWARE_CLASSES = __MIDDLEWARE__
else:
    MIDDLEWARE = __MIDDLEWARE__

STATIC_URL = '/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'test_media'

SECRET_KEY = 'django_summernote'

ROOT_URLCONF = 'django_summernote.urls'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django_summernote',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ]
        },
    },
]

if django.VERSION >= (3, 0):
    X_FRAME_OPTIONS = 'SAMEORIGIN'


from bot.api.telegram import TelegramBotApi
from bot.storage import State

class Api:
    def __init__(self, telegram_api: TelegramBotApi, state: State):
        self.telegram_api = telegram_api
        self.state = state

    def get_me(self):
        return self.telegram_api.get_me()

    def send_message(self, message):
        return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text,
                                              reply_to_message_id=message.reply_to_message_id)

    def get_pending_updates(self):
        return self.get_updates(timeout=0)

    def get_updates(self, timeout=45):
        updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout)
        for update in updates:
            self.__set_updates_offset(update.update_id)
            yield update

    def __get_updates_offset(self):
        return self.state.next_update_id

    def __set_updates_offset(self, last_update_id):
        self.state.next_update_id = str(last_update_id + 1)

Response:
<REPLACE_OLD> yield from <REPLACE_NEW> return <REPLACE_END> <|endoftext|> from bot.api.telegram import TelegramBotApi
from bot.storage import State

class Api:
    def __init__(self, telegram_api: TelegramBotApi, state: State):
        self.telegram_api = telegram_api
        self.state = state

    def get_me(self):
        return self.telegram_api.get_me()

    def send_message(self, message):
        return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text,
                                              reply_to_message_id=message.reply_to_message_id)

    def get_pending_updates(self):
        return self.get_updates(timeout=0)

    def get_updates(self, timeout=45):
        updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout)
        for update in updates:
            self.__set_updates_offset(update.update_id)
            yield update

    def __get_updates_offset(self):
        return self.state.next_update_id

    def __set_updates_offset(self, last_update_id):
        self.state.next_update_id = str(last_update_id + 1)

Prompt:
Change yield from to return to be compatible with python 3.2

from bot.api.telegram import TelegramBotApi
from bot.storage import State

class Api:
    def __init__(self, telegram_api: TelegramBotApi, state: State):
        self.telegram_api = telegram_api
        self.state = state

    def get_me(self):
        return self.telegram_api.get_me()

    def send_message(self, message):
        return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text,
                                              reply_to_message_id=message.reply_to_message_id)

    def get_pending_updates(self):
        yield from self.get_updates(timeout=0)

    def get_updates(self, timeout=45):
        updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout)
        for update in updates:
            self.__set_updates_offset(update.update_id)
            yield update

    def __get_updates_offset(self):
        return self.state.next_update_id

    def __set_updates_offset(self, last_update_id):
        self.state.next_update_id = str(last_update_id + 1)


from setuptools import find_packages, setup

setup(
    name="redshift-etl",
    version="0.27.1",
    author="Harry's Data Engineering and Contributors",
    description="ETL code to ferry data from PostgreSQL databases (or S3 files) to Redshift cluster",
    license="MIT",
    keywords="redshift postgresql etl extract transform load",
    url="https://github.com/harrystech/harrys-redshift-etl",
    package_dir={"": "python"},
    packages=find_packages("python"),
    package_data={
        "etl": [
            "assets/*",
            "config/*"
        ]
    },
    scripts=[
        "python/scripts/submit_arthur.sh",
        "python/scripts/re_run_partial_pipeline.py"
    ],
    entry_points={
        "console_scripts": [
            # NB The script must end in ".py" so that spark submit accepts it as a Python script.
            "arthur.py = etl.commands:run_arg_as_command",
            "run_tests.py = etl.selftest:run_tests"
        ]
    }
)

Response:
<REPLACE_OLD> version="0.27.0",
 <REPLACE_NEW> version="0.27.1",
 <REPLACE_END> <|endoftext|> from setuptools import find_packages, setup

setup(
    name="redshift-etl",
    version="0.27.1",
    author="Harry's Data Engineering and Contributors",
    description="ETL code to ferry data from PostgreSQL databases (or S3 files) to Redshift cluster",
    license="MIT",
    keywords="redshift postgresql etl extract transform load",
    url="https://github.com/harrystech/harrys-redshift-etl",
    package_dir={"": "python"},
    packages=find_packages("python"),
    package_data={
        "etl": [
            "assets/*",
            "config/*"
        ]
    },
    scripts=[
        "python/scripts/submit_arthur.sh",
        "python/scripts/re_run_partial_pipeline.py"
    ],
    entry_points={
        "console_scripts": [
            # NB The script must end in ".py" so that spark submit accepts it as a Python script.
            "arthur.py = etl.commands:run_arg_as_command",
            "run_tests.py = etl.selftest:run_tests"
        ]
    }
)

Prompt:
Drop max-concurrency for update in refresh pipeline (invalid arg)

from setuptools import find_packages, setup

setup(
    name="redshift-etl",
    version="0.27.0",
    author="Harry's Data Engineering and Contributors",
    description="ETL code to ferry data from PostgreSQL databases (or S3 files) to Redshift cluster",
    license="MIT",
    keywords="redshift postgresql etl extract transform load",
    url="https://github.com/harrystech/harrys-redshift-etl",
    package_dir={"": "python"},
    packages=find_packages("python"),
    package_data={
        "etl": [
            "assets/*",
            "config/*"
        ]
    },
    scripts=[
        "python/scripts/submit_arthur.sh",
        "python/scripts/re_run_partial_pipeline.py"
    ],
    entry_points={
        "console_scripts": [
            # NB The script must end in ".py" so that spark submit accepts it as a Python script.
            "arthur.py = etl.commands:run_arg_as_command",
            "run_tests.py = etl.selftest:run_tests"
        ]
    }
)


import numpy as np
import pandas as pd
import matplotlib_venn
import matplotlib.pyplot as plt
import brewer2mpl

set1 = brewer2mpl.get_map('Set1', 'qualitative', 9).mpl_colors
red = set1[0]
blue = set1[1]
green = set1[2]
purple = set1[3]
orange = set1[4]
yellow = set1[5]
brown = set1[6]
pink = set1[7]
grey = set1[8]

Add file for easy ipython imports

Add file for easy ipython imports

Response:
<REPLACE_OLD>  <REPLACE_NEW> import numpy as np
import pandas as pd
import matplotlib_venn
import matplotlib.pyplot as plt
import brewer2mpl

set1 = brewer2mpl.get_map('Set1', 'qualitative', 9).mpl_colors
red = set1[0]
blue = set1[1]
green = set1[2]
purple = set1[3]
orange = set1[4]
yellow = set1[5]
brown = set1[6]
pink = set1[7]
grey = set1[8] <REPLACE_END> <|endoftext|> import numpy as np
import pandas as pd
import matplotlib_venn
import matplotlib.pyplot as plt
import brewer2mpl

set1 = brewer2mpl.get_map('Set1', 'qualitative', 9).mpl_colors
red = set1[0]
blue = set1[1]
green = set1[2]
purple = set1[3]
orange = set1[4]
yellow = set1[5]
brown = set1[6]
pink = set1[7]
grey = set1[8]

Prompt: Add file for easy ipython imports


Response:
<REPLACE_OLD> check

self.count( ... ) # Sample a raw count metric

self.monotonic_count( ... ) # Sample an increasing counter metric
 <REPLACE_NEW> check
 <REPLACE_END> <|endoftext|> self.gauge( ... ) # Sample a gauge metric

self.increment( ... ) # Increment a counter metric

self.decrement( ... ) # Decrement a counter metric

self.histogram( ... ) # Sample a histogram metric

self.rate( ... ) # Sample a point, with the rate calculated at the end of the check

Prompt:
Revert "Document AgentCheck count and monotonic_count methods"

This reverts commit e731c3a4a8590f5cddd23fd2f9af265749f08a38.

self.gauge( ... ) # Sample a gauge metric

self.increment( ... ) # Increment a counter metric

self.decrement( ... ) # Decrement a counter metric

self.histogram( ... ) # Sample a histogram metric

self.rate( ... ) # Sample a point, with the rate calculated at the end of the check

self.count( ... ) # Sample a raw count metric

self.monotonic_count( ... ) # Sample an increasing counter metric


"""
``python-future``: pure Python implementation of Python 3 round().
"""

from future.utils import PYPY

def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)

__all__ = ['newround']

Response:
<REPLACE_OLD>
def <REPLACE_NEW>
from future.utils import PYPY

def <REPLACE_END> <REPLACE_OLD> (-ndigits)
 <REPLACE_NEW> (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)
 <REPLACE_END> <|endoftext|> """
``python-future``: pure Python implementation of Python 3 round().
"""

from future.utils import PYPY

def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)

__all__ = ['newround']

Prompt:
Add workaround for PyPy round() bug with NumPy data types

"""
``python-future``: pure Python implementation of Python 3 round().
"""

def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)

__all__ = ['newround']


Solve Code Fights correct lineup problem

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/local/bin/python
# Code Fights Correct Lineup Problem

def correctLineup(athletes):
    return [a for t in zip(athletes[1::2], athletes[::2]) for a in t]

def main():
    tests = [
        [[1, 2, 3, 4, 5, 6], [2, 1, 4, 3, 6, 5]],
        [[13, 42], [42, 13]],
        [[2, 3, 1, 100, 99, 45, 22, 28], [3, 2, 100, 1, 45, 99, 28, 22]],
        [[85, 32, 45, 67, 32, 12, 45, 67], [32, 85, 67, 45, 12, 32, 67, 45]],
        [[60, 2, 24, 40], [2, 60, 40, 24]]
    ]

    for t in tests:
        res = correctLineup(t[0])
        ans = t[1]
        if ans == res:
            print("PASSED: correctLineup({}) returned {}"
                  .format(t[0], res))
        else:
            print(("FAILED: correctLineup({}) returned {},"
                   "answer: {}").format(t[0], res, ans))

if __name__ == '__main__':
    main()
 <REPLACE_END> <|endoftext|> #!/usr/local/bin/python
# Code Fights Correct Lineup Problem

def correctLineup(athletes):
    return [a for t in zip(athletes[1::2], athletes[::2]) for a in t]

def main():
    tests = [
        [[1, 2, 3, 4, 5, 6], [2, 1, 4, 3, 6, 5]],
        [[13, 42], [42, 13]],
        [[2, 3, 1, 100, 99, 45, 22, 28], [3, 2, 100, 1, 45, 99, 28, 22]],
        [[85, 32, 45, 67, 32, 12, 45, 67], [32, 85, 67, 45, 12, 32, 67, 45]],
        [[60, 2, 24, 40], [2, 60, 40, 24]]
    ]

    for t in tests:
        res = correctLineup(t[0])
        ans = t[1]
        if ans == res:
            print("PASSED: correctLineup({}) returned {}"
                  .format(t[0], res))
        else:
            print(("FAILED: correctLineup({}) returned {},"
                   "answer: {}").format(t[0], res, ans))

if __name__ == '__main__':
    main()

Prompt: Solve Code Fights correct lineup problem


import tensorflow as tf

from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout

def char2doc(document,
             *,
             char_space_size,
             char_embedding_size,
             document_embedding_size,
             dropout_prob,
             hidden_layer_size,
             output_layer_size,
             context_vector_size):
  with tf.variable_scope("char2doc"):
    char_embeddings = embeddings(id_space_size=char_space_size,
                                 embedding_size=char_embedding_size)

    document_embedding = id_sequence_to_embedding(
        document,
        char_embeddings,
        output_embedding_size=document_embedding_size,
        context_vector_size=context_vector_size)

    hidden_layer = dropout(_activate(linear(_activate(document_embedding),
                                            hidden_layer_size)),
                           dropout_prob)
    return linear(hidden_layer, output_layer_size)

def _activate(tensor):
  return tf.nn.elu(tensor)

Response:
<REPLACE_OLD> embeddings_to_embedding, ids_to_embeddings, <REPLACE_NEW> id_sequence_to_embedding, <REPLACE_END> <REPLACE_OLD> char2doc(forward_document,
             backward_document,
 <REPLACE_NEW> char2doc(document,
 <REPLACE_END> <DELETE> def char_ids_to_doc_embedding(document):
      return embeddings_to_embedding(
          ids_to_embeddings(document, char_embeddings),
          output_embedding_size=document_embedding_size,
          context_vector_size=context_vector_size)

    <DELETE_END> <REPLACE_OLD> tf.concat(
        1,
        list(map(char_ids_to_doc_embedding,
                 [forward_document, backward_document])))

 <REPLACE_NEW> id_sequence_to_embedding(
        document,
        char_embeddings,
        output_embedding_size=document_embedding_size,
        context_vector_size=context_vector_size)

 <REPLACE_END> <|endoftext|> import tensorflow as tf

from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout

def char2doc(document,
             *,
             char_space_size,
             char_embedding_size,
             document_embedding_size,
             dropout_prob,
             hidden_layer_size,
             output_layer_size,
             context_vector_size):
  with tf.variable_scope("char2doc"):
    char_embeddings = embeddings(id_space_size=char_space_size,
                                 embedding_size=char_embedding_size)

    document_embedding = id_sequence_to_embedding(
        document,
        char_embeddings,
        output_embedding_size=document_embedding_size,
        context_vector_size=context_vector_size)

    hidden_layer = dropout(_activate(linear(_activate(document_embedding),
                                            hidden_layer_size)),
                           dropout_prob)
    return linear(hidden_layer, output_layer_size)

def _activate(tensor):
  return tf.nn.elu(tensor)

Prompt:
Use id_sequence_to_embedding and only forward document

import tensorflow as tf

from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings
from ..linear import linear
from ..dropout import dropout

def char2doc(forward_document,
             backward_document,
             *,
             char_space_size,
             char_embedding_size,
             document_embedding_size,
             dropout_prob,
             hidden_layer_size,
             output_layer_size,
             context_vector_size):
  with tf.variable_scope("char2doc"):
    char_embeddings = embeddings(id_space_size=char_space_size,
                                 embedding_size=char_embedding_size)

    def char_ids_to_doc_embedding(document):
      return embeddings_to_embedding(
          ids_to_embeddings(document, char_embeddings),
          output_embedding_size=document_embedding_size,
          context_vector_size=context_vector_size)

    document_embedding = tf.concat(
        1,
        list(map(char_ids_to_doc_embedding,
                 [forward_document, backward_document])))

    hidden_layer = dropout(_activate(linear(_activate(document_embedding),
                                            hidden_layer_size)),
                           dropout_prob)
    return linear(hidden_layer, output_layer_size)

def _activate(tensor):
  return tf.nn.elu(tensor)


from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose

def test_lowpass_filtering_of_envelope():
    mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
                      squeeze_me=True)
    envelope = mat['unfiltered_env']
    target = mat['lp_filtered_env']
    filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
    assert_allclose(filtered_envelope, target, atol=1e-7)

def test_erb():
    bw = aud.erbbw(1000)
    assert_allclose(bw, 132.63, rtol=1e-4)

# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
    mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
    center_f = mat['midfreq'].squeeze()
    fs = mat['fs'].squeeze()
    signal = mat['signal'].squeeze()
    targets = mat['GT_output'].squeeze()
    target = targets[:,:,0].T
    out = aud.gammatone_filtering(signal, center_f, fs)
    assert_allclose(out, target)

Response:
<REPLACE_OLD> rtol=1e-4)
 <REPLACE_NEW> rtol=1e-4)

# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
    mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
    center_f = mat['midfreq'].squeeze()
    fs = mat['fs'].squeeze()
    signal = mat['signal'].squeeze()
    targets = mat['GT_output'].squeeze()
    target = targets[:,:,0].T
    out = aud.gammatone_filtering(signal, center_f, fs)
    assert_allclose(out, target)
 <REPLACE_END> <|endoftext|> from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose

def test_lowpass_filtering_of_envelope():
    mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
                      squeeze_me=True)
    envelope = mat['unfiltered_env']
    target = mat['lp_filtered_env']
    filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
    assert_allclose(filtered_envelope, target, atol=1e-7)

def test_erb():
    bw = aud.erbbw(1000)
    assert_allclose(bw, 132.63, rtol=1e-4)

# We use a different implementation than the Matlab one and the delay
# are different.
@pytest.mark.xfail
def test_gammatone_filtering():
    mat = sio.loadmat('./test_files/test_gammatone_filtering.mat')
    center_f = mat['midfreq'].squeeze()
    fs = mat['fs'].squeeze()
    signal = mat['signal'].squeeze()
    targets = mat['GT_output'].squeeze()
    target = targets[:,:,0].T
    out = aud.gammatone_filtering(signal, center_f, fs)
    assert_allclose(out, target)

Prompt:
Add test, which fails, of the gammatone filtering.

from __future__ import division, print_function
import pytest
import numpy as np
from pambox import auditory as aud
import scipy.io as sio
from numpy.testing import assert_allclose

def test_lowpass_filtering_of_envelope():
    mat = sio.loadmat("./test_files/test_hilbert_env_and_lp_filtering_v1.mat",
                      squeeze_me=True)
    envelope = mat['unfiltered_env']
    target = mat['lp_filtered_env']
    filtered_envelope = aud.lowpass_env_filtering(envelope, 150., 1, 22050.)
    assert_allclose(filtered_envelope, target, atol=1e-7)

def test_erb():
    bw = aud.erbbw(1000)
    assert_allclose(bw, 132.63, rtol=1e-4)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cfp', '0047_auto_20150412_0647'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='conference',
            name='topics',
        ),
        migrations.RemoveField(
            model_name='savedsearch',
            name='topic',
        ),
    ]

Remove topics from models migration

Remove topics from models migration

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

from django.db import models, migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('cfp', '0047_auto_20150412_0647'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='conference',
            name='topics',
        ),
        migrations.RemoveField(
            model_name='savedsearch',
            name='topic',
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cfp', '0047_auto_20150412_0647'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='conference',
            name='topics',
        ),
        migrations.RemoveField(
            model_name='savedsearch',
            name='topic',
        ),
    ]

Prompt: Remove topics from models migration


from django.db import models

from organizer.models import Startup, Tag

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Post(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField(
        max_length=63,
        help_text='A label for URL config',
        unique_for_month='pub_date')
    text = models.TextField()
    pub_date = models.DateField(
        'date published',
        auto_now_add=True)
    tags = models.ManyToManyField(
        Tag, related_name='blog_posts')
    startups = models.ManyToManyField(
        Startup, related_name='blog_posts')

Add options to Post model fields.

Response:
<REPLACE_OLD> models.SlugField()
 <REPLACE_NEW> models.SlugField(
        max_length=63,
        help_text='A label for URL config',
        unique_for_month='pub_date')
 <REPLACE_END> <REPLACE_OLD> models.DateField()
 <REPLACE_NEW> models.DateField(
        'date published',
        auto_now_add=True)
 <REPLACE_END> <REPLACE_OLD> models.ManyToManyField(Tag)
 <REPLACE_NEW> models.ManyToManyField(
        Tag, related_name='blog_posts')
 <REPLACE_END> <REPLACE_OLD> models.ManyToManyField(Startup)
 <REPLACE_NEW> models.ManyToManyField(
        Startup, related_name='blog_posts')
 <REPLACE_END> <|endoftext|> from django.db import models

from organizer.models import Startup, Tag

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Post(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField(
        max_length=63,
        help_text='A label for URL config',
        unique_for_month='pub_date')
    text = models.TextField()
    pub_date = models.DateField(
        'date published',
        auto_now_add=True)
    tags = models.ManyToManyField(
        Tag, related_name='blog_posts')
    startups = models.ManyToManyField(
        Startup, related_name='blog_posts')

Prompt:
Ch03: Add options to Post model fields. [skip ci]

from django.db import models

from organizer.models import Startup, Tag

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Post(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField()
    text = models.TextField()
    pub_date = models.DateField()
    tags = models.ManyToManyField(Tag)
    startups = models.ManyToManyField(Startup)


from unittest.case import TestCase

from zsl.utils.string_helper import camelcase_to_underscore, underscore_to_camelcase

class InflectionTestCase(TestCase):
    def testCamelCaseToUnderscore(self):
        self.assertEquals(
            "camel_case_to_underscore",
            camelcase_to_underscore("camelCaseToUnderscore"),
            "CC to usc conversion"
        )
        self.assertEquals(
            "camel_case_to_underscore",
            camelcase_to_underscore("CamelCaseToUnderscore"),
            "CC to usc conversion"
        )

    def testUnderscoreToCamelCase(self):
        self.assertEquals(
            "camelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore", False),
            "CC to usc conversion"
        )
        self.assertEquals(
            "CamelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore"),
            "CC to usc conversion"
        )
        self.assertEquals(
            "CamelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore", True),
            "CC to usc conversion"
        )

Add tests of the improved camelcase/underscore conversion

Response:
<REPLACE_OLD>  <REPLACE_NEW> from unittest.case import TestCase

from zsl.utils.string_helper import camelcase_to_underscore, underscore_to_camelcase

class InflectionTestCase(TestCase):
    def testCamelCaseToUnderscore(self):
        self.assertEquals(
            "camel_case_to_underscore",
            camelcase_to_underscore("camelCaseToUnderscore"),
            "CC to usc conversion"
        )
        self.assertEquals(
            "camel_case_to_underscore",
            camelcase_to_underscore("CamelCaseToUnderscore"),
            "CC to usc conversion"
        )

    def testUnderscoreToCamelCase(self):
        self.assertEquals(
            "camelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore", False),
            "CC to usc conversion"
        )
        self.assertEquals(
            "CamelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore"),
            "CC to usc conversion"
        )
        self.assertEquals(
            "CamelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore", True),
            "CC to usc conversion"
        ) <REPLACE_END> <|endoftext|> from unittest.case import TestCase

from zsl.utils.string_helper import camelcase_to_underscore, underscore_to_camelcase

class InflectionTestCase(TestCase):
    def testCamelCaseToUnderscore(self):
        self.assertEquals(
            "camel_case_to_underscore",
            camelcase_to_underscore("camelCaseToUnderscore"),
            "CC to usc conversion"
        )
        self.assertEquals(
            "camel_case_to_underscore",
            camelcase_to_underscore("CamelCaseToUnderscore"),
            "CC to usc conversion"
        )

    def testUnderscoreToCamelCase(self):
        self.assertEquals(
            "camelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore", False),
            "CC to usc conversion"
        )
        self.assertEquals(
            "CamelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore"),
            "CC to usc conversion"
        )
        self.assertEquals(
            "CamelCaseToUnderscore",
            underscore_to_camelcase("camel_case_to_underscore", True),
            "CC to usc conversion"
        )

Prompt: Add tests of the improved camelcase/underscore conversion


from django.conf.urls import patterns, url, include
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.autodiscover()

from rest_framework.routers import DefaultRouter
from jobs.views import JobViewSet, UserViewSet, ResultViewSet

router = DefaultRouter()
router.register(r'jobs', JobViewSet, base_name='job')
router.register(r'results', ResultViewSet)
router.register(r'users', UserViewSet)

urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    url(r'^login/$', 'jobs.views.login', name='login')
)

urlpatterns += patterns('backend.views',
    url(r'^admin/', include(admin.site.urls))
)

urlpatterns = patterns('',
    (r'^robots\.txt$',
     lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain"))
)

Disable indexing via robots.txt url.

Disable indexing via robots.txt url.

Response:
<REPLACE_OLD> include(admin.site.urls))
)
 <REPLACE_NEW> include(admin.site.urls))
)

urlpatterns = patterns('',
    (r'^robots\.txt$',
     lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain"))
)
 <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, url, include
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.autodiscover()

from rest_framework.routers import DefaultRouter
from jobs.views import JobViewSet, UserViewSet, ResultViewSet

router = DefaultRouter()
router.register(r'jobs', JobViewSet, base_name='job')
router.register(r'results', ResultViewSet)
router.register(r'users', UserViewSet)

urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    url(r'^login/$', 'jobs.views.login', name='login')
)

urlpatterns += patterns('backend.views',
    url(r'^admin/', include(admin.site.urls))
)

urlpatterns = patterns('',
    (r'^robots\.txt$',
     lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain"))
)

Prompt:
Disable indexing via robots.txt url.
from django.conf.urls import patterns, url, include
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
from django.contrib import admin
admin.autodiscover()

from rest_framework.routers import DefaultRouter
from jobs.views import JobViewSet, UserViewSet, ResultViewSet

router = DefaultRouter()
router.register(r'jobs', JobViewSet, base_name='job')
router.register(r'results', ResultViewSet)
router.register(r'users', UserViewSet)

urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    url(r'^login/$', 'jobs.views.login', name='login')
)

urlpatterns += patterns('backend.views',
    url(r'^admin/', include(admin.site.urls))
)


import eventlet
import os
import sys

from oslo.config import cfg

from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history

LOG = logging.getLogger(__name__)

eventlet.monkey_patch(
    os=True,
    select=True,
    socket=True,
    thread=False if '--use-debugger' in sys.argv else True,
    time=True)

def _setup():
    # Parse args to setup config.
    config.parse_args()

    # Setup logging.
    logging.setup(cfg.CONF.history.logging)

    # All other setup which requires config to be parsed and logging to be correctly setup.
    db_setup(cfg.CONF.database.db_name, cfg.CONF.database.host, cfg.CONF.database.port)

def _teardown():
    db_teardown()

def main():
    try:
        _setup()
        LOG.info('(PID=%s) Historian started.', os.getpid())
        history.work()
    except (KeyboardInterrupt, SystemExit):
        LOG.info('(PID=%s) Historian stopped.', os.getpid())
        return 0
    except:
        LOG.exception('(PID=%s) Historian quit due to exception.', os.getpid())
        return 1
    finally:
        _teardown()
    return 0

Move code from _run_worker into main

Move code from _run_worker into main

Response:
<REPLACE_OLD> _run_worker():
 <REPLACE_NEW> _teardown():
    db_teardown()

def main():
    try:
        _setup()
     <REPLACE_END> <REPLACE_OLD> History worker <REPLACE_NEW> Historian <REPLACE_END> <DELETE>    try:
 <DELETE_END> <REPLACE_OLD> History worker <REPLACE_NEW> Historian <REPLACE_END> <INSERT>     return 0
    <INSERT_END> <INSERT>        LOG.exception('(PID=%s) Historian quit due to exception.', os.getpid())
 <INSERT_END> <INSERT> finally:
        _teardown()
    <INSERT_END> <REPLACE_OLD> 0

def _teardown():
    db_teardown()

def main():
    try:
        _setup()
        return _run_worker()
    except:
        LOG.exception('(PID=%s) History worker quit due to exception.', os.getpid())
        return 1
    finally:
        _teardown()
 <REPLACE_NEW> 0
 <REPLACE_END> <|endoftext|> import eventlet
import os
import sys

from oslo.config import cfg

from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history

LOG = logging.getLogger(__name__)

eventlet.monkey_patch(
    os=True,
    select=True,
    socket=True,
    thread=False if '--use-debugger' in sys.argv else True,
    time=True)

def _setup():
    # Parse args to setup config.
    config.parse_args()

    # Setup logging.
    logging.setup(cfg.CONF.history.logging)

    # All other setup which requires config to be parsed and logging to be correctly setup.
    db_setup(cfg.CONF.database.db_name, cfg.CONF.database.host, cfg.CONF.database.port)

def _teardown():
    db_teardown()

def main():
    try:
        _setup()
        LOG.info('(PID=%s) Historian started.', os.getpid())
        history.work()
    except (KeyboardInterrupt, SystemExit):
        LOG.info('(PID=%s) Historian stopped.', os.getpid())
        return 0
    except:
        LOG.exception('(PID=%s) Historian quit due to exception.', os.getpid())
        return 1
    finally:
        _teardown()
    return 0

Prompt:
Move code from _run_worker into main

import eventlet
import os
import sys

from oslo.config import cfg

from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history

LOG = logging.getLogger(__name__)

eventlet.monkey_patch(
    os=True,
    select=True,
    socket=True,
    thread=False if '--use-debugger' in sys.argv else True,
    time=True)

def _setup():
    # Parse args to setup config.
    config.parse_args()

    # Setup logging.
    logging.setup(cfg.CONF.history.logging)

    # All other setup which requires config to be parsed and logging to be correctly setup.
    db_setup(cfg.CONF.database.db_name, cfg.CONF.database.host, cfg.CONF.database.port)

def _run_worker():
    LOG.info('(PID=%s) History worker started.', os.getpid())
    try:
        history.work()
    except (KeyboardInterrupt, SystemExit):
        LOG.info('(PID=%s) History worker stopped.', os.getpid())
    except:
        return 1
    return 0

def _teardown():
    db_teardown()

def main():
    try:
        _setup()
        return _run_worker()
    except:
        LOG.exception('(PID=%s) History worker quit due to exception.', os.getpid())
        return 1
    finally:
        _teardown()


import analytics

from django.db import InterfaceError, OperationalError, ProgrammingError

from tracker.service import TrackerService

class PublishTrackerService(TrackerService):
    def __init__(self, key=''):
        self.cluster_id = None
        self.analytics = analytics
        self.analytics.write_key = key

    def get_cluster_id(self):
        if self.cluster_id:
            return self.cluster_id

        from clusters.models import Cluster
        try:
            cluster_uuid = Cluster.load().uuid.hex
            self.cluster_id = cluster_uuid
        except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError):
            pass
        return self.cluster_id

    def record_event(self, event):
        cluster_id = self.get_cluster_id()
        if not cluster_id:
            return

        if event.event_type == 'cluster.created':
            self.analytics.identify(
                cluster_id,
                event.serialize(dumps=False),
            )
        self.analytics.track(
            cluster_id,
            event.event_type,
            event.serialize(dumps=False),
        )

    def setup(self):
        super(PublishTrackerService, self).setup()
        self.cluster_id = self.get_cluster_id()

Update check on cluster id

Update check on cluster id

Response:
<INSERT> cluster_id = self.get_cluster_id()
        <INSERT_END> <REPLACE_OLD> self.cluster_id:
 <REPLACE_NEW> cluster_id:
 <REPLACE_END> <REPLACE_OLD> self.get_cluster_id(),
 <REPLACE_NEW> cluster_id,
 <REPLACE_END> <REPLACE_OLD> self.get_cluster_id(),
 <REPLACE_NEW> cluster_id,
 <REPLACE_END> <|endoftext|> import analytics

from django.db import InterfaceError, OperationalError, ProgrammingError

from tracker.service import TrackerService

class PublishTrackerService(TrackerService):
    def __init__(self, key=''):
        self.cluster_id = None
        self.analytics = analytics
        self.analytics.write_key = key

    def get_cluster_id(self):
        if self.cluster_id:
            return self.cluster_id

        from clusters.models import Cluster
        try:
            cluster_uuid = Cluster.load().uuid.hex
            self.cluster_id = cluster_uuid
        except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError):
            pass
        return self.cluster_id

    def record_event(self, event):
        cluster_id = self.get_cluster_id()
        if not cluster_id:
            return

        if event.event_type == 'cluster.created':
            self.analytics.identify(
                cluster_id,
                event.serialize(dumps=False),
            )
        self.analytics.track(
            cluster_id,
            event.event_type,
            event.serialize(dumps=False),
        )

    def setup(self):
        super(PublishTrackerService, self).setup()
        self.cluster_id = self.get_cluster_id()

Prompt:
Update check on cluster id

import analytics

from django.db import InterfaceError, OperationalError, ProgrammingError

from tracker.service import TrackerService

class PublishTrackerService(TrackerService):
    def __init__(self, key=''):
        self.cluster_id = None
        self.analytics = analytics
        self.analytics.write_key = key

    def get_cluster_id(self):
        if self.cluster_id:
            return self.cluster_id

        from clusters.models import Cluster
        try:
            cluster_uuid = Cluster.load().uuid.hex
            self.cluster_id = cluster_uuid
        except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError):
            pass
        return self.cluster_id

    def record_event(self, event):
        if not self.cluster_id:
            return

        if event.event_type == 'cluster.created':
            self.analytics.identify(
                self.get_cluster_id(),
                event.serialize(dumps=False),
            )
        self.analytics.track(
            self.get_cluster_id(),
            event.event_type,
            event.serialize(dumps=False),
        )

    def setup(self):
        super(PublishTrackerService, self).setup()
        self.cluster_id = self.get_cluster_id()


"""
This migration subscribes each user to USER_SUBSCRIPTIONS_AVAILABLE if a subscription
does not already exist.
"""

import logging
import sys

from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key

from scripts import utils as scripts_utils

logger = logging.getLogger(__name__)

app = init_app()

def add_global_subscriptions():

    notification_type = 'email_transactional'
    user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE

    for user in models.User.find():
        if user.is_active and user.is_registered:
            for user_event in user_events:
                user_event_id = to_subscription_key(user._id, user_event)

                subscription = NotificationSubscription.load(user_event_id)
                if not subscription:
                    subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
                    subscription.add_user_to_subscription(user, notification_type)
                    subscription.save()
                    logger.info('No subscription found. {} created.'.format(subscription))
                else:
                    logger.info('Subscription {} found.'.format(subscription))

if __name__ == '__main__':
    dry = '--dry' in sys.argv
    if not dry:
        scripts_utils.add_file_logger(logger, __file__)
    add_global_subscriptions()

Response:
<INSERT> if user.is_active and user.is_registered:
            <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> """
This migration subscribes each user to USER_SUBSCRIPTIONS_AVAILABLE if a subscription
does not already exist.
"""

import logging
import sys

from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key

from scripts import utils as scripts_utils

logger = logging.getLogger(__name__)

app = init_app()

def add_global_subscriptions():

    notification_type = 'email_transactional'
    user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE

    for user in models.User.find():
        if user.is_active and user.is_registered:
            for user_event in user_events:
                user_event_id = to_subscription_key(user._id, user_event)

                subscription = NotificationSubscription.load(user_event_id)
                if not subscription:
                    subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
                    subscription.add_user_to_subscription(user, notification_type)
                    subscription.save()
                    logger.info('No subscription found. {} created.'.format(subscription))
                else:
                    logger.info('Subscription {} found.'.format(subscription))

if __name__ == '__main__':
    dry = '--dry' in sys.argv
    if not dry:
        scripts_utils.add_file_logger(logger, __file__)
    add_global_subscriptions()

Prompt:
Add check for active and registered users

"""
This migration subscribes each user to USER_SUBSCRIPTIONS_AVAILABLE if a subscription
does not already exist.
"""

import logging
import sys

from website.app import init_app
from website import models
from website.notifications.model import NotificationSubscription
from website.notifications import constants
from website.notifications.utils import to_subscription_key

from scripts import utils as scripts_utils

logger = logging.getLogger(__name__)

app = init_app()

def add_global_subscriptions():

    notification_type = 'email_transactional'
    user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE

    for user in models.User.find():
        for user_event in user_events:
            user_event_id = to_subscription_key(user._id, user_event)

            subscription = NotificationSubscription.load(user_event_id)
            if not subscription:
                subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event)
                subscription.add_user_to_subscription(user, notification_type)
                subscription.save()
                logger.info('No subscription found. {} created.'.format(subscription))
            else:
                logger.info('Subscription {} found.'.format(subscription))

if __name__ == '__main__':
    dry = '--dry' in sys.argv
    if not dry:
        scripts_utils.add_file_logger(logger, __file__)
    add_global_subscriptions()


from spock.mcp import datautils
from spock.utils import BoundBuffer

def test_unpack_varint():
    largebuff = BoundBuffer(b'\x80\x94\xeb\xdc\x03')
    smallbuff = BoundBuffer(b'\x14')
    assert datautils.unpack_varint(smallbuff) == 20
    assert datautils.unpack_varint(largebuff) == 1000000000

def test_pack_varint():
    assert datautils.pack_varint(20) == b'\x14'
    assert datautils.pack_varint(1000000000) == b'\x80\x94\xeb\xdc\x03'
    assert datautils.pack_varint(-10000000000) is None
    assert datautils.pack_varint(10000000000) is None

def test_unpack_varlong():
    largebuff = BoundBuffer(b'\x80\xc8\xaf\xa0%')
    smallbuff = BoundBuffer(b'\x14')
    assert datautils.unpack_varlong(smallbuff) == 20
    assert datautils.unpack_varlong(largebuff) == 10000000000
pass

def test_pack_varlong():
    assert datautils.pack_varlong(20) == b'\x14'
    assert datautils.pack_varlong(10000000000) == b'\x80\xc8\xaf\xa0%'
    assert datautils.pack_varlong(10000000000000000000) is None
    assert datautils.pack_varlong(-10000000000000000000) is None

Add varint and varlong tests

Add varint and varlong tests

Response:
<INSERT> from spock.mcp import datautils
from spock.utils import BoundBuffer

def test_unpack_varint():
 <INSERT_END> <INSERT>   largebuff = BoundBuffer(b'\x80\x94\xeb\xdc\x03')
    smallbuff = BoundBuffer(b'\x14')
    assert datautils.unpack_varint(smallbuff) == 20
    assert datautils.unpack_varint(largebuff) == 1000000000

def test_pack_varint():
    assert datautils.pack_varint(20) == b'\x14'
    assert datautils.pack_varint(1000000000) == b'\x80\x94\xeb\xdc\x03'
    assert datautils.pack_varint(-10000000000) is None
    assert datautils.pack_varint(10000000000) is None

def test_unpack_varlong():
    largebuff = BoundBuffer(b'\x80\xc8\xaf\xa0%')
    smallbuff = BoundBuffer(b'\x14')
    assert datautils.unpack_varlong(smallbuff) == 20
    assert datautils.unpack_varlong(largebuff) == 10000000000
pass

def test_pack_varlong():
    assert datautils.pack_varlong(20) == b'\x14'
    assert datautils.pack_varlong(10000000000) == b'\x80\xc8\xaf\xa0%'
    assert datautils.pack_varlong(10000000000000000000) is None
    assert datautils.pack_varlong(-10000000000000000000) is None
 <INSERT_END> <|endoftext|> from spock.mcp import datautils
from spock.utils import BoundBuffer

def test_unpack_varint():
    largebuff = BoundBuffer(b'\x80\x94\xeb\xdc\x03')
    smallbuff = BoundBuffer(b'\x14')
    assert datautils.unpack_varint(smallbuff) == 20
    assert datautils.unpack_varint(largebuff) == 1000000000

def test_pack_varint():
    assert datautils.pack_varint(20) == b'\x14'
    assert datautils.pack_varint(1000000000) == b'\x80\x94\xeb\xdc\x03'
    assert datautils.pack_varint(-10000000000) is None
    assert datautils.pack_varint(10000000000) is None

def test_unpack_varlong():
    largebuff = BoundBuffer(b'\x80\xc8\xaf\xa0%')
    smallbuff = BoundBuffer(b'\x14')
    assert datautils.unpack_varlong(smallbuff) == 20
    assert datautils.unpack_varlong(largebuff) == 10000000000
pass

def test_pack_varlong():
    assert datautils.pack_varlong(20) == b'\x14'
    assert datautils.pack_varlong(10000000000) == b'\x80\xc8\xaf\xa0%'
    assert datautils.pack_varlong(10000000000000000000) is None
    assert datautils.pack_varlong(-10000000000000000000) is None

Prompt: Add varint and varlong tests


from unittest import TestCase

import plotly.graph_objs as go
import plotly.graph_reference as gr

OLD_CLASS_NAMES = ['AngularAxis', 'Annotation', 'Annotations', 'Area',
                   'Bar', 'Box', 'ColorBar', 'Contour', 'Contours',
                   'Data', 'ErrorX', 'ErrorY', 'ErrorZ', 'Figure',
                   'Font', 'Heatmap', 'Histogram', 'Histogram2d',
                   'Histogram2dContour', 'Layout', 'Legend', 'Line',
                   'Margin', 'Marker', 'RadialAxis', 'Scatter',
                   'Scatter3d', 'Scene', 'Stream', 'Surface', 'Trace',
                   'XAxis', 'XBins', 'YAxis', 'YBins', 'ZAxis']

class TestBackwardsCompat(TestCase):

    def test_old_class_names(self):

        # these were all defined at one point, we want to maintain backwards
        # compat, so we basically just create a checkpoint with this test.

        for class_name in OLD_CLASS_NAMES:
            self.assertIn(class_name, go.__dict__.keys())

class TestGraphObjs(TestCase):

    def test_traces_should_be_defined(self):

        # we *always* want to create classes for traces

        class_names = [gr.string_to_class_name(object_name)
                       for object_name in gr.TRACE_NAMES]
        for class_name in class_names:
            self.assertIn(class_name, go.__dict__.keys())

    def test_no_new_classes(self):

        # for maintenance reasons, we don't want to generate new class defs

        expected_class_names = {gr.string_to_class_name(object_name)
                                for object_name in gr.TRACE_NAMES}
        expected_class_names.update(OLD_CLASS_NAMES)

        # assume that CapitalCased keys are the classes we defined
        current_class_names = {key for key in go.__dict__.keys()
                               if key[0].isupper()}
        self.assertEqual(current_class_names, expected_class_names)

Add failing specs for current/future class names.

Response:
<REPLACE_OLD>  <REPLACE_NEW> from unittest import TestCase

import plotly.graph_objs as go
import plotly.graph_reference as gr

OLD_CLASS_NAMES = ['AngularAxis', 'Annotation', 'Annotations', 'Area',
                   'Bar', 'Box', 'ColorBar', 'Contour', 'Contours',
                   'Data', 'ErrorX', 'ErrorY', 'ErrorZ', 'Figure',
                   'Font', 'Heatmap', 'Histogram', 'Histogram2d',
                   'Histogram2dContour', 'Layout', 'Legend', 'Line',
                   'Margin', 'Marker', 'RadialAxis', 'Scatter',
                   'Scatter3d', 'Scene', 'Stream', 'Surface', 'Trace',
                   'XAxis', 'XBins', 'YAxis', 'YBins', 'ZAxis']

class TestBackwardsCompat(TestCase):

    def test_old_class_names(self):

        # these were all defined at one point, we want to maintain backwards
        # compat, so we basically just create a checkpoint with this test.

        for class_name in OLD_CLASS_NAMES:
            self.assertIn(class_name, go.__dict__.keys())

class TestGraphObjs(TestCase):

    def test_traces_should_be_defined(self):

        # we *always* want to create classes for traces

        class_names = [gr.string_to_class_name(object_name)
                       for object_name in gr.TRACE_NAMES]
        for class_name in class_names:
            self.assertIn(class_name, go.__dict__.keys())

    def test_no_new_classes(self):

        # for maintenance reasons, we don't want to generate new class defs

        expected_class_names = {gr.string_to_class_name(object_name)
                                for object_name in gr.TRACE_NAMES}
        expected_class_names.update(OLD_CLASS_NAMES)

        # assume that CapitalCased keys are the classes we defined
        current_class_names = {key for key in go.__dict__.keys()
                               if key[0].isupper()}
        self.assertEqual(current_class_names, expected_class_names)
 <REPLACE_END> <|endoftext|> from unittest import TestCase

import plotly.graph_objs as go
import plotly.graph_reference as gr

OLD_CLASS_NAMES = ['AngularAxis', 'Annotation', 'Annotations', 'Area',
                   'Bar', 'Box', 'ColorBar', 'Contour', 'Contours',
                   'Data', 'ErrorX', 'ErrorY', 'ErrorZ', 'Figure',
                   'Font', 'Heatmap', 'Histogram', 'Histogram2d',
                   'Histogram2dContour', 'Layout', 'Legend', 'Line',
                   'Margin', 'Marker', 'RadialAxis', 'Scatter',
                   'Scatter3d', 'Scene', 'Stream', 'Surface', 'Trace',
                   'XAxis', 'XBins', 'YAxis', 'YBins', 'ZAxis']

class TestBackwardsCompat(TestCase):

    def test_old_class_names(self):

        # these were all defined at one point, we want to maintain backwards
        # compat, so we basically just create a checkpoint with this test.

        for class_name in OLD_CLASS_NAMES:
            self.assertIn(class_name, go.__dict__.keys())

class TestGraphObjs(TestCase):

    def test_traces_should_be_defined(self):

        # we *always* want to create classes for traces

        class_names = [gr.string_to_class_name(object_name)
                       for object_name in gr.TRACE_NAMES]
        for class_name in class_names:
            self.assertIn(class_name, go.__dict__.keys())

    def test_no_new_classes(self):

        # for maintenance reasons, we don't want to generate new class defs

        expected_class_names = {gr.string_to_class_name(object_name)
                                for object_name in gr.TRACE_NAMES}
        expected_class_names.update(OLD_CLASS_NAMES)

        # assume that CapitalCased keys are the classes we defined
        current_class_names = {key for key in go.__dict__.keys()
                               if key[0].isupper()}
        self.assertEqual(current_class_names, expected_class_names)

Prompt: Add failing specs for current/future class names.


from __future__ import absolute_import
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime
from matplotlib.dates import date2num
import plotly.tools as tls
from unittest import TestCase

from plotly.tests.test_optional.optional_utils import compare_dict, run_fig

class TestDateTimes(TestCase):
    def test_normal_mpl_dates(self):
        datetime_format = '%Y-%m-%d %H:%M:%S'
        y = [1, 2, 3, 4]
        date_strings = ['2010-01-04 00:00:00',
                        '2010-01-04 10:00:00',
                        '2010-01-04 23:00:59',
                        '2010-01-05 00:00:00']

        # 1. create datetimes from the strings
        dates = [datetime.datetime.strptime(date_string, datetime_format)
                 for date_string in date_strings]

        # 2. create the mpl_dates from these datetimes
        mpl_dates = date2num(dates)

        # make a figure in mpl
        fig, ax = plt.subplots()
        ax.plot_date(mpl_dates, y)

        # convert this figure to plotly's graph_objs
        pfig = tls.mpl_to_plotly(fig)

        print date_strings
        print pfig['data'][0]['x']
        # we use the same format here, so we expect equality here
        self.assertEqual(pfig['data'][0]['x'], date_strings)

Add test for dates in mpl.

Add test for dates in mpl.

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import absolute_import
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime
from matplotlib.dates import date2num
import plotly.tools as tls
from unittest import TestCase

from plotly.tests.test_optional.optional_utils import compare_dict, run_fig

class TestDateTimes(TestCase):
    def test_normal_mpl_dates(self):
        datetime_format = '%Y-%m-%d %H:%M:%S'
        y = [1, 2, 3, 4]
        date_strings = ['2010-01-04 00:00:00',
                        '2010-01-04 10:00:00',
                        '2010-01-04 23:00:59',
                        '2010-01-05 00:00:00']

        # 1. create datetimes from the strings
        dates = [datetime.datetime.strptime(date_string, datetime_format)
                 for date_string in date_strings]

        # 2. create the mpl_dates from these datetimes
        mpl_dates = date2num(dates)

        # make a figure in mpl
        fig, ax = plt.subplots()
        ax.plot_date(mpl_dates, y)

        # convert this figure to plotly's graph_objs
        pfig = tls.mpl_to_plotly(fig)

        print date_strings
        print pfig['data'][0]['x']
        # we use the same format here, so we expect equality here
        self.assertEqual(pfig['data'][0]['x'], date_strings)
 <REPLACE_END> <|endoftext|> from __future__ import absolute_import
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime
from matplotlib.dates import date2num
import plotly.tools as tls
from unittest import TestCase

from plotly.tests.test_optional.optional_utils import compare_dict, run_fig

class TestDateTimes(TestCase):
    def test_normal_mpl_dates(self):
        datetime_format = '%Y-%m-%d %H:%M:%S'
        y = [1, 2, 3, 4]
        date_strings = ['2010-01-04 00:00:00',
                        '2010-01-04 10:00:00',
                        '2010-01-04 23:00:59',
                        '2010-01-05 00:00:00']

        # 1. create datetimes from the strings
        dates = [datetime.datetime.strptime(date_string, datetime_format)
                 for date_string in date_strings]

        # 2. create the mpl_dates from these datetimes
        mpl_dates = date2num(dates)

        # make a figure in mpl
        fig, ax = plt.subplots()
        ax.plot_date(mpl_dates, y)

        # convert this figure to plotly's graph_objs
        pfig = tls.mpl_to_plotly(fig)

        print date_strings
        print pfig['data'][0]['x']
        # we use the same format here, so we expect equality here
        self.assertEqual(pfig['data'][0]['x'], date_strings)

Prompt: Add test for dates in mpl.


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

# coding=utf-8
"""Package metadata for RLDS.

This is kept in a separate module so that it can be imported from setup.py, at
a time when RLDS's dependencies may not have been installed yet.
"""

# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '1'
_PATCH_VERSION = '5'

# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])

Response:
<REPLACE_OLD> '4'

# <REPLACE_NEW> '5'

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

# coding=utf-8
"""Package metadata for RLDS.

This is kept in a separate module so that it can be imported from setup.py, at
a time when RLDS's dependencies may not have been installed yet.
"""

# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '1'
_PATCH_VERSION = '5'

# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])

Prompt:
Update RLDS to 0.1.5 (already uploaded to Pypi)

PiperOrigin-RevId: 467605984
Change-Id: I421e884c38da5be935e085d5419642b8decf5373

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

# coding=utf-8
"""Package metadata for RLDS.

This is kept in a separate module so that it can be imported from setup.py, at
a time when RLDS's dependencies may not have been installed yet.
"""

# We follow Semantic Versioning (https://semver.org/)
_MAJOR_VERSION = '0'
_MINOR_VERSION = '1'
_PATCH_VERSION = '4'

# Example: '0.4.2'
__version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])


# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-27 22:51
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('member', '0007_auto_20160726_1703'),
    ]

    operations = [
        migrations.RenameField(
            model_name='address',
            old_name='lat',
            new_name='latitude',
        ),
        migrations.RenameField(
            model_name='address',
            old_name='lon',
            new_name='longitude',
        ),
    ]

Add missing migration file for latitude and longitude

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-27 22:51
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('member', '0007_auto_20160726_1703'),
    ]

    operations = [
        migrations.RenameField(
            model_name='address',
            old_name='lat',
            new_name='latitude',
        ),
        migrations.RenameField(
            model_name='address',
            old_name='lon',
            new_name='longitude',
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-27 22:51
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('member', '0007_auto_20160726_1703'),
    ]

    operations = [
        migrations.RenameField(
            model_name='address',
            old_name='lat',
            new_name='latitude',
        ),
        migrations.RenameField(
            model_name='address',
            old_name='lon',
            new_name='longitude',
        ),
    ]

Prompt: Add missing migration file for latitude and longitude


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

from wlauto.common.resources import FileResource

class ReventFile(FileResource):

    name = 'revent'

    def __init__(self, owner, stage):
        super(ReventFile, self).__init__(owner)
        self.stage = stage

class JarFile(FileResource):

    name = 'jar'

class ApkFile(FileResource):

    name = 'apk'

    def __init__(self, owner, platform=None):
        super(ApkFile, self).__init__(owner)
        self.platform = platform

    def __str__(self):
        return '<{}\'s {} APK>'.format(self.owner, self.platform)

class UiautoApkFile(FileResource):

    name = 'uiautoapk'

    def __init__(self, owner, platform=None):
        super(UiautoApkFile, self).__init__(owner)
        self.platform = platform

    def __str__(self):
        return '<{}\'s {} UiAuto APK>'.format(self.owner, self.platform)

Add a UiautoApk resource type.

Response:
<INSERT> self.platform)

class UiautoApkFile(FileResource):

    name = 'uiautoapk'

    def __init__(self, owner, platform=None):
        super(UiautoApkFile, self).__init__(owner)
        self.platform = platform

    def __str__(self):
        return '<{}\'s {} UiAuto APK>'.format(self.owner, <INSERT_END> <|endoftext|> #    Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from wlauto.common.resources import FileResource

class ReventFile(FileResource):

    name = 'revent'

    def __init__(self, owner, stage):
        super(ReventFile, self).__init__(owner)
        self.stage = stage

class JarFile(FileResource):

    name = 'jar'

class ApkFile(FileResource):

    name = 'apk'

    def __init__(self, owner, platform=None):
        super(ApkFile, self).__init__(owner)
        self.platform = platform

    def __str__(self):
        return '<{}\'s {} APK>'.format(self.owner, self.platform)

class UiautoApkFile(FileResource):

    name = 'uiautoapk'

    def __init__(self, owner, platform=None):
        super(UiautoApkFile, self).__init__(owner)
        self.platform = platform

    def __str__(self):
        return '<{}\'s {} UiAuto APK>'.format(self.owner, self.platform)

Prompt:
AndroidResource: Add a UiautoApk resource type.

When moving to Uiautomation 2, tests are now complied into apk files rather than
jar files. To avoid conflicts with regular workload apks a new resource type is
added to retrieve the test files which will be renamed to have the extension
.uiautoapk

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

from wlauto.common.resources import FileResource

class ReventFile(FileResource):

    name = 'revent'

    def __init__(self, owner, stage):
        super(ReventFile, self).__init__(owner)
        self.stage = stage

class JarFile(FileResource):

    name = 'jar'

class ApkFile(FileResource):

    name = 'apk'

    def __init__(self, owner, platform=None):
        super(ApkFile, self).__init__(owner)
        self.platform = platform

    def __str__(self):
        return '<{}\'s {} APK>'.format(self.owner, self.platform)


# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 35.0.0

from troposphere import Tags

from . import AWSObject, AWSProperty
from .validators import integer

class Repository(AWSProperty):
    props = {
        "PathComponent": (str, True),
        "RepositoryUrl": (str, True),
    }

class EnvironmentEC2(AWSObject):
    resource_type = "AWS::Cloud9::EnvironmentEC2"

    props = {
        "AutomaticStopTimeMinutes": (integer, False),
        "ConnectionType": (str, False),
        "Description": (str, False),
        "ImageId": (str, False),
        "InstanceType": (str, True),
        "Name": (str, False),
        "OwnerArn": (str, False),
        "Repositories": ([Repository], False),
        "SubnetId": (str, False),
        "Tags": (Tags, False),
    }

Update Cloud9 per 2021-04-01 changes

Update Cloud9 per 2021-04-01 changes

Response:
<REPLACE_OLD> 2012-2017, <REPLACE_NEW> 2012-2021, <REPLACE_END> <REPLACE_OLD> license.

from <REPLACE_NEW> license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 35.0.0

from troposphere import Tags

from <REPLACE_END> <INSERT> "ConnectionType": (str, False),
        <INSERT_END> <INSERT> (str, False),
        "ImageId": <INSERT_END> <INSERT>     "Tags": (Tags, False),
    <INSERT_END> <|endoftext|> # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 35.0.0

from troposphere import Tags

from . import AWSObject, AWSProperty
from .validators import integer

class Repository(AWSProperty):
    props = {
        "PathComponent": (str, True),
        "RepositoryUrl": (str, True),
    }

class EnvironmentEC2(AWSObject):
    resource_type = "AWS::Cloud9::EnvironmentEC2"

    props = {
        "AutomaticStopTimeMinutes": (integer, False),
        "ConnectionType": (str, False),
        "Description": (str, False),
        "ImageId": (str, False),
        "InstanceType": (str, True),
        "Name": (str, False),
        "OwnerArn": (str, False),
        "Repositories": ([Repository], False),
        "SubnetId": (str, False),
        "Tags": (Tags, False),
    }

Prompt:
Update Cloud9 per 2021-04-01 changes

# Copyright (c) 2012-2017, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.

from . import AWSObject, AWSProperty
from .validators import integer

class Repository(AWSProperty):
    props = {
        "PathComponent": (str, True),
        "RepositoryUrl": (str, True),
    }

class EnvironmentEC2(AWSObject):
    resource_type = "AWS::Cloud9::EnvironmentEC2"

    props = {
        "AutomaticStopTimeMinutes": (integer, False),
        "Description": (str, False),
        "InstanceType": (str, True),
        "Name": (str, False),
        "OwnerArn": (str, False),
        "Repositories": ([Repository], False),
        "SubnetId": (str, False),
    }


"""Module containing a preprocessor that removes the outputs from code cells"""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from .base import Preprocessor

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ClearOutputPreprocessor(Preprocessor):
    """
    Removes the output from all code cells in a notebook.
    """

    def preprocess_cell(self, cell, resources, cell_index):
        """
        Apply a transformation on each cell. See base.py for details.
        """
        if cell.cell_type == 'code':
            cell.outputs = []
            cell.prompt_number = None
        return cell, resources

Response:
<REPLACE_OLD> cell['prompt_number'] <REPLACE_NEW> cell.prompt_number <REPLACE_END> <|endoftext|> """Module containing a preprocessor that removes the outputs from code cells"""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from .base import Preprocessor

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ClearOutputPreprocessor(Preprocessor):
    """
    Removes the output from all code cells in a notebook.
    """

    def preprocess_cell(self, cell, resources, cell_index):
        """
        Apply a transformation on each cell. See base.py for details.
        """
        if cell.cell_type == 'code':
            cell.outputs = []
            cell.prompt_number = None
        return cell, resources

Prompt:
Use cell.prompt_number rather than cell['prompt_number']

"""Module containing a preprocessor that removes the outputs from code cells"""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from .base import Preprocessor

#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ClearOutputPreprocessor(Preprocessor):
    """
    Removes the output from all code cells in a notebook.
    """

    def preprocess_cell(self, cell, resources, cell_index):
        """
        Apply a transformation on each cell. See base.py for details.
        """
        if cell.cell_type == 'code':
            cell.outputs = []
            cell['prompt_number'] = None
        return cell, resources


from django.test import SimpleTestCase

class OtherTest(SimpleTestCase):
    """
    In reality, apps often can have so many tests this is a more practical
    organising pattern.
    """

    def test_success(self):
        self.assertEqual(1 + 1, 2)

Document from the reality that while breaking apps down is a good idea, even then you often have a sufficient number of topic areas to cover that can't be easily split into more apps, i.e. TestCase classes are insufficient to group the relevant tests together, and a 5k tests.py file is almost certainly a bad idea.

Response:
<INSERT> from django.test import SimpleTestCase

class OtherTest(SimpleTestCase):
 <INSERT_END> <INSERT>   """
    In reality, apps often can have so many tests this is a more practical
    organising pattern.
    """

    def test_success(self):
        self.assertEqual(1 + 1, 2)

 <INSERT_END> <|endoftext|> from django.test import SimpleTestCase

class OtherTest(SimpleTestCase):
    """
    In reality, apps often can have so many tests this is a more practical
    organising pattern.
    """

    def test_success(self):
        self.assertEqual(1 + 1, 2)

Prompt: Document from the reality that while breaking apps down is a good idea, even then you often have a sufficient number of topic areas to cover that can't be easily split into more apps, i.e. TestCase classes are insufficient to group the relevant tests together, and a 5k tests.py file is almost certainly a bad idea.


import os
import re

from django.conf import settings
from django.core.management import call_command, BaseCommand

class Command(BaseCommand):
    """Load the Django project fixtures and all version fixtures"""

    def handle(self, **options):
        fixtures_dir = os.path.join(settings.DIRNAME, 'cbv', 'fixtures')
        self.stdout.write('Loading project.json')
        call_command('loaddata', 'cbv/fixtures/project.json')
        version_fixtures = [re.match(r'((?:\d+\.){2,3}json)', filename) for filename in os.listdir(fixtures_dir)]
        for match in version_fixtures:
            try:
                fixture = match.group()
            except AttributeError:
                continue
            self.stdout.write('Loading {}'.format(fixture))
            call_command('loaddata', 'cbv/fixtures/{}'.format(fixture))

Add management command to load all version fixtures

Because life's too short

Response:
<INSERT> import os
import re

from django.conf import settings
from django.core.management import call_command, BaseCommand

class Command(BaseCommand):
 <INSERT_END> <INSERT>   """Load the Django project fixtures and all version fixtures"""

    def handle(self, **options):
        fixtures_dir = os.path.join(settings.DIRNAME, 'cbv', 'fixtures')
        self.stdout.write('Loading project.json')
        call_command('loaddata', 'cbv/fixtures/project.json')
        version_fixtures = [re.match(r'((?:\d+\.){2,3}json)', filename) for filename in os.listdir(fixtures_dir)]
        for match in version_fixtures:
            try:
                fixture = match.group()
            except AttributeError:
                continue
            self.stdout.write('Loading {}'.format(fixture))
            call_command('loaddata', 'cbv/fixtures/{}'.format(fixture))
 <INSERT_END> <|endoftext|> import os
import re

from django.conf import settings
from django.core.management import call_command, BaseCommand

class Command(BaseCommand):
    """Load the Django project fixtures and all version fixtures"""

    def handle(self, **options):
        fixtures_dir = os.path.join(settings.DIRNAME, 'cbv', 'fixtures')
        self.stdout.write('Loading project.json')
        call_command('loaddata', 'cbv/fixtures/project.json')
        version_fixtures = [re.match(r'((?:\d+\.){2,3}json)', filename) for filename in os.listdir(fixtures_dir)]
        for match in version_fixtures:
            try:
                fixture = match.group()
            except AttributeError:
                continue
            self.stdout.write('Loading {}'.format(fixture))
            call_command('loaddata', 'cbv/fixtures/{}'.format(fixture))

Prompt:
Add management command to load all version fixtures

Because life's too short


from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'upload.views.home', name='home'),

    url(r'^$', lambda x: HttpResponseRedirect('/upload/new/')),
    url(r'^upload/', include('fileupload.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

from os.path import join, abspath, dirname
urlpatterns += patterns('',
    (r'^media/(.*)$', 'django.views.static.serve', {'document_root': join(abspath(dirname(dirname(__file__))), 'media')}),
)

Fix serve media files path

Fix serve media files path

Response:
<REPLACE_OLD> include(admin.site.urls)),
)

import os
urlpatterns <REPLACE_NEW> include(admin.site.urls)),
)

from os.path import join, abspath, dirname
urlpatterns <REPLACE_END> <REPLACE_OLD> os.path.join(os.path.abspath(os.path.dirname(__file__)), <REPLACE_NEW> join(abspath(dirname(dirname(__file__))), <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'upload.views.home', name='home'),

    url(r'^$', lambda x: HttpResponseRedirect('/upload/new/')),
    url(r'^upload/', include('fileupload.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

from os.path import join, abspath, dirname
urlpatterns += patterns('',
    (r'^media/(.*)$', 'django.views.static.serve', {'document_root': join(abspath(dirname(dirname(__file__))), 'media')}),
)

Prompt:
Fix serve media files path

from django.conf.urls import patterns, include, url
from django.http import HttpResponseRedirect

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'upload.views.home', name='home'),

    url(r'^$', lambda x: HttpResponseRedirect('/upload/new/')),
    url(r'^upload/', include('fileupload.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

import os
urlpatterns += patterns('',
    (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)


from setuptools import setup, find_packages
from ckanext.qa import __version__

setup(
    name='ckanext-qa',
    version=__version__,
    description='Quality Assurance plugin for CKAN',
    long_description='',
    classifiers=[],
    keywords='',
    author='Open Knowledge Foundation',
    author_email='info@okfn.org',
    url='http://ckan.org/wiki/Extensions',
    license='mit',
    packages=find_packages(exclude=['tests']),
    namespace_packages=['ckanext', 'ckanext.qa'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'celery==2.4.2',
        'kombu==2.1.3',
        'kombu-sqlalchemy==1.1.0',
        'SQLAlchemy>=0.6.6',
        'requests==0.6.4',
    ],
    tests_require=[
        'nose',
        'mock',
    ],
    entry_points='''
    [paste.paster_command]
    qa=ckanext.qa.commands:QACommand

    [ckan.plugins]
    qa=ckanext.qa.plugin:QAPlugin

    [ckan.celery_task]
    tasks=ckanext.qa.celery_import:task_imports
    ''',
)

Response:
<REPLACE_OLD> 'celery==2.4.5',
 <REPLACE_NEW> 'celery==2.4.2',
 <REPLACE_END> <REPLACE_OLD> 'kombu==1.5.1',
 <REPLACE_NEW> 'kombu==2.1.3',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
from ckanext.qa import __version__

setup(
    name='ckanext-qa',
    version=__version__,
    description='Quality Assurance plugin for CKAN',
    long_description='',
    classifiers=[],
    keywords='',
    author='Open Knowledge Foundation',
    author_email='info@okfn.org',
    url='http://ckan.org/wiki/Extensions',
    license='mit',
    packages=find_packages(exclude=['tests']),
    namespace_packages=['ckanext', 'ckanext.qa'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'celery==2.4.2',
        'kombu==2.1.3',
        'kombu-sqlalchemy==1.1.0',
        'SQLAlchemy>=0.6.6',
        'requests==0.6.4',
    ],
    tests_require=[
        'nose',
        'mock',
    ],
    entry_points='''
    [paste.paster_command]
    qa=ckanext.qa.commands:QACommand

    [ckan.plugins]
    qa=ckanext.qa.plugin:QAPlugin

    [ckan.celery_task]
    tasks=ckanext.qa.celery_import:task_imports
    ''',
)

Prompt:
Change celery and kombu requirements to match ckanext-datastorer

from setuptools import setup, find_packages
from ckanext.qa import __version__

setup(
    name='ckanext-qa',
    version=__version__,
    description='Quality Assurance plugin for CKAN',
    long_description='',
    classifiers=[],
    keywords='',
    author='Open Knowledge Foundation',
    author_email='info@okfn.org',
    url='http://ckan.org/wiki/Extensions',
    license='mit',
    packages=find_packages(exclude=['tests']),
    namespace_packages=['ckanext', 'ckanext.qa'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'celery==2.4.5',
        'kombu==1.5.1',
        'kombu-sqlalchemy==1.1.0',
        'SQLAlchemy>=0.6.6',
        'requests==0.6.4',
    ],
    tests_require=[
        'nose',
        'mock',
    ],
    entry_points='''
    [paste.paster_command]
    qa=ckanext.qa.commands:QACommand

    [ckan.plugins]
    qa=ckanext.qa.plugin:QAPlugin

    [ckan.celery_task]
    tasks=ckanext.qa.celery_import:task_imports
    ''',
)