#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import os
import re

import cv2
from jsk_recognition_utils import bounding_rect_of_mask

parser = argparse.ArgumentParser()
parser.add_argument('container_path')
args = parser.parse_args()

container_path = args.container_path
output_dir = os.path.abspath(container_path + '_mask_applied')

if not os.path.exists(output_dir):
    print('creating output directory: {}'.format(output_dir))
    os.mkdir(output_dir)

categs = os.listdir(container_path)

os.chdir(container_path)

for categ in categs:
    os.chdir(categ)

    print('processing category: {}'.format(categ))
    files = os.listdir('.')
    img_files = filter(lambda x: re.match('^N\d*?_\d*?.jpg', x), files)
    print('found {} images'.format(len(img_files)))

    categ_output_dir = os.path.join(output_dir, categ)
    if not os.path.exists(categ_output_dir):
        os.mkdir(categ_output_dir)

    for img_file in img_files:
        base, _ = os.path.splitext(img_file)
        mask_file = os.path.join('masks', base + '_mask.pbm')
        img = cv2.imread(img_file)
        mask = cv2.imread(mask_file, 0)
        applied = bounding_rect_of_mask(img, ~mask)
        cv2.imwrite(os.path.join(output_dir, categ, img_file), applied)

    os.chdir('..')

os.chdir('..')

Add script to create mask applied dataset

Response:
<INSERT> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import os
import re

import cv2
from jsk_recognition_utils import bounding_rect_of_mask

parser = argparse.ArgumentParser()
parser.add_argument('container_path')
args = parser.parse_args()

container_path = args.container_path
output_dir = os.path.abspath(container_path + '_mask_applied')

if not os.path.exists(output_dir):
 <INSERT_END> <INSERT>   print('creating output directory: {}'.format(output_dir))
    os.mkdir(output_dir)

categs = os.listdir(container_path)

os.chdir(container_path)

for categ in categs:
    os.chdir(categ)

    print('processing category: {}'.format(categ))
    files = os.listdir('.')
    img_files = filter(lambda x: re.match('^N\d*?_\d*?.jpg', x), files)
    print('found {} images'.format(len(img_files)))

    categ_output_dir = os.path.join(output_dir, categ)
    if not os.path.exists(categ_output_dir):
        os.mkdir(categ_output_dir)

    for img_file in img_files:
        base, _ = os.path.splitext(img_file)
        mask_file = os.path.join('masks', base + '_mask.pbm')
        img = cv2.imread(img_file)
        mask = cv2.imread(mask_file, 0)
        applied = bounding_rect_of_mask(img, ~mask)
        cv2.imwrite(os.path.join(output_dir, categ, img_file), applied)

    os.chdir('..')

os.chdir('..')
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import os
import re

import cv2
from jsk_recognition_utils import bounding_rect_of_mask

parser = argparse.ArgumentParser()
parser.add_argument('container_path')
args = parser.parse_args()

container_path = args.container_path
output_dir = os.path.abspath(container_path + '_mask_applied')

if not os.path.exists(output_dir):
    print('creating output directory: {}'.format(output_dir))
    os.mkdir(output_dir)

categs = os.listdir(container_path)

os.chdir(container_path)

for categ in categs:
    os.chdir(categ)

    print('processing category: {}'.format(categ))
    files = os.listdir('.')
    img_files = filter(lambda x: re.match('^N\d*?_\d*?.jpg', x), files)
    print('found {} images'.format(len(img_files)))

    categ_output_dir = os.path.join(output_dir, categ)
    if not os.path.exists(categ_output_dir):
        os.mkdir(categ_output_dir)

    for img_file in img_files:
        base, _ = os.path.splitext(img_file)
        mask_file = os.path.join('masks', base + '_mask.pbm')
        img = cv2.imread(img_file)
        mask = cv2.imread(mask_file, 0)
        applied = bounding_rect_of_mask(img, ~mask)
        cv2.imwrite(os.path.join(output_dir, categ, img_file), applied)

    os.chdir('..')

os.chdir('..')

Prompt: Add script to create mask applied dataset


import os.path
import shutil

sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';

-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
        name            text PRIMARY KEY,
        time            integer,
        description     text
);
INSERT INTO version(name,time,description)
    SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';

-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
        name            text PRIMARY KEY,
        owner           text,
        description     text
);
INSERT INTO component(name,owner,description)
    SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""

def do_upgrade(env, ver, cursor):
    cursor.execute(sql)

    # Copy the new default wiki macros over to the environment
    from trac.siteconfig import __default_macros_dir__ as macros_dir
    for f in os.listdir(macros_dir):
        if not f.endswith('.py'):
            continue
        src = os.path.join(macros_dir, f)
        dst = os.path.join(env.path, 'wiki-macros', f)
        if not os.path.isfile(dst):
            shutil.copy2(src, dst)

Fix typo in upgrade script

Response:
<REPLACE_OLD> __default_macro_dir__ <REPLACE_NEW> __default_macros_dir__ <REPLACE_END> <REPLACE_OLD> macro_dir
 <REPLACE_NEW> macros_dir
 <REPLACE_END> <REPLACE_OLD> os.listdir(macro_dir):
 <REPLACE_NEW> os.listdir(macros_dir):
 <REPLACE_END> <REPLACE_OLD> os.path.join(macro_dir, <REPLACE_NEW> os.path.join(macros_dir, <REPLACE_END> <|endoftext|> import os.path
import shutil

sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';

-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
        name            text PRIMARY KEY,
        time            integer,
        description     text
);
INSERT INTO version(name,time,description)
    SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';

-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
        name            text PRIMARY KEY,
        owner           text,
        description     text
);
INSERT INTO component(name,owner,description)
    SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""

def do_upgrade(env, ver, cursor):
    cursor.execute(sql)

    # Copy the new default wiki macros over to the environment
    from trac.siteconfig import __default_macros_dir__ as macros_dir
    for f in os.listdir(macros_dir):
        if not f.endswith('.py'):
            continue
        src = os.path.join(macros_dir, f)
        dst = os.path.join(env.path, 'wiki-macros', f)
        if not os.path.isfile(dst):
            shutil.copy2(src, dst)

Prompt:
Fix typo in upgrade script

git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@1647 af82e41b-90c4-0310-8c96-b1721e28e2e2

import os.path
import shutil

sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';

-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
        name            text PRIMARY KEY,
        time            integer,
        description     text
);
INSERT INTO version(name,time,description)
    SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';

-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
        name            text PRIMARY KEY,
        owner           text,
        description     text
);
INSERT INTO component(name,owner,description)
    SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""

def do_upgrade(env, ver, cursor):
    cursor.execute(sql)

    # Copy the new default wiki macros over to the environment
    from trac.siteconfig import __default_macro_dir__ as macro_dir
    for f in os.listdir(macro_dir):
        if not f.endswith('.py'):
            continue
        src = os.path.join(macro_dir, f)
        dst = os.path.join(env.path, 'wiki-macros', f)
        if not os.path.isfile(dst):
            shutil.copy2(src, dst)


try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import toml

with open("README.rst") as readme_file:
    readme_string = readme_file.read()

setup(
    name="toml",
    version=toml.__version__,
    description="Python Library for Tom's Obvious, Minimal Language",
    author="Uiri Noyb",
    author_email="uiri@xqz.ca",
    url="https://github.com/uiri/toml",
    packages=['toml'],
    license="MIT",
    long_description=readme_string,
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6']
)

Add trove classifier for license

Response:
<REPLACE_OLD> license="License :: OSI Approved :: MIT License",
 <REPLACE_NEW> license="MIT",
 <REPLACE_END> <INSERT>        'License :: OSI Approved :: MIT License',
 <INSERT_END> <|endoftext|> try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import toml

with open("README.rst") as readme_file:
    readme_string = readme_file.read()

setup(
    name="toml",
    version=toml.__version__,
    description="Python Library for Tom's Obvious, Minimal Language",
    author="Uiri Noyb",
    author_email="uiri@xqz.ca",
    url="https://github.com/uiri/toml",
    packages=['toml'],
    license="MIT",
    long_description=readme_string,
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6']
)

Prompt:
Add trove classifier for license

The trove classifiers are listed on PyPI to help users know -- at a
glance -- what license the project uses. Helps users decide if the
library is appropriate for integration. A full list of available trove
classifiers can be found at:

https://pypi.org/pypi?%3Aaction=list_classifiers

The setuptools "license" argument is not intended to use trove
classifier notation. Simplify it to "MIT". Details can be found:

https://docs.python.org/3/distutils/setupscript.html#additional-meta-data

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import toml

with open("README.rst") as readme_file:
    readme_string = readme_file.read()

setup(
    name="toml",
    version=toml.__version__,
    description="Python Library for Tom's Obvious, Minimal Language",
    author="Uiri Noyb",
    author_email="uiri@xqz.ca",
    url="https://github.com/uiri/toml",
    packages=['toml'],
    license="License :: OSI Approved :: MIT License",
    long_description=readme_string,
    classifiers=[
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6']
)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from sqlalchemy import engine_from_config
import aybu.manager.models

def setup(env):
    settings = env['request'].registry.settings
    env['models'] = aybu.manager.models
    env['engine'] = engine_from_config(settings, 'sqlalchemy.')
    env['request'].set_db_engine = env['engine']
    aybu.manager.models.Base.metadata.bind = env['engine']
    aybu.manager.models.Environment.initialize(settings)
    env['session'] = env['request'].db_session

Response:
<REPLACE_OLD> aybu.core.models.Base.metadata.bind <REPLACE_NEW> aybu.manager.models.Base.metadata.bind <REPLACE_END> <INSERT>    aybu.manager.models.Environment.initialize(settings)
    env['session'] = env['request'].db_session

 <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from sqlalchemy import engine_from_config
import aybu.manager.models

def setup(env):
    settings = env['request'].registry.settings
    env['models'] = aybu.manager.models
    env['engine'] = engine_from_config(settings, 'sqlalchemy.')
    env['request'].set_db_engine = env['engine']
    aybu.manager.models.Base.metadata.bind = env['engine']
    aybu.manager.models.Environment.initialize(settings)
    env['session'] = env['request'].db_session

Prompt:
Initialize session and environment in shell

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from sqlalchemy import engine_from_config
import aybu.manager.models

def setup(env):
    settings = env['request'].registry.settings
    env['models'] = aybu.manager.models
    env['engine'] = engine_from_config(settings, 'sqlalchemy.')
    env['request'].set_db_engine = env['engine']
    aybu.core.models.Base.metadata.bind = env['engine']


import os, glob, string, shutil
from distutils.core import setup

# Packages

packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']

def main():

    setup (name = 'neuroimaging',
           version = '0.01a',
           description = 'This is a neuroimaging python package',
           author = 'Various, one of whom is Jonathan Taylor',
           author_email = 'jonathan.taylor@stanford.edu',
           ext_package = 'neuroimaging',
           packages=packages,
           package_dir = {'neuroimaging': 'lib'},
           url = 'http://neuroimaging.scipy.org',
           long_description =
           '''
           ''')

if __name__ == "__main__":
    main()

Test edit - to check svn email hook

Test edit - to check svn email hook

Response:
<DELETE> from distutils.core <DELETE_END> <DELETE> setup
import <DELETE_END> <REPLACE_OLD> shutil

# <REPLACE_NEW> shutil
from distutils.core import setup

# <REPLACE_END> <|endoftext|> import os, glob, string, shutil
from distutils.core import setup

# Packages

packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']

def main():

    setup (name = 'neuroimaging',
           version = '0.01a',
           description = 'This is a neuroimaging python package',
           author = 'Various, one of whom is Jonathan Taylor',
           author_email = 'jonathan.taylor@stanford.edu',
           ext_package = 'neuroimaging',
           packages=packages,
           package_dir = {'neuroimaging': 'lib'},
           url = 'http://neuroimaging.scipy.org',
           long_description =
           '''
           ''')

if __name__ == "__main__":
    main()

Prompt:
Test edit - to check svn email hook
from distutils.core import setup
import os, glob, string, shutil

# Packages

packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']

def main():

    setup (name = 'neuroimaging',
           version = '0.01a',
           description = 'This is a neuroimaging python package',
           author = 'Various, one of whom is Jonathan Taylor',
           author_email = 'jonathan.taylor@stanford.edu',
           ext_package = 'neuroimaging',
           packages=packages,
           package_dir = {'neuroimaging': 'lib'},
           url = 'http://neuroimaging.scipy.org',
           long_description =
           '''
           ''')

if __name__ == "__main__":
    main()


from setuptools import setup

name = 'turbasen'
VERSION = '2.5.0'

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    long_description='Documentation: https://turbasenpy.readthedocs.io/',
    author='Ali Kaafarani',
    author_email='ali.kaafarani@dnt.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests>=2.10.0,<3'],
    extras_require={
        'dev': ['sphinx', 'ipython', 'flake8'],
    }
)

Add sphinx to dev requirements

Add sphinx to dev requirements

Response:
<REPLACE_OLD> ['ipython', <REPLACE_NEW> ['sphinx', 'ipython', <REPLACE_END> <|endoftext|> from setuptools import setup

name = 'turbasen'
VERSION = '2.5.0'

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    long_description='Documentation: https://turbasenpy.readthedocs.io/',
    author='Ali Kaafarani',
    author_email='ali.kaafarani@dnt.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests>=2.10.0,<3'],
    extras_require={
        'dev': ['sphinx', 'ipython', 'flake8'],
    }
)

Prompt:
Add sphinx to dev requirements

from setuptools import setup

name = 'turbasen'
VERSION = '2.5.0'

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    long_description='Documentation: https://turbasenpy.readthedocs.io/',
    author='Ali Kaafarani',
    author_email='ali.kaafarani@dnt.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests>=2.10.0,<3'],
    extras_require={
        'dev': ['ipython', 'flake8'],
    }
)


#!/usr/bin/env python3

from setuptools import setup

setup(
    name='todoman',
    description='A simple CalDav-based todo manager.',
    author='Hugo Osvaldo Barrera',
    author_email='hugo@barrera.io',
    url='https://github.com/pimutils/todoman',
    license='MIT',
    packages=['todoman'],
    entry_points={
        'console_scripts': [
            'todo = todoman.cli:cli',
        ]
    },
    install_requires=[
        open('requirements.txt').readlines()
    ],
    long_description=open('README.rst').read(),
    use_scm_version={
        'version_scheme': 'post-release',
        'write_to': 'todoman/version.py',
    },
    setup_requires=['setuptools_scm != 1.12.0', 'pytest-runner'],
    tests_require=['pytest'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Console :: Curses',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Office/Business :: Scheduling',
        'Topic :: Utilities',
    ]
)

Response:
<INSERT> 'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        <INSERT_END> <|endoftext|> #!/usr/bin/env python3

from setuptools import setup

setup(
    name='todoman',
    description='A simple CalDav-based todo manager.',
    author='Hugo Osvaldo Barrera',
    author_email='hugo@barrera.io',
    url='https://github.com/pimutils/todoman',
    license='MIT',
    packages=['todoman'],
    entry_points={
        'console_scripts': [
            'todo = todoman.cli:cli',
        ]
    },
    install_requires=[
        open('requirements.txt').readlines()
    ],
    long_description=open('README.rst').read(),
    use_scm_version={
        'version_scheme': 'post-release',
        'write_to': 'todoman/version.py',
    },
    setup_requires=['setuptools_scm != 1.12.0', 'pytest-runner'],
    tests_require=['pytest'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Console :: Curses',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Office/Business :: Scheduling',
        'Topic :: Utilities',
    ]
)

Prompt:
Add classifiers for supported python versions

#!/usr/bin/env python3

from setuptools import setup

setup(
    name='todoman',
    description='A simple CalDav-based todo manager.',
    author='Hugo Osvaldo Barrera',
    author_email='hugo@barrera.io',
    url='https://github.com/pimutils/todoman',
    license='MIT',
    packages=['todoman'],
    entry_points={
        'console_scripts': [
            'todo = todoman.cli:cli',
        ]
    },
    install_requires=[
        open('requirements.txt').readlines()
    ],
    long_description=open('README.rst').read(),
    use_scm_version={
        'version_scheme': 'post-release',
        'write_to': 'todoman/version.py',
    },
    setup_requires=['setuptools_scm != 1.12.0', 'pytest-runner'],
    tests_require=['pytest'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Console :: Curses',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX',
        'Topic :: Office/Business :: Scheduling',
        'Topic :: Utilities',
    ]
)


from setuptools import setup, find_packages
import os

setup(
    name="cpgintegrate",
    version="0.2.17",
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.18.4',
        'pandas>=0.23.0',
        'xlrd',
        'sqlalchemy>=1.0',
        'beautifulsoup4',
        'lxml<5.0',
        'numpy',
        'scipy',
    ],
    extras_require={'dev': [
            'pytest>=3.2.2',
            'apache-airflow>=1.10.0',
        ],
        'win_auto': [
            'pywinauto',
            'patool',
        ],
                    },
    data_files=[
        (os.path.join(os.environ.get('AIRFLOW_HOME', 'airflow'), 'plugins'),
         ['cpgintegrate/airflow/cpg_airflow_plugin.py'])
    ],
)

Bump version, allow newer lxml

Bump version, allow newer lxml

Response:
<REPLACE_OLD> version="0.2.17-SNAPSHOT",
 <REPLACE_NEW> version="0.2.17",
 <REPLACE_END> <REPLACE_OLD> 'lxml<4.0',
 <REPLACE_NEW> 'lxml<5.0',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
import os

setup(
    name="cpgintegrate",
    version="0.2.17",
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.18.4',
        'pandas>=0.23.0',
        'xlrd',
        'sqlalchemy>=1.0',
        'beautifulsoup4',
        'lxml<5.0',
        'numpy',
        'scipy',
    ],
    extras_require={'dev': [
            'pytest>=3.2.2',
            'apache-airflow>=1.10.0',
        ],
        'win_auto': [
            'pywinauto',
            'patool',
        ],
                    },
    data_files=[
        (os.path.join(os.environ.get('AIRFLOW_HOME', 'airflow'), 'plugins'),
         ['cpgintegrate/airflow/cpg_airflow_plugin.py'])
    ],
)

Prompt:
Bump version, allow newer lxml

from setuptools import setup, find_packages
import os

setup(
    name="cpgintegrate",
    version="0.2.17-SNAPSHOT",
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'requests>=2.18.4',
        'pandas>=0.23.0',
        'xlrd',
        'sqlalchemy>=1.0',
        'beautifulsoup4',
        'lxml<4.0',
        'numpy',
        'scipy',
    ],
    extras_require={'dev': [
            'pytest>=3.2.2',
            'apache-airflow>=1.10.0',
        ],
        'win_auto': [
            'pywinauto',
            'patool',
        ],
                    },
    data_files=[
        (os.path.join(os.environ.get('AIRFLOW_HOME', 'airflow'), 'plugins'),
         ['cpgintegrate/airflow/cpg_airflow_plugin.py'])
    ],
)


from distutils.core import setup, Extension
import os

os.environ['CFLAGS'] = "-Qunused-arguments"
setup(name = "Indexer", version = "0.1", ext_modules = [Extension("rabin", ["src/rabin.c", ])])

Fix compile error on OS X 10.9

Fix compile error on OS X 10.9

Response:
<REPLACE_OLD> Extension

setup(name <REPLACE_NEW> Extension
import os

os.environ['CFLAGS'] = "-Qunused-arguments"
setup(name <REPLACE_END> <|endoftext|> from distutils.core import setup, Extension
import os

os.environ['CFLAGS'] = "-Qunused-arguments"
setup(name = "Indexer", version = "0.1", ext_modules = [Extension("rabin", ["src/rabin.c", ])])

Prompt:
Fix compile error on OS X 10.9

from distutils.core import setup, Extension

setup(name = "Indexer", version = "0.1", ext_modules = [Extension("rabin", ["src/rabin.c", ])])


from . import LayerView

def getMetaData():
    return {
        'type': 'view',
        'plugin': {
            "name": "Layer View"
        },
        'view': {
            'name': 'Layers'
        }
    }

def register(app):
    return LayerView.LayerView()

Response:
<REPLACE_OLD> { <REPLACE_NEW> {
        'type': 'view',
        'plugin': {
            <REPLACE_END> <REPLACE_OLD> "LayerView", "type": "View" <REPLACE_NEW> "Layer View"
        },
        'view': {
            'name': 'Layers'
        }
   <REPLACE_END> <|endoftext|> from . import LayerView

def getMetaData():
    return {
        'type': 'view',
        'plugin': {
            "name": "Layer View"
        },
        'view': {
            'name': 'Layers'
        }
    }

def register(app):
    return LayerView.LayerView()

Prompt:
Update plugin metadata to the new format

from . import LayerView

def getMetaData():
    return { "name": "LayerView", "type": "View"  }

def register(app):
    return LayerView.LayerView()


"""Simple blueprint."""
import os

from flask import Blueprint, current_app, make_response, render_template

blueprint = Blueprint('simple', __name__, url_prefix='/simple',
                   template_folder='templates')

@blueprint.route('', methods=['POST'])
def search_simple():
    """Handling pip search."""
    return make_response('Not implemented', 501)

@blueprint.route('', methods=['GET'])
def get_simple():
    """List all packages."""
    packages = os.listdir(current_app.config['BASEDIR'])
    return render_template('simple.html', packages=packages)

@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
    """List versions of a package."""
    package_path = os.path.join(current_app.config['BASEDIR'],
                                package.lower())
    if os.path.isdir(package_path):
        files = os.listdir(package_path)

        packages = []
        for filename in files:
            if filename.endswith('md5'):
                digest_file = os.path.join(package_path, filename)
                with open(digest_file, 'r') as md5_digest:
                    item = {
                        'name': package,
                        'version': filename.replace('.md5', ''),
                        'digest': md5_digest.read()
                    }
                    packages.append(item)
        return render_template('simple_package.html', packages=packages,
                               letter=package[:1].lower())
    else:
        return make_response('404', 404)

Response:
<INSERT> if os.path.isdir(package_path):
        <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     digest_file = os.path.join(package_path, filename)
                <INSERT_END> <REPLACE_OLD> open(os.path.join(package_path, filename), <REPLACE_NEW> open(digest_file, <REPLACE_END> <REPLACE_OLD> md5_digest:
 <REPLACE_NEW> md5_digest:
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>    else:
        return make_response('404', 404)
 <INSERT_END> <|endoftext|> """Simple blueprint."""
import os

from flask import Blueprint, current_app, make_response, render_template

blueprint = Blueprint('simple', __name__, url_prefix='/simple',
                   template_folder='templates')

@blueprint.route('', methods=['POST'])
def search_simple():
    """Handling pip search."""
    return make_response('Not implemented', 501)

@blueprint.route('', methods=['GET'])
def get_simple():
    """List all packages."""
    packages = os.listdir(current_app.config['BASEDIR'])
    return render_template('simple.html', packages=packages)

@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
    """List versions of a package."""
    package_path = os.path.join(current_app.config['BASEDIR'],
                                package.lower())
    if os.path.isdir(package_path):
        files = os.listdir(package_path)

        packages = []
        for filename in files:
            if filename.endswith('md5'):
                digest_file = os.path.join(package_path, filename)
                with open(digest_file, 'r') as md5_digest:
                    item = {
                        'name': package,
                        'version': filename.replace('.md5', ''),
                        'digest': md5_digest.read()
                    }
                    packages.append(item)
        return render_template('simple_package.html', packages=packages,
                               letter=package[:1].lower())
    else:
        return make_response('404', 404)

Prompt:
Return 404 if package was not found instead of raising an exception

"""Simple blueprint."""
import os

from flask import Blueprint, current_app, make_response, render_template

blueprint = Blueprint('simple', __name__, url_prefix='/simple',
                   template_folder='templates')

@blueprint.route('', methods=['POST'])
def search_simple():
    """Handling pip search."""
    return make_response('Not implemented', 501)

@blueprint.route('', methods=['GET'])
def get_simple():
    """List all packages."""
    packages = os.listdir(current_app.config['BASEDIR'])
    return render_template('simple.html', packages=packages)

@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
    """List versions of a package."""
    package_path = os.path.join(current_app.config['BASEDIR'],
                                package.lower())
    files = os.listdir(package_path)

    packages = []
    for filename in files:
        if filename.endswith('md5'):
            with open(os.path.join(package_path, filename), 'r') as md5_digest:
                item = {
                    'name': package,
                    'version': filename.replace('.md5', ''),
                    'digest': md5_digest.read()
                }
                packages.append(item)
    return render_template('simple_package.html', packages=packages,
                           letter=package[:1].lower())


import io
from setuptools import setup, find_packages

long_description = '\n'.join((
    io.open('README.rst', encoding='utf-8').read(),
    io.open('CHANGES.txt', encoding='utf-8').read()
))

tests_require = [
    'pytest >= 2.0',
    'pytest-cov',
    'WebTest >= 2.0.14',
    'mock',
    ]

setup(
    name='bowerstatic',
    version='0.10.dev0',
    description="A Bower-centric static file server for WSGI",
    long_description=long_description,
    author="Martijn Faassen",
    author_email="faassen@startifact.com",
    license="BSD",
    url='http://bowerstatic.readthedocs.org',
    keywords='wsgi bower',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'WebOb',
    ],
    tests_require=tests_require,
    extras_require=dict(
        test=tests_require,
    )
)

Response:
<REPLACE_OLD> from <REPLACE_NEW> import io
from <REPLACE_END> <REPLACE_OLD> (
 <REPLACE_NEW> '\n'.join((
 <REPLACE_END> <REPLACE_OLD> open('README.rst').read()
 <REPLACE_NEW> io.open('README.rst', encoding='utf-8').read(),
 <REPLACE_END> <REPLACE_OLD> + '\n' +
    open('CHANGES.txt').read())

tests_require <REPLACE_NEW> io.open('CHANGES.txt', encoding='utf-8').read()
))

tests_require <REPLACE_END> <|endoftext|> import io
from setuptools import setup, find_packages

long_description = '\n'.join((
    io.open('README.rst', encoding='utf-8').read(),
    io.open('CHANGES.txt', encoding='utf-8').read()
))

tests_require = [
    'pytest >= 2.0',
    'pytest-cov',
    'WebTest >= 2.0.14',
    'mock',
    ]

setup(
    name='bowerstatic',
    version='0.10.dev0',
    description="A Bower-centric static file server for WSGI",
    long_description=long_description,
    author="Martijn Faassen",
    author_email="faassen@startifact.com",
    license="BSD",
    url='http://bowerstatic.readthedocs.org',
    keywords='wsgi bower',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'WebOb',
    ],
    tests_require=tests_require,
    extras_require=dict(
        test=tests_require,
    )
)

Prompt:
Use io.open with encoding='utf-8' and flake8 compliance

from setuptools import setup, find_packages

long_description = (
    open('README.rst').read()
    + '\n' +
    open('CHANGES.txt').read())

tests_require = [
    'pytest >= 2.0',
    'pytest-cov',
    'WebTest >= 2.0.14',
    'mock',
    ]

setup(
    name='bowerstatic',
    version='0.10.dev0',
    description="A Bower-centric static file server for WSGI",
    long_description=long_description,
    author="Martijn Faassen",
    author_email="faassen@startifact.com",
    license="BSD",
    url='http://bowerstatic.readthedocs.org',
    keywords='wsgi bower',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'WebOb',
    ],
    tests_require=tests_require,
    extras_require=dict(
        test=tests_require,
    )
)


# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import

from ..interface import TableLoaderInterface

class TableLoaderManager(TableLoaderInterface):

    def __init__(self, loader):
        self.__loader = loader

    @property
    def loader(self):
        return self.__loader

    @property
    def format_name(self):
        return self.__loader.format_name

    @property
    def source_type(self):
        return self.__loader.source_type

    @property
    def table_name(self):
        return self.__loader.table_name

    @table_name.setter
    def table_name(self, value):
        self.__loader.table_name = value

    @property
    def encoding(self):
        try:
            return self.__loader.encoding
        except AttributeError:
            return None

    @encoding.setter
    def encoding(self, codec_name):
        self.__loader.encoding = codec_name

    def load(self):
        return self.__loader.load()

    def inc_table_count(self):
        self.__loader.inc_table_count()

Add an interface to change table_name

Add an interface to change table_name

Response:
<INSERT> table_name(self):
        return self.__loader.table_name

    @table_name.setter
    def table_name(self, value):
        self.__loader.table_name = value

    @property
    def <INSERT_END> <|endoftext|> # encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import

from ..interface import TableLoaderInterface

class TableLoaderManager(TableLoaderInterface):

    def __init__(self, loader):
        self.__loader = loader

    @property
    def loader(self):
        return self.__loader

    @property
    def format_name(self):
        return self.__loader.format_name

    @property
    def source_type(self):
        return self.__loader.source_type

    @property
    def table_name(self):
        return self.__loader.table_name

    @table_name.setter
    def table_name(self, value):
        self.__loader.table_name = value

    @property
    def encoding(self):
        try:
            return self.__loader.encoding
        except AttributeError:
            return None

    @encoding.setter
    def encoding(self, codec_name):
        self.__loader.encoding = codec_name

    def load(self):
        return self.__loader.load()

    def inc_table_count(self):
        self.__loader.inc_table_count()

Prompt:
Add an interface to change table_name

# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import

from ..interface import TableLoaderInterface

class TableLoaderManager(TableLoaderInterface):

    def __init__(self, loader):
        self.__loader = loader

    @property
    def loader(self):
        return self.__loader

    @property
    def format_name(self):
        return self.__loader.format_name

    @property
    def source_type(self):
        return self.__loader.source_type

    @property
    def encoding(self):
        try:
            return self.__loader.encoding
        except AttributeError:
            return None

    @encoding.setter
    def encoding(self, codec_name):
        self.__loader.encoding = codec_name

    def load(self):
        return self.__loader.load()

    def inc_table_count(self):
        self.__loader.inc_table_count()


"""A Trie (prefix tree) class for use in typeahead search.

Every node in the TypeaheadSearchTrie is another TypeaheadSearchTrie instance.
"""

from weakref import WeakSet

class TypeaheadSearchTrie(object):
    def __init__(self):
        # The children of this node. Because ordered traversals are not
        # important, these are stored in a dictionary.
        self.children = {}

        # Data entries associated with the word stored in the path to
        # this node. Stored in a WeakSet so that entries disappear
        # automatically when data entries are deleted.
        self.entries = WeakSet()

    def add(self, word, entry):
        """Adds the given data entry to the given Trie word.
        The word is created in the Trie if it doesn't already exist.
        """
        if word:
            self.children.setdefault(
                word[0],
                TypeaheadSearchTrie()
            ).add(word[1:], entry)

        else:
            self.entries.add(entry)

    def search(self, word):
        """Return a set of all data entries represented by prefix `word`.
        Returns an empty set if this prefix is not in the Trie.
        """
        if word:
            try:
                return self.children[word[0]].search(word[1:])
            except KeyError:
                return set()

        else:
            return self.gather_entries()

    def gather_entries(self):
        """Gather all data entries stored in this node and its children."""
        return set(self.entries).update(
            child.gather_entries() for child in self.children.itervalues()
        )

[typeahead_search] Add a Trie for storage of data string tokens.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """A Trie (prefix tree) class for use in typeahead search.

Every node in the TypeaheadSearchTrie is another TypeaheadSearchTrie instance.
"""

from weakref import WeakSet

class TypeaheadSearchTrie(object):
    def __init__(self):
        # The children of this node. Because ordered traversals are not
        # important, these are stored in a dictionary.
        self.children = {}

        # Data entries associated with the word stored in the path to
        # this node. Stored in a WeakSet so that entries disappear
        # automatically when data entries are deleted.
        self.entries = WeakSet()

    def add(self, word, entry):
        """Adds the given data entry to the given Trie word.
        The word is created in the Trie if it doesn't already exist.
        """
        if word:
            self.children.setdefault(
                word[0],
                TypeaheadSearchTrie()
            ).add(word[1:], entry)

        else:
            self.entries.add(entry)

    def search(self, word):
        """Return a set of all data entries represented by prefix `word`.
        Returns an empty set if this prefix is not in the Trie.
        """
        if word:
            try:
                return self.children[word[0]].search(word[1:])
            except KeyError:
                return set()

        else:
            return self.gather_entries()

    def gather_entries(self):
        """Gather all data entries stored in this node and its children."""
        return set(self.entries).update(
            child.gather_entries() for child in self.children.itervalues()
        )
 <REPLACE_END> <|endoftext|> """A Trie (prefix tree) class for use in typeahead search.

Every node in the TypeaheadSearchTrie is another TypeaheadSearchTrie instance.
"""

from weakref import WeakSet

class TypeaheadSearchTrie(object):
    def __init__(self):
        # The children of this node. Because ordered traversals are not
        # important, these are stored in a dictionary.
        self.children = {}

        # Data entries associated with the word stored in the path to
        # this node. Stored in a WeakSet so that entries disappear
        # automatically when data entries are deleted.
        self.entries = WeakSet()

    def add(self, word, entry):
        """Adds the given data entry to the given Trie word.
        The word is created in the Trie if it doesn't already exist.
        """
        if word:
            self.children.setdefault(
                word[0],
                TypeaheadSearchTrie()
            ).add(word[1:], entry)

        else:
            self.entries.add(entry)

    def search(self, word):
        """Return a set of all data entries represented by prefix `word`.
        Returns an empty set if this prefix is not in the Trie.
        """
        if word:
            try:
                return self.children[word[0]].search(word[1:])
            except KeyError:
                return set()

        else:
            return self.gather_entries()

    def gather_entries(self):
        """Gather all data entries stored in this node and its children."""
        return set(self.entries).update(
            child.gather_entries() for child in self.children.itervalues()
        )

Prompt: [typeahead_search] Add a Trie for storage of data string tokens.


try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='fabtools',
    version='0.1',
    description='Tools for writing awesome Fabric files',
    author='Ronan Amicel',
    author_email='ronan.amicel@gmail.com',
    url='http://github.com/ronnix/fabtools',
    install_requires=[
        "fabric>=1.2.0",
    ],
    setup_requires=[],
    tests_require=[
        "unittest2",
        "mock",
    ],
    packages=find_packages(exclude=['ez_setup', 'tests']),
    include_package_data=True,
    zip_safe=False,
    classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: BSD License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.5',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: Software Development',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'Topic :: System :: Software Distribution',
          'Topic :: System :: Systems Administration',
    ],
)

Exclude tests directory from install

Exclude tests directory from install

Response:
<REPLACE_OLD> packages=find_packages(exclude=['ez_setup']),
 <REPLACE_NEW> packages=find_packages(exclude=['ez_setup', 'tests']),
 <REPLACE_END> <|endoftext|> try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='fabtools',
    version='0.1',
    description='Tools for writing awesome Fabric files',
    author='Ronan Amicel',
    author_email='ronan.amicel@gmail.com',
    url='http://github.com/ronnix/fabtools',
    install_requires=[
        "fabric>=1.2.0",
    ],
    setup_requires=[],
    tests_require=[
        "unittest2",
        "mock",
    ],
    packages=find_packages(exclude=['ez_setup', 'tests']),
    include_package_data=True,
    zip_safe=False,
    classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: BSD License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.5',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: Software Development',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'Topic :: System :: Software Distribution',
          'Topic :: System :: Systems Administration',
    ],
)

Prompt:
Exclude tests directory from install

try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='fabtools',
    version='0.1',
    description='Tools for writing awesome Fabric files',
    author='Ronan Amicel',
    author_email='ronan.amicel@gmail.com',
    url='http://github.com/ronnix/fabtools',
    install_requires=[
        "fabric>=1.2.0",
    ],
    setup_requires=[],
    tests_require=[
        "unittest2",
        "mock",
    ],
    packages=find_packages(exclude=['ez_setup']),
    include_package_data=True,
    zip_safe=False,
    classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: BSD License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.5',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: Software Development',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'Topic :: System :: Software Distribution',
          'Topic :: System :: Systems Administration',
    ],
)


# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import unicode_literals

import itertools

import pytest
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode

nan = float("nan")
inf = float("inf")

class Test_Binary_is_type(object):
    @pytest.mark.parametrize(
        ["value", "strict_level", "expected"],
        list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False]))
        + list(
            itertools.product(
                ["abc".encode("utf_8"), "いろは".encode("utf_8")],
                [StrictLevel.MIN, StrictLevel.MAX],
                [True],
            )
        )
        + list(
            itertools.product(
                [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], [True]
            )
        )
        + list(
            itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False])
        ),
    )
    def test_normal(self, value, strict_level, expected):
        type_checker = Binary(value, strict_level=strict_level)

        assert type_checker.is_type() == expected
        assert type_checker.typecode == Typecode.STRING

Fix test cases for Python2

Fix test cases for Python2

Response:
<REPLACE_OLD> pytest
import six
from <REPLACE_NEW> pytest
from <REPLACE_END> <REPLACE_OLD> [six.b("abc"), "いろは".encode("utf_8")], <REPLACE_NEW> ["abc".encode("utf_8"), "いろは".encode("utf_8")],
                <REPLACE_END> <REPLACE_OLD> StrictLevel.MAX], <REPLACE_NEW> StrictLevel.MAX],
                [True],
            )
        )
        + list(
            itertools.product(
                [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], <REPLACE_END> <DELETE>        + list(itertools.product([six.b(""), six.b(" "), six.b("\n")], [StrictLevel.MIN], [True]))
 <DELETE_END> <|endoftext|> # encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import unicode_literals

import itertools

import pytest
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode

nan = float("nan")
inf = float("inf")

class Test_Binary_is_type(object):
    @pytest.mark.parametrize(
        ["value", "strict_level", "expected"],
        list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False]))
        + list(
            itertools.product(
                ["abc".encode("utf_8"), "いろは".encode("utf_8")],
                [StrictLevel.MIN, StrictLevel.MAX],
                [True],
            )
        )
        + list(
            itertools.product(
                [" ".encode("utf_8"), "\n".encode("utf_8")], [StrictLevel.MIN], [True]
            )
        )
        + list(
            itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False])
        ),
    )
    def test_normal(self, value, strict_level, expected):
        type_checker = Binary(value, strict_level=strict_level)

        assert type_checker.is_type() == expected
        assert type_checker.typecode == Typecode.STRING

Prompt:
Fix test cases for Python2

# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import unicode_literals

import itertools

import pytest
import six
from six import MAXSIZE
from typepy import Binary, StrictLevel, Typecode

nan = float("nan")
inf = float("inf")

class Test_Binary_is_type(object):
    @pytest.mark.parametrize(
        ["value", "strict_level", "expected"],
        list(itertools.product([], [StrictLevel.MIN, StrictLevel.MAX], [False]))
        + list(
            itertools.product(
                [six.b("abc"), "いろは".encode("utf_8")], [StrictLevel.MIN, StrictLevel.MAX], [True]
            )
        )
        + list(itertools.product([six.b(""), six.b(" "), six.b("\n")], [StrictLevel.MIN], [True]))
        + list(
            itertools.product(["", " ", "\n", MAXSIZE, inf, nan, None], [StrictLevel.MAX], [False])
        ),
    )
    def test_normal(self, value, strict_level, expected):
        type_checker = Binary(value, strict_level=strict_level)

        assert type_checker.is_type() == expected
        assert type_checker.typecode == Typecode.STRING


import subprocess, io, shlex, os
import pandas as pd

def read_pdf_table(input_path, options=""):
  JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
  jar_dir = os.path.abspath(os.path.dirname(__file__))
  jar_path = os.path.join(jar_dir, JAR_NAME)
  args = ["java", "-jar", jar_path] + shlex.split(options) + [input_path]

  result = subprocess.run(args, stdout=subprocess.PIPE)

  if len(result.stdout) == 0:
    return

  return pd.read_csv(io.BytesIO(result.stdout))

Response:
<DELETE> jar_path = os.path.abspath(os.path.dirname(__file__))
  <DELETE_END> <INSERT> jar_dir = os.path.abspath(os.path.dirname(__file__))
  jar_path = os.path.join(jar_dir, JAR_NAME)
  <INSERT_END> <REPLACE_OLD> "-jar"] + [jar_path + "/" + JAR_NAME] <REPLACE_NEW> "-jar", jar_path] <REPLACE_END> <|endoftext|> import subprocess, io, shlex, os
import pandas as pd

def read_pdf_table(input_path, options=""):
  JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
  jar_dir = os.path.abspath(os.path.dirname(__file__))
  jar_path = os.path.join(jar_dir, JAR_NAME)
  args = ["java", "-jar", jar_path] + shlex.split(options) + [input_path]

  result = subprocess.run(args, stdout=subprocess.PIPE)

  if len(result.stdout) == 0:
    return

  return pd.read_csv(io.BytesIO(result.stdout))

Prompt:
Use os.path.join for Jar path to make it OS independent

import subprocess, io, shlex, os
import pandas as pd

def read_pdf_table(input_path, options=""):
  jar_path = os.path.abspath(os.path.dirname(__file__))
  JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
  args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path]

  result = subprocess.run(args, stdout=subprocess.PIPE)

  if len(result.stdout) == 0:
    return

  return pd.read_csv(io.BytesIO(result.stdout))


# flake8: noqa

"""
A library for creating Latex files.

..  :copyright: (c) 2014 by Jelte Fennema.
    :license: MIT, see License for more details.
"""

from .document import Document
from .math import Math, VectorName, Matrix
from .package import Package
from .section import Section, Subsection, Subsubsection
from .table import Table, MultiColumn, MultiRow, Tabular, Tabu, LongTable, \
    LongTabu
from .pgfplots import TikZ, Axis, Plot
from .graphics import Figure, SubFigure, MatplotlibFigure
from .lists import Enumerate, Itemize, Description
from .quantities import Quantity
from .base_classes import Command

Response:
<REPLACE_OLD> Tabular
from <REPLACE_NEW> Tabular, Tabu, LongTable, \
    LongTabu
from <REPLACE_END> <|endoftext|> # flake8: noqa

"""
A library for creating Latex files.

..  :copyright: (c) 2014 by Jelte Fennema.
    :license: MIT, see License for more details.
"""

from .document import Document
from .math import Math, VectorName, Matrix
from .package import Package
from .section import Section, Subsection, Subsubsection
from .table import Table, MultiColumn, MultiRow, Tabular, Tabu, LongTable, \
    LongTabu
from .pgfplots import TikZ, Axis, Plot
from .graphics import Figure, SubFigure, MatplotlibFigure
from .lists import Enumerate, Itemize, Description
from .quantities import Quantity
from .base_classes import Command

Prompt:
Add Tabu, LongTable and LongTabu global import

# flake8: noqa

"""
A library for creating Latex files.

..  :copyright: (c) 2014 by Jelte Fennema.
    :license: MIT, see License for more details.
"""

from .document import Document
from .math import Math, VectorName, Matrix
from .package import Package
from .section import Section, Subsection, Subsubsection
from .table import Table, MultiColumn, MultiRow, Tabular
from .pgfplots import TikZ, Axis, Plot
from .graphics import Figure, SubFigure, MatplotlibFigure
from .lists import Enumerate, Itemize, Description
from .quantities import Quantity
from .base_classes import Command


import sys

from setuptools import find_packages, setup

with open('VERSION') as version_fp:
    VERSION = version_fp.read().strip()

install_requires = [
    'django-local-settings>=1.0a13',
    'stashward',
]

if sys.version_info[:2] < (3, 4):
    install_requires.append('enum34')

setup(
    name='django-arcutils',
    version=VERSION,
    url='https://github.com/PSU-OIT-ARC/django-arcutils',
    author='PSU - OIT - ARC',
    author_email='consultants@pdx.edu',
    description='Common utilities used in ARC Django projects',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=install_requires,
    extras_require={
        'ldap': [
            'certifi>=2015.11.20.1',
            'ldap3>=1.0.4',
        ],
        'dev': [
            'django>=1.7,<1.9',
            'djangorestframework>3.3',
            'flake8',
            'ldap3',
        ],
    },
    entry_points="""
    [console_scripts]
    arcutils = arcutils.__main__:main

    """,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Framework :: Django',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)

Update ldap3 1.0.3 => 1.0.4

Update ldap3 1.0.3 => 1.0.4

Response:
<REPLACE_OLD> 'ldap3>=1.0.3',
 <REPLACE_NEW> 'ldap3>=1.0.4',
 <REPLACE_END> <|endoftext|> import sys

from setuptools import find_packages, setup

with open('VERSION') as version_fp:
    VERSION = version_fp.read().strip()

install_requires = [
    'django-local-settings>=1.0a13',
    'stashward',
]

if sys.version_info[:2] < (3, 4):
    install_requires.append('enum34')

setup(
    name='django-arcutils',
    version=VERSION,
    url='https://github.com/PSU-OIT-ARC/django-arcutils',
    author='PSU - OIT - ARC',
    author_email='consultants@pdx.edu',
    description='Common utilities used in ARC Django projects',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=install_requires,
    extras_require={
        'ldap': [
            'certifi>=2015.11.20.1',
            'ldap3>=1.0.4',
        ],
        'dev': [
            'django>=1.7,<1.9',
            'djangorestframework>3.3',
            'flake8',
            'ldap3',
        ],
    },
    entry_points="""
    [console_scripts]
    arcutils = arcutils.__main__:main

    """,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Framework :: Django',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)

Prompt:
Update ldap3 1.0.3 => 1.0.4

import sys

from setuptools import find_packages, setup

with open('VERSION') as version_fp:
    VERSION = version_fp.read().strip()

install_requires = [
    'django-local-settings>=1.0a13',
    'stashward',
]

if sys.version_info[:2] < (3, 4):
    install_requires.append('enum34')

setup(
    name='django-arcutils',
    version=VERSION,
    url='https://github.com/PSU-OIT-ARC/django-arcutils',
    author='PSU - OIT - ARC',
    author_email='consultants@pdx.edu',
    description='Common utilities used in ARC Django projects',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=install_requires,
    extras_require={
        'ldap': [
            'certifi>=2015.11.20.1',
            'ldap3>=1.0.3',
        ],
        'dev': [
            'django>=1.7,<1.9',
            'djangorestframework>3.3',
            'flake8',
            'ldap3',
        ],
    },
    entry_points="""
    [console_scripts]
    arcutils = arcutils.__main__:main

    """,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Framework :: Django',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)


# -*- coding: utf-8 -*-
from django.db import models

class PositiveBigIntegerField(models.PositiveIntegerField):
    """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
    empty_strings_allowed = False

    def db_type(self, connection):
        if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
            # This is how MySQL defines 64 bit unsigned integer data types
            return "BIGINT UNSIGNED"
        return super(PositiveBigIntegerField, self).db_type(connection)

try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
    pass

Response:
<DELETE>    def get_internal_type(self):
        return "PositiveBigIntegerField"

 <DELETE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.db import models

class PositiveBigIntegerField(models.PositiveIntegerField):
    """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
    empty_strings_allowed = False

    def db_type(self, connection):
        if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
            # This is how MySQL defines 64 bit unsigned integer data types
            return "BIGINT UNSIGNED"
        return super(PositiveBigIntegerField, self).db_type(connection)

try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
    pass

Prompt:
Fix tests by removing obsolete internal field type declaration

# -*- coding: utf-8 -*-
from django.db import models

class PositiveBigIntegerField(models.PositiveIntegerField):
    """Represents MySQL's unsigned BIGINT data type (works with MySQL only!)"""
    empty_strings_allowed = False

    def get_internal_type(self):
        return "PositiveBigIntegerField"

    def db_type(self, connection):
        if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
            # This is how MySQL defines 64 bit unsigned integer data types
            return "BIGINT UNSIGNED"
        return super(PositiveBigIntegerField, self).db_type(connection)

try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ['bawebauth\.fields\.PositiveBigIntegerField'])
except ImportError:
    pass


"""
Benchmark of message serialization.

The goal here is to mostly focus on performance of serialization, in a vaguely
realistic manner. That is, mesages are logged in context of a message with a
small number of fields.
"""

from __future__ import unicode_literals

import time

from eliot import Message, start_action, to_file

# Ensure JSON serialization is part of benchmark:
to_file(open("/dev/null", "w"))

N = 10000

def run():
    start = time.time()
    for i in range(N):
        with start_action(action_type="my_action"):
            with start_action(action_type="my_action2"):
                Message.log(
                    message_type="my_message",
                    integer=3, string=b"abcdeft", string2="dgsjdlkgjdsl",
                    list=[1, 2, 3, 4])
    end = time.time()

    # Each iteration has 5 messages: start/end of my_action, start/end of
    # my_action2, and my_message.
    print("%.6f per message" % ((end - start) / (N * 5),))
    print("%s messages/sec" % (int(N / (end-start)),))

if __name__ == '__main__':
    run()

Response:
<REPLACE_OLD> benchmark:
to_file(open("/dev/null"))

N <REPLACE_NEW> benchmark:
to_file(open("/dev/null", "w"))

N <REPLACE_END> <|endoftext|> """
Benchmark of message serialization.

The goal here is to mostly focus on performance of serialization, in a vaguely
realistic manner. That is, mesages are logged in context of a message with a
small number of fields.
"""

from __future__ import unicode_literals

import time

from eliot import Message, start_action, to_file

# Ensure JSON serialization is part of benchmark:
to_file(open("/dev/null", "w"))

N = 10000

def run():
    start = time.time()
    for i in range(N):
        with start_action(action_type="my_action"):
            with start_action(action_type="my_action2"):
                Message.log(
                    message_type="my_message",
                    integer=3, string=b"abcdeft", string2="dgsjdlkgjdsl",
                    list=[1, 2, 3, 4])
    end = time.time()

    # Each iteration has 5 messages: start/end of my_action, start/end of
    # my_action2, and my_message.
    print("%.6f per message" % ((end - start) / (N * 5),))
    print("%s messages/sec" % (int(N / (end-start)),))

if __name__ == '__main__':
    run()

Prompt:
Fix the benchmark so it's not throwing exceptions every time a message is written
"""
Benchmark of message serialization.

The goal here is to mostly focus on performance of serialization, in a vaguely
realistic manner. That is, mesages are logged in context of a message with a
small number of fields.
"""

from __future__ import unicode_literals

import time

from eliot import Message, start_action, to_file

# Ensure JSON serialization is part of benchmark:
to_file(open("/dev/null"))

N = 10000

def run():
    start = time.time()
    for i in range(N):
        with start_action(action_type="my_action"):
            with start_action(action_type="my_action2"):
                Message.log(
                    message_type="my_message",
                    integer=3, string=b"abcdeft", string2="dgsjdlkgjdsl",
                    list=[1, 2, 3, 4])
    end = time.time()

    # Each iteration has 5 messages: start/end of my_action, start/end of
    # my_action2, and my_message.
    print("%.6f per message" % ((end - start) / (N * 5),))
    print("%s messages/sec" % (int(N / (end-start)),))

if __name__ == '__main__':
    run()


import platform
import string
import glob
import os
import stat

def getPossibleSDcardDrives():
	drives = []
	if platform.system() == "Windows":
		from ctypes import windll
		import ctypes
		bitmask = windll.kernel32.GetLogicalDrives()
		for letter in string.uppercase:
			if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2:
				volumeName = ''
				nameBuffer = ctypes.create_unicode_buffer(1024)
				if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0:
					volumeName = nameBuffer.value
				if volumeName == '':
					volumeName = 'NO NAME'

				drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName))
			bitmask >>= 1
	elif platform.system() == "Darwin":
		for volume in glob.glob('/Volumes/*'):
			if stat.S_ISLNK(os.lstat(volume).st_mode):
				continue
			#'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume))
			drives.append((os.path.basename(volume), os.path.basename(volume), volume))
	else:
		for volume in glob.glob('/media/*'):
			drives.append((os.path.basename(volume), os.path.basename(volume), volume))
	return drives

Response:
<REPLACE_OLD> windll
		bitmask <REPLACE_NEW> windll
		import ctypes
		bitmask <REPLACE_END> <REPLACE_OLD> 2:
				drives.append(letter <REPLACE_NEW> 2:
				volumeName = ''
				nameBuffer = ctypes.create_unicode_buffer(1024)
				if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter <REPLACE_END> <REPLACE_OLD> ':/')
			bitmask <REPLACE_NEW> ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0:
					volumeName = nameBuffer.value
				if volumeName == '':
					volumeName = 'NO NAME'

				drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName))
			bitmask <REPLACE_END> <REPLACE_OLD> (volume))
			drives.append(volume)
	else:
		for <REPLACE_NEW> (volume))
			drives.append((os.path.basename(volume), os.path.basename(volume), volume))
	else:
		for <REPLACE_END> <REPLACE_OLD> glob.glob('/media/*'):
			drives.append(volume)
	return <REPLACE_NEW> glob.glob('/media/*'):
			drives.append((os.path.basename(volume), os.path.basename(volume), volume))
	return <REPLACE_END> <|endoftext|> import platform
import string
import glob
import os
import stat

def getPossibleSDcardDrives():
	drives = []
	if platform.system() == "Windows":
		from ctypes import windll
		import ctypes
		bitmask = windll.kernel32.GetLogicalDrives()
		for letter in string.uppercase:
			if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2:
				volumeName = ''
				nameBuffer = ctypes.create_unicode_buffer(1024)
				if windll.kernel32.GetVolumeInformationW(ctypes.c_wchar_p(letter + ':/'), nameBuffer, ctypes.sizeof(nameBuffer), None, None, None, None, 0) == 0:
					volumeName = nameBuffer.value
				if volumeName == '':
					volumeName = 'NO NAME'

				drives.append(('%s (%s:)' % (volumeName, letter), letter + ':/', volumeName))
			bitmask >>= 1
	elif platform.system() == "Darwin":
		for volume in glob.glob('/Volumes/*'):
			if stat.S_ISLNK(os.lstat(volume).st_mode):
				continue
			#'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume))
			drives.append((os.path.basename(volume), os.path.basename(volume), volume))
	else:
		for volume in glob.glob('/media/*'):
			drives.append((os.path.basename(volume), os.path.basename(volume), volume))
	return drives

Prompt:
Enhance the SD card list with more info.

import platform
import string
import glob
import os
import stat

def getPossibleSDcardDrives():
	drives = []
	if platform.system() == "Windows":
		from ctypes import windll
		bitmask = windll.kernel32.GetLogicalDrives()
		for letter in string.uppercase:
			if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/') == 2:
				drives.append(letter + ':/')
			bitmask >>= 1
	elif platform.system() == "Darwin":
		for volume in glob.glob('/Volumes/*'):
			if stat.S_ISLNK(os.lstat(volume).st_mode):
				continue
			#'Ejectable: Yes' in os.system('diskutil info \'%s\'' % (volume))
			drives.append(volume)
	else:
		for volume in glob.glob('/media/*'):
			drives.append(volume)
	return drives


# Generated by Django 2.0.13 on 2020-04-06 13:40

from django.conf import settings
from django.contrib.gis.geos import Point, LineString
from django.db import migrations

def remove_generated_paths_factories(apps, schema_editor):
    PathModel = apps.get_model('core', 'Path')
    PathModel.objects.filter(geom=LineString(Point(700000, 6600000), Point(700100, 6600100), srid=settings.SRID)).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0016_auto_20200406_1340'),
    ]

    operations = [
        migrations.RunPython(remove_generated_paths_factories)
    ]

Add migration remove generated paths

Add migration remove generated paths

Response:
<INSERT> # Generated by Django 2.0.13 on 2020-04-06 13:40

from django.conf import settings
from django.contrib.gis.geos import Point, LineString
from django.db import migrations

def remove_generated_paths_factories(apps, schema_editor):
 <INSERT_END> <INSERT>   PathModel = apps.get_model('core', 'Path')
    PathModel.objects.filter(geom=LineString(Point(700000, 6600000), Point(700100, 6600100), srid=settings.SRID)).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0016_auto_20200406_1340'),
    ]

    operations = [
        migrations.RunPython(remove_generated_paths_factories)
    ]
 <INSERT_END> <|endoftext|> # Generated by Django 2.0.13 on 2020-04-06 13:40

from django.conf import settings
from django.contrib.gis.geos import Point, LineString
from django.db import migrations

def remove_generated_paths_factories(apps, schema_editor):
    PathModel = apps.get_model('core', 'Path')
    PathModel.objects.filter(geom=LineString(Point(700000, 6600000), Point(700100, 6600100), srid=settings.SRID)).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0016_auto_20200406_1340'),
    ]

    operations = [
        migrations.RunPython(remove_generated_paths_factories)
    ]

Prompt: Add migration remove generated paths


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

"""Dumps a list of known slaves, along with their OS and master."""

import argparse
import collections
import json
import logging
import os
import subprocess
import sys

# This file is located inside tests. Update this path if that changes.
BUILD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPTS = os.path.join(BUILD, 'scripts')
LIST_SLAVES = os.path.join(SCRIPTS, 'tools', 'list_slaves.py')

sys.path.append(SCRIPTS)

from common import chromium_utils

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
    '-g',
    '--gen',
    '--generate',
    action='store_true',
    dest='generate',
    help='Generate slaves.expected for all masters.',
  )
  args = parser.parse_args()

  masters = chromium_utils.ListMastersWithSlaves()
  master_map = {}

  for master_path in masters:
    # Convert ~/<somewhere>/master.<whatever> to just whatever.
    master = os.path.basename(master_path).split('.', 1)[-1]
    botmap = json.loads(subprocess.check_output([
        LIST_SLAVES, '--json', '--master', master]))

    slave_map = collections.defaultdict(set)

    for entry in botmap:
      assert entry['mastername'] == 'master.%s' % master

      for builder in entry['builder']:
        slave_map[builder].add(entry['hostname'])

    master_map[master_path] = {}

    for buildername in sorted(slave_map.keys()):
      master_map[master_path][buildername] = sorted(slave_map[buildername])

  retcode = 0

  for master_path, slaves_expectation in master_map.iteritems():
    if os.path.exists(master_path):
      slaves_expectation_file = os.path.join(master_path, 'slaves.expected')

      if args.generate:
        with open(slaves_expectation_file, 'w') as fp:
          json.dump(slaves_expectation, fp, indent=2, sort_keys=True)
        print 'Wrote expectation: %s.' % slaves_expectation_file
      else:
        if os.path.exists(slaves_expectation_file):
          with open(slaves_expectation_file) as fp:
            if json.load(fp) != slaves_expectation:
              logging.error(
                  'Mismatched expectation: %s.', slaves_expectation_file)
              retcode = 1
        else:
          logging.error('File not found: %s.', slaves_expectation_file)
          retcode = 1

  return retcode

if __name__ == '__main__':
  sys.exit(main())

Add script for generating slave expectations

BUG=489880
R=friedman@chromium.org

Review URL: https://codereview.chromium.org/1178383002.

git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@295683 0039d316-1c4b-4281-b951-d872f2087c98

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Dumps a list of known slaves, along with their OS and master."""

import argparse
import collections
import json
import logging
import os
import subprocess
import sys

# This file is located inside tests. Update this path if that changes.
BUILD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPTS = os.path.join(BUILD, 'scripts')
LIST_SLAVES = os.path.join(SCRIPTS, 'tools', 'list_slaves.py')

sys.path.append(SCRIPTS)

from common import chromium_utils

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
    '-g',
    '--gen',
    '--generate',
    action='store_true',
    dest='generate',
    help='Generate slaves.expected for all masters.',
  )
  args = parser.parse_args()

  masters = chromium_utils.ListMastersWithSlaves()
  master_map = {}

  for master_path in masters:
    # Convert ~/<somewhere>/master.<whatever> to just whatever.
    master = os.path.basename(master_path).split('.', 1)[-1]
    botmap = json.loads(subprocess.check_output([
        LIST_SLAVES, '--json', '--master', master]))

    slave_map = collections.defaultdict(set)

    for entry in botmap:
      assert entry['mastername'] == 'master.%s' % master

      for builder in entry['builder']:
        slave_map[builder].add(entry['hostname'])

    master_map[master_path] = {}

    for buildername in sorted(slave_map.keys()):
      master_map[master_path][buildername] = sorted(slave_map[buildername])

  retcode = 0

  for master_path, slaves_expectation in master_map.iteritems():
    if os.path.exists(master_path):
      slaves_expectation_file = os.path.join(master_path, 'slaves.expected')

      if args.generate:
        with open(slaves_expectation_file, 'w') as fp:
          json.dump(slaves_expectation, fp, indent=2, sort_keys=True)
        print 'Wrote expectation: %s.' % slaves_expectation_file
      else:
        if os.path.exists(slaves_expectation_file):
          with open(slaves_expectation_file) as fp:
            if json.load(fp) != slaves_expectation:
              logging.error(
                  'Mismatched expectation: %s.', slaves_expectation_file)
              retcode = 1
        else:
          logging.error('File not found: %s.', slaves_expectation_file)
          retcode = 1

  return retcode

if __name__ == '__main__':
  sys.exit(main())
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Dumps a list of known slaves, along with their OS and master."""

import argparse
import collections
import json
import logging
import os
import subprocess
import sys

# This file is located inside tests. Update this path if that changes.
BUILD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPTS = os.path.join(BUILD, 'scripts')
LIST_SLAVES = os.path.join(SCRIPTS, 'tools', 'list_slaves.py')

sys.path.append(SCRIPTS)

from common import chromium_utils

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
    '-g',
    '--gen',
    '--generate',
    action='store_true',
    dest='generate',
    help='Generate slaves.expected for all masters.',
  )
  args = parser.parse_args()

  masters = chromium_utils.ListMastersWithSlaves()
  master_map = {}

  for master_path in masters:
    # Convert ~/<somewhere>/master.<whatever> to just whatever.
    master = os.path.basename(master_path).split('.', 1)[-1]
    botmap = json.loads(subprocess.check_output([
        LIST_SLAVES, '--json', '--master', master]))

    slave_map = collections.defaultdict(set)

    for entry in botmap:
      assert entry['mastername'] == 'master.%s' % master

      for builder in entry['builder']:
        slave_map[builder].add(entry['hostname'])

    master_map[master_path] = {}

    for buildername in sorted(slave_map.keys()):
      master_map[master_path][buildername] = sorted(slave_map[buildername])

  retcode = 0

  for master_path, slaves_expectation in master_map.iteritems():
    if os.path.exists(master_path):
      slaves_expectation_file = os.path.join(master_path, 'slaves.expected')

      if args.generate:
        with open(slaves_expectation_file, 'w') as fp:
          json.dump(slaves_expectation, fp, indent=2, sort_keys=True)
        print 'Wrote expectation: %s.' % slaves_expectation_file
      else:
        if os.path.exists(slaves_expectation_file):
          with open(slaves_expectation_file) as fp:
            if json.load(fp) != slaves_expectation:
              logging.error(
                  'Mismatched expectation: %s.', slaves_expectation_file)
              retcode = 1
        else:
          logging.error('File not found: %s.', slaves_expectation_file)
          retcode = 1

  return retcode

if __name__ == '__main__':
  sys.exit(main())

Prompt:
Add script for generating slave expectations

BUG=489880
R=friedman@chromium.org

Review URL: https://codereview.chromium.org/1178383002.

git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@295683 0039d316-1c4b-4281-b951-d872f2087c98


from nap import models, fields, api, serialiser, publisher

from .models import Choice, Poll

class ChoiceSerialiser(models.ModelSerialiser):

    class Meta:
        model = Choice
        exclude = ('poll,')

class PollSerialiser(serialiser.Serialiser):
    api_name = 'poll'

    question = fields.Field()
    published = fields.DateTimeField('pub_date')
    choices = fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())

class PollPublisher(publisher.Publisher):
    serialiser = PollSerialiser()
    api_name = 'polls'

    def get_object_list(self):
        return Poll.objects.all()

api.register('api', PollPublisher)

Response:
<REPLACE_OLD> fields.ManySerialiserField(serialiser=ChoiceSerialiser())

class <REPLACE_NEW> fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())

class <REPLACE_END> <|endoftext|>
from nap import models, fields, api, serialiser, publisher

from .models import Choice, Poll

class ChoiceSerialiser(models.ModelSerialiser):

    class Meta:
        model = Choice
        exclude = ('poll,')

class PollSerialiser(serialiser.Serialiser):
    api_name = 'poll'

    question = fields.Field()
    published = fields.DateTimeField('pub_date')
    choices = fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())

class PollPublisher(publisher.Publisher):
    serialiser = PollSerialiser()
    api_name = 'polls'

    def get_object_list(self):
        return Poll.objects.all()

api.register('api', PollPublisher)

Prompt:
Add attribute to choices field declaration

from nap import models, fields, api, serialiser, publisher

from .models import Choice, Poll

class ChoiceSerialiser(models.ModelSerialiser):

    class Meta:
        model = Choice
        exclude = ('poll,')

class PollSerialiser(serialiser.Serialiser):
    api_name = 'poll'

    question = fields.Field()
    published = fields.DateTimeField('pub_date')
    choices = fields.ManySerialiserField(serialiser=ChoiceSerialiser())

class PollPublisher(publisher.Publisher):
    serialiser = PollSerialiser()
    api_name = 'polls'

    def get_object_list(self):
        return Poll.objects.all()

api.register('api', PollPublisher)


major = 0
minor=0
patch=26
branch="master"
timestamp=1376610243.26

Response:
<REPLACE_OLD> 0
minor=0
patch=25
branch="master"
timestamp=1376610207.69 <REPLACE_NEW> 0
minor=0
patch=26
branch="master"
timestamp=1376610243.26 <REPLACE_END> <|endoftext|> major = 0
minor=0
patch=26
branch="master"
timestamp=1376610243.26

Prompt:
Tag commit for v0.0.26-master generated by gitmake.py

major = 0
minor=0
patch=25
branch="master"
timestamp=1376610207.69


"""Tests for coverage.data"""

from coverage.data import CoverageData
from coveragetest import CoverageTest

class DataTest(CoverageTest):
    def test_reading(self):
        covdata = CoverageData()
        covdata.read()
        self.assertEqual(covdata.summary(), {})

Response:
<REPLACE_OLD> coverage.data"""

import unittest
from <REPLACE_NEW> coverage.data"""

from <REPLACE_END> <REPLACE_OLD> CoverageData

class DataTest(unittest.TestCase):
 <REPLACE_NEW> CoverageData
from coveragetest import CoverageTest

class DataTest(CoverageTest):
 <REPLACE_END> <|endoftext|> """Tests for coverage.data"""

from coverage.data import CoverageData
from coveragetest import CoverageTest

class DataTest(CoverageTest):
    def test_reading(self):
        covdata = CoverageData()
        covdata.read()
        self.assertEqual(covdata.summary(), {})

Prompt:
Use our CoverageTest base class to get isolation (in a new directory) for the data tests.

"""Tests for coverage.data"""

import unittest
from coverage.data import CoverageData

class DataTest(unittest.TestCase):
    def test_reading(self):
        covdata = CoverageData()
        covdata.read()
        self.assertEqual(covdata.summary(), {})


import os
import sys

from optparse import OptionParser

from conda_verify.errors import RecipeError
from conda_verify.verify import Verify
from conda_verify.utilities import render_metadata, iter_cfgs

def cli():
    p = OptionParser(
        usage="usage: %prog [options] <path to recipes or packages>",
        description="tool for (passively) verifying conda recipes and conda "
                    "packages for the Anaconda distribution")

    p.add_option('-v', '--version',
                 help="display the version being used and exit",
                 action="store_true")

    opts, args = p.parse_args()

    if opts.version:
        from conda_verify import __version__
        sys.exit('conda-verify {}' .format(__version__))

    verifier = Verify()
    for path in args:
        meta_file = os.path.join(path, 'meta.yaml')
        if os.path.isfile(meta_file):
            print('Verifying {}...' .format(meta_file))
            for cfg in iter_cfgs():
                meta = render_metadata(path, cfg)
                try:
                    verifier.verify_recipe(rendered_meta=meta, recipe_dir=path)
                except RecipeError as e:
                    sys.stderr.write("RecipeError: %s\n" % e)

        elif path.endswith(('.tar.bz2', '.tar')):
            print('Verifying {}...' .format(path))
            verifier.verify_package(path_to_package=path)

Change script run message output

Change script run message output

Response:
<INSERT> meta_file = os.path.join(path, 'meta.yaml')
        <INSERT_END> <REPLACE_OLD> os.path.isfile(os.path.join(path, 'meta.yaml')):
            print("==> %s <==" % path)
 <REPLACE_NEW> os.path.isfile(meta_file):
            print('Verifying {}...' .format(meta_file))
 <REPLACE_END> <|endoftext|> import os
import sys

from optparse import OptionParser

from conda_verify.errors import RecipeError
from conda_verify.verify import Verify
from conda_verify.utilities import render_metadata, iter_cfgs

def cli():
    p = OptionParser(
        usage="usage: %prog [options] <path to recipes or packages>",
        description="tool for (passively) verifying conda recipes and conda "
                    "packages for the Anaconda distribution")

    p.add_option('-v', '--version',
                 help="display the version being used and exit",
                 action="store_true")

    opts, args = p.parse_args()

    if opts.version:
        from conda_verify import __version__
        sys.exit('conda-verify {}' .format(__version__))

    verifier = Verify()
    for path in args:
        meta_file = os.path.join(path, 'meta.yaml')
        if os.path.isfile(meta_file):
            print('Verifying {}...' .format(meta_file))
            for cfg in iter_cfgs():
                meta = render_metadata(path, cfg)
                try:
                    verifier.verify_recipe(rendered_meta=meta, recipe_dir=path)
                except RecipeError as e:
                    sys.stderr.write("RecipeError: %s\n" % e)

        elif path.endswith(('.tar.bz2', '.tar')):
            print('Verifying {}...' .format(path))
            verifier.verify_package(path_to_package=path)

Prompt:
Change script run message output

import os
import sys

from optparse import OptionParser

from conda_verify.errors import RecipeError
from conda_verify.verify import Verify
from conda_verify.utilities import render_metadata, iter_cfgs

def cli():
    p = OptionParser(
        usage="usage: %prog [options] <path to recipes or packages>",
        description="tool for (passively) verifying conda recipes and conda "
                    "packages for the Anaconda distribution")

    p.add_option('-v', '--version',
                 help="display the version being used and exit",
                 action="store_true")

    opts, args = p.parse_args()

    if opts.version:
        from conda_verify import __version__
        sys.exit('conda-verify {}' .format(__version__))

    verifier = Verify()
    for path in args:
        if os.path.isfile(os.path.join(path, 'meta.yaml')):
            print("==> %s <==" % path)
            for cfg in iter_cfgs():
                meta = render_metadata(path, cfg)
                try:
                    verifier.verify_recipe(rendered_meta=meta, recipe_dir=path)
                except RecipeError as e:
                    sys.stderr.write("RecipeError: %s\n" % e)

        elif path.endswith(('.tar.bz2', '.tar')):
            print('Verifying {}...' .format(path))
            verifier.verify_package(path_to_package=path)


import os
import sys
from setuptools import setup, find_packages, Command

class Doctest(Command):
    if sys.argv[-1] == 'test':
        print("Running docs make and make doctest")
        os.system("make doctest -C docs/")

class Pep8Test(Command):
    if sys.argv[-1] == 'test':
        print("Running pep8 under source code folder")
        os.system("python3 setup.py pep8 --exclude '.eggs*'")

setup(name='Kytos OpenFlow Parser library',
      version='0.1',
      description='Library to parse and generate OpenFlow messages',
      url='http://github.com/kytos/python-openflow',
      author='Kytos Team',
      author_email='of-ng-dev@ncc.unesp.br',
      license='MIT',
      test_suite='tests',
      packages=find_packages(exclude=["tests", "*v0x02*"]),
      setup_requires=['setuptools-pep8'],
      cmdclass={
        'doctests': Doctest
      },
      zip_safe=False)

Response:
<REPLACE_OLD> Command

SEP='<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>'

class <REPLACE_NEW> Command

class <REPLACE_END> <DELETE>        print(SEP)
 <DELETE_END> <REPLACE_OLD> docs/")
        print(SEP)

class <REPLACE_NEW> docs/")

class <REPLACE_END> <REPLACE_OLD> os.system("python <REPLACE_NEW> os.system("python3 <REPLACE_END> <REPLACE_OLD> '.eggs*'")
        print(SEP)

setup(name='Kytos <REPLACE_NEW> '.eggs*'")

setup(name='Kytos <REPLACE_END> <|endoftext|> import os
import sys
from setuptools import setup, find_packages, Command

class Doctest(Command):
    if sys.argv[-1] == 'test':
        print("Running docs make and make doctest")
        os.system("make doctest -C docs/")

class Pep8Test(Command):
    if sys.argv[-1] == 'test':
        print("Running pep8 under source code folder")
        os.system("python3 setup.py pep8 --exclude '.eggs*'")

setup(name='Kytos OpenFlow Parser library',
      version='0.1',
      description='Library to parse and generate OpenFlow messages',
      url='http://github.com/kytos/python-openflow',
      author='Kytos Team',
      author_email='of-ng-dev@ncc.unesp.br',
      license='MIT',
      test_suite='tests',
      packages=find_packages(exclude=["tests", "*v0x02*"]),
      setup_requires=['setuptools-pep8'],
      cmdclass={
        'doctests': Doctest
      },
      zip_safe=False)

Prompt:
Enforce python3 on pep8 test (and remove print markers)

import os
import sys
from setuptools import setup, find_packages, Command

SEP='<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>'

class Doctest(Command):
    if sys.argv[-1] == 'test':
        print(SEP)
        print("Running docs make and make doctest")
        os.system("make doctest -C docs/")
        print(SEP)

class Pep8Test(Command):
    if sys.argv[-1] == 'test':
        print("Running pep8 under source code folder")
        os.system("python setup.py pep8 --exclude '.eggs*'")
        print(SEP)

setup(name='Kytos OpenFlow Parser library',
      version='0.1',
      description='Library to parse and generate OpenFlow messages',
      url='http://github.com/kytos/python-openflow',
      author='Kytos Team',
      author_email='of-ng-dev@ncc.unesp.br',
      license='MIT',
      test_suite='tests',
      packages=find_packages(exclude=["tests", "*v0x02*"]),
      setup_requires=['setuptools-pep8'],
      cmdclass={
        'doctests': Doctest
      },
      zip_safe=False)


# -*- coding: utf-8 -*-
"""
    tests.deprecations
    ~~~~~~~~~~~~~~~~~~

    Tests deprecation support. Not used currently.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

import pytest

import flask

class TestRequestDeprecation(object):

    def test_request_json(self, catch_deprecation_warnings):
        """Request.json is deprecated"""
        app = flask.Flask(__name__)
        app.testing = True

        @app.route('/', methods=['POST'])
        def index():
            assert flask.request.json == {'spam': 42}
            print(flask.request.json)
            return 'OK'

        with catch_deprecation_warnings() as captured:
            c = app.test_client()
            c.post('/', data='{"spam": 42}', content_type='application/json')

        assert len(captured) == 1

    def test_request_module(self, catch_deprecation_warnings):
        """Request.module is deprecated"""
        app = flask.Flask(__name__)
        app.testing = True

        @app.route('/')
        def index():
            assert flask.request.module is None
            return 'OK'

        with catch_deprecation_warnings() as captured:
            c = app.test_client()
            c.get('/')

        assert len(captured) == 1

Response:
<REPLACE_OLD> details.
"""
 <REPLACE_NEW> details.
"""

import pytest

import flask

class TestRequestDeprecation(object):

    def test_request_json(self, catch_deprecation_warnings):
        """Request.json is deprecated"""
        app = flask.Flask(__name__)
        app.testing = True

        @app.route('/', methods=['POST'])
        def index():
            assert flask.request.json == {'spam': 42}
            print(flask.request.json)
            return 'OK'

        with catch_deprecation_warnings() as captured:
            c = app.test_client()
            c.post('/', data='{"spam": 42}', content_type='application/json')

        assert len(captured) == 1

    def test_request_module(self, catch_deprecation_warnings):
        """Request.module is deprecated"""
        app = flask.Flask(__name__)
        app.testing = True

        @app.route('/')
        def index():
            assert flask.request.module is None
            return 'OK'

        with catch_deprecation_warnings() as captured:
            c = app.test_client()
            c.get('/')

        assert len(captured) == 1
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
    tests.deprecations
    ~~~~~~~~~~~~~~~~~~

    Tests deprecation support. Not used currently.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

import pytest

import flask

class TestRequestDeprecation(object):

    def test_request_json(self, catch_deprecation_warnings):
        """Request.json is deprecated"""
        app = flask.Flask(__name__)
        app.testing = True

        @app.route('/', methods=['POST'])
        def index():
            assert flask.request.json == {'spam': 42}
            print(flask.request.json)
            return 'OK'

        with catch_deprecation_warnings() as captured:
            c = app.test_client()
            c.post('/', data='{"spam": 42}', content_type='application/json')

        assert len(captured) == 1

    def test_request_module(self, catch_deprecation_warnings):
        """Request.module is deprecated"""
        app = flask.Flask(__name__)
        app.testing = True

        @app.route('/')
        def index():
            assert flask.request.module is None
            return 'OK'

        with catch_deprecation_warnings() as captured:
            c = app.test_client()
            c.get('/')

        assert len(captured) == 1

Prompt:
Add test for deprecated flask.Request properties.

# -*- coding: utf-8 -*-
"""
    tests.deprecations
    ~~~~~~~~~~~~~~~~~~

    Tests deprecation support. Not used currently.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""