import os
from pathlib import Path
from string import Template

from dotenv import load_dotenv

load_dotenv()  # helps with local dev

TEMPLATE_PATH = Path.cwd() / "email.md"

STARMINDER_COUNT = int(os.getenv("STARMINDER_COUNT"))
STARMINDER_RECIPIENT = os.getenv("STARMINDER_RECIPIENT")
STARMINDER_SUBJECT = Template("[Starminder] Reminders for $today")

AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_FROM = os.getenv("AWS_FROM")

GITHUB_TOKEN = os.getenv("GH_TOKEN")
GITHUB_SERVER_URL = os.getenv("GITHUB_SERVER_URL")
GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY")
GITHUB_FORK_URL = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}"

Rename GH token env var

Response:
<REPLACE_OLD> os.getenv("GITHUB_TOKEN")
GITHUB_SERVER_URL <REPLACE_NEW> os.getenv("GH_TOKEN")
GITHUB_SERVER_URL <REPLACE_END> <|endoftext|> import os
from pathlib import Path
from string import Template

from dotenv import load_dotenv

load_dotenv()  # helps with local dev

TEMPLATE_PATH = Path.cwd() / "email.md"

STARMINDER_COUNT = int(os.getenv("STARMINDER_COUNT"))
STARMINDER_RECIPIENT = os.getenv("STARMINDER_RECIPIENT")
STARMINDER_SUBJECT = Template("[Starminder] Reminders for $today")

AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_FROM = os.getenv("AWS_FROM")

GITHUB_TOKEN = os.getenv("GH_TOKEN")
GITHUB_SERVER_URL = os.getenv("GITHUB_SERVER_URL")
GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY")
GITHUB_FORK_URL = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}"

Prompt:
Rename GH token env var

GitHub disallows user set GITHUB_ prefixed ones.

import os
from pathlib import Path
from string import Template

from dotenv import load_dotenv

load_dotenv()  # helps with local dev

TEMPLATE_PATH = Path.cwd() / "email.md"

STARMINDER_COUNT = int(os.getenv("STARMINDER_COUNT"))
STARMINDER_RECIPIENT = os.getenv("STARMINDER_RECIPIENT")
STARMINDER_SUBJECT = Template("[Starminder] Reminders for $today")

AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_FROM = os.getenv("AWS_FROM")

GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
GITHUB_SERVER_URL = os.getenv("GITHUB_SERVER_URL")
GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY")
GITHUB_FORK_URL = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}"


#!/usr/bin/python3
# THIS FILE IS AN EXPERIMENTAL PROGRAM TO LEARN ABOUT OS_WALK

import os, sys, datetime

#dt = datetime.datetime(1970,1,1).total_seconds()
#	print(dt)

walk_dir = sys.argv[1]

with open("fsscan.scan", "w") as f:

	print("SCANFROM" + walk_dir)

	for root, subdirs, files in os.walk(walk_dir):
		f.write(root + "\n")

	for filename in files:
		file_path = os.path.join(root, filename)
		f.write(file_path + filename + "\n")

Add write dump to file

Add write dump to file

Response:
<REPLACE_OLD> sys

walk_dir <REPLACE_NEW> sys, datetime

#dt <REPLACE_END> <REPLACE_OLD> sys.argv[1]

print("walk directory: " <REPLACE_NEW> datetime.datetime(1970,1,1).total_seconds()
#	print(dt)

walk_dir = sys.argv[1]

with open("fsscan.scan", "w") as f:

	print("SCANFROM" <REPLACE_END> <REPLACE_OLD> walk_dir)

print("Walk directory (absolute) = " + os.path.abspath(walk_dir))
print("\n\n\n\n\n\n\n\n\n")

for <REPLACE_NEW> walk_dir)

	for <REPLACE_END> <REPLACE_OLD> os.walk(walk_dir):
	print(root)
	#list_file_path = os.path.join(root, "dirlist.txt")
	#print("dirlist = ", list_file_path)

	#for subdir in subdirs:
	#	print(subdir)

	for <REPLACE_NEW> os.walk(walk_dir):
		f.write(root + "\n")

	for <REPLACE_END> <REPLACE_OLD> filename)
		print(file_path <REPLACE_NEW> filename)
		f.write(file_path <REPLACE_END> <REPLACE_OLD> filename) <REPLACE_NEW> filename + "\n") <REPLACE_END> <|endoftext|> #!/usr/bin/python3
# THIS FILE IS AN EXPERIMENTAL PROGRAM TO LEARN ABOUT OS_WALK

import os, sys, datetime

#dt = datetime.datetime(1970,1,1).total_seconds()
#	print(dt)

walk_dir = sys.argv[1]

with open("fsscan.scan", "w") as f:

	print("SCANFROM" + walk_dir)

	for root, subdirs, files in os.walk(walk_dir):
		f.write(root + "\n")

	for filename in files:
		file_path = os.path.join(root, filename)
		f.write(file_path + filename + "\n")

Prompt:
Add write dump to file

#!/usr/bin/python3
# THIS FILE IS AN EXPERIMENTAL PROGRAM TO LEARN ABOUT OS_WALK

import os, sys

walk_dir = sys.argv[1]

print("walk directory: " + walk_dir)

print("Walk directory (absolute) = " + os.path.abspath(walk_dir))
print("\n\n\n\n\n\n\n\n\n")

for root, subdirs, files in os.walk(walk_dir):
	print(root)
	#list_file_path = os.path.join(root, "dirlist.txt")
	#print("dirlist = ", list_file_path)

	#for subdir in subdirs:
	#	print(subdir)

	for filename in files:
		file_path = os.path.join(root, filename)
		print(file_path + filename)


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

"""
test_create_template
--------------------
"""

import os
import pytest
import subprocess

def run_tox(plugin):
    """Run the tox suite of the newly created plugin."""
    try:
        subprocess.check_call([
            'tox',
            plugin,
            '-c', os.path.join(plugin, 'tox.ini'),
            '-e', 'py'
        ])
    except subprocess.CalledProcessError as e:
        pytest.fail(e)

def test_run_cookiecutter_and_plugin_tests(cookies):
    """Create a new plugin via cookiecutter and run its tests."""
    result = cookies.bake()

    assert result.exit_code == 0
    assert result.exception is None
    assert result.project.basename == 'pytest-foobar'
    assert result.project.isdir()

    run_tox(str(result.project))

Response:
<INSERT> result.exit_code == 0
    assert result.exception is None
    assert <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

"""
test_create_template
--------------------
"""

import os
import pytest
import subprocess

def run_tox(plugin):
    """Run the tox suite of the newly created plugin."""
    try:
        subprocess.check_call([
            'tox',
            plugin,
            '-c', os.path.join(plugin, 'tox.ini'),
            '-e', 'py'
        ])
    except subprocess.CalledProcessError as e:
        pytest.fail(e)

def test_run_cookiecutter_and_plugin_tests(cookies):
    """Create a new plugin via cookiecutter and run its tests."""
    result = cookies.bake()

    assert result.exit_code == 0
    assert result.exception is None
    assert result.project.basename == 'pytest-foobar'
    assert result.project.isdir()

    run_tox(str(result.project))

Prompt:
Extend test to check for the exit code and for an exception

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

"""
test_create_template
--------------------
"""

import os
import pytest
import subprocess

def run_tox(plugin):
    """Run the tox suite of the newly created plugin."""
    try:
        subprocess.check_call([
            'tox',
            plugin,
            '-c', os.path.join(plugin, 'tox.ini'),
            '-e', 'py'
        ])
    except subprocess.CalledProcessError as e:
        pytest.fail(e)

def test_run_cookiecutter_and_plugin_tests(cookies):
    """Create a new plugin via cookiecutter and run its tests."""
    result = cookies.bake()

    assert result.project.basename == 'pytest-foobar'
    assert result.project.isdir()

    run_tox(str(result.project))


import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser

t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')

tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')
run_time = tcx.completed_at

def convert_time_to_unix(time):
    parsed_time = dateutil.parser.parse(time)
    time_in_unix = parsed_time.strftime('%s')
    return time_in_unix

unix_run_time = convert_time_to_unix(run_time)
darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/42.3601,-71.0589," + unix_run_time + "?exclude=currently,flags").read()
print(darksky_request)

class getWeather:
    def __init__(self, date, time):
        self.date = date
        self.time = time

    def goodbye(self, date):
        print("my name is " + date)

Response:
<DELETE> darksky import forecast
from <DELETE_END> <REPLACE_OLD> ConfigParser

# <REPLACE_NEW> ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser

t = '1984-06-02T19:05:00.000Z'
# <REPLACE_END> <REPLACE_OLD> API.
# <REPLACE_NEW> API
# <REPLACE_END> <REPLACE_OLD> tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')

print(tcx.duration)
boston <REPLACE_NEW> tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')
run_time <REPLACE_END> <REPLACE_OLD> forecast(darksky_key, 42.3601, -71.0589)
print(boston)
 <REPLACE_NEW> tcx.completed_at

def convert_time_to_unix(time):
    parsed_time = dateutil.parser.parse(time)
    time_in_unix = parsed_time.strftime('%s')
    return time_in_unix

unix_run_time = convert_time_to_unix(run_time)
darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/42.3601,-71.0589," + unix_run_time + "?exclude=currently,flags").read()
print(darksky_request)

class getWeather:
    def __init__(self, date, time):
        self.date = date
        self.time = time

    def goodbye(self, date):
        print("my name is " + date)
 <REPLACE_END> <|endoftext|> import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser

t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')

tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')
run_time = tcx.completed_at

def convert_time_to_unix(time):
    parsed_time = dateutil.parser.parse(time)
    time_in_unix = parsed_time.strftime('%s')
    return time_in_unix

unix_run_time = convert_time_to_unix(run_time)
darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/42.3601,-71.0589," + unix_run_time + "?exclude=currently,flags").read()
print(darksky_request)

class getWeather:
    def __init__(self, date, time):
        self.date = date
        self.time = time

    def goodbye(self, date):
        print("my name is " + date)

Prompt:
Call Darksky API with TCX run time
Use simpler GET request to Darksky API rather than a third party Python
wrapper

import tcxparser
from darksky import forecast
from configparser import ConfigParser

# Darksky weather API.
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')

tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')

print(tcx.duration)
boston = forecast(darksky_key, 42.3601, -71.0589)
print(boston)


from distutils.core import setup

setup(
    name='Flask-thumbnails',
    version='0.2.1',
    url='https://github.com/SilentSokolov/flask-thumbnails',
    license='MIT',
    author='Dmitriy Sokolov',
    author_email='silentsokolov@gmail.com',
    description='A simple extension to create a thumbs for the Flask',
    packages=['flask_thumbnails'],
    zip_safe=False,
    include_package_data=True,
    platforms='any',
    install_requires=[
        'Flask',
        'Pillow>=4.1.1',
    ],
)

Response:
<REPLACE_OLD> 'Pillow==2.6.0',
 <REPLACE_NEW> 'Pillow>=4.1.1',
 <REPLACE_END> <|endoftext|> from distutils.core import setup

setup(
    name='Flask-thumbnails',
    version='0.2.1',
    url='https://github.com/SilentSokolov/flask-thumbnails',
    license='MIT',
    author='Dmitriy Sokolov',
    author_email='silentsokolov@gmail.com',
    description='A simple extension to create a thumbs for the Flask',
    packages=['flask_thumbnails'],
    zip_safe=False,
    include_package_data=True,
    platforms='any',
    install_requires=[
        'Flask',
        'Pillow>=4.1.1',
    ],
)

Prompt:
Update pillow and stop requiring exact pillow version

from distutils.core import setup

setup(
    name='Flask-thumbnails',
    version='0.2.1',
    url='https://github.com/SilentSokolov/flask-thumbnails',
    license='MIT',
    author='Dmitriy Sokolov',
    author_email='silentsokolov@gmail.com',
    description='A simple extension to create a thumbs for the Flask',
    packages=['flask_thumbnails'],
    zip_safe=False,
    include_package_data=True,
    platforms='any',
    install_requires=[
        'Flask',
        'Pillow==2.6.0',
    ],
)


from sublime_plugin import WindowCommand, TextCommand

from ..git_command import GitCommand

LOG_GRAPH_TITLE = "GRAPH"

class GsLogGraphCommand(WindowCommand, GitCommand):

    """
    Open a new window displaying an ASCII-graphic representation
    of the repo's branch relationships.
    """

    def run(self):
        repo_path = self.repo_path
        view = self.window.new_file()
        view.settings().set("git_savvy.log_graph_view", True)
        view.settings().set("git_savvy.repo_path", repo_path)
        view.set_name(LOG_GRAPH_TITLE)
        view.set_scratch(True)
        view.set_read_only(True)
        view.run_command("gs_log_graph_initialize")

class GsLogGraphInitializeCommand(TextCommand, GitCommand):

    def run(self, edit):
        branch_graph = self.git("log", "--oneline", "--graph", "--all", "--decorate")
        self.view.run_command("gs_replace_view_text", {"text": branch_graph})

Response:
<INSERT> "--all", <INSERT_END> <|endoftext|> from sublime_plugin import WindowCommand, TextCommand

from ..git_command import GitCommand

LOG_GRAPH_TITLE = "GRAPH"

class GsLogGraphCommand(WindowCommand, GitCommand):

    """
    Open a new window displaying an ASCII-graphic representation
    of the repo's branch relationships.
    """

    def run(self):
        repo_path = self.repo_path
        view = self.window.new_file()
        view.settings().set("git_savvy.log_graph_view", True)
        view.settings().set("git_savvy.repo_path", repo_path)
        view.set_name(LOG_GRAPH_TITLE)
        view.set_scratch(True)
        view.set_read_only(True)
        view.run_command("gs_log_graph_initialize")

class GsLogGraphInitializeCommand(TextCommand, GitCommand):

    def run(self, edit):
        branch_graph = self.git("log", "--oneline", "--graph", "--all", "--decorate")
        self.view.run_command("gs_replace_view_text", {"text": branch_graph})

Prompt:
Add `--all` to graph command to show other branches (esp. origin)

from sublime_plugin import WindowCommand, TextCommand

from ..git_command import GitCommand

LOG_GRAPH_TITLE = "GRAPH"

class GsLogGraphCommand(WindowCommand, GitCommand):

    """
    Open a new window displaying an ASCII-graphic representation
    of the repo's branch relationships.
    """

    def run(self):
        repo_path = self.repo_path
        view = self.window.new_file()
        view.settings().set("git_savvy.log_graph_view", True)
        view.settings().set("git_savvy.repo_path", repo_path)
        view.set_name(LOG_GRAPH_TITLE)
        view.set_scratch(True)
        view.set_read_only(True)
        view.run_command("gs_log_graph_initialize")

class GsLogGraphInitializeCommand(TextCommand, GitCommand):

    def run(self, edit):
        branch_graph = self.git("log", "--oneline", "--graph", "--decorate")
        self.view.run_command("gs_replace_view_text", {"text": branch_graph})


# IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.

"""
IdeaScaly: IdeaScale API client
"""

__version__ = '0.1'
__author__ = 'Jorge Saldivar'
__license__ = 'MIT'

from ideascaly.api import API
from ideascaly.auth import AuthNonSSO, AuthNonSSOMem, AuthSSO, AuthResearch
from ideascaly.error import IdeaScalyError
from ideascaly.models import Author, Idea, Campaign, Comment, Vote, JSONModel, ModelFactory, Model
from ideascaly.parsers import Parser, RawParser, JSONParser, ModelParser

Add details of the project

Add details of the project

Response:
<REPLACE_OLD> __author__ <REPLACE_NEW> # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.

"""
IdeaScaly: IdeaScale API client
"""

__version__ <REPLACE_END> <REPLACE_OLD> 'jorgesaldivar'
 <REPLACE_NEW> '0.1'
__author__ = 'Jorge Saldivar'
__license__ = 'MIT'

from ideascaly.api import API
from ideascaly.auth import AuthNonSSO, AuthNonSSOMem, AuthSSO, AuthResearch
from ideascaly.error import IdeaScalyError
from ideascaly.models import Author, Idea, Campaign, Comment, Vote, JSONModel, ModelFactory, Model
from ideascaly.parsers import Parser, RawParser, JSONParser, ModelParser
 <REPLACE_END> <|endoftext|> # IdeaScaly
# Copyright 2015 Jorge Saldivar
# See LICENSE for details.

"""
IdeaScaly: IdeaScale API client
"""

__version__ = '0.1'
__author__ = 'Jorge Saldivar'
__license__ = 'MIT'

from ideascaly.api import API
from ideascaly.auth import AuthNonSSO, AuthNonSSOMem, AuthSSO, AuthResearch
from ideascaly.error import IdeaScalyError
from ideascaly.models import Author, Idea, Campaign, Comment, Vote, JSONModel, ModelFactory, Model
from ideascaly.parsers import Parser, RawParser, JSONParser, ModelParser

Prompt:
Add details of the project

__author__ = 'jorgesaldivar'


from sqlobject import IntCol, SQLObject
from sqlobject.tests.dbtest import getConnection, setupClass

########################################
# Identity (MS SQL)
########################################

class SOTestIdentity(SQLObject):
    n = IntCol()

def test_identity():
    # (re)create table
    SOTestIdentity.dropTable(connection=getConnection(), ifExists=True)
    setupClass(SOTestIdentity)

    # insert without giving identity
    SOTestIdentity(n=100)  # i1
    # verify result
    i1get = SOTestIdentity.get(1)
    assert (i1get.n == 100)

    # insert while giving identity
    SOTestIdentity(id=2, n=200)  # i2
    # verify result
    i2get = SOTestIdentity.get(2)
    assert (i2get.n == 200)

Response:
<REPLACE_OLD> assert(i1get.n <REPLACE_NEW> assert (i1get.n <REPLACE_END> <REPLACE_OLD> assert(i2get.n <REPLACE_NEW> assert (i2get.n <REPLACE_END> <|endoftext|> from sqlobject import IntCol, SQLObject
from sqlobject.tests.dbtest import getConnection, setupClass

########################################
# Identity (MS SQL)
########################################

class SOTestIdentity(SQLObject):
    n = IntCol()

def test_identity():
    # (re)create table
    SOTestIdentity.dropTable(connection=getConnection(), ifExists=True)
    setupClass(SOTestIdentity)

    # insert without giving identity
    SOTestIdentity(n=100)  # i1
    # verify result
    i1get = SOTestIdentity.get(1)
    assert (i1get.n == 100)

    # insert while giving identity
    SOTestIdentity(id=2, n=200)  # i2
    # verify result
    i2get = SOTestIdentity.get(2)
    assert (i2get.n == 200)

Prompt:
Style: Fix `flake8` E275 missing whitespace after keyword

from sqlobject import IntCol, SQLObject
from sqlobject.tests.dbtest import getConnection, setupClass

########################################
# Identity (MS SQL)
########################################

class SOTestIdentity(SQLObject):
    n = IntCol()

def test_identity():
    # (re)create table
    SOTestIdentity.dropTable(connection=getConnection(), ifExists=True)
    setupClass(SOTestIdentity)

    # insert without giving identity
    SOTestIdentity(n=100)  # i1
    # verify result
    i1get = SOTestIdentity.get(1)
    assert(i1get.n == 100)

    # insert while giving identity
    SOTestIdentity(id=2, n=200)  # i2
    # verify result
    i2get = SOTestIdentity.get(2)
    assert(i2get.n == 200)


#!/usr/bin/env python

import os
import sys
from distutils.core import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

_install_requires = [
    "parsimonious>=0.5,<0.6",
]

if sys.version_info[:2] <= (2, 6):
    _install_requires.append("argparse==1.2.1")

setup(
    name='mammoth',
    version='0.1.1',
    description='Convert Word documents to simple and clean HTML',
    long_description=read("README"),
    author='Michael Williamson',
    author_email='mike@zwobble.org',
    url='http://github.com/mwilliamson/python-mammoth',
    packages=['mammoth', 'mammoth.docx', 'mammoth.style_reader'],
    scripts=["scripts/mammoth"],
    keywords="docx word office clean html",
    install_requires=_install_requires,
)

Support CLI on Python 2.6

Support CLI on Python 2.6

Response:
<REPLACE_OLD> os
from <REPLACE_NEW> os
import sys
from <REPLACE_END> <REPLACE_OLD> fname)).read()

setup(
 <REPLACE_NEW> fname)).read()

_install_requires = [
    "parsimonious>=0.5,<0.6",
]

if sys.version_info[:2] <= (2, 6):
    _install_requires.append("argparse==1.2.1")

setup(
 <REPLACE_END> <REPLACE_OLD> install_requires=[
        "parsimonious>=0.5,<0.6",
    ]
)

 <REPLACE_NEW> install_requires=_install_requires,
)

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os
import sys
from distutils.core import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

_install_requires = [
    "parsimonious>=0.5,<0.6",
]

if sys.version_info[:2] <= (2, 6):
    _install_requires.append("argparse==1.2.1")

setup(
    name='mammoth',
    version='0.1.1',
    description='Convert Word documents to simple and clean HTML',
    long_description=read("README"),
    author='Michael Williamson',
    author_email='mike@zwobble.org',
    url='http://github.com/mwilliamson/python-mammoth',
    packages=['mammoth', 'mammoth.docx', 'mammoth.style_reader'],
    scripts=["scripts/mammoth"],
    keywords="docx word office clean html",
    install_requires=_install_requires,
)

Prompt:
Support CLI on Python 2.6

#!/usr/bin/env python

import os
from distutils.core import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='mammoth',
    version='0.1.1',
    description='Convert Word documents to simple and clean HTML',
    long_description=read("README"),
    author='Michael Williamson',
    author_email='mike@zwobble.org',
    url='http://github.com/mwilliamson/python-mammoth',
    packages=['mammoth', 'mammoth.docx', 'mammoth.style_reader'],
    scripts=["scripts/mammoth"],
    keywords="docx word office clean html",
    install_requires=[
        "parsimonious>=0.5,<0.6",
    ]
)


import os
import boto3
import botocore
from boto3.core.session import Session

os.environ['AWS_CONFIG_FILE'] = "/etc/profiles.cfg"

orig_owner = ""
shared_owner = ""

region = "us-west-2"
session = botocore.session.get_session()
session.profile = 'beta'

session = Session(session=session)
ec2_conn = session.connect_to('ec2', region_name=region)
response_data = ec2_conn.describe_images(
    filters=[{'Name': "tag:Role", "Values": ["ScannerDy"]},
             {'Name': "tag:Version", "Values": ["1051"]}])
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))
owner_id = response_data['Images'][0]['OwnerId']
if owner_id != orig_owner:
    exit
ami_id = response_data['Images'][0]['ImageId']
tags = response_data['Images'][0]['Tags']

response_data = ec2_conn.describe_image_attribute(
    image_id=ami_id, attribute='launchPermission')
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

permission = {"Add": [{"UserId": shared_owner}]}
response_data = ec2_conn.modify_image_attribute(
    image_id=ami_id, launch_permission=permission)
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

print '-' * 10, 'switched'

session = botocore.session.get_session()
session.profile = 'qa'

session = Session(session=session)
ec2_conn = session.connect_to('ec2', region_name=region)
reponse_data = ec2_conn.create_tags(resources=[ami_id], tags=tags)
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

response_data = ec2_conn.describe_images(
    filters=[{'Name': "tag:Role", "Values": ["ScannerDy"]},
             {'Name': "tag:Version", "Values": ["1051"]}])
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

Update the example via boto3

Update the example via boto3

Response:
<INSERT> import os
import boto3
import botocore
from boto3.core.session import Session

os.environ['AWS_CONFIG_FILE'] = "/etc/profiles.cfg"

orig_owner = ""
shared_owner = ""

region = "us-west-2"
session = botocore.session.get_session()
session.profile = 'beta'

session = Session(session=session)
ec2_conn = session.connect_to('ec2', region_name=region)
response_data = ec2_conn.describe_images(
 <INSERT_END> <INSERT>   filters=[{'Name': "tag:Role", "Values": ["ScannerDy"]},
             {'Name': "tag:Version", "Values": ["1051"]}])
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))
owner_id = response_data['Images'][0]['OwnerId']
if owner_id != orig_owner:
    exit
ami_id = response_data['Images'][0]['ImageId']
tags = response_data['Images'][0]['Tags']

response_data = ec2_conn.describe_image_attribute(
    image_id=ami_id, attribute='launchPermission')
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

permission = {"Add": [{"UserId": shared_owner}]}
response_data = ec2_conn.modify_image_attribute(
    image_id=ami_id, launch_permission=permission)
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

print '-' * 10, 'switched'

session = botocore.session.get_session()
session.profile = 'qa'

session = Session(session=session)
ec2_conn = session.connect_to('ec2', region_name=region)
reponse_data = ec2_conn.create_tags(resources=[ami_id], tags=tags)
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

response_data = ec2_conn.describe_images(
    filters=[{'Name': "tag:Role", "Values": ["ScannerDy"]},
             {'Name': "tag:Version", "Values": ["1051"]}])
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))
 <INSERT_END> <|endoftext|> import os
import boto3
import botocore
from boto3.core.session import Session

os.environ['AWS_CONFIG_FILE'] = "/etc/profiles.cfg"

orig_owner = ""
shared_owner = ""

region = "us-west-2"
session = botocore.session.get_session()
session.profile = 'beta'

session = Session(session=session)
ec2_conn = session.connect_to('ec2', region_name=region)
response_data = ec2_conn.describe_images(
    filters=[{'Name': "tag:Role", "Values": ["ScannerDy"]},
             {'Name': "tag:Version", "Values": ["1051"]}])
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))
owner_id = response_data['Images'][0]['OwnerId']
if owner_id != orig_owner:
    exit
ami_id = response_data['Images'][0]['ImageId']
tags = response_data['Images'][0]['Tags']

response_data = ec2_conn.describe_image_attribute(
    image_id=ami_id, attribute='launchPermission')
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

permission = {"Add": [{"UserId": shared_owner}]}
response_data = ec2_conn.modify_image_attribute(
    image_id=ami_id, launch_permission=permission)
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

print '-' * 10, 'switched'

session = botocore.session.get_session()
session.profile = 'qa'

session = Session(session=session)
ec2_conn = session.connect_to('ec2', region_name=region)
reponse_data = ec2_conn.create_tags(resources=[ami_id], tags=tags)
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

response_data = ec2_conn.describe_images(
    filters=[{'Name': "tag:Role", "Values": ["ScannerDy"]},
             {'Name': "tag:Version", "Values": ["1051"]}])
import json
print json.dumps(response_data, sort_keys=True, indent=4, separators=(',', ': '))

Prompt: Update the example via boto3


from cStringIO import StringIO
import tldextract
import web

try:
  import json
except ImportError:
  from django.utils import simplejson as json

urls = (
        '/api/extract', 'Extract',
        '/api/re', 'TLDSet',
        '/test', 'Test',
    )

class Extract:
    def GET(self):
        url = web.input(url='').url
        if not url:
            return web.webapi.badrequest()

        ext = tldextract.extract(url)._asdict()
        web.header('Content-Type', 'application/json')
        return json.dumps(ext) + '\n'

class TLDSet:
    def GET(self):
        extractor = tldextract.tldextract._get_tld_extractor()
        web.header('Content-Type', 'text/html; charset=utf-8')
        return '<br/>'.join(sorted(extractor.tlds))

class Test:
    def GET(self):
        stream = StringIO()
        tldextract.tldextract.run_tests(stream)
        return stream.getvalue()

app = web.application(urls, globals())
main = app.cgirun()

Fix viewing live TLD definitions on GAE

Fix viewing live TLD definitions on GAE

Response:
<REPLACE_OLD> 'TheRegex',
 <REPLACE_NEW> 'TLDSet',
 <REPLACE_END> <REPLACE_OLD> TheRegex:
 <REPLACE_NEW> TLDSet:
 <REPLACE_END> <REPLACE_OLD> tldextract.tldextract._get_extract_tld_re()
 <REPLACE_NEW> tldextract.tldextract._get_tld_extractor()
 <REPLACE_END> <REPLACE_OLD> '<br/>'.join(extractor.tlds)

class <REPLACE_NEW> '<br/>'.join(sorted(extractor.tlds))

class <REPLACE_END> <|endoftext|> from cStringIO import StringIO
import tldextract
import web

try:
  import json
except ImportError:
  from django.utils import simplejson as json

urls = (
        '/api/extract', 'Extract',
        '/api/re', 'TLDSet',
        '/test', 'Test',
    )

class Extract:
    def GET(self):
        url = web.input(url='').url
        if not url:
            return web.webapi.badrequest()

        ext = tldextract.extract(url)._asdict()
        web.header('Content-Type', 'application/json')
        return json.dumps(ext) + '\n'

class TLDSet:
    def GET(self):
        extractor = tldextract.tldextract._get_tld_extractor()
        web.header('Content-Type', 'text/html; charset=utf-8')
        return '<br/>'.join(sorted(extractor.tlds))

class Test:
    def GET(self):
        stream = StringIO()
        tldextract.tldextract.run_tests(stream)
        return stream.getvalue()

app = web.application(urls, globals())
main = app.cgirun()

Prompt:
Fix viewing live TLD definitions on GAE

from cStringIO import StringIO
import tldextract
import web

try:
  import json
except ImportError:
  from django.utils import simplejson as json

urls = (
        '/api/extract', 'Extract',
        '/api/re', 'TheRegex',
        '/test', 'Test',
    )

class Extract:
    def GET(self):
        url = web.input(url='').url
        if not url:
            return web.webapi.badrequest()

        ext = tldextract.extract(url)._asdict()
        web.header('Content-Type', 'application/json')
        return json.dumps(ext) + '\n'

class TheRegex:
    def GET(self):
        extractor = tldextract.tldextract._get_extract_tld_re()
        web.header('Content-Type', 'text/html; charset=utf-8')
        return '<br/>'.join(extractor.tlds)

class Test:
    def GET(self):
        stream = StringIO()
        tldextract.tldextract.run_tests(stream)
        return stream.getvalue()

app = web.application(urls, globals())
main = app.cgirun()


from __future__ import unicode_literals

# Authentication and Authorisation
from functools import wraps

from . import http

def permit(test_func, response_class=http.Forbidden):
    '''Decorate a handler to control access'''
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(self, *args, **kwargs):
            if test_func(self, *args, **kwargs):
                return view_func(self, *args, **kwargs)
            return response_class()
        return _wrapped_view
    return decorator

# Helpers for people wanting to control response class
def test_logged_in(self, *args, **kwargs):
    return self.request.user.is_authenticated()

def test_staff(self, *args, **kwargs):
    return self.request.user.is_staff

permit_logged_in = permit(test_logged_in)
permit_staff = permit(test_staff)

def permit_groups(*groups, response_class=http.Forbidden):
    def in_groups(self, *args, **kwargs):
        return self.request.user.groups.filter(name__in=groups).exists()
    return permit(in_groups, response_class=response_class)

Make it DRYer for people

Make it DRYer for people

Response:
<REPLACE_OLD> decorator

permit_logged_in = permit(
 <REPLACE_NEW> decorator

# Helpers for people wanting to control response class
def test_logged_in(self, *args, **kwargs):
 <REPLACE_END> <REPLACE_OLD> lambda self, <REPLACE_NEW> return self.request.user.is_authenticated()

def test_staff(self, <REPLACE_END> <REPLACE_OLD> **kwargs: self.request.user.is_authenticated()
)

permit_staff = permit(
 <REPLACE_NEW> **kwargs):
 <REPLACE_END> <REPLACE_OLD> lambda self, *args, **kwargs: self.request.user.is_staff
)

def permit_groups(*groups):
 <REPLACE_NEW> return self.request.user.is_staff

permit_logged_in = permit(test_logged_in)
permit_staff = permit(test_staff)

def permit_groups(*groups, response_class=http.Forbidden):
 <REPLACE_END> <REPLACE_OLD> permit(in_groups)
 <REPLACE_NEW> permit(in_groups, response_class=response_class)
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

# Authentication and Authorisation
from functools import wraps

from . import http

def permit(test_func, response_class=http.Forbidden):
    '''Decorate a handler to control access'''
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(self, *args, **kwargs):
            if test_func(self, *args, **kwargs):
                return view_func(self, *args, **kwargs)
            return response_class()
        return _wrapped_view
    return decorator

# Helpers for people wanting to control response class
def test_logged_in(self, *args, **kwargs):
    return self.request.user.is_authenticated()

def test_staff(self, *args, **kwargs):
    return self.request.user.is_staff

permit_logged_in = permit(test_logged_in)
permit_staff = permit(test_staff)

def permit_groups(*groups, response_class=http.Forbidden):
    def in_groups(self, *args, **kwargs):
        return self.request.user.groups.filter(name__in=groups).exists()
    return permit(in_groups, response_class=response_class)

Prompt:
Make it DRYer for people

from __future__ import unicode_literals

# Authentication and Authorisation
from functools import wraps

from . import http

def permit(test_func, response_class=http.Forbidden):
    '''Decorate a handler to control access'''
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(self, *args, **kwargs):
            if test_func(self, *args, **kwargs):
                return view_func(self, *args, **kwargs)
            return response_class()
        return _wrapped_view
    return decorator

permit_logged_in = permit(
    lambda self, *args, **kwargs: self.request.user.is_authenticated()
)

permit_staff = permit(
    lambda self, *args, **kwargs: self.request.user.is_staff
)

def permit_groups(*groups):
    def in_groups(self, *args, **kwargs):
        return self.request.user.groups.filter(name__in=groups).exists()
    return permit(in_groups)


from django.conf import settings
from django.utils.translation import ugettext_lazy as _

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .models import Picture

class PicturePlugin(CMSPluginBase):
    model = Picture
    name = _("Picture")
    render_template = "cms/plugins/picture.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        if instance.url:
            link = instance.url
        elif instance.page_link:
            link = instance.page_link.get_absolute_url()
        else:
            link = ""
        context.update({
            'picture': instance,
            'link': link,
            'placeholder': placeholder
        })
        return context

plugin_pool.register_plugin(PicturePlugin)

Modify the picture plugin slightly

Modify the picture plugin slightly

Response:
<REPLACE_OLD> context

    def icon_src(self, instance):
        # TODO - possibly use 'instance' and provide a thumbnail image
        return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"

plugin_pool.register_plugin(PicturePlugin)
 <REPLACE_NEW> context

plugin_pool.register_plugin(PicturePlugin)
 <REPLACE_END> <|endoftext|> from django.conf import settings
from django.utils.translation import ugettext_lazy as _

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .models import Picture

class PicturePlugin(CMSPluginBase):
    model = Picture
    name = _("Picture")
    render_template = "cms/plugins/picture.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        if instance.url:
            link = instance.url
        elif instance.page_link:
            link = instance.page_link.get_absolute_url()
        else:
            link = ""
        context.update({
            'picture': instance,
            'link': link,
            'placeholder': placeholder
        })
        return context

plugin_pool.register_plugin(PicturePlugin)

Prompt:
Modify the picture plugin slightly

from django.conf import settings
from django.utils.translation import ugettext_lazy as _

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .models import Picture

class PicturePlugin(CMSPluginBase):
    model = Picture
    name = _("Picture")
    render_template = "cms/plugins/picture.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        if instance.url:
            link = instance.url
        elif instance.page_link:
            link = instance.page_link.get_absolute_url()
        else:
            link = ""
        context.update({
            'picture': instance,
            'link': link,
            'placeholder': placeholder
        })
        return context

    def icon_src(self, instance):
        # TODO - possibly use 'instance' and provide a thumbnail image
        return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"

plugin_pool.register_plugin(PicturePlugin)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase

from opps.articles.models import Post

class PostModelTest(TestCase):

    fixtures = ['tests/initial_data.json']

    def test_basic_post_exist(self):
        post = Post.objects.all()

        self.assertTrue(post)
        self.assertEqual(len(post), 1)
        self.assertEqual(post[0].slug, u'test-post-application')
        self.assertEqual(post[0].title, u'test post application')
        self.assertTrue(post[0].short_url)

    def test_child_class(self):
        post = Post.objects.get(id=1)

        self.assertTrue(post.child_class)
        self.assertEqual(post.child_class, 'Post')

Response:
<REPLACE_OLD> self.assertTrue(post[0].short_url)
 <REPLACE_NEW> self.assertTrue(post[0].short_url)

    def test_child_class(self):
        post = Post.objects.get(id=1)

        self.assertTrue(post.child_class)
        self.assertEqual(post.child_class, 'Post')
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase

from opps.articles.models import Post

class PostModelTest(TestCase):

    fixtures = ['tests/initial_data.json']

    def test_basic_post_exist(self):
        post = Post.objects.all()

        self.assertTrue(post)
        self.assertEqual(len(post), 1)
        self.assertEqual(post[0].slug, u'test-post-application')
        self.assertEqual(post[0].title, u'test post application')
        self.assertTrue(post[0].short_url)

    def test_child_class(self):
        post = Post.objects.get(id=1)

        self.assertTrue(post.child_class)
        self.assertEqual(post.child_class, 'Post')

Prompt:
Add test articles (post), check child_class

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase

from opps.articles.models import Post

class PostModelTest(TestCase):

    fixtures = ['tests/initial_data.json']

    def test_basic_post_exist(self):
        post = Post.objects.all()

        self.assertTrue(post)
        self.assertEqual(len(post), 1)
        self.assertEqual(post[0].slug, u'test-post-application')
        self.assertEqual(post[0].title, u'test post application')
        self.assertTrue(post[0].short_url)


from IPython.config.loader import Config
from IPython.utils.traitlets import Unicode

from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path

aliases = {}
aliases.update(base_aliases)
aliases.update({
    'regexp': 'FindStudentID.regexp'
})

flags = {}
flags.update(base_flags)
flags.update({
    'serve': (
        {'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
        "Run the form grading server"
    )
})

class FormgradeApp(CustomNbConvertApp):

    name = Unicode(u'nbgrader-formgrade')
    description = Unicode(u'Grade a notebook using an HTML form')
    aliases = aliases
    flags = flags

    student_id = Unicode(u'', config=True)

    def _export_format_default(self):
        return 'html'

    def build_extra_config(self):
        self.extra_config = Config()
        self.extra_config.Exporter.preprocessors = [
            'nbgrader.preprocessors.FindStudentID'
        ]
        self.extra_config.Exporter.template_file = 'formgrade'
        self.extra_config.Exporter.template_path = ['.', get_template_path()]
        self.config.merge(self.extra_config)

Make form grade server be a flag

Make form grade server be a flag

Response:
<DELETE> IPython.config.application import catch_config_error
from <DELETE_END> <DELETE> get_template, <DELETE_END> <REPLACE_OLD> {}
flags.update(base_flags)
flags.update({
})

class FormgradeApp(CustomNbConvertApp):
 <REPLACE_NEW> {}
flags.update(base_flags)
flags.update({
 <REPLACE_END> <REPLACE_OLD>
 <REPLACE_NEW> 'serve': (
        {'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
        "Run the form grading server"
    )
})

class FormgradeApp(CustomNbConvertApp):

 <REPLACE_END> <DELETE>    @catch_config_error
    def initialize(self, argv=None):
        self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
        super(FormgradeApp, self).initialize(argv)

 <DELETE_END> <|endoftext|> from IPython.config.loader import Config
from IPython.utils.traitlets import Unicode

from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template_path

aliases = {}
aliases.update(base_aliases)
aliases.update({
    'regexp': 'FindStudentID.regexp'
})

flags = {}
flags.update(base_flags)
flags.update({
    'serve': (
        {'FormgradeApp': {'postprocessor_class': 'nbgrader.postprocessors.ServeFormGrader'}},
        "Run the form grading server"
    )
})

class FormgradeApp(CustomNbConvertApp):

    name = Unicode(u'nbgrader-formgrade')
    description = Unicode(u'Grade a notebook using an HTML form')
    aliases = aliases
    flags = flags

    student_id = Unicode(u'', config=True)

    def _export_format_default(self):
        return 'html'

    def build_extra_config(self):
        self.extra_config = Config()
        self.extra_config.Exporter.preprocessors = [
            'nbgrader.preprocessors.FindStudentID'
        ]
        self.extra_config.Exporter.template_file = 'formgrade'
        self.extra_config.Exporter.template_path = ['.', get_template_path()]
        self.config.merge(self.extra_config)

Prompt:
Make form grade server be a flag

from IPython.config.loader import Config
from IPython.config.application import catch_config_error
from IPython.utils.traitlets import Unicode

from nbgrader.apps.customnbconvertapp import CustomNbConvertApp
from nbgrader.apps.customnbconvertapp import aliases as base_aliases
from nbgrader.apps.customnbconvertapp import flags as base_flags
from nbgrader.templates import get_template, get_template_path

aliases = {}
aliases.update(base_aliases)
aliases.update({
    'regexp': 'FindStudentID.regexp'
})

flags = {}
flags.update(base_flags)
flags.update({
})

class FormgradeApp(CustomNbConvertApp):

    name = Unicode(u'nbgrader-formgrade')
    description = Unicode(u'Grade a notebook using an HTML form')
    aliases = aliases
    flags = flags

    student_id = Unicode(u'', config=True)

    def _export_format_default(self):
        return 'html'

    @catch_config_error
    def initialize(self, argv=None):
        self.postprocessor_class = 'nbgrader.postprocessors.ServeFormGrader'
        super(FormgradeApp, self).initialize(argv)

    def build_extra_config(self):
        self.extra_config = Config()
        self.extra_config.Exporter.preprocessors = [
            'nbgrader.preprocessors.FindStudentID'
        ]
        self.extra_config.Exporter.template_file = 'formgrade'
        self.extra_config.Exporter.template_path = ['.', get_template_path()]
        self.config.merge(self.extra_config)


# -*- coding: utf-8 -*-
"""
An extension for keywords which expose pieces of native python objects.
"""
from __future__ import absolute_import

from Cauldron.types import Integer, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary

__all__ = ['ExposeAttribute']

class ExposeAttribute(DispatcherKeywordType):
    """This keyword exposes a specific attribute from an object.
    """

    KTL_REGISTERED = False

    def __init__(self, name, service, obj, attribute, *args, **kwargs):
        self._object = obj
        self._attribute = attribute
        super(ExposeAttribute, self).__init__(name, service, *args, **kwargs)

    def read(self):
        """Read this keyword from the target object."""
        return getattr(self._object, self._attribute)

    def write(self, value):
        """Write this keyword to the target object."""
        setattr(self._object, self._attribute, value)

FIx a bug in exposed attribute keyword

FIx a bug in exposed attribute keyword

Response:
<REPLACE_OLD> super(HeartbeatKeyword, <REPLACE_NEW> super(ExposeAttribute, <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
An extension for keywords which expose pieces of native python objects.
"""
from __future__ import absolute_import

from Cauldron.types import Integer, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary

__all__ = ['ExposeAttribute']

class ExposeAttribute(DispatcherKeywordType):
    """This keyword exposes a specific attribute from an object.
    """

    KTL_REGISTERED = False

    def __init__(self, name, service, obj, attribute, *args, **kwargs):
        self._object = obj
        self._attribute = attribute
        super(ExposeAttribute, self).__init__(name, service, *args, **kwargs)

    def read(self):
        """Read this keyword from the target object."""
        return getattr(self._object, self._attribute)

    def write(self, value):
        """Write this keyword to the target object."""
        setattr(self._object, self._attribute, value)

Prompt:
FIx a bug in exposed attribute keyword

# -*- coding: utf-8 -*-
"""
An extension for keywords which expose pieces of native python objects.
"""
from __future__ import absolute_import

from Cauldron.types import Integer, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary

__all__ = ['ExposeAttribute']

class ExposeAttribute(DispatcherKeywordType):
    """This keyword exposes a specific attribute from an object.
    """

    KTL_REGISTERED = False

    def __init__(self, name, service, obj, attribute, *args, **kwargs):
        self._object = obj
        self._attribute = attribute
        super(HeartbeatKeyword, self).__init__(name, service, *args, **kwargs)

    def read(self):
        """Read this keyword from the target object."""
        return getattr(self._object, self._attribute)

    def write(self, value):
        """Write this keyword to the target object."""
        setattr(self._object, self._attribute, value)


from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.3.0',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.26',
        'future>=0.16,<0.19',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
        'six>=1.9',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<4.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)

Response:
<REPLACE_OLD> 'requests>=2.4.2,<2.25',
 <REPLACE_NEW> 'requests>=2.4.2,<2.26',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.3.0',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.26',
        'future>=0.16,<0.19',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
        'six>=1.9',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<4.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)

Prompt:
Update requests requirement from <2.25,>=2.4.2 to >=2.4.2,<2.26

Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.4.2...v2.25.0)

Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages

setup(
    name='panoptes_client',
    url='https://github.com/zooniverse/panoptes-python-client',
    author='Adam McMaster',
    author_email='adam@zooniverse.org',
    version='1.3.0',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.4.2,<2.25',
        'future>=0.16,<0.19',
        'python-magic>=0.4,<0.5',
        'redo>=1.7',
        'six>=1.9',
    ],
    extras_require={
        'testing': [
            'mock>=2.0,<4.1',
        ],
        'docs': [
            'sphinx',
        ],
        ':python_version == "2.7"': ['futures'],
    }
)


import unittest
import user
from users import UserDatabase

class FakeDatabaseSession:
    def __init__(self):
        self.didCommit = False
        self.things = [ ]
    def commit(self):
        self.didCommit = True
    def add(self, thingToAdd):
        self.things.append(thingToAdd)

class FakeDatabase:
    def __init__(self):
        self.session = FakeDatabaseSession()

class TestUserOperations(unittest.TestCase):
    def setUp(self):
        self.userDB = UserDatabase()
        self.appDB = FakeDatabase()
        self.appDBSession = self.appDB.session
    def tearDown(self):
        self.userDB = None
        self.appDB = None
        self.appDBSession = None
    def register_ash(self):
        self.userDB.registerUser("AshKetchum", "pallettown123", "000000000000", self.appDB)

    def test_registration(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        self.assertEqual(user.username, "AshKetchum")
        self.assertTrue(self.appDB.session.didCommit)
    def test_catching_pokemon_works(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Catch Pikachu
        self.userDB.catchPokemonForUser(user, 25, self.appDB)
        # Grab the state of the Pokemon @ 25
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 1)
    def test_new_user_hasnt_caught_pokemon(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Grab the state of the Pokemon @ 25
        # It should be 0
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 0)
    def test_catching_then_releasing_pokemon_works(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Catch Pikachu
        self.userDB.catchPokemonForUser(user, 25, self.appDB)
        # Release Pikachu :-(
        self.userDB.uncatchPokemonForUser(user, 25, self.appDB)
        # Grab the state of the Pokemon @ 25
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 0)

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

Add some unit tests for common user operations

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest
import user
from users import UserDatabase

class FakeDatabaseSession:
    def __init__(self):
        self.didCommit = False
        self.things = [ ]
    def commit(self):
        self.didCommit = True
    def add(self, thingToAdd):
        self.things.append(thingToAdd)

class FakeDatabase:
    def __init__(self):
        self.session = FakeDatabaseSession()

class TestUserOperations(unittest.TestCase):
    def setUp(self):
        self.userDB = UserDatabase()
        self.appDB = FakeDatabase()
        self.appDBSession = self.appDB.session
    def tearDown(self):
        self.userDB = None
        self.appDB = None
        self.appDBSession = None
    def register_ash(self):
        self.userDB.registerUser("AshKetchum", "pallettown123", "000000000000", self.appDB)

    def test_registration(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        self.assertEqual(user.username, "AshKetchum")
        self.assertTrue(self.appDB.session.didCommit)
    def test_catching_pokemon_works(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Catch Pikachu
        self.userDB.catchPokemonForUser(user, 25, self.appDB)
        # Grab the state of the Pokemon @ 25
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 1)
    def test_new_user_hasnt_caught_pokemon(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Grab the state of the Pokemon @ 25
        # It should be 0
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 0)
    def test_catching_then_releasing_pokemon_works(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Catch Pikachu
        self.userDB.catchPokemonForUser(user, 25, self.appDB)
        # Release Pikachu :-(
        self.userDB.uncatchPokemonForUser(user, 25, self.appDB)
        # Grab the state of the Pokemon @ 25
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 0)

if __name__ == '__main__':
    unittest.main()
 <REPLACE_END> <|endoftext|> import unittest
import user
from users import UserDatabase

class FakeDatabaseSession:
    def __init__(self):
        self.didCommit = False
        self.things = [ ]
    def commit(self):
        self.didCommit = True
    def add(self, thingToAdd):
        self.things.append(thingToAdd)

class FakeDatabase:
    def __init__(self):
        self.session = FakeDatabaseSession()

class TestUserOperations(unittest.TestCase):
    def setUp(self):
        self.userDB = UserDatabase()
        self.appDB = FakeDatabase()
        self.appDBSession = self.appDB.session
    def tearDown(self):
        self.userDB = None
        self.appDB = None
        self.appDBSession = None
    def register_ash(self):
        self.userDB.registerUser("AshKetchum", "pallettown123", "000000000000", self.appDB)

    def test_registration(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        self.assertEqual(user.username, "AshKetchum")
        self.assertTrue(self.appDB.session.didCommit)
    def test_catching_pokemon_works(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Catch Pikachu
        self.userDB.catchPokemonForUser(user, 25, self.appDB)
        # Grab the state of the Pokemon @ 25
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 1)
    def test_new_user_hasnt_caught_pokemon(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Grab the state of the Pokemon @ 25
        # It should be 0
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 0)
    def test_catching_then_releasing_pokemon_works(self):
        self.register_ash()
        user = self.appDBSession.things[0]
        # Catch Pikachu
        self.userDB.catchPokemonForUser(user, 25, self.appDB)
        # Release Pikachu :-(
        self.userDB.uncatchPokemonForUser(user, 25, self.appDB)
        # Grab the state of the Pokemon @ 25
        state = self.userDB._stateOfPokemonForUser(user, 25, self.appDB)
        state = int(state)
        self.assertEqual(state, 0)

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

Prompt: Add some unit tests for common user operations


import uuid

from django.db import migrations, models

import waldur_core.core.fields

def gen_uuid(apps, schema_editor):
    InvoiceItem = apps.get_model('invoices', 'InvoiceItem')
    for row in InvoiceItem.objects.all():
        row.uuid = uuid.uuid4().hex
        row.save(update_fields=['uuid'])

class Migration(migrations.Migration):

    dependencies = [
        ('invoices', '0052_delete_servicedowntime'),
    ]

    operations = [
        migrations.AddField(
            model_name='invoiceitem', name='uuid', field=models.UUIDField(null=True),
        ),
        migrations.RunPython(gen_uuid, elidable=True),
        migrations.AlterField(
            model_name='invoiceitem',
            name='uuid',
            field=waldur_core.core.fields.UUIDField(),
        ),
    ]

Response:
<REPLACE_OLD> migrations

import <REPLACE_NEW> migrations, models

import <REPLACE_END> <REPLACE_OLD> model_name='invoiceitem',
            name='uuid',
            field=waldur_core.core.fields.UUIDField(null=True),
 <REPLACE_NEW> model_name='invoiceitem', name='uuid', field=models.UUIDField(null=True),
 <REPLACE_END> <|endoftext|> import uuid

from django.db import migrations, models

import waldur_core.core.fields

def gen_uuid(apps, schema_editor):
    InvoiceItem = apps.get_model('invoices', 'InvoiceItem')
    for row in InvoiceItem.objects.all():
        row.uuid = uuid.uuid4().hex
        row.save(update_fields=['uuid'])

class Migration(migrations.Migration):

    dependencies = [
        ('invoices', '0052_delete_servicedowntime'),
    ]

    operations = [
        migrations.AddField(
            model_name='invoiceitem', name='uuid', field=models.UUIDField(null=True),
        ),
        migrations.RunPython(gen_uuid, elidable=True),
        migrations.AlterField(
            model_name='invoiceitem',
            name='uuid',
            field=waldur_core.core.fields.UUIDField(),
        ),
    ]

Prompt:
Fix database migration script for UUID field in invoice item model.

import uuid

from django.db import migrations

import waldur_core.core.fields

def gen_uuid(apps, schema_editor):
    InvoiceItem = apps.get_model('invoices', 'InvoiceItem')
    for row in InvoiceItem.objects.all():
        row.uuid = uuid.uuid4().hex
        row.save(update_fields=['uuid'])

class Migration(migrations.Migration):

    dependencies = [
        ('invoices', '0052_delete_servicedowntime'),
    ]

    operations = [
        migrations.AddField(
            model_name='invoiceitem',
            name='uuid',
            field=waldur_core.core.fields.UUIDField(null=True),
        ),
        migrations.RunPython(gen_uuid, elidable=True),
        migrations.AlterField(
            model_name='invoiceitem',
            name='uuid',
            field=waldur_core.core.fields.UUIDField(),
        ),
    ]


"""Configuration for Django system."""

__version__ = "0.13.3"
__version_info__ = tuple(
    [
        int(num) if num.isdigit() else num
        for num in __version__.replace("-", ".", 1).split(".")
    ]
)

Increment version number to 0.13.3

Increment version number to 0.13.3

Response:
<REPLACE_OLD> "0.13.2"
__version_info__ <REPLACE_NEW> "0.13.3"
__version_info__ <REPLACE_END> <|endoftext|> """Configuration for Django system."""

__version__ = "0.13.3"
__version_info__ = tuple(
    [
        int(num) if num.isdigit() else num
        for num in __version__.replace("-", ".", 1).split(".")
    ]
)

Prompt:
Increment version number to 0.13.3

"""Configuration for Django system."""

__version__ = "0.13.2"
__version_info__ = tuple(
    [
        int(num) if num.isdigit() else num
        for num in __version__.replace("-", ".", 1).split(".")
    ]
)


"""
    ydf/instructions
    ~~~~~~~~~~~~~~~~

    Convert objects parsed from YAML to those that represent Dockerfile instructions.
"""

import collections
import functools

from ydf import meta

__all__ = []

FROM = 'FROM'
RUN = 'RUN'
CMD = 'CMD'
LABEL = 'LABEL'
EXPOSE = 'EXPOSE'
ENV = 'ENV'
ADD = 'ADD'
COPY = 'COPY'
ENTRYPOINT = 'ENTRYPOINT'
VOLUME = 'VOLUME'
USER = 'USER'
WORKDIR = 'WORKDIR'
ARG = 'ARG'
ONBUILD = 'ONBUILD'
STOPSIGNAL = 'STOPSIGNAL'
HEALTHCHECK = 'HEALTHCHECK'
SHELL = 'SHELL'

def get_instructions():
    """
    Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`.
    """
    instructions = collections.defaultdict(dict)
    for func in (value for key, value in globals().items() if meta.is_instruction(value)):
        instructions[func.instruction_name][func.instruction_type] = func
    return instructions

def instruction(name, type, desc):
    """
    Decorate a function to indicate that it is responsible for converting a python type to a Docker
    instruction.

    :param name: Name of docker instruction
    :param type: Type of python object it can convert
    :param desc: Short description of expected format for the python object.
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return '{} {}'.format(name, func(*args, **kwargs))
        wrapper.instruction_name = name
        wrapper.instruction_type = type
        wrapper.instruction_desc = desc
        return wrapper
    return decorator

Response:
<REPLACE_OLD> instructions.
"""

__all__ <REPLACE_NEW> instructions.
"""

import collections
import functools

from ydf import meta

__all__ <REPLACE_END> <REPLACE_OLD> 'SHELL'
 <REPLACE_NEW> 'SHELL'

def get_instructions():
    """
    Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`.
    """
    instructions = collections.defaultdict(dict)
    for func in (value for key, value in globals().items() if meta.is_instruction(value)):
        instructions[func.instruction_name][func.instruction_type] = func
    return instructions

def instruction(name, type, desc):
    """
    Decorate a function to indicate that it is responsible for converting a python type to a Docker
    instruction.

    :param name: Name of docker instruction
    :param type: Type of python object it can convert
    :param desc: Short description of expected format for the python object.
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return '{} {}'.format(name, func(*args, **kwargs))
        wrapper.instruction_name = name
        wrapper.instruction_type = type
        wrapper.instruction_desc = desc
        return wrapper
    return decorator
 <REPLACE_END> <|endoftext|> """
    ydf/instructions
    ~~~~~~~~~~~~~~~~

    Convert objects parsed from YAML to those that represent Dockerfile instructions.
"""

import collections
import functools

from ydf import meta

__all__ = []

FROM = 'FROM'
RUN = 'RUN'
CMD = 'CMD'
LABEL = 'LABEL'
EXPOSE = 'EXPOSE'
ENV = 'ENV'
ADD = 'ADD'
COPY = 'COPY'
ENTRYPOINT = 'ENTRYPOINT'
VOLUME = 'VOLUME'
USER = 'USER'
WORKDIR = 'WORKDIR'
ARG = 'ARG'
ONBUILD = 'ONBUILD'
STOPSIGNAL = 'STOPSIGNAL'
HEALTHCHECK = 'HEALTHCHECK'
SHELL = 'SHELL'

def get_instructions():
    """
    Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`.
    """
    instructions = collections.defaultdict(dict)
    for func in (value for key, value in globals().items() if meta.is_instruction(value)):
        instructions[func.instruction_name][func.instruction_type] = func
    return instructions

def instruction(name, type, desc):
    """
    Decorate a function to indicate that it is responsible for converting a python type to a Docker
    instruction.

    :param name: Name of docker instruction
    :param type: Type of python object it can convert
    :param desc: Short description of expected format for the python object.
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return '{} {}'.format(name, func(*args, **kwargs))
        wrapper.instruction_name = name
        wrapper.instruction_type = type
        wrapper.instruction_desc = desc
        return wrapper
    return decorator

Prompt:
Add @instruction decorator to mark module level funcs as handlers.

"""
    ydf/instructions
    ~~~~~~~~~~~~~~~~

    Convert objects parsed from YAML to those that represent Dockerfile instructions.
"""

__all__ = []

FROM = 'FROM'
RUN = 'RUN'
CMD = 'CMD'
LABEL = 'LABEL'
EXPOSE = 'EXPOSE'
ENV = 'ENV'
ADD = 'ADD'
COPY = 'COPY'
ENTRYPOINT = 'ENTRYPOINT'
VOLUME = 'VOLUME'
USER = 'USER'
WORKDIR = 'WORKDIR'
ARG = 'ARG'
ONBUILD = 'ONBUILD'
STOPSIGNAL = 'STOPSIGNAL'
HEALTHCHECK = 'HEALTHCHECK'
SHELL = 'SHELL'


__version__ = '0.5.0'

# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process import Process, TimeDependentProcess, ImplicitProcess, DiagnosticProcess, EnergyBudget
from climlab.process import process_like, get_axes

Increment version number to 0.5.0

Increment version number to 0.5.0

Response:
<REPLACE_OLD> '0.5.0.dev0'

# <REPLACE_NEW> '0.5.0'

# <REPLACE_END> <|endoftext|> __version__ = '0.5.0'

# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process import Process, TimeDependentProcess, ImplicitProcess, DiagnosticProcess, EnergyBudget
from climlab.process import process_like, get_axes

Prompt:
Increment version number to 0.5.0
__version__ = '0.5.0.dev0'

# this should ensure that we can still import constants.py as climlab.constants
from climlab.utils import constants
from climlab.utils import thermo, legendre
# some more useful shorcuts
from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel
from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal
from climlab.domain import domain
from climlab.domain.field import Field, global_mean
from climlab.domain.axis import Axis
from climlab.domain.initial import column_state, surface_state
from climlab.process import Process, TimeDependentProcess, ImplicitProcess, DiagnosticProcess, EnergyBudget
from climlab.process import process_like, get_axes


#!/usr/bin/env python

from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math

class getDistance(EventState):
    """
    Calcule la distance entre deux points donnes.

    ### InputKey
    ># point1
    ># point2

    ### OutputKey
    #> distance

    <= done
    """
    def __init__(self):
        """Constructor"""

        super(getDistance, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])

    def execute(self, userdata):
        """Wait for action result and return outcome accordingly"""

        userdata.distance= calculate_distance(userdata.point1,userdata.point2)
        return 'done'

    def calculate_distance(p1,p2):
        return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))

Correct call to super constructor

Correct call to super constructor

Response:
<REPLACE_OLD> super(GetNumberFromText, <REPLACE_NEW> super(getDistance, <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math

class getDistance(EventState):
    """
    Calcule la distance entre deux points donnes.

    ### InputKey
    ># point1
    ># point2

    ### OutputKey
    #> distance

    <= done
    """
    def __init__(self):
        """Constructor"""

        super(getDistance, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])

    def execute(self, userdata):
        """Wait for action result and return outcome accordingly"""

        userdata.distance= calculate_distance(userdata.point1,userdata.point2)
        return 'done'

    def calculate_distance(p1,p2):
        return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))

Prompt:
Correct call to super constructor

#!/usr/bin/env python

from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math

class getDistance(EventState):
    """
    Calcule la distance entre deux points donnes.

    ### InputKey
    ># point1
    ># point2

    ### OutputKey
    #> distance

    <= done
    """
    def __init__(self):
        """Constructor"""

        super(GetNumberFromText, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])

    def execute(self, userdata):
        """Wait for action result and return outcome accordingly"""

        userdata.distance= calculate_distance(userdata.point1,userdata.point2)
        return 'done'

    def calculate_distance(p1,p2):
        return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))


#!/usr/bin/env python

# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
import fsurfer

setup(name='fsurfer-backend',
      version=fsurfer.__version__,
      description='Scripts to handle background freesurfer processing',
      author='Suchandra Thapa',
      author_email='sthapa@ci.uchicago.edu',
      url='https://github.com/OSGConnect/freesurfer_workflow',
      scripts=['process_mri.py',
               'update_fsurf_job.py',
               'purge_inputs.py',
               'purge_results.py',
               'warn_purge.py'],
      license='Apache 2.0')

Add purge and warn scripts

Add purge and warn scripts

Response:
<REPLACE_OLD> scripts=['process_mri.py', 'update_fsurf_job.py'],
 <REPLACE_NEW> scripts=['process_mri.py',
               'update_fsurf_job.py',
               'purge_inputs.py',
               'purge_results.py',
               'warn_purge.py'],
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
import fsurfer

setup(name='fsurfer-backend',
      version=fsurfer.__version__,
      description='Scripts to handle background freesurfer processing',
      author='Suchandra Thapa',
      author_email='sthapa@ci.uchicago.edu',
      url='https://github.com/OSGConnect/freesurfer_workflow',
      scripts=['process_mri.py',
               'update_fsurf_job.py',
               'purge_inputs.py',
               'purge_results.py',
               'warn_purge.py'],
      license='Apache 2.0')

Prompt:
Add purge and warn scripts

#!/usr/bin/env python

# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
import fsurfer

setup(name='fsurfer-backend',
      version=fsurfer.__version__,
      description='Scripts to handle background freesurfer processing',
      author='Suchandra Thapa',
      author_email='sthapa@ci.uchicago.edu',
      url='https://github.com/OSGConnect/freesurfer_workflow',
      scripts=['process_mri.py', 'update_fsurf_job.py'],
      license='Apache 2.0')


FFMPEG_PATH = '/usr/local/bin/ffmpeg'

VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode
VIDEO_ENCODER = 'h264_omx'

AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode
AUDIO_ENCODER = 'aac'

BITRATE = '2500k'

INPUT_EXTS = ['.mkv', '.mp4']
OUTPUT_EXT = '.mp4'

Add mp4 as input ext

Add mp4 as input ext

Response:
<REPLACE_OLD> ['.mkv']
OUTPUT_EXT <REPLACE_NEW> ['.mkv', '.mp4']
OUTPUT_EXT <REPLACE_END> <|endoftext|> FFMPEG_PATH = '/usr/local/bin/ffmpeg'

VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode
VIDEO_ENCODER = 'h264_omx'

AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode
AUDIO_ENCODER = 'aac'

BITRATE = '2500k'

INPUT_EXTS = ['.mkv', '.mp4']
OUTPUT_EXT = '.mp4'

Prompt:
Add mp4 as input ext

FFMPEG_PATH = '/usr/local/bin/ffmpeg'

VIDEO_CODEC = 'h264' # used with ffprobe to detect whether or not we need to encode
VIDEO_ENCODER = 'h264_omx'

AUDIO_CODEC = 'aac' # used with ffprobe to detect whether or not we need to encode
AUDIO_ENCODER = 'aac'

BITRATE = '2500k'

INPUT_EXTS = ['.mkv']
OUTPUT_EXT = '.mp4'


"""
DIW
MTW
UTW
"""

import time

import requests
from bs4 import BeautifulSoup

from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point

from authorities.models import Authority, MapitArea
from authorities import constants
from authorities.helpers import geocode

class Command(BaseCommand):

    def add_arguments(self, parser):
            parser.add_argument('mapit_type', type=str)

    def handle(self, *args, **options):
        print(options)
        self.get_type_from_mapit(options['mapit_type'])

    def get_type_from_mapit(self, mapit_type):
        req = requests.get('%sareas/%s' % (
            constants.MAPIT_URL, mapit_type))
        for mapit_id, area in list(req.json().items()):
            print(area)
            authority = Authority.objects.get(mapit_id=area['parent_area'])
            MapitArea.objects.get_or_create(
                gss=area['codes']['gss'],
                parent_authority=authority,
                name=area['name'],
                area_type=area['type'],
                unit_id=area['codes']['unit_id'],
                type_name=area['type_name'],
                country_name=area['country_name'],
            )

Response:
<REPLACE_OLD> import <REPLACE_NEW> """
DIW
MTW
UTW
"""

import <REPLACE_END> <INSERT> print(area)
            <INSERT_END> <|endoftext|> """
DIW
MTW
UTW
"""

import time

import requests
from bs4 import BeautifulSoup

from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point

from authorities.models import Authority, MapitArea
from authorities import constants
from authorities.helpers import geocode

class Command(BaseCommand):

    def add_arguments(self, parser):
            parser.add_argument('mapit_type', type=str)

    def handle(self, *args, **options):
        print(options)
        self.get_type_from_mapit(options['mapit_type'])

    def get_type_from_mapit(self, mapit_type):
        req = requests.get('%sareas/%s' % (
            constants.MAPIT_URL, mapit_type))
        for mapit_id, area in list(req.json().items()):
            print(area)
            authority = Authority.objects.get(mapit_id=area['parent_area'])
            MapitArea.objects.get_or_create(
                gss=area['codes']['gss'],
                parent_authority=authority,
                name=area['name'],
                area_type=area['type'],
                unit_id=area['codes']['unit_id'],
                type_name=area['type_name'],
                country_name=area['country_name'],
            )

Prompt:
Comment for types of area that need importing

import time

import requests
from bs4 import BeautifulSoup

from django.core.management.base import BaseCommand
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point

from authorities.models import Authority, MapitArea
from authorities import constants
from authorities.helpers import geocode

class Command(BaseCommand):

    def add_arguments(self, parser):
            parser.add_argument('mapit_type', type=str)

    def handle(self, *args, **options):
        print(options)
        self.get_type_from_mapit(options['mapit_type'])

    def get_type_from_mapit(self, mapit_type):
        req = requests.get('%sareas/%s' % (
            constants.MAPIT_URL, mapit_type))
        for mapit_id, area in list(req.json().items()):
            authority = Authority.objects.get(mapit_id=area['parent_area'])
            MapitArea.objects.get_or_create(
                gss=area['codes']['gss'],
                parent_authority=authority,
                name=area['name'],
                area_type=area['type'],
                unit_id=area['codes']['unit_id'],
                type_name=area['type_name'],
                country_name=area['country_name'],
            )


"""
All the different types that the compiler handles.
"""
from collections import namedtuple

IntegerType = namedtuple('IntegerType', [])
Integer = IntegerType()

ByteType = namedtuple('ByteType', [])
Byte = ByteType()

PointerTo = namedtuple('PointerTo', ['type'])
ArrayOf = namedtuple('ArrayOf', ['type', 'count'])
FunctionPointer = namedtuple('FunctionPointer', ['return_type', 'params'])
TypeName = namedtuple('TypeName', ['name'])

# Structure is a bit of an oddity - it can't actually be used in 'raw form'
# by the user, but is always aliased in a declare block.
#
# Also, fields is an OrderedDict, since the order of fields matters for layout,
Struct = namedtuple('Struct', ['fields'])

# This is used merely to record that a function has been declared - the
# actual reified type is FunctionPointer
FunctionDecl = namedtuple('FunctionDecl', ['return_type', 'params'])

AliasDef = namedtuple('AliasDef', ['type'])

# Raw types are types which can be used as variables
RAW_TYPES = (types.IntegerType, types.ByteType, types.TypeName,
        types.PointerTo, types.ArrayOf, types.FunctionPointer)

def decay_if_array(type_obj):
    """
    Decays arrays types into pointers.
    """
    if isinstance(type_obj, types.ArrayOf):
        return type_obj.PointerTo(type_obj.type)
    else:
        return type_obj

def func_decl_to_ptr(func_decl):
    """
    Converts a function declaration to a pointer.
    """
    return FunctionPointer(*func_decl)

Response:
<REPLACE_OLD> block
Struct <REPLACE_NEW> block.
#
# Also, fields is an OrderedDict, since the order of fields matters for layout,
Struct <REPLACE_END> <|endoftext|> """
All the different types that the compiler handles.
"""
from collections import namedtuple

IntegerType = namedtuple('IntegerType', [])
Integer = IntegerType()

ByteType = namedtuple('ByteType', [])
Byte = ByteType()

PointerTo = namedtuple('PointerTo', ['type'])
ArrayOf = namedtuple('ArrayOf', ['type', 'count'])
FunctionPointer = namedtuple('FunctionPointer', ['return_type', 'params'])
TypeName = namedtuple('TypeName', ['name'])

# Structure is a bit of an oddity - it can't actually be used in 'raw form'
# by the user, but is always aliased in a declare block.
#
# Also, fields is an OrderedDict, since the order of fields matters for layout,
Struct = namedtuple('Struct', ['fields'])

# This is used merely to record that a function has been declared - the
# actual reified type is FunctionPointer
FunctionDecl = namedtuple('FunctionDecl', ['return_type', 'params'])

AliasDef = namedtuple('AliasDef', ['type'])

# Raw types are types which can be used as variables
RAW_TYPES = (types.IntegerType, types.ByteType, types.TypeName,
        types.PointerTo, types.ArrayOf, types.FunctionPointer)

def decay_if_array(type_obj):
    """
    Decays arrays types into pointers.
    """
    if isinstance(type_obj, types.ArrayOf):
        return type_obj.PointerTo(type_obj.type)
    else:
        return type_obj

def func_decl_to_ptr(func_decl):
    """
    Converts a function declaration to a pointer.
    """
    return FunctionPointer(*func_decl)

Prompt:
Add note that Struct's field collection is an OrderedDict

"""
All the different types that the compiler handles.
"""
from collections import namedtuple

IntegerType = namedtuple('IntegerType', [])
Integer = IntegerType()

ByteType = namedtuple('ByteType', [])
Byte = ByteType()

PointerTo = namedtuple('PointerTo', ['type'])
ArrayOf = namedtuple('ArrayOf', ['type', 'count'])
FunctionPointer = namedtuple('FunctionPointer', ['return_type', 'params'])
TypeName = namedtuple('TypeName', ['name'])

# Structure is a bit of an oddity - it can't actually be used in 'raw form'
# by the user, but is always aliased in a declare block
Struct = namedtuple('Struct', ['fields'])

# This is used merely to record that a function has been declared - the
# actual reified type is FunctionPointer
FunctionDecl = namedtuple('FunctionDecl', ['return_type', 'params'])

AliasDef = namedtuple('AliasDef', ['type'])

# Raw types are types which can be used as variables
RAW_TYPES = (types.IntegerType, types.ByteType, types.TypeName,
        types.PointerTo, types.ArrayOf, types.FunctionPointer)

def decay_if_array(type_obj):
    """
    Decays arrays types into pointers.
    """
    if isinstance(type_obj, types.ArrayOf):
        return type_obj.PointerTo(type_obj.type)
    else:
        return type_obj

def func_decl_to_ptr(func_decl):
    """
    Converts a function declaration to a pointer.
    """
    return FunctionPointer(*func_decl)


import re

def find_memtions(content):
    regex = re.compile(r"@(?P<username>)(\s|$)", re.I)
    return [m.group("username") for m in regex.finditer(content)]

Add the method for finding names using regular expression matching.

Response:
<INSERT> import re

def find_memtions(content):
 <INSERT_END> <INSERT>   regex = re.compile(r"@(?P<username>)(\s|$)", re.I)
    return [m.group("username") for m in regex.finditer(content)]

 <INSERT_END> <|endoftext|> import re

def find_memtions(content):
    regex = re.compile(r"@(?P<username>)(\s|$)", re.I)
    return [m.group("username") for m in regex.finditer(content)]

Prompt: Add the method for finding names using regular expression matching.


import os

os.chdir('tests/cmdline')

lines = file('coverage.out', 'r').readlines()

files = {}

for line in lines:
	filename, lineno = line.split("----------")

	if filename not in files:
		files[filename] = set()

	files[filename].add(int(lineno))

filenames = files.keys()
filenames.sort()

for filename in filenames:
	linenos = files[filename]

	file_contents = file(filename.strip(), 'r').readlines()

	coverage_name = filename.strip() + '-coverage.html'
	print "Creating", coverage_name
	coverage_file = file(coverage_name, 'w')
	coverage_file.write('\n')

	for i, line in enumerate(file_contents):
		if i + 1 in linenos:
			covered = 'covered'
		else:
			covered = 'uncovered'
		coverage_file.write('
%s
\n' % (covered, line))

	coverage_file.write('')

Add makefile build rule for building HTML files which show which lines are covered and which are not.

Response:
<REPLACE_OLD>  <REPLACE_NEW>
import os

os.chdir('tests/cmdline')

lines = file('coverage.out', 'r').readlines()

files = {}

for line in lines:
	filename, lineno = line.split("----------")

	if filename not in files:
		files[filename] = set()

	files[filename].add(int(lineno))

filenames = files.keys()
filenames.sort()

for filename in filenames:
	linenos = files[filename]

	file_contents = file(filename.strip(), 'r').readlines()

	coverage_name = filename.strip() + '-coverage.html'
	print "Creating", coverage_name
	coverage_file = file(coverage_name, 'w')
	coverage_file.write('<html><head><style type="text/css">div {white-space: pre; font-family: monospace} .covered {color: green} .uncovered{color: red}</style></head><body>\n')

	for i, line in enumerate(file_contents):
		if i + 1 in linenos:
			covered = 'covered'
		else:
			covered = 'uncovered'
		coverage_file.write('<div class="%s">%s</div>\n' % (covered, line))

	coverage_file.write('</body></html>')

 <REPLACE_END> <|endoftext|>
import os

os.chdir('tests/cmdline')

lines = file('coverage.out', 'r').readlines()

files = {}

for line in lines:
	filename, lineno = line.split("----------")

	if filename not in files:
		files[filename] = set()

	files[filename].add(int(lineno))

filenames = files.keys()
filenames.sort()

for filename in filenames:
	linenos = files[filename]

	file_contents = file(filename.strip(), 'r').readlines()

	coverage_name = filename.strip() + '-coverage.html'
	print "Creating", coverage_name
	coverage_file = file(coverage_name, 'w')
	coverage_file.write('<html><head><style type="text/css">div {white-space: pre; font-family: monospace} .covered {color: green} .uncovered{color: red}</style></head><body>\n')

	for i, line in enumerate(file_contents):
		if i + 1 in linenos:
			covered = 'covered'
		else:
			covered = 'uncovered'
		coverage_file.write('<div class="%s">%s</div>\n' % (covered, line))

	coverage_file.write('</body></html>')

Prompt: Add makefile build rule for building HTML files which show which lines are covered and which are not.


from contextlib import contextmanager
from functools import wraps

from fastats.core.ast_transforms.convert_to_jit import convert_to_jit
from fastats.core.ast_transforms.processor import AstProcessor

@contextmanager
def code_transform(func, replaced):
    try:
        yield func
    finally:
        for k, v in replaced.items():
            func.__globals__[k] = v
        replaced.clear()

def fs(func):
    # The initial function *must* be jittable,
    # else we can't do anything.
    _func = func
    replaced = {}

    @wraps(func)
    def fs_wrapper(*args, **kwargs):
        return_callable = kwargs.pop('return_callable', None)

        if not kwargs:
            return _func(*args)

        with code_transform(_func, replaced) as _f:
            # TODO : remove fastats keywords such as 'debug'
            # before passing into AstProcessor

            new_funcs = {v.__name__: convert_to_jit(v) for v in kwargs.values()
                         if v.__name__ not in kwargs}
            kwargs = {k: convert_to_jit(v) for k, v in kwargs.items()}

            processor = AstProcessor(_f, kwargs, replaced, new_funcs)
            proc = processor.process()
            if return_callable:
                return convert_to_jit(proc)
            return convert_to_jit(proc)(*args)

    return fs_wrapper

Response:
<REPLACE_OLD> {}
            <REPLACE_NEW> {v.__name__: convert_to_jit(v) <REPLACE_END> <REPLACE_OLD> kwargs.values():
 <REPLACE_NEW> kwargs.values()
          <REPLACE_END> <INSERT> not <INSERT_END> <REPLACE_OLD> kwargs:
                    continue

                new_funcs[v.__name__] = convert_to_jit(v)

 <REPLACE_NEW> kwargs}
 <REPLACE_END> <|endoftext|>
from contextlib import contextmanager
from functools import wraps

from fastats.core.ast_transforms.convert_to_jit import convert_to_jit
from fastats.core.ast_transforms.processor import AstProcessor

@contextmanager
def code_transform(func, replaced):
    try:
        yield func
    finally:
        for k, v in replaced.items():
            func.__globals__[k] = v
        replaced.clear()

def fs(func):
    # The initial function *must* be jittable,
    # else we can't do anything.
    _func = func
    replaced = {}

    @wraps(func)
    def fs_wrapper(*args, **kwargs):
        return_callable = kwargs.pop('return_callable', None)

        if not kwargs:
            return _func(*args)

        with code_transform(_func, replaced) as _f:
            # TODO : remove fastats keywords such as 'debug'
            # before passing into AstProcessor

            new_funcs = {v.__name__: convert_to_jit(v) for v in kwargs.values()
                         if v.__name__ not in kwargs}
            kwargs = {k: convert_to_jit(v) for k, v in kwargs.items()}

            processor = AstProcessor(_f, kwargs, replaced, new_funcs)
            proc = processor.process()
            if return_callable:
                return convert_to_jit(proc)
            return convert_to_jit(proc)(*args)

    return fs_wrapper

Prompt:
Remove a for loop in favour of a dict comprehension

from contextlib import contextmanager
from functools import wraps

from fastats.core.ast_transforms.convert_to_jit import convert_to_jit
from fastats.core.ast_transforms.processor import AstProcessor

@contextmanager
def code_transform(func, replaced):
    try:
        yield func
    finally:
        for k, v in replaced.items():
            func.__globals__[k] = v
        replaced.clear()

def fs(func):
    # The initial function *must* be jittable,
    # else we can't do anything.
    _func = func
    replaced = {}

    @wraps(func)
    def fs_wrapper(*args, **kwargs):
        return_callable = kwargs.pop('return_callable', None)

        if not kwargs:
            return _func(*args)

        with code_transform(_func, replaced) as _f:
            # TODO : remove fastats keywords such as 'debug'
            # before passing into AstProcessor

            new_funcs = {}
            for v in kwargs.values():
                if v.__name__ in kwargs:
                    continue

                new_funcs[v.__name__] = convert_to_jit(v)

            kwargs = {k: convert_to_jit(v) for k, v in kwargs.items()}

            processor = AstProcessor(_f, kwargs, replaced, new_funcs)
            proc = processor.process()
            if return_callable:
                return convert_to_jit(proc)
            return convert_to_jit(proc)(*args)

    return fs_wrapper


#
# Code to load project paths
#

import os, sys

MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.." ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )

sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MRCAP_PATH ]

Change to path, made relative

Response:
<REPLACE_OLD> "/Users/dmhembere44/MR-connectome" <REPLACE_NEW> "../.." <REPLACE_END> <|endoftext|> #
# Code to load project paths
#

import os, sys

MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.." ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )

sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MRCAP_PATH ]

Prompt:
Change to path, made relative

Former-commit-id: f00bf782fad3f6ddc6d2c97a23ff4f087ad3a22f

#
# Code to load project paths
#

import os, sys

MR_BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "/Users/dmhembere44/MR-connectome" ))
MR_CMAPPER_PATH = os.path.join(MR_BASE_PATH, "cmapper" )
MR_MRCAP_PATH = os.path.join(MR_BASE_PATH, "mrcap" )

sys.path += [ MR_BASE_PATH, MR_CMAPPER_PATH, MR_MRCAP_PATH ]


#!/usr/bin/env python

import os
from distutils.core import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='whack',
    version='0.3.4',
    description='Utility for installing binaries from source with a single command',
    long_description=read("README"),
    author='Michael Williamson',
    url='http://github.com/mwilliamson/whack',
    scripts=["scripts/whack"],
    packages=['whack'],
    install_requires=[
        'blah>=0.1.10,<0.2',
        'requests>=1,<2',
        "catchy>=0.1.2,<0.2",
        "spur>=0.3,<0.4",
        "locket>=0.1.1,<0.2",
    ],
)

Update locket to 0.1.1 for bug fix

Update locket to 0.1.1 for bug fix

Response:
<REPLACE_OLD> "locket>=0.1,<0.2",
 <REPLACE_NEW> "locket>=0.1.1,<0.2",
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os
from distutils.core import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='whack',
    version='0.3.4',
    description='Utility for installing binaries from source with a single command',
    long_description=read("README"),
    author='Michael Williamson',
    url='http://github.com/mwilliamson/whack',
    scripts=["scripts/whack"],
    packages=['whack'],
    install_requires=[
        'blah>=0.1.10,<0.2',
        'requests>=1,<2',
        "catchy>=0.1.2,<0.2",
        "spur>=0.3,<0.4",
        "locket>=0.1.1,<0.2",
    ],
)

Prompt:
Update locket to 0.1.1 for bug fix

#!/usr/bin/env python

import os
from distutils.core import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='whack',
    version='0.3.4',
    description='Utility for installing binaries from source with a single command',
    long_description=read("README"),
    author='Michael Williamson',
    url='http://github.com/mwilliamson/whack',
    scripts=["scripts/whack"],
    packages=['whack'],
    install_requires=[
        'blah>=0.1.10,<0.2',
        'requests>=1,<2',
        "catchy>=0.1.2,<0.2",
        "spur>=0.3,<0.4",
        "locket>=0.1,<0.2",
    ],
)


"""
Process 20 lines of output at a time.

Example runs:
python buffer_results.py
"""
import sys
import time
import drainers

# fake this
def setup_cruncher():
    time.sleep(1)

def do_something_expensive(file):
    time.sleep(0.005)

def destroy_cruncher():
    time.sleep(0.8)

files = []

def crunch(files):
    print 'Setting up cruncher...'
    setup_cruncher()
    while len(files) > 0:
        f = files.pop(0)
        print '- Crunching file %s...' % f.strip()
        do_something_expensive(f)
    print 'Releasing cruncher...'
    destroy_cruncher()

def add_to_buffer(line, is_err):
    if is_err:
        # ignore all errors
        return
    files.append(line)

    # start crunch synchronously after 20 items have been read
    if len(files) >= 20:
        crunch(files)

d = drainers.Drainer(['find', '.', '-type', 'f'], read_event_cb=add_to_buffer)
d.start()

Add result buffering/batch processing example.

Response:
<INSERT> """
Process 20 lines of output at a time.

Example runs:
python buffer_results.py
"""
import sys
import time
import drainers

# fake this
def setup_cruncher():
 <INSERT_END> <INSERT>   time.sleep(1)

def do_something_expensive(file):
    time.sleep(0.005)

def destroy_cruncher():
    time.sleep(0.8)

files = []

def crunch(files):
    print 'Setting up cruncher...'
    setup_cruncher()
    while len(files) > 0:
        f = files.pop(0)
        print '- Crunching file %s...' % f.strip()
        do_something_expensive(f)
    print 'Releasing cruncher...'
    destroy_cruncher()

def add_to_buffer(line, is_err):
    if is_err:
        # ignore all errors
        return
    files.append(line)

    # start crunch synchronously after 20 items have been read
    if len(files) >= 20:
        crunch(files)

d = drainers.Drainer(['find', '.', '-type', 'f'], read_event_cb=add_to_buffer)
d.start()
 <INSERT_END> <|endoftext|> """
Process 20 lines of output at a time.

Example runs:
python buffer_results.py
"""
import sys
import time
import drainers

# fake this
def setup_cruncher():
    time.sleep(1)

def do_something_expensive(file):
    time.sleep(0.005)

def destroy_cruncher():
    time.sleep(0.8)

files = []

def crunch(files):
    print 'Setting up cruncher...'
    setup_cruncher()
    while len(files) > 0:
        f = files.pop(0)
        print '- Crunching file %s...' % f.strip()
        do_something_expensive(f)
    print 'Releasing cruncher...'
    destroy_cruncher()

def add_to_buffer(line, is_err):
    if is_err:
        # ignore all errors
        return
    files.append(line)

    # start crunch synchronously after 20 items have been read
    if len(files) >= 20:
        crunch(files)

d = drainers.Drainer(['find', '.', '-type', 'f'], read_event_cb=add_to_buffer)
d.start()

Prompt: Add result buffering/batch processing example.


def print_generated_sequence(g, num, *, sep=", ", seed=None):
    """
    Helper function which prints a sequence of `num` items
    produced by the random generator `g`.
    """
    if seed:
       g.reset(seed)

    elems = [str(next(g)) for _ in range(num)]
    sep_initial = "\n" if sep == "\n" else " "
    print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))

Response:
<REPLACE_OLD> "):
 <REPLACE_NEW> ", seed=None):
 <REPLACE_END> <REPLACE_OLD> """

 <REPLACE_NEW> """
    if seed:
       g.reset(seed)

 <REPLACE_END> <|endoftext|> def print_generated_sequence(g, num, *, sep=", ", seed=None):
    """
    Helper function which prints a sequence of `num` items
    produced by the random generator `g`.
    """
    if seed:
       g.reset(seed)

    elems = [str(next(g)) for _ in range(num)]
    sep_initial = "\n" if sep == "\n" else " "
    print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))

Prompt:
Allow passing seed directly to helper function

def print_generated_sequence(g, num, *, sep=", "):
    """
    Helper function which prints a sequence of `num` items
    produced by the random generator `g`.
    """

    elems = [str(next(g)) for _ in range(num)]
    sep_initial = "\n" if sep == "\n" else " "
    print("Generated sequence:{}{}".format(sep_initial, sep.join(elems)))