from nose.tools import *

from scripts.box.migrate_to_external_account import do_migration, get_targets

from framework.auth import Auth

from tests.base import OsfTestCase
from tests.factories import ProjectFactory, UserFactory

from website.addons.box.model import BoxUserSettings
from website.addons.box.tests.factories import BoxOAuthSettingsFactory

class TestBoxMigration(OsfTestCase):
    # Note: BoxUserSettings.user_settings has to be changed to foreign_user_settings (model and mongo). See migration instructions

    def test_migration_no_project(self):

        user = UserFactory()

        user.add_addon('box')
        user_addon = user.get_addon('box')
        user_addon.oauth_settings = BoxOAuthSettingsFactory()
        user_addon.save()

        do_migration([user_addon])
        user_addon.reload()

        assert_is_none(user_addon.oauth_settings)
        assert_equal(len(user.external_accounts), 1)

        account = user.external_accounts[0]
        assert_equal(account.provider, 'box')
        assert_equal(account.oauth_key, 'abcdef1')

    def test_migration_removes_targets(self):
        BoxUserSettings.remove()

        user = UserFactory()
        project = ProjectFactory(creator=user)

        user.add_addon('box', auth=Auth(user))
        user_addon = user.get_addon('box')
        user_addon.oauth_settings = BoxOAuthSettingsFactory()
        user_addon.save()

        project.add_addon('box', auth=Auth(user))
        node_addon = project.get_addon('box')
        node_addon.foreign_user_settings = user_addon
        node_addon.save()

        assert_equal(get_targets().count(), 1)

        do_migration([user_addon])
        user_addon.reload()

        assert_equal(get_targets().count(), 0)

    def test_migration_multiple_users(self):
        user1 = UserFactory()
        user2 = UserFactory()
        oauth_settings = BoxOAuthSettingsFactory()

        user1.add_addon('box')
        user1_addon = user1.get_addon('box')
        user1_addon.oauth_settings = oauth_settings
        user1_addon.save()

        user2.add_addon('box')
        user2_addon = user2.get_addon('box')
        user2_addon.oauth_settings = oauth_settings
        user2_addon.save()

        do_migration([user1_addon, user2_addon])
        user1_addon.reload()
        user2_addon.reload()

        assert_equal(
            user1.external_accounts[0],
            user2.external_accounts[0],
        )

    def test_get_targets(self):
        BoxUserSettings.remove()
        addons = [
            BoxUserSettings(),
            BoxUserSettings(oauth_settings=BoxOAuthSettingsFactory()),
        ]
        for addon in addons:
            addon.save()
        targets = get_targets()
        assert_equal(targets.count(), 1)
        assert_equal(targets[0]._id, addons[-1]._id)

Add test for box migration script

Add test for box migration script

Response:
<REPLACE_OLD>  <REPLACE_NEW> from nose.tools import *

from scripts.box.migrate_to_external_account import do_migration, get_targets

from framework.auth import Auth

from tests.base import OsfTestCase
from tests.factories import ProjectFactory, UserFactory

from website.addons.box.model import BoxUserSettings
from website.addons.box.tests.factories import BoxOAuthSettingsFactory

class TestBoxMigration(OsfTestCase):
    # Note: BoxUserSettings.user_settings has to be changed to foreign_user_settings (model and mongo). See migration instructions

    def test_migration_no_project(self):

        user = UserFactory()

        user.add_addon('box')
        user_addon = user.get_addon('box')
        user_addon.oauth_settings = BoxOAuthSettingsFactory()
        user_addon.save()

        do_migration([user_addon])
        user_addon.reload()

        assert_is_none(user_addon.oauth_settings)
        assert_equal(len(user.external_accounts), 1)

        account = user.external_accounts[0]
        assert_equal(account.provider, 'box')
        assert_equal(account.oauth_key, 'abcdef1')

    def test_migration_removes_targets(self):
        BoxUserSettings.remove()

        user = UserFactory()
        project = ProjectFactory(creator=user)

        user.add_addon('box', auth=Auth(user))
        user_addon = user.get_addon('box')
        user_addon.oauth_settings = BoxOAuthSettingsFactory()
        user_addon.save()

        project.add_addon('box', auth=Auth(user))
        node_addon = project.get_addon('box')
        node_addon.foreign_user_settings = user_addon
        node_addon.save()

        assert_equal(get_targets().count(), 1)

        do_migration([user_addon])
        user_addon.reload()

        assert_equal(get_targets().count(), 0)

    def test_migration_multiple_users(self):
        user1 = UserFactory()
        user2 = UserFactory()
        oauth_settings = BoxOAuthSettingsFactory()

        user1.add_addon('box')
        user1_addon = user1.get_addon('box')
        user1_addon.oauth_settings = oauth_settings
        user1_addon.save()

        user2.add_addon('box')
        user2_addon = user2.get_addon('box')
        user2_addon.oauth_settings = oauth_settings
        user2_addon.save()

        do_migration([user1_addon, user2_addon])
        user1_addon.reload()
        user2_addon.reload()

        assert_equal(
            user1.external_accounts[0],
            user2.external_accounts[0],
        )

    def test_get_targets(self):
        BoxUserSettings.remove()
        addons = [
            BoxUserSettings(),
            BoxUserSettings(oauth_settings=BoxOAuthSettingsFactory()),
        ]
        for addon in addons:
            addon.save()
        targets = get_targets()
        assert_equal(targets.count(), 1)
        assert_equal(targets[0]._id, addons[-1]._id)
 <REPLACE_END> <|endoftext|> from nose.tools import *

from scripts.box.migrate_to_external_account import do_migration, get_targets

from framework.auth import Auth

from tests.base import OsfTestCase
from tests.factories import ProjectFactory, UserFactory

from website.addons.box.model import BoxUserSettings
from website.addons.box.tests.factories import BoxOAuthSettingsFactory

class TestBoxMigration(OsfTestCase):
    # Note: BoxUserSettings.user_settings has to be changed to foreign_user_settings (model and mongo). See migration instructions

    def test_migration_no_project(self):

        user = UserFactory()

        user.add_addon('box')
        user_addon = user.get_addon('box')
        user_addon.oauth_settings = BoxOAuthSettingsFactory()
        user_addon.save()

        do_migration([user_addon])
        user_addon.reload()

        assert_is_none(user_addon.oauth_settings)
        assert_equal(len(user.external_accounts), 1)

        account = user.external_accounts[0]
        assert_equal(account.provider, 'box')
        assert_equal(account.oauth_key, 'abcdef1')

    def test_migration_removes_targets(self):
        BoxUserSettings.remove()

        user = UserFactory()
        project = ProjectFactory(creator=user)

        user.add_addon('box', auth=Auth(user))
        user_addon = user.get_addon('box')
        user_addon.oauth_settings = BoxOAuthSettingsFactory()
        user_addon.save()

        project.add_addon('box', auth=Auth(user))
        node_addon = project.get_addon('box')
        node_addon.foreign_user_settings = user_addon
        node_addon.save()

        assert_equal(get_targets().count(), 1)

        do_migration([user_addon])
        user_addon.reload()

        assert_equal(get_targets().count(), 0)

    def test_migration_multiple_users(self):
        user1 = UserFactory()
        user2 = UserFactory()
        oauth_settings = BoxOAuthSettingsFactory()

        user1.add_addon('box')
        user1_addon = user1.get_addon('box')
        user1_addon.oauth_settings = oauth_settings
        user1_addon.save()

        user2.add_addon('box')
        user2_addon = user2.get_addon('box')
        user2_addon.oauth_settings = oauth_settings
        user2_addon.save()

        do_migration([user1_addon, user2_addon])
        user1_addon.reload()
        user2_addon.reload()

        assert_equal(
            user1.external_accounts[0],
            user2.external_accounts[0],
        )

    def test_get_targets(self):
        BoxUserSettings.remove()
        addons = [
            BoxUserSettings(),
            BoxUserSettings(oauth_settings=BoxOAuthSettingsFactory()),
        ]
        for addon in addons:
            addon.save()
        targets = get_targets()
        assert_equal(targets.count(), 1)
        assert_equal(targets[0]._id, addons[-1]._id)

Prompt: Add test for box migration script


# -*- coding: UTF-8 -*-
"""
    trytond_async.celery

    Implementation of the celery app

    This module is named celery because of the way celery workers lookup
    the app when `--proj` argument is passed to the worker. For more details
    see the celery documentation at:
    http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#about-the-app-argument
"""
from __future__ import absolute_import

import os

from celery import Celery
from trytond.config import config

try:
    from raven import Client
    from raven.contrib.celery import register_signal
except ImportError:
    pass
else:
    if os.environ.get('SENTRY_DSN'):
        register_signal(Client(os.environ.get('SENTRY_DSN')))

config.update_etc()

broker_url = config.get('async', 'broker_url')
backend_url = config.get('async', 'backend_url')

app = Celery(
    'trytond_async',
    broker=broker_url or os.environ.get('TRYTOND_ASYNC__BROKER_URL'),
    backend=backend_url or os.environ.get('TRYTOND_ASYNC__BACKEND_URL'),
    include=['trytond_async.tasks']
)

app.conf.update(
    CELERY_TASK_RESULT_EXPIRES=3600,
    CELERY_TASK_SERIALIZER='tryson',
    CELERY_RESULT_SERIALIZER='tryson',
    CELERY_ACCEPT_CONTENT=[
        'application/x-tryson',
        'application/x-python-serialize'
    ]
)

if __name__ == '__main__':
    app.start()

Use raven for logging if available

Use raven for logging if available

Response:
<REPLACE_OLD> config

config.update_etc()

broker_url <REPLACE_NEW> config

try:
    from raven import Client
    from raven.contrib.celery import register_signal
except ImportError:
    pass
else:
    if os.environ.get('SENTRY_DSN'):
        register_signal(Client(os.environ.get('SENTRY_DSN')))

config.update_etc()

broker_url <REPLACE_END> <|endoftext|> # -*- coding: UTF-8 -*-
"""
    trytond_async.celery

    Implementation of the celery app

    This module is named celery because of the way celery workers lookup
    the app when `--proj` argument is passed to the worker. For more details
    see the celery documentation at:
    http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#about-the-app-argument
"""
from __future__ import absolute_import

import os

from celery import Celery
from trytond.config import config

try:
    from raven import Client
    from raven.contrib.celery import register_signal
except ImportError:
    pass
else:
    if os.environ.get('SENTRY_DSN'):
        register_signal(Client(os.environ.get('SENTRY_DSN')))

config.update_etc()

broker_url = config.get('async', 'broker_url')
backend_url = config.get('async', 'backend_url')

app = Celery(
    'trytond_async',
    broker=broker_url or os.environ.get('TRYTOND_ASYNC__BROKER_URL'),
    backend=backend_url or os.environ.get('TRYTOND_ASYNC__BACKEND_URL'),
    include=['trytond_async.tasks']
)

app.conf.update(
    CELERY_TASK_RESULT_EXPIRES=3600,
    CELERY_TASK_SERIALIZER='tryson',
    CELERY_RESULT_SERIALIZER='tryson',
    CELERY_ACCEPT_CONTENT=[
        'application/x-tryson',
        'application/x-python-serialize'
    ]
)

if __name__ == '__main__':
    app.start()

Prompt:
Use raven for logging if available

# -*- coding: UTF-8 -*-
"""
    trytond_async.celery

    Implementation of the celery app

    This module is named celery because of the way celery workers lookup
    the app when `--proj` argument is passed to the worker. For more details
    see the celery documentation at:
    http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#about-the-app-argument
"""
from __future__ import absolute_import

import os

from celery import Celery
from trytond.config import config

config.update_etc()

broker_url = config.get('async', 'broker_url')
backend_url = config.get('async', 'backend_url')

app = Celery(
    'trytond_async',
    broker=broker_url or os.environ.get('TRYTOND_ASYNC__BROKER_URL'),
    backend=backend_url or os.environ.get('TRYTOND_ASYNC__BACKEND_URL'),
    include=['trytond_async.tasks']
)

app.conf.update(
    CELERY_TASK_RESULT_EXPIRES=3600,
    CELERY_TASK_SERIALIZER='tryson',
    CELERY_RESULT_SERIALIZER='tryson',
    CELERY_ACCEPT_CONTENT=[
        'application/x-tryson',
        'application/x-python-serialize'
    ]
)

if __name__ == '__main__':
    app.start()


from werkzeug import routing
from werkzeug import serving
from werkzeug import wrappers

from . import routes

class Steinie(routes.Router):
    def __init__(self, host="127.0.0.1", port=5151, debug=False):
        self.host = host
        self.port = port
        self.debug = debug
        super(Steinie, self).__init__()

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)

    def wsgi_app(self, environ, start_response):
        request = wrappers.Request(environ)
        response = self.handle(request)
        return wrappers.Response(response)(environ, start_response)

    def run(self):
        serving.run_simple(self.host, self.port, self, use_debugger=self.debug)

    def use(self, route, router):
        if route.startswith('/'):
            route = route[1:]
        submount = route
        if not submount.startswith('/'):
            submount = '/' + submount
        rules = [a for a in router.map.iter_rules()]

        mount = routing.EndpointPrefix(route, [routes.Submount(submount, rules)])
        self.map.add(mount)

Remove some commented out code

Remove some commented out code

Response:
<DELETE>        # if not route.endswith('/'):
        #     route += '/'
 <DELETE_END> <DELETE>        # import ipdb; ipdb.set_trace()
 <DELETE_END> <|endoftext|> from werkzeug import routing
from werkzeug import serving
from werkzeug import wrappers

from . import routes

class Steinie(routes.Router):
    def __init__(self, host="127.0.0.1", port=5151, debug=False):
        self.host = host
        self.port = port
        self.debug = debug
        super(Steinie, self).__init__()

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)

    def wsgi_app(self, environ, start_response):
        request = wrappers.Request(environ)
        response = self.handle(request)
        return wrappers.Response(response)(environ, start_response)

    def run(self):
        serving.run_simple(self.host, self.port, self, use_debugger=self.debug)

    def use(self, route, router):
        if route.startswith('/'):
            route = route[1:]
        submount = route
        if not submount.startswith('/'):
            submount = '/' + submount
        rules = [a for a in router.map.iter_rules()]

        mount = routing.EndpointPrefix(route, [routes.Submount(submount, rules)])
        self.map.add(mount)

Prompt:
Remove some commented out code

from werkzeug import routing
from werkzeug import serving
from werkzeug import wrappers

from . import routes

class Steinie(routes.Router):
    def __init__(self, host="127.0.0.1", port=5151, debug=False):
        self.host = host
        self.port = port
        self.debug = debug
        super(Steinie, self).__init__()

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)

    def wsgi_app(self, environ, start_response):
        request = wrappers.Request(environ)
        response = self.handle(request)
        return wrappers.Response(response)(environ, start_response)

    def run(self):
        serving.run_simple(self.host, self.port, self, use_debugger=self.debug)

    def use(self, route, router):
        # if not route.endswith('/'):
        #     route += '/'
        if route.startswith('/'):
            route = route[1:]
        submount = route
        if not submount.startswith('/'):
            submount = '/' + submount
        rules = [a for a in router.map.iter_rules()]

        mount = routing.EndpointPrefix(route, [routes.Submount(submount, rules)])
        self.map.add(mount)
        # import ipdb; ipdb.set_trace()


from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse

CONST_COLLECTIONS_NAME = 'collections'

def generateArgumentsFromParser():
    parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for creating a collection of items.")
    parser.add_argument('--action', dest='action', required=True)
    parser.add_argument('--user', dest='username', required=True)
    parser.add_argument('--name', dest='collectionName', required=True)
    parser.add_argument('--type', dest='collectionType', required=False)
    return parser.parse_args()

def generateFileName(username, collectionName):
    return CONST_COLLECTIONS_NAME + "/" + username + "_" + CONST_COLLECTIONS_NAME + "/" + username + "_" + collectionName + "_collection.dat"

def generateNewCollection(username, collectionType, collectionName):
    return Collection(username, collectionType, collectionName, [])

def writeCollectionToFile(collectionFileName, arguments):
    collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
    collectionFile = open(collectionFileName, 'w')
    collectionFile.write(collection.toJSON())
    collectionFile.close()

def main():
        arguments = generateArgumentsFromParser()
        collectionFileName = generateFileName(arguments.username, arguments.collectionName)

        if arguments.action.lower() == "create":
            createCollectionFile(arguments.username, arguments.collectionName)
            writeCollectionToFile(collectionFileName, arguments)

        elif arguments.action.lower() == "update":
            return None

if __name__ == '__main__':
    main()

Refactor create action into function

Refactor create action into function

Response:
<INSERT> writeCollectionToFile(collectionFileName, arguments):
    collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
    collectionFile = open(collectionFileName, 'w')
    collectionFile.write(collection.toJSON())
    collectionFile.close()

def <INSERT_END> <REPLACE_OLD> collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
            collectionFile = open(collectionFileName, 'w')
            collectionFile.write(collection.toJSON())
            collectionFile.close()

 <REPLACE_NEW> writeCollectionToFile(collectionFileName, arguments)

 <REPLACE_END> <|endoftext|> from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse

CONST_COLLECTIONS_NAME = 'collections'

def generateArgumentsFromParser():
    parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for creating a collection of items.")
    parser.add_argument('--action', dest='action', required=True)
    parser.add_argument('--user', dest='username', required=True)
    parser.add_argument('--name', dest='collectionName', required=True)
    parser.add_argument('--type', dest='collectionType', required=False)
    return parser.parse_args()

def generateFileName(username, collectionName):
    return CONST_COLLECTIONS_NAME + "/" + username + "_" + CONST_COLLECTIONS_NAME + "/" + username + "_" + collectionName + "_collection.dat"

def generateNewCollection(username, collectionType, collectionName):
    return Collection(username, collectionType, collectionName, [])

def writeCollectionToFile(collectionFileName, arguments):
    collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
    collectionFile = open(collectionFileName, 'w')
    collectionFile.write(collection.toJSON())
    collectionFile.close()

def main():
        arguments = generateArgumentsFromParser()
        collectionFileName = generateFileName(arguments.username, arguments.collectionName)

        if arguments.action.lower() == "create":
            createCollectionFile(arguments.username, arguments.collectionName)
            writeCollectionToFile(collectionFileName, arguments)

        elif arguments.action.lower() == "update":
            return None

if __name__ == '__main__':
    main()

Prompt:
Refactor create action into function

from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse

CONST_COLLECTIONS_NAME = 'collections'

def generateArgumentsFromParser():
    parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for creating a collection of items.")
    parser.add_argument('--action', dest='action', required=True)
    parser.add_argument('--user', dest='username', required=True)
    parser.add_argument('--name', dest='collectionName', required=True)
    parser.add_argument('--type', dest='collectionType', required=False)
    return parser.parse_args()

def generateFileName(username, collectionName):
    return CONST_COLLECTIONS_NAME + "/" + username + "_" + CONST_COLLECTIONS_NAME + "/" + username + "_" + collectionName + "_collection.dat"

def generateNewCollection(username, collectionType, collectionName):
    return Collection(username, collectionType, collectionName, [])

def main():
        arguments = generateArgumentsFromParser()
        collectionFileName = generateFileName(arguments.username, arguments.collectionName)

        if arguments.action.lower() == "create":
            createCollectionFile(arguments.username, arguments.collectionName)
            collection = generateNewCollection(arguments.username, arguments.collectionType, arguments.collectionName)
            collectionFile = open(collectionFileName, 'w')
            collectionFile.write(collection.toJSON())
            collectionFile.close()

        elif arguments.action.lower() == "update":
            return None

if __name__ == '__main__':
    main()


"""This is an example app, demonstrating usage."""

import os

from flask import Flask

from flask_jsondash.charts_builder import charts

app = Flask(__name__)
app.config['SECRET_KEY'] = 'NOTSECURELOL'
app.config.update(
    JSONDASH_FILTERUSERS=False,
    JSONDASH_GLOBALDASH=True,
    JSONDASH_GLOBAL_USER='global',
)
app.debug = True
app.register_blueprint(charts)

def _can_edit_global():
    return True

def _can_delete():
    return True

def _can_clone():
    return True

def _get_username():
    return 'anonymous'

# Config examples.
app.config['JSONDASH'] = dict(
    metadata=dict(
        created_by=_get_username,
        username=_get_username,
    ),
    static=dict(
        js_path='js/vendor/',
        css_path='css/vendor/',
    ),
    auth=dict(
        edit_global=_can_edit_global,
        clone=_can_clone,
        delete=_can_delete,
    )
)

@app.route('/', methods=['GET'])
def index():
    """Sample index."""
    return 'Visit the charts blueprint.'

if __name__ == '__main__':
    PORT = int(os.getenv('PORT', 5002))
    app.run(debug=True, port=PORT)

Enable global by default in example.

Enable global by default in example.

Response:
<REPLACE_OLD> JSONDASH_GLOBALDASH=False,
 <REPLACE_NEW> JSONDASH_GLOBALDASH=True,
 <REPLACE_END> <|endoftext|> """This is an example app, demonstrating usage."""

import os

from flask import Flask

from flask_jsondash.charts_builder import charts

app = Flask(__name__)
app.config['SECRET_KEY'] = 'NOTSECURELOL'
app.config.update(
    JSONDASH_FILTERUSERS=False,
    JSONDASH_GLOBALDASH=True,
    JSONDASH_GLOBAL_USER='global',
)
app.debug = True
app.register_blueprint(charts)

def _can_edit_global():
    return True

def _can_delete():
    return True

def _can_clone():
    return True

def _get_username():
    return 'anonymous'

# Config examples.
app.config['JSONDASH'] = dict(
    metadata=dict(
        created_by=_get_username,
        username=_get_username,
    ),
    static=dict(
        js_path='js/vendor/',
        css_path='css/vendor/',
    ),
    auth=dict(
        edit_global=_can_edit_global,
        clone=_can_clone,
        delete=_can_delete,
    )
)

@app.route('/', methods=['GET'])
def index():
    """Sample index."""
    return '<a href="/charts">Visit the charts blueprint.</a>'

if __name__ == '__main__':
    PORT = int(os.getenv('PORT', 5002))
    app.run(debug=True, port=PORT)

Prompt:
Enable global by default in example.

"""This is an example app, demonstrating usage."""

import os

from flask import Flask

from flask_jsondash.charts_builder import charts

app = Flask(__name__)
app.config['SECRET_KEY'] = 'NOTSECURELOL'
app.config.update(
    JSONDASH_FILTERUSERS=False,
    JSONDASH_GLOBALDASH=False,
    JSONDASH_GLOBAL_USER='global',
)
app.debug = True
app.register_blueprint(charts)

def _can_edit_global():
    return True

def _can_delete():
    return True

def _can_clone():
    return True

def _get_username():
    return 'anonymous'

# Config examples.
app.config['JSONDASH'] = dict(
    metadata=dict(
        created_by=_get_username,
        username=_get_username,
    ),
    static=dict(
        js_path='js/vendor/',
        css_path='css/vendor/',
    ),
    auth=dict(
        edit_global=_can_edit_global,
        clone=_can_clone,
        delete=_can_delete,
    )
)

@app.route('/', methods=['GET'])
def index():
    """Sample index."""
    return 'Visit the charts blueprint.'

if __name__ == '__main__':
    PORT = int(os.getenv('PORT', 5002))
    app.run(debug=True, port=PORT)


from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config

auth = HTTPBasicAuth()

def validate_email(email):
	''' Method to check that a valid email is provided '''
    email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
    return True if search(email_re, email) else False

@auth.verify_token
def verify_token(token=None):
    ''' Method to verify token '''
    token = request.headers.get('x-access-token')
    user_id = User.verify_authentication_token(token)
    if user_id:
        g.current_user = User.query.filter_by(id=user.id).first()
        return True
    return False

Response:
<REPLACE_OLD> HTTPBasicAuth() <REPLACE_NEW> HTTPBasicAuth()

def validate_email(email):
	''' Method to check that a valid email is provided '''
    email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
    return True if search(email_re, email) else False

@auth.verify_token
def verify_token(token=None):
    ''' Method to verify token '''
    token = request.headers.get('x-access-token')
    user_id = User.verify_authentication_token(token)
    if user_id:
        g.current_user = User.query.filter_by(id=user.id).first()
        return True
    return False
 <REPLACE_END> <|endoftext|> from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config

auth = HTTPBasicAuth()

def validate_email(email):
	''' Method to check that a valid email is provided '''
    email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
    return True if search(email_re, email) else False

@auth.verify_token
def verify_token(token=None):
    ''' Method to verify token '''
    token = request.headers.get('x-access-token')
    user_id = User.verify_authentication_token(token)
    if user_id:
        g.current_user = User.query.filter_by(id=user.id).first()
        return True
    return False

Prompt:
Add validate_email and verify_token methods
Methods to be used to:
	- check that a valid email is provided
	- check the token authenticity

from re import search
from flask import g
from flask_restplus import abort
from flask_httpauth import HTTPBasicAuth
from app.models.user import User
from instance.config import Config

auth = HTTPBasicAuth()


"""Dashboard template filters"""
from django import template
import littlechef

from kitchen.settings import REPO

register = template.Library()

@register.filter(name='get_role_list')
def get_role_list(run_list):
    """Returns the role sublist from the given run_list"""
    if run_list:
        all_roles = littlechef.lib.get_roles_in_node(
            {'run_list': run_list})
        role_list = []
        for role in all_roles:
            if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX']):
                # Only add if it doesn't start with excluded role prefixes
                role_list.append(role)
        return role_list
    else:
        return []

@register.filter(name='get_recipe_list')
def get_recipe_list(run_list):
    """Returns the recipe sublist from the given run_list"""
    if run_list:
        return littlechef.lib.get_recipes_in_node({'run_list': run_list})
    else:
        return []

Response:
<REPLACE_OLD> prev_role_list <REPLACE_NEW> if run_list:
        all_roles <REPLACE_END> <REPLACE_OLD> littlechef.lib.get_roles_in_node({'run_list': <REPLACE_NEW> littlechef.lib.get_roles_in_node(
            {'run_list': <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> prev_role_list:
 <REPLACE_NEW> all_roles:
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> role_list

@register.filter(name='get_recipe_list')
def <REPLACE_NEW> role_list
    else:
        return []

@register.filter(name='get_recipe_list')
def <REPLACE_END> <INSERT> if run_list:
        <INSERT_END> <INSERT>    else:
        return []
 <INSERT_END> <|endoftext|> """Dashboard template filters"""
from django import template
import littlechef

from kitchen.settings import REPO

register = template.Library()

@register.filter(name='get_role_list')
def get_role_list(run_list):
    """Returns the role sublist from the given run_list"""
    if run_list:
        all_roles = littlechef.lib.get_roles_in_node(
            {'run_list': run_list})
        role_list = []
        for role in all_roles:
            if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX']):
                # Only add if it doesn't start with excluded role prefixes
                role_list.append(role)
        return role_list
    else:
        return []

@register.filter(name='get_recipe_list')
def get_recipe_list(run_list):
    """Returns the recipe sublist from the given run_list"""
    if run_list:
        return littlechef.lib.get_recipes_in_node({'run_list': run_list})
    else:
        return []

Prompt:
Check 'role_list' before sending it to little_chef

"""Dashboard template filters"""
from django import template
import littlechef

from kitchen.settings import REPO

register = template.Library()

@register.filter(name='get_role_list')
def get_role_list(run_list):
    """Returns the role sublist from the given run_list"""
    prev_role_list = littlechef.lib.get_roles_in_node({'run_list': run_list})
    role_list = []
    for role in prev_role_list:
        if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX']):
            # Only add if it doesn't start with excluded role prefixes
            role_list.append(role)
    return role_list

@register.filter(name='get_recipe_list')
def get_recipe_list(run_list):
    """Returns the recipe sublist from the given run_list"""
    return littlechef.lib.get_recipes_in_node({'run_list': run_list})


from bs4 import BeautifulSoup
import json

# The URL for the page where the parking lots are listed
data_url = "http://example.com"

# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"

# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"

def parse_html(html):
    soup = BeautifulSoup(html)

    # Do everything necessary to scrape the contents of the html
    # into a dictionary of the format specified by the schema.

def get_geodata_for_lot(lot_name):
    geofile = open("./cities/" + file_name + ".geojson")
    geodata = geofile.read()
    geofile.close()
    geodata = json.loads(geodata)

    for feature in geodata["features"]:
        if feature["properties"]["name"] == lot_name:
            return {
                "lon": feature["geometry"]["coordinates"][0],
                "lat": feature["geometry"]["coordinates"][1]
            }
    return []

if __name__ == "__main__":
    file = open("../tests/sample_city.html")
    html_data = file.read()
    file.close()
    parse_html(html_data)

Add geodata parsing to sample city file

Add geodata parsing to sample city file

Response:
<REPLACE_OLD> BeautifulSoup

# <REPLACE_NEW> BeautifulSoup
import json

# <REPLACE_END> <REPLACE_OLD> schema.
 <REPLACE_NEW> schema.

def get_geodata_for_lot(lot_name):
    geofile = open("./cities/" + file_name + ".geojson")
    geodata = geofile.read()
    geofile.close()
    geodata = json.loads(geodata)

    for feature in geodata["features"]:
        if feature["properties"]["name"] == lot_name:
            return {
                "lon": feature["geometry"]["coordinates"][0],
                "lat": feature["geometry"]["coordinates"][1]
            }
    return []

if __name__ == "__main__":
    file = open("../tests/sample_city.html")
    html_data = file.read()
    file.close()
    parse_html(html_data)
 <REPLACE_END> <|endoftext|> from bs4 import BeautifulSoup
import json

# The URL for the page where the parking lots are listed
data_url = "http://example.com"

# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"

# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"

def parse_html(html):
    soup = BeautifulSoup(html)

    # Do everything necessary to scrape the contents of the html
    # into a dictionary of the format specified by the schema.

def get_geodata_for_lot(lot_name):
    geofile = open("./cities/" + file_name + ".geojson")
    geodata = geofile.read()
    geofile.close()
    geodata = json.loads(geodata)

    for feature in geodata["features"]:
        if feature["properties"]["name"] == lot_name:
            return {
                "lon": feature["geometry"]["coordinates"][0],
                "lat": feature["geometry"]["coordinates"][1]
            }
    return []

if __name__ == "__main__":
    file = open("../tests/sample_city.html")
    html_data = file.read()
    file.close()
    parse_html(html_data)

Prompt:
Add geodata parsing to sample city file

from bs4 import BeautifulSoup

# The URL for the page where the parking lots are listed
data_url = "http://example.com"

# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"

# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"

def parse_html(html):
    soup = BeautifulSoup(html)

    # Do everything necessary to scrape the contents of the html
    # into a dictionary of the format specified by the schema.


from select import select
import logging
import socket

logger = logging.getLogger("HTTPServer")

from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler

class HttpServerBase(object):
    def __init__(self, assets_path, address, backlog=10):
        self.assets_handler = FileHandler(assets_path)
        self.ws_handler = WebSocketHandler()

        self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(address)
        s.listen(backlog)

        if address[1] == 0:
            from sys import stdout
            address = s.getsockname()
            stdout.write("LISTEN ON %i\n" % address[1])
            stdout.flush()

        logger.info("Listen HTTP on %s:%s" % address)

    def serve_forever(self):
        self.running = True

        args = ((self.sock, ), (), (), 30.)
        while self.running:
            try:
                rl = select(*args)[0]

                if rl:
                    self.on_accept()
            except InterruptedError:
                pass

Add auto select port function

Add auto select port function

Response:
<REPLACE_OLD> s.listen(backlog)
 <REPLACE_NEW> s.listen(backlog)

        if address[1] == 0:
            from sys import stdout
            address = s.getsockname()
            stdout.write("LISTEN ON %i\n" % address[1])
            stdout.flush()

 <REPLACE_END> <|endoftext|>
from select import select
import logging
import socket

logger = logging.getLogger("HTTPServer")

from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler

class HttpServerBase(object):
    def __init__(self, assets_path, address, backlog=10):
        self.assets_handler = FileHandler(assets_path)
        self.ws_handler = WebSocketHandler()

        self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(address)
        s.listen(backlog)

        if address[1] == 0:
            from sys import stdout
            address = s.getsockname()
            stdout.write("LISTEN ON %i\n" % address[1])
            stdout.flush()

        logger.info("Listen HTTP on %s:%s" % address)

    def serve_forever(self):
        self.running = True

        args = ((self.sock, ), (), (), 30.)
        while self.running:
            try:
                rl = select(*args)[0]

                if rl:
                    self.on_accept()
            except InterruptedError:
                pass

Prompt:
Add auto select port function

from select import select
import logging
import socket

logger = logging.getLogger("HTTPServer")

from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler

class HttpServerBase(object):
    def __init__(self, assets_path, address, backlog=10):
        self.assets_handler = FileHandler(assets_path)
        self.ws_handler = WebSocketHandler()

        self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(address)
        s.listen(backlog)
        logger.info("Listen HTTP on %s:%s" % address)

    def serve_forever(self):
        self.running = True

        args = ((self.sock, ), (), (), 30.)
        while self.running:
            try:
                rl = select(*args)[0]

                if rl:
                    self.on_accept()
            except InterruptedError:
                pass


#!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'

if TRAJECTORY == 'linear':
    SIMULATION_TIME_IN_SECONDS = 60.0
elif TRAJECTORY == 'circular':
    SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
    SIMULATION_TIME_IN_SECONDS = 160.0

DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)

# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90

# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00

K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000

Response:
<REPLACE_OLD> 80.0
elif <REPLACE_NEW> 60.0
elif <REPLACE_END> <|endoftext|> #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'

if TRAJECTORY == 'linear':
    SIMULATION_TIME_IN_SECONDS = 60.0
elif TRAJECTORY == 'circular':
    SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
    SIMULATION_TIME_IN_SECONDS = 160.0

DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)

# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90

# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00

K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000

Prompt:
Change simulation time of linear trajectory to 60 seconds

#!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'

if TRAJECTORY == 'linear':
    SIMULATION_TIME_IN_SECONDS = 80.0
elif TRAJECTORY == 'circular':
    SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
    SIMULATION_TIME_IN_SECONDS = 160.0

DELTA_T = 0.1 # this is the sampling time
STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T)

# control constants
K_X = 0.90
K_Y = 0.90
K_THETA = 0.90

# PID control constants
K_P_V = 0.2
K_I_V = 1.905
K_D_V = 0.00

K_P_W = 0.45
K_I_W = 1.25
K_D_W = 0.000


#!/usr/bin/env python3

from setuptools import setup, find_packages

setup(
    name='ppp_datamodel',
    version='0.5',
    description='Data model for the Projet Pensées Profondes.',
    url='https://github.com/ProjetPP/PPP-datamodel-Python',
    author='Valentin Lorentz',
    author_email='valentin.lorentz+ppp@ens-lyon.org',
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries',
    ],
    packages=[
        'ppp_datamodel',
    ],
)

Bump version number to 0.5

Bump version number to 0.5

Response:
<REPLACE_OLD> version='0.4',
 <REPLACE_NEW> version='0.5',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3

from setuptools import setup, find_packages

setup(
    name='ppp_datamodel',
    version='0.5',
    description='Data model for the Projet Pensées Profondes.',
    url='https://github.com/ProjetPP/PPP-datamodel-Python',
    author='Valentin Lorentz',
    author_email='valentin.lorentz+ppp@ens-lyon.org',
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries',
    ],
    packages=[
        'ppp_datamodel',
    ],
)

Prompt:
Bump version number to 0.5

#!/usr/bin/env python3

from setuptools import setup, find_packages

setup(
    name='ppp_datamodel',
    version='0.4',
    description='Data model for the Projet Pensées Profondes.',
    url='https://github.com/ProjetPP/PPP-datamodel-Python',
    author='Valentin Lorentz',
    author_email='valentin.lorentz+ppp@ens-lyon.org',
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries',
    ],
    packages=[
        'ppp_datamodel',
    ],
)


import unittest
from cleanupfilename import rename

class TestRename(unittest.TestCase):
    files = []
    dirs = []

    def setUp(self):
        self.files = [('filename-sample.x264.mp4', 'filename.mp4'),
                      ('filename.mp4', 'filename.mp4')]
        self.dirs = [('filename sample mp4', 'filename'),
                     ('filename 540p', 'filename'),
                     ('filename [web-DL] part001.', 'filename'),
                     ('actual.file.name-1080p.BluRay.x264-GECKOS[rarbg]', 'actual file name'),
                     ]

    def test_list(self):
        for file, output in self.files:
            self.assertEqual(rename(file, False), output)
        for file, output in self.dirs:
            self.assertEqual(rename(file, True), output)

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

Add test for sabnzbd cleanupfilename.py

Add test for sabnzbd cleanupfilename.py

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest
from cleanupfilename import rename

class TestRename(unittest.TestCase):
    files = []
    dirs = []

    def setUp(self):
        self.files = [('filename-sample.x264.mp4', 'filename.mp4'),
                      ('filename.mp4', 'filename.mp4')]
        self.dirs = [('filename sample mp4', 'filename'),
                     ('filename 540p', 'filename'),
                     ('filename [web-DL] part001.', 'filename'),
                     ('actual.file.name-1080p.BluRay.x264-GECKOS[rarbg]', 'actual file name'),
                     ]

    def test_list(self):
        for file, output in self.files:
            self.assertEqual(rename(file, False), output)
        for file, output in self.dirs:
            self.assertEqual(rename(file, True), output)

if __name__ == '__main__':
    unittest.main()
 <REPLACE_END> <|endoftext|> import unittest
from cleanupfilename import rename

class TestRename(unittest.TestCase):
    files = []
    dirs = []

    def setUp(self):
        self.files = [('filename-sample.x264.mp4', 'filename.mp4'),
                      ('filename.mp4', 'filename.mp4')]
        self.dirs = [('filename sample mp4', 'filename'),
                     ('filename 540p', 'filename'),
                     ('filename [web-DL] part001.', 'filename'),
                     ('actual.file.name-1080p.BluRay.x264-GECKOS[rarbg]', 'actual file name'),
                     ]

    def test_list(self):
        for file, output in self.files:
            self.assertEqual(rename(file, False), output)
        for file, output in self.dirs:
            self.assertEqual(rename(file, True), output)

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

Prompt: Add test for sabnzbd cleanupfilename.py


from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase

from ppp_spell_checker import app

class RequestHandlerTest(PPPTestCase(app)):
    def testCorrectSentence(self):
        original = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'sentence', 'value': original}}
        answer = self.request(j)
        self.assertEqual(len(answer), 0, answer)

    def testWrongSentence(self):
        original = 'Who is the pesident of the United States'
        expected = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'sentence', 'value': original}}
        answer = self.request(j)
        self.assertEqual(len(answer), 1, answer)
        self.assertEqual(answer[0].tree, Sentence(value=expected))

    def testIrrelevantInput(self):
        original = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'resource', 'value': original}}
        answer = self.request(j)
        self.assertEqual(len(answer), 0, answer)

Write tests in a better way

Write tests in a better way

Response:
<REPLACE_OLD> self.assertEquals(len(answer), 0)

 <REPLACE_NEW> self.assertEqual(len(answer), 0, answer)

 <REPLACE_END> <REPLACE_OLD> self.assertEquals(len(answer), 1)
        self.assertIsInstance(answer[0].tree, Sentence)
        result = answer[0].tree.__getattr__('value')
        self.assertEqual(result, expected)

 <REPLACE_NEW> self.assertEqual(len(answer), 1, answer)
        self.assertEqual(answer[0].tree, Sentence(value=expected))

 <REPLACE_END> <REPLACE_OLD> self.assertEquals(len(answer), 0)
 <REPLACE_NEW> self.assertEqual(len(answer), 0, answer)
 <REPLACE_END> <|endoftext|> from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase

from ppp_spell_checker import app

class RequestHandlerTest(PPPTestCase(app)):
    def testCorrectSentence(self):
        original = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'sentence', 'value': original}}
        answer = self.request(j)
        self.assertEqual(len(answer), 0, answer)

    def testWrongSentence(self):
        original = 'Who is the pesident of the United States'
        expected = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'sentence', 'value': original}}
        answer = self.request(j)
        self.assertEqual(len(answer), 1, answer)
        self.assertEqual(answer[0].tree, Sentence(value=expected))

    def testIrrelevantInput(self):
        original = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'resource', 'value': original}}
        answer = self.request(j)
        self.assertEqual(len(answer), 0, answer)

Prompt:
Write tests in a better way

from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase

from ppp_spell_checker import app

class RequestHandlerTest(PPPTestCase(app)):
    def testCorrectSentence(self):
        original = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'sentence', 'value': original}}
        answer = self.request(j)
        self.assertEquals(len(answer), 0)

    def testWrongSentence(self):
        original = 'Who is the pesident of the United States'
        expected = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'sentence', 'value': original}}
        answer = self.request(j)
        self.assertEquals(len(answer), 1)
        self.assertIsInstance(answer[0].tree, Sentence)
        result = answer[0].tree.__getattr__('value')
        self.assertEqual(result, expected)

    def testIrrelevantInput(self):
        original = 'Who is the president of the United States'
        j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
             'tree': {'type': 'resource', 'value': original}}
        answer = self.request(j)
        self.assertEquals(len(answer), 0)


from django.test import TestCase
from django.test.client import Client
from django.conf import settings
from importlib import import_module

from ..views import PleaOnlineForms

class TestTimeout(TestCase):

    def setUp(self):
        self.client = Client()
        # http://code.djangoproject.com/ticket/10899
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

    def test_no_urn_no_refresh_headers(self):
        response = self.client.get('/plea/case/')

        self.assertEqual(response.has_header('Refresh'), False)

    def test_when_urn_has_refresh_headers(self):
        session = self.session
        session["case"] = {"urn": "51/AA/00000/00"}
        session.save()

        response = self.client.get('/plea/case/')

        wait = str(getattr(settings, "SESSION_COOKIE_AGE", 3600));

        self.assertEqual(response.has_header('Refresh'), True)
        self.assertTrue("Refresh: " + wait + "; url=/session-timeout/" in response.serialize_headers())

Add unit tests for session timeout http headers

These tests check for the absence or presence
of the session timeout redirect headers.

[MAPDEV326]

Response:
<REPLACE_OLD>  <REPLACE_NEW> from django.test import TestCase
from django.test.client import Client
from django.conf import settings
from importlib import import_module

from ..views import PleaOnlineForms

class TestTimeout(TestCase):

    def setUp(self):
        self.client = Client()
        # http://code.djangoproject.com/ticket/10899
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

    def test_no_urn_no_refresh_headers(self):
        response = self.client.get('/plea/case/')

        self.assertEqual(response.has_header('Refresh'), False)

    def test_when_urn_has_refresh_headers(self):
        session = self.session
        session["case"] = {"urn": "51/AA/00000/00"}
        session.save()

        response = self.client.get('/plea/case/')

        wait = str(getattr(settings, "SESSION_COOKIE_AGE", 3600));

        self.assertEqual(response.has_header('Refresh'), True)
        self.assertTrue("Refresh: " + wait + "; url=/session-timeout/" in response.serialize_headers())
 <REPLACE_END> <|endoftext|> from django.test import TestCase
from django.test.client import Client
from django.conf import settings
from importlib import import_module

from ..views import PleaOnlineForms

class TestTimeout(TestCase):

    def setUp(self):
        self.client = Client()
        # http://code.djangoproject.com/ticket/10899
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

    def test_no_urn_no_refresh_headers(self):
        response = self.client.get('/plea/case/')

        self.assertEqual(response.has_header('Refresh'), False)

    def test_when_urn_has_refresh_headers(self):
        session = self.session
        session["case"] = {"urn": "51/AA/00000/00"}
        session.save()

        response = self.client.get('/plea/case/')

        wait = str(getattr(settings, "SESSION_COOKIE_AGE", 3600));

        self.assertEqual(response.has_header('Refresh'), True)
        self.assertTrue("Refresh: " + wait + "; url=/session-timeout/" in response.serialize_headers())

Prompt:
Add unit tests for session timeout http headers

These tests check for the absence or presence
of the session timeout redirect headers.

[MAPDEV326]


# You are given as input an unsorted array of n distinct numbers,
# where n is a power of 2.
# Give an algorithm that identifies the second-largest number in the array,
# and that uses at most n + log2n - 2 comparisons.

A = [4, 512, 8, 64, 16, 2, 32, 256] # Uses at most 9 comparisons

# def second_largest (Array):
# 	divided = merge_split(Array)

# 	print divided

# def merge_split (Array) :
# 	left = Array[:len(Array)/2]
# 	right = Array[len(Array)/2:]

# 	if(len(left) > 1):
# 		left = merge_split(left)

# 	if(len(right) > 1):
# 		right = merge_split(right)

# 	return [left, right]

# def merge (left, right, result) :
# 	if left[0] < right[0]:
# 		result.append(left[0])
# 	else:
# 		result.append(right[0])
# 	return result

def mergesort(aList):
 	return _mergesort( aList, 0, len( aList ) - 1 )

def _mergesort( aList, first, last ):
  # break problem into smaller structurally identical pieces
  mid = ( first + last ) / 2
  if first < last:
    _mergesort( aList, first, mid )
    _mergesort( aList, mid + 1, last )

  # merge solved pieces to get solution to original problem
  a, f, l = 0, first, mid + 1
  tmp = [None] * ( last - first + 1 )

  while f <= mid and l <= last:
    if aList[f] < aList[l] :
      tmp[a] = aList[f]
      f += 1
    else:
      tmp[a] = aList[l]
      l += 1
    a += 1

  if f <= mid :
    tmp[a:] = aList[f:mid + 1]

  if l <= last:
    tmp[a:] = aList[l:last + 1]

  a = 0
  while first <= last:
    aList[first] = tmp[a]
    first += 1
    a += 1

  return aList

# second_largest(A)
print mergesort(A)

Add solution to hamming numbers kata

Add solution to hamming numbers kata

Response:
<REPLACE_OLD>  <REPLACE_NEW> # You are given as input an unsorted array of n distinct numbers,
# where n is a power of 2.
# Give an algorithm that identifies the second-largest number in the array,
# and that uses at most n + log2n - 2 comparisons.

A = [4, 512, 8, 64, 16, 2, 32, 256] # Uses at most 9 comparisons

# def second_largest (Array):
# 	divided = merge_split(Array)

# 	print divided

# def merge_split (Array) :
# 	left = Array[:len(Array)/2]
# 	right = Array[len(Array)/2:]

# 	if(len(left) > 1):
# 		left = merge_split(left)

# 	if(len(right) > 1):
# 		right = merge_split(right)

# 	return [left, right]

# def merge (left, right, result) :
# 	if left[0] < right[0]:
# 		result.append(left[0])
# 	else:
# 		result.append(right[0])
# 	return result

def mergesort(aList):
 	return _mergesort( aList, 0, len( aList ) - 1 )

def _mergesort( aList, first, last ):
  # break problem into smaller structurally identical pieces
  mid = ( first + last ) / 2
  if first < last:
    _mergesort( aList, first, mid )
    _mergesort( aList, mid + 1, last )

  # merge solved pieces to get solution to original problem
  a, f, l = 0, first, mid + 1
  tmp = [None] * ( last - first + 1 )

  while f <= mid and l <= last:
    if aList[f] < aList[l] :
      tmp[a] = aList[f]
      f += 1
    else:
      tmp[a] = aList[l]
      l += 1
    a += 1

  if f <= mid :
    tmp[a:] = aList[f:mid + 1]

  if l <= last:
    tmp[a:] = aList[l:last + 1]

  a = 0
  while first <= last:
    aList[first] = tmp[a]
    first += 1
    a += 1

  return aList

# second_largest(A)
print mergesort(A) <REPLACE_END> <|endoftext|> # You are given as input an unsorted array of n distinct numbers,
# where n is a power of 2.
# Give an algorithm that identifies the second-largest number in the array,
# and that uses at most n + log2n - 2 comparisons.

A = [4, 512, 8, 64, 16, 2, 32, 256] # Uses at most 9 comparisons

# def second_largest (Array):
# 	divided = merge_split(Array)

# 	print divided

# def merge_split (Array) :
# 	left = Array[:len(Array)/2]
# 	right = Array[len(Array)/2:]

# 	if(len(left) > 1):
# 		left = merge_split(left)

# 	if(len(right) > 1):
# 		right = merge_split(right)

# 	return [left, right]

# def merge (left, right, result) :
# 	if left[0] < right[0]:
# 		result.append(left[0])
# 	else:
# 		result.append(right[0])
# 	return result

def mergesort(aList):
 	return _mergesort( aList, 0, len( aList ) - 1 )

def _mergesort( aList, first, last ):
  # break problem into smaller structurally identical pieces
  mid = ( first + last ) / 2
  if first < last:
    _mergesort( aList, first, mid )
    _mergesort( aList, mid + 1, last )

  # merge solved pieces to get solution to original problem
  a, f, l = 0, first, mid + 1
  tmp = [None] * ( last - first + 1 )

  while f <= mid and l <= last:
    if aList[f] < aList[l] :
      tmp[a] = aList[f]
      f += 1
    else:
      tmp[a] = aList[l]
      l += 1
    a += 1

  if f <= mid :
    tmp[a:] = aList[f:mid + 1]

  if l <= last:
    tmp[a:] = aList[l:last + 1]

  a = 0
  while first <= last:
    aList[first] = tmp[a]
    first += 1
    a += 1

  return aList

# second_largest(A)
print mergesort(A)

Prompt: Add solution to hamming numbers kata


# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Breakpad for Python.

Sends a notification when a process stops on an exception."""

import atexit
import getpass
import urllib
import traceback
import sys

def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
  print 'Do you want to send a crash report [y/N]? ',
  if sys.stdin.read(1).lower() == 'y':
    try:
      params = {
          'args': sys.argv,
          'stack': stack,
          'user': getpass.getuser(),
      }
      request = urllib.urlopen(url, urllib.urlencode(params))
      print request.read()
      request.close()
    except IOError:
      print('There was a failure while trying to send the stack trace. Too bad.')

#@atexit.register
def CheckForException():
  if 'test' in sys.modules['__main__'].__file__:
    # Probably a unit test.
    return
  last_tb = getattr(sys, 'last_traceback', None)
  if last_tb:
    SendStack(''.join(traceback.format_tb(last_tb)))

Response:
<REPLACE_OLD> bad.')

@atexit.register
def <REPLACE_NEW> bad.')

#@atexit.register
def <REPLACE_END> <|endoftext|> # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Breakpad for Python.

Sends a notification when a process stops on an exception."""

import atexit
import getpass
import urllib
import traceback
import sys

def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
  print 'Do you want to send a crash report [y/N]? ',
  if sys.stdin.read(1).lower() == 'y':
    try:
      params = {
          'args': sys.argv,
          'stack': stack,
          'user': getpass.getuser(),
      }
      request = urllib.urlopen(url, urllib.urlencode(params))
      print request.read()
      request.close()
    except IOError:
      print('There was a failure while trying to send the stack trace. Too bad.')

#@atexit.register
def CheckForException():
  if 'test' in sys.modules['__main__'].__file__:
    # Probably a unit test.
    return
  last_tb = getattr(sys, 'last_traceback', None)
  if last_tb:
    SendStack(''.join(traceback.format_tb(last_tb)))

Prompt:
Disable braekpad automatic registration while we figure out stuff

Review URL: http://codereview.chromium.org/462022

git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33686 0039d316-1c4b-4281-b951-d872f2087c98

# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Breakpad for Python.

Sends a notification when a process stops on an exception."""

import atexit
import getpass
import urllib
import traceback
import sys

def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
  print 'Do you want to send a crash report [y/N]? ',
  if sys.stdin.read(1).lower() == 'y':
    try:
      params = {
          'args': sys.argv,
          'stack': stack,
          'user': getpass.getuser(),
      }
      request = urllib.urlopen(url, urllib.urlencode(params))
      print request.read()
      request.close()
    except IOError:
      print('There was a failure while trying to send the stack trace. Too bad.')

@atexit.register
def CheckForException():
  if 'test' in sys.modules['__main__'].__file__:
    # Probably a unit test.
    return
  last_tb = getattr(sys, 'last_traceback', None)
  if last_tb:
    SendStack(''.join(traceback.format_tb(last_tb)))


# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-12 20:59
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0011_auto_20161011_2135'),
    ]

    operations = [
        migrations.AlterField(
            model_name='regulationfile',
            name='hexhash',
            field=models.CharField(max_length=64, primary_key=True, serialize=False),
        ),
    ]

Remove default keyword from hexhash key for RegulationFile.

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-12 20:59
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('jobs', '0011_auto_20161011_2135'),
    ]

    operations = [
        migrations.AlterField(
            model_name='regulationfile',
            name='hexhash',
            field=models.CharField(max_length=64, primary_key=True, serialize=False),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-12 20:59
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0011_auto_20161011_2135'),
    ]

    operations = [
        migrations.AlterField(
            model_name='regulationfile',
            name='hexhash',
            field=models.CharField(max_length=64, primary_key=True, serialize=False),
        ),
    ]

Prompt: Remove default keyword from hexhash key for RegulationFile.


from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript

import random
from binascii import hexlify, unhexlify

# Pad outputs until it reaches at least min_size

def pad_tx(tx, min_size=None):
    if min_size is None:
        min_size = MIN_TX_SIZE

    curr_size = len(tx.serialize())

    while curr_size < min_size:
        # txout.value + txout.pk_script bytes + op_return
        extra_bytes = 8 + 1 + 1
        padding_len = max(0, min_size - curr_size - extra_bytes)
        padding_len = min(padding_len, MAX_TXOUT_PUBKEY_SCRIPT)
        if padding_len == 0:
            tx.vout.append(CTxOut(0, CScript([OP_RETURN])))
        else:
            padding = random.randrange(
                1 << 8 * padding_len - 2, 1 << 8 * padding_len - 1)
            tx.vout.append(
                CTxOut(0, CScript([padding, OP_RETURN])))
        curr_size = len(tx.serialize())

    tx.rehash()

# Pad outputs until it reaches at least min_size

def pad_raw_tx(rawtx_hex, min_size=None):
    tx = CTransaction()
    FromHex(tx, rawtx_hex)
    pad_tx(tx, min_size)
    return ToHex(tx)

Fix pad_tx off by one error + nits

Response:
<REPLACE_OLD> 1, <REPLACE_NEW> 2, <REPLACE_END> <REPLACE_OLD> padding_len)
 <REPLACE_NEW> padding_len - 1)
 <REPLACE_END> <DELETE>  <DELETE_END> <REPLACE_OLD> min_size=None):

 <REPLACE_NEW> min_size=None):
 <REPLACE_END> <|endoftext|> from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript

import random
from binascii import hexlify, unhexlify

# Pad outputs until it reaches at least min_size

def pad_tx(tx, min_size=None):
    if min_size is None:
        min_size = MIN_TX_SIZE

    curr_size = len(tx.serialize())

    while curr_size < min_size:
        # txout.value + txout.pk_script bytes + op_return
        extra_bytes = 8 + 1 + 1
        padding_len = max(0, min_size - curr_size - extra_bytes)
        padding_len = min(padding_len, MAX_TXOUT_PUBKEY_SCRIPT)
        if padding_len == 0:
            tx.vout.append(CTxOut(0, CScript([OP_RETURN])))
        else:
            padding = random.randrange(
                1 << 8 * padding_len - 2, 1 << 8 * padding_len - 1)
            tx.vout.append(
                CTxOut(0, CScript([padding, OP_RETURN])))
        curr_size = len(tx.serialize())

    tx.rehash()

# Pad outputs until it reaches at least min_size

def pad_raw_tx(rawtx_hex, min_size=None):
    tx = CTransaction()
    FromHex(tx, rawtx_hex)
    pad_tx(tx, min_size)
    return ToHex(tx)

Prompt:
Fix pad_tx off by one error + nits

Summary: See title

Test Plan: test_runner.py

Reviewers: deadalnix, schancel, #bitcoin_abc

Reviewed By: schancel, #bitcoin_abc

Subscribers: teamcity

Differential Revision: https://reviews.bitcoinabc.org/D2096

from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript

import random
from binascii import hexlify, unhexlify

# Pad outputs until it reaches at least min_size

def pad_tx(tx, min_size=None):
    if min_size is None:
        min_size = MIN_TX_SIZE

    curr_size = len(tx.serialize())

    while curr_size < min_size:
        # txout.value + txout.pk_script bytes + op_return
        extra_bytes = 8 + 1 + 1
        padding_len = max(0, min_size - curr_size - extra_bytes)
        padding_len = min(padding_len, MAX_TXOUT_PUBKEY_SCRIPT)
        if padding_len == 0:
            tx.vout.append(CTxOut(0, CScript([OP_RETURN])))
        else:
            padding = random.randrange(
                1 << 8 * padding_len - 1, 1 << 8 * padding_len)
            tx.vout.append(
                CTxOut(0, CScript([padding, OP_RETURN])))
        curr_size = len(tx.serialize())

    tx.rehash()

# Pad  outputs until it reaches at least min_size

def pad_raw_tx(rawtx_hex, min_size=None):

    tx = CTransaction()
    FromHex(tx, rawtx_hex)
    pad_tx(tx, min_size)
    return ToHex(tx)


"""
Client for Yandex.Disk.
"""
__version__ = '0.3.3'

from .YaDiskClient import YaDiskException, YaDisk

Change version, upload to pypi.

Change version, upload to pypi.

Response:
<REPLACE_OLD> '0.3.2'

from <REPLACE_NEW> '0.3.3'

from <REPLACE_END> <|endoftext|> """
Client for Yandex.Disk.
"""
__version__ = '0.3.3'

from .YaDiskClient import YaDiskException, YaDisk

Prompt:
Change version, upload to pypi.

"""
Client for Yandex.Disk.
"""
__version__ = '0.3.2'

from .YaDiskClient import YaDiskException, YaDisk


# Test various loop types, some may be implemented/optimized differently
while True:
    try:
        break
    finally:
        print('finally 1')

for i in [1, 5, 10]:
    try:
        continue
    finally:
        print('finally 2')

for i in range(3):
    try:
        continue
    finally:
        print('finally 3')

# Multi-level
for i in range(4):
    print(i)
    try:
        while True:
            try:
                try:
                    break
                finally:
                    print('finally 1')
            finally:
                print('finally 2')
        print('here')
    finally:
        print('finnaly 3')

# break from within try-finally, within for-loop
for i in [1]:
    try:
        print(i)
        break
    finally:
        print('finally 4')

Response:
<REPLACE_OLD> 3')
 <REPLACE_NEW> 3')

# break from within try-finally, within for-loop
for i in [1]:
    try:
        print(i)
        break
    finally:
        print('finally 4')
 <REPLACE_END> <|endoftext|> # Test various loop types, some may be implemented/optimized differently
while True:
    try:
        break
    finally:
        print('finally 1')

for i in [1, 5, 10]:
    try:
        continue
    finally:
        print('finally 2')

for i in range(3):
    try:
        continue
    finally:
        print('finally 3')

# Multi-level
for i in range(4):
    print(i)
    try:
        while True:
            try:
                try:
                    break
                finally:
                    print('finally 1')
            finally:
                print('finally 2')
        print('here')
    finally:
        print('finnaly 3')

# break from within try-finally, within for-loop
for i in [1]:
    try:
        print(i)
        break
    finally:
        print('finally 4')

Prompt:
tests/basics: Add test for break from within try within a for-loop.

# Test various loop types, some may be implemented/optimized differently
while True:
    try:
        break
    finally:
        print('finally 1')

for i in [1, 5, 10]:
    try:
        continue
    finally:
        print('finally 2')

for i in range(3):
    try:
        continue
    finally:
        print('finally 3')

# Multi-level
for i in range(4):
    print(i)
    try:
        while True:
            try:
                try:
                    break
                finally:
                    print('finally 1')
            finally:
                print('finally 2')
        print('here')
    finally:
        print('finnaly 3')


#!/usr/bin/env python

from __future__ import with_statement

import sys

from setuptools import setup, find_packages

long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""

install_requires = [
    'beautifulsoup4==4.4.1',
    'requests==2.9.1',
]

setup(
    name='pypimirror-simple',
    version='0.1.0a0',
    description='A simple pypimirror',
    long_description=long_description,
    author='wilypomegranate',
    author_email='wilypomegranate@users.noreply.github.com>',
    packages=find_packages(),
    test_suite='py.test',
    tests_require=['pytest'],
    install_requires=install_requires,
    entry_points={
        'console_scripts': [
            'pypimirror = pypimirror.__main__:main',
        ]
    },
    classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.7',
          'Topic :: System :: Systems Administration',
    ],
)

Response:
<REPLACE_OLD> name='pypimirror',
    version='0.1.0a',
    description='pypimirror',
 <REPLACE_NEW> name='pypimirror-simple',
    version='0.1.0a0',
    description='A simple pypimirror',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from __future__ import with_statement

import sys

from setuptools import setup, find_packages

long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""

install_requires = [
    'beautifulsoup4==4.4.1',
    'requests==2.9.1',
]

setup(
    name='pypimirror-simple',
    version='0.1.0a0',
    description='A simple pypimirror',
    long_description=long_description,
    author='wilypomegranate',
    author_email='wilypomegranate@users.noreply.github.com>',
    packages=find_packages(),
    test_suite='py.test',
    tests_require=['pytest'],
    install_requires=install_requires,
    entry_points={
        'console_scripts': [
            'pypimirror = pypimirror.__main__:main',
        ]
    },
    classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.7',
          'Topic :: System :: Systems Administration',
    ],
)

Prompt:
Change project name to avoid pypi conflict

#!/usr/bin/env python

from __future__ import with_statement

import sys

from setuptools import setup, find_packages

long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""

install_requires = [
    'beautifulsoup4==4.4.1',
    'requests==2.9.1',
]

setup(
    name='pypimirror',
    version='0.1.0a',
    description='pypimirror',
    long_description=long_description,
    author='wilypomegranate',
    author_email='wilypomegranate@users.noreply.github.com>',
    packages=find_packages(),
    test_suite='py.test',
    tests_require=['pytest'],
    install_requires=install_requires,
    entry_points={
        'console_scripts': [
            'pypimirror = pypimirror.__main__:main',
        ]
    },
    classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.7',
          'Topic :: System :: Systems Administration',
    ],
)


import os
import json
from setuptools import setup

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

f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.read())
f.close()

setup(
    name=package['name'],
    version=package['version'],
    description=package['description'],
    long_description=readme,
    long_description_content_type='text/markdown',
    author=package['author']['name'],
    author_email=package['author']['email'],
    url=package['homepage'],
    packages=['s3direct'],
    include_package_data=True,
    install_requires=['django>=1.8'],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
)

Add description content type for pypi.

Add description content type for pypi.

Response:
<INSERT>    long_description_content_type='text/markdown',
 <INSERT_END> <|endoftext|> import os
import json
from setuptools import setup

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

f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.read())
f.close()

setup(
    name=package['name'],
    version=package['version'],
    description=package['description'],
    long_description=readme,
    long_description_content_type='text/markdown',
    author=package['author']['name'],
    author_email=package['author']['email'],
    url=package['homepage'],
    packages=['s3direct'],
    include_package_data=True,
    install_requires=['django>=1.8'],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
)

Prompt:
Add description content type for pypi.

import os
import json
from setuptools import setup

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

f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.read())
f.close()

setup(
    name=package['name'],
    version=package['version'],
    description=package['description'],
    long_description=readme,
    author=package['author']['name'],
    author_email=package['author']['email'],
    url=package['homepage'],
    packages=['s3direct'],
    include_package_data=True,
    install_requires=['django>=1.8'],
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
)


i=10
d=2.5
s="HackerRank"
# Declare second integer, double, and String variables.
ii=int(raw_input())
dd=float(raw_input())
ss=raw_input()
# Read and save an integer, double, and String to your variables.

# Print the sum of both integer variables on a new line.
print i+ii
# Print the sum of the double variables on a new line.
print d+dd
# Concatenate and print the String variables on a new line
print s+ " " + ss
# The 's' variable above should be printed first.

Print sum of same data types on a different line

Response:
<REPLACE_OLD>  <REPLACE_NEW> i=10
d=2.5
s="HackerRank"
# Declare second integer, double, and String variables.
ii=int(raw_input())
dd=float(raw_input())
ss=raw_input()
# Read and save an integer, double, and String to your variables.

# Print the sum of both integer variables on a new line.
print i+ii
# Print the sum of the double variables on a new line.
print d+dd
# Concatenate and print the String variables on a new line
print s+ " " + ss
# The 's' variable above should be printed first.
 <REPLACE_END> <|endoftext|> i=10
d=2.5
s="HackerRank"
# Declare second integer, double, and String variables.
ii=int(raw_input())
dd=float(raw_input())
ss=raw_input()
# Read and save an integer, double, and String to your variables.

# Print the sum of both integer variables on a new line.
print i+ii
# Print the sum of the double variables on a new line.
print d+dd
# Concatenate and print the String variables on a new line
print s+ " " + ss
# The 's' variable above should be printed first.

Prompt: Print sum of same data types on a different line


from itertools import combinations_with_replacement
from operator import mul

three_digit_numbers = tuple(range(100, 1000))

combinations = combinations_with_replacement(three_digit_numbers, 2)

products = [mul(*x) for x in combinations]

max_palindrome = max([x for x in products if str(x)[::-1] == str(x)])

Add solution for problem 4

Add solution for problem 4

Response:
<REPLACE_OLD>  <REPLACE_NEW> from itertools import combinations_with_replacement
from operator import mul

three_digit_numbers = tuple(range(100, 1000))

combinations = combinations_with_replacement(three_digit_numbers, 2)

products = [mul(*x) for x in combinations]

max_palindrome = max([x for x in products if str(x)[::-1] == str(x)])
 <REPLACE_END> <|endoftext|> from itertools import combinations_with_replacement
from operator import mul

three_digit_numbers = tuple(range(100, 1000))

combinations = combinations_with_replacement(three_digit_numbers, 2)

products = [mul(*x) for x in combinations]

max_palindrome = max([x for x in products if str(x)[::-1] == str(x)])

Prompt: Add solution for problem 4


import sys
import pytest
from .scripts import SCRIPTS

# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.

@pytest.fixture(scope="session")
def path_to_sleep():
    return SCRIPTS["sleep"]

@pytest.fixture(scope="session")
def path_to_python():
    return sys.executable

Response:
<INSERT> sys
import <INSERT_END> <REPLACE_OLD> SCRIPTS["sleep"]
 <REPLACE_NEW> SCRIPTS["sleep"]

@pytest.fixture(scope="session")
def path_to_python():
    return sys.executable
 <REPLACE_END> <|endoftext|> import sys
import pytest
from .scripts import SCRIPTS

# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.

@pytest.fixture(scope="session")
def path_to_sleep():
    return SCRIPTS["sleep"]

@pytest.fixture(scope="session")
def path_to_python():
    return sys.executable

Prompt:
Add path_to_python fixture to make writing multiplatform job scripts easier.

import pytest
from .scripts import SCRIPTS

# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.

@pytest.fixture(scope="session")
def path_to_sleep():
    return SCRIPTS["sleep"]


# -*- coding: utf-8 -*-

"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.
"""

import luigi

from tasks.ena import Ena
from tasks.ensembl.ensembl import Ensembl
from tasks.pdb import Pdb
from tasks.rfam import RfamSequences
from tasks.rfam import RfamFamilies
from tasks.rgd import Rgd

class ProcessData(luigi.WrapperTask):  # pylint: disable=R0904
    """
    This will generate the CSV's to import for all the databases we update each
    release.
    """

    def requires(self):
        yield Ena()
        yield Ensembl()
        yield RfamSequences()
        yield RfamFamilies()
        yield Pdb()
        yield Rgd()

Response:
<REPLACE_OLD> RfamFamilies

class <REPLACE_NEW> RfamFamilies
from tasks.rgd import Rgd

class <REPLACE_END> <INSERT>        yield Rgd()
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.
"""

import luigi

from tasks.ena import Ena
from tasks.ensembl.ensembl import Ensembl
from tasks.pdb import Pdb
from tasks.rfam import RfamSequences
from tasks.rfam import RfamFamilies
from tasks.rgd import Rgd

class ProcessData(luigi.WrapperTask):  # pylint: disable=R0904
    """
    This will generate the CSV's to import for all the databases we update each
    release.
    """

    def requires(self):
        yield Ena()
        yield Ensembl()
        yield RfamSequences()
        yield RfamFamilies()
        yield Pdb()
        yield Rgd()

Prompt:
Add RGD as part of the regular update pipeline

I'm not sure if this will always be part of the update, but it is for at
least for this release.

# -*- coding: utf-8 -*-

"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.
"""

import luigi

from tasks.ena import Ena
from tasks.ensembl.ensembl import Ensembl
from tasks.pdb import Pdb
from tasks.rfam import RfamSequences
from tasks.rfam import RfamFamilies

class ProcessData(luigi.WrapperTask):  # pylint: disable=R0904
    """
    This will generate the CSV's to import for all the databases we update each
    release.
    """

    def requires(self):
        yield Ena()
        yield Ensembl()
        yield RfamSequences()
        yield RfamFamilies()
        yield Pdb()


# -*- coding: utf-8 -*-
"""HTTP headers

.. seealso:: :rfc:`2616#section-2.2`

.. seealso:: :rfc:`2616#section-4.2`

.. seealso:: :rfc:`2616#section-14`
"""

__all__ = ['Headers']

# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?

import inspect

from httoop.header.element import HEADER, HeaderElement, HeaderType
from httoop.header.messaging import Server, UserAgent
from httoop.header.headers import Headers

from httoop.header import semantics
from httoop.header import messaging
from httoop.header import conditional
from httoop.header import range
from httoop.header import cache
from httoop.header import auth

types = (semantics, messaging, conditional, range, cache, auth)

for _, member in (member for type_ in types for member in inspect.getmembers(type_, inspect.isclass)):
	if isinstance(member, HeaderType) and member is not HeaderElement:
		HEADER[member.__name__] = member
		globals()[_] = member

Response:
<INSERT> member
		globals()[_] = <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
"""HTTP headers

.. seealso:: :rfc:`2616#section-2.2`

.. seealso:: :rfc:`2616#section-4.2`

.. seealso:: :rfc:`2616#section-14`
"""

__all__ = ['Headers']

# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?

import inspect

from httoop.header.element import HEADER, HeaderElement, HeaderType
from httoop.header.messaging import Server, UserAgent
from httoop.header.headers import Headers

from httoop.header import semantics
from httoop.header import messaging
from httoop.header import conditional
from httoop.header import range
from httoop.header import cache
from httoop.header import auth

types = (semantics, messaging, conditional, range, cache, auth)

for _, member in (member for type_ in types for member in inspect.getmembers(type_, inspect.isclass)):
	if isinstance(member, HeaderType) and member is not HeaderElement:
		HEADER[member.__name__] = member
		globals()[_] = member

Prompt:
Add all header elements to httoop.header

# -*- coding: utf-8 -*-
"""HTTP headers

.. seealso:: :rfc:`2616#section-2.2`

.. seealso:: :rfc:`2616#section-4.2`

.. seealso:: :rfc:`2616#section-14`
"""

__all__ = ['Headers']

# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?

import inspect

from httoop.header.element import HEADER, HeaderElement, HeaderType
from httoop.header.messaging import Server, UserAgent
from httoop.header.headers import Headers

from httoop.header import semantics
from httoop.header import messaging
from httoop.header import conditional
from httoop.header import range
from httoop.header import cache
from httoop.header import auth

types = (semantics, messaging, conditional, range, cache, auth)

for _, member in (member for type_ in types for member in inspect.getmembers(type_, inspect.isclass)):
	if isinstance(member, HeaderType) and member is not HeaderElement:
		HEADER[member.__name__] = member


import os

from flask import Flask, send_file
app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World from Flask in a uWSGI Nginx Docker container with \
     Python 3.6 (from the example template)"

@app.route("/")
def main():
    index_path = os.path.join(app.static_folder, 'index.html')
    return send_file(index_path)

# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = os.path.join(app.static_folder, path)
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        index_path = os.path.join(app.static_folder, 'index.html')
        return send_file(index_path)

if __name__ == "__main__":
    # Only for debugging while developing
    app.run(host='0.0.0.0', debug=True, port=80)

Response:
<INSERT> index_path = os.path.join(app.static_folder, 'index.html')
    <INSERT_END> <REPLACE_OLD> send_file('./static/index.html')

# <REPLACE_NEW> send_file(index_path)

# <REPLACE_END> <REPLACE_OLD> './static/' + path
 <REPLACE_NEW> os.path.join(app.static_folder, path)
 <REPLACE_END> <INSERT> index_path = os.path.join(app.static_folder, 'index.html')
        <INSERT_END> <REPLACE_OLD> send_file('./static/index.html')

if <REPLACE_NEW> send_file(index_path)

if <REPLACE_END> <|endoftext|> import os

from flask import Flask, send_file
app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World from Flask in a uWSGI Nginx Docker container with \
     Python 3.6 (from the example template)"

@app.route("/")
def main():
    index_path = os.path.join(app.static_folder, 'index.html')
    return send_file(index_path)

# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = os.path.join(app.static_folder, path)
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        index_path = os.path.join(app.static_folder, 'index.html')
        return send_file(index_path)

if __name__ == "__main__":
    # Only for debugging while developing
    app.run(host='0.0.0.0', debug=True, port=80)

Prompt:
Update view function to keep working even when moved to a package project structure

import os

from flask import Flask, send_file
app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World from Flask in a uWSGI Nginx Docker container with \
     Python 3.6 (from the example template)"

@app.route("/")
def main():
    return send_file('./static/index.html')

# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = './static/' + path
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        return send_file('./static/index.html')

if __name__ == "__main__":
    # Only for debugging while developing
    app.run(host='0.0.0.0', debug=True, port=80)


from datetime import datetime
import pytz

DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'

ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')

def decode_elvis_timestamp(timestamp: str):
    """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
    str_timestamp = str(timestamp).strip()
    if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
        milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
        timezone_offset = 0
        try:
            if "+" in milliseconds:
                timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
                milliseconds = milliseconds[:milliseconds.index("+")]
                if len(timezone_offset_string) == 4:
                    timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
            seconds = int(milliseconds) / 1000
        except ValueError:
            return timestamp

        # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
        return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone(
            pytz.FixedOffset(-timezone_offset)
        ).replace(tzinfo=None))

    return timestamp

Fix date parsing having wrong offset

Fix date parsing having wrong offset

Response:
<REPLACE_OLD> datetime, timedelta
import <REPLACE_NEW> datetime
import <REPLACE_END> <REPLACE_OLD> pytz.timezone('Europe/Tallinn')

def <REPLACE_NEW> pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')

def <REPLACE_END> <REPLACE_OLD> datetime.fromtimestamp(seconds).astimezone(
            ELVIS_TIMEZONE
        ) + timedelta(minutes=timezone_offset)

 <REPLACE_NEW> ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone(
            pytz.FixedOffset(-timezone_offset)
        ).replace(tzinfo=None))

 <REPLACE_END> <|endoftext|> from datetime import datetime
import pytz

DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'

ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')

def decode_elvis_timestamp(timestamp: str):
    """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
    str_timestamp = str(timestamp).strip()
    if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
        milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
        timezone_offset = 0
        try:
            if "+" in milliseconds:
                timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
                milliseconds = milliseconds[:milliseconds.index("+")]
                if len(timezone_offset_string) == 4:
                    timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
            seconds = int(milliseconds) / 1000
        except ValueError:
            return timestamp

        # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
        return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone(
            pytz.FixedOffset(-timezone_offset)
        ).replace(tzinfo=None))

    return timestamp

Prompt:
Fix date parsing having wrong offset

from datetime import datetime, timedelta
import pytz

DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'

ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')

def decode_elvis_timestamp(timestamp: str):
    """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
    str_timestamp = str(timestamp).strip()
    if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX):
        milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)]
        timezone_offset = 0
        try:
            if "+" in milliseconds:
                timezone_offset_string = milliseconds[milliseconds.index("+")+1:]
                milliseconds = milliseconds[:milliseconds.index("+")]
                if len(timezone_offset_string) == 4:
                    timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:])
            seconds = int(milliseconds) / 1000
        except ValueError:
            return timestamp

        # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn)
        return datetime.fromtimestamp(seconds).astimezone(
            ELVIS_TIMEZONE
        ) + timedelta(minutes=timezone_offset)

    return timestamp