from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet

class DataSetInline(admin.StackedInline):
    model = DataSet
    fields = ('name',)
    extra = 0

class BackdropUserAdmin(reversion.VersionAdmin):
    search_fields = ['email', 'data_sets']
    list_display = ('email', 'numer_of_datasets_user_has_access_to',)
    list_per_page = 30
    filter_horizontal = ('data_sets',)

    def queryset(self, request):
        return BackdropUser.objects.annotate(
            dataset_count=models.Count('data_sets')
        )

    def numer_of_datasets_user_has_access_to(self, obj):
        return obj.dataset_count

    numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'

admin.site.register(BackdropUser, BackdropUserAdmin)

Response:
<REPLACE_OLD> 30

 <REPLACE_NEW> 30
    filter_horizontal = ('data_sets',)

 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet

class DataSetInline(admin.StackedInline):
    model = DataSet
    fields = ('name',)
    extra = 0

class BackdropUserAdmin(reversion.VersionAdmin):
    search_fields = ['email', 'data_sets']
    list_display = ('email', 'numer_of_datasets_user_has_access_to',)
    list_per_page = 30
    filter_horizontal = ('data_sets',)

    def queryset(self, request):
        return BackdropUser.objects.annotate(
            dataset_count=models.Count('data_sets')
        )

    def numer_of_datasets_user_has_access_to(self, obj):
        return obj.dataset_count

    numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'

admin.site.register(BackdropUser, BackdropUserAdmin)

Prompt:
Add filter_horizontal to backdrop user admin

- Provides a much more usable interface to filter and add data_sets for backdrop admin users

from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet

class DataSetInline(admin.StackedInline):
    model = DataSet
    fields = ('name',)
    extra = 0

class BackdropUserAdmin(reversion.VersionAdmin):
    search_fields = ['email', 'data_sets']
    list_display = ('email', 'numer_of_datasets_user_has_access_to',)
    list_per_page = 30

    def queryset(self, request):
        return BackdropUser.objects.annotate(
            dataset_count=models.Count('data_sets')
        )

    def numer_of_datasets_user_has_access_to(self, obj):
        return obj.dataset_count

    numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'

admin.site.register(BackdropUser, BackdropUserAdmin)


from django.shortcuts import render, get_object_or_404

from config.utils import get_active_event

from .models import Talk

def list_talks(request):
    event = get_active_event()
    talks = event.talks.prefetch_related(
        'applicants',
        'applicants__user',
        'skill_level',
        'sponsor',
    ).order_by('-keynote', 'title')

    return render(request, 'talks/list_talks.html', {
        "talks": talks,
    })

def view_talk(request, slug):
    event = get_active_event()
    talk = get_object_or_404(Talk, slug=slug, event=event)

    return render(request, 'talks/view_talk.html', {
        'talk': talk})

Response:
<DELETE> # Temporary hack to let only admins & committee members see the talks
    user = request.user
    permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member())
    if not permitted:
        talks = event.talks.none()

    <DELETE_END> <|endoftext|> from django.shortcuts import render, get_object_or_404

from config.utils import get_active_event

from .models import Talk

def list_talks(request):
    event = get_active_event()
    talks = event.talks.prefetch_related(
        'applicants',
        'applicants__user',
        'skill_level',
        'sponsor',
    ).order_by('-keynote', 'title')

    return render(request, 'talks/list_talks.html', {
        "talks": talks,
    })

def view_talk(request, slug):
    event = get_active_event()
    talk = get_object_or_404(Talk, slug=slug, event=event)

    return render(request, 'talks/view_talk.html', {
        'talk': talk})

Prompt:
Revert "Temporarily make talks visible only to committee"

This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.

from django.shortcuts import render, get_object_or_404

from config.utils import get_active_event

from .models import Talk

def list_talks(request):
    event = get_active_event()
    talks = event.talks.prefetch_related(
        'applicants',
        'applicants__user',
        'skill_level',
        'sponsor',
    ).order_by('-keynote', 'title')

    # Temporary hack to let only admins & committee members see the talks
    user = request.user
    permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member())
    if not permitted:
        talks = event.talks.none()

    return render(request, 'talks/list_talks.html', {
        "talks": talks,
    })

def view_talk(request, slug):
    event = get_active_event()
    talk = get_object_or_404(Talk, slug=slug, event=event)

    return render(request, 'talks/view_talk.html', {
        'talk': talk})


import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO

testfname = "nixrawio-1.5.nix"

class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
    rawioclass = NIXRawIO
    entities_to_test = [testfname]
    files_to_download = [testfname]

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

Change filename for NIXRawIO tests

Response:
<REPLACE_OLD> "neoraw.nix"

class <REPLACE_NEW> "nixrawio-1.5.nix"

class <REPLACE_END> <REPLACE_OLD> unittest.TestCase, ):
 <REPLACE_NEW> unittest.TestCase):
 <REPLACE_END> <|endoftext|> import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO

testfname = "nixrawio-1.5.nix"

class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
    rawioclass = NIXRawIO
    entities_to_test = [testfname]
    files_to_download = [testfname]

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

Prompt:
[nixio] Change filename for NIXRawIO tests

import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO

testfname = "neoraw.nix"

class TestNixRawIO(BaseTestRawIO, unittest.TestCase, ):
    rawioclass = NIXRawIO
    entities_to_test = [testfname]
    files_to_download = [testfname]

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


from models import User
from forms import LoginForm

def load_user(user_id):
    """Returns a user from the database based on their id"""
    return User.query.filter_by(id=user_id).first()

def login(request):
    """Handle a login request from a user."""
    form = LoginForm.from_json(request.form)
    if request.method == 'POST' and form.validate():
        return True

Response:
<DELETE> app_factory.create_app import db
from <DELETE_END> <DELETE> RegistrationForm, <DELETE_END> <INSERT>    """Returns a user from the database based on their id"""
 <INSERT_END> <INSERT>    """Handle a login request from a user."""
 <INSERT_END> <|endoftext|> from models import User
from forms import LoginForm

def load_user(user_id):
    """Returns a user from the database based on their id"""
    return User.query.filter_by(id=user_id).first()

def login(request):
    """Handle a login request from a user."""
    form = LoginForm.from_json(request.form)
    if request.method == 'POST' and form.validate():
        return True

Prompt:
Clean up unused imports and add docstrings

from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm

def load_user(user_id):
    return User.query.filter_by(id=user_id).first()

def login(request):
    form = LoginForm.from_json(request.form)
    if request.method == 'POST' and form.validate():
        return True


# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import api, tools, SUPERUSER_ID

def post_init_hook(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    coa_generic_tmpl = env.ref(
        'l10n_br_coa_generic.l10n_br_coa_generic_template')
    if env['ir.module.module'].search_count([
        ('name', '=', 'l10n_br_account'),
        ('state', '=', 'installed'),
    ]):
        from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes
        # Relate fiscal taxes to account taxes.
        load_fiscal_taxes(env, coa_generic_tmpl)

    # Load COA to Demo Company
    if not tools.config.get('without_demo'):
        user_admin = env.ref('base.user_admin')
        user_admin.company_id = env.ref(
            'l10n_br_base.empresa_lucro_presumido')
        coa_generic_tmpl.sudo(
            user=user_admin.id).try_loading_for_current_company()
        user_admin.company_id = env.ref('base.main_company')

Use admin user to create COA

Response:
<REPLACE_OLD> env.user.company_id <REPLACE_NEW> user_admin = env.ref('base.user_admin')
        user_admin.company_id <REPLACE_END> <REPLACE_OLD> 'l10n_br_fiscal.empresa_lucro_presumido')
 <REPLACE_NEW> 'l10n_br_base.empresa_lucro_presumido')
 <REPLACE_END> <REPLACE_OLD> coa_generic_tmpl.try_loading_for_current_company()
 <REPLACE_NEW> coa_generic_tmpl.sudo(
            user=user_admin.id).try_loading_for_current_company()
        user_admin.company_id = env.ref('base.main_company')
 <REPLACE_END> <|endoftext|> # Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import api, tools, SUPERUSER_ID

def post_init_hook(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    coa_generic_tmpl = env.ref(
        'l10n_br_coa_generic.l10n_br_coa_generic_template')
    if env['ir.module.module'].search_count([
        ('name', '=', 'l10n_br_account'),
        ('state', '=', 'installed'),
    ]):
        from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes
        # Relate fiscal taxes to account taxes.
        load_fiscal_taxes(env, coa_generic_tmpl)

    # Load COA to Demo Company
    if not tools.config.get('without_demo'):
        user_admin = env.ref('base.user_admin')
        user_admin.company_id = env.ref(
            'l10n_br_base.empresa_lucro_presumido')
        coa_generic_tmpl.sudo(
            user=user_admin.id).try_loading_for_current_company()
        user_admin.company_id = env.ref('base.main_company')

Prompt:
[FIX] l10n_br_coa_generic: Use admin user to create COA

# Copyright (C) 2020 - Gabriel Cardoso de Faria <gabriel.cardoso@kmee.com.br>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import api, tools, SUPERUSER_ID

def post_init_hook(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    coa_generic_tmpl = env.ref(
        'l10n_br_coa_generic.l10n_br_coa_generic_template')
    if env['ir.module.module'].search_count([
        ('name', '=', 'l10n_br_account'),
        ('state', '=', 'installed'),
    ]):
        from odoo.addons.l10n_br_account.hooks import load_fiscal_taxes
        # Relate fiscal taxes to account taxes.
        load_fiscal_taxes(env, coa_generic_tmpl)

    # Load COA to Demo Company
    if not tools.config.get('without_demo'):
        env.user.company_id = env.ref(
            'l10n_br_fiscal.empresa_lucro_presumido')
        coa_generic_tmpl.try_loading_for_current_company()


"""
Downgrade to pip < 20.2 when running on PyPy.

Unfortunately pip 20.2 (the most recent release at the time of writing) breaks
compatibility with PyPy, thereby causing Travis CI builds of py2deb to fail as
well. For details please refer to https://github.com/pypa/pip/issues/8653.
"""

import pip
import platform
import subprocess

from distutils.version import LooseVersion

if platform.python_implementation() == 'PyPy':
    installed_release = LooseVersion(pip.__version__)
    known_bad_release = LooseVersion('20.2')
    if installed_release >= known_bad_release:
        # Given that pip is broken, we can't use it to downgrade itself!
        # Fortunately setuptools provides easy_install which works fine.
        subprocess.check_call(['easy_install', 'pip < 20.2'])

Response:
<REPLACE_OLD> PyPy because <REPLACE_NEW> PyPy.

Unfortunately <REPLACE_END> <REPLACE_OLD> recent
release <REPLACE_NEW> recent release <REPLACE_END> <REPLACE_OLD> breaks compatibility <REPLACE_NEW> breaks
compatibility <REPLACE_END> <REPLACE_OLD> causing
Travis <REPLACE_NEW> causing Travis <REPLACE_END> <REPLACE_OLD> as well. <REPLACE_NEW> as
well. <REPLACE_END> <DELETE> more <DELETE_END> <REPLACE_OLD> to
https://github.com/pypa/pip/issues/8653.
"""

import <REPLACE_NEW> to https://github.com/pypa/pip/issues/8653.
"""

import <REPLACE_END> <|endoftext|> """
Downgrade to pip < 20.2 when running on PyPy.

Unfortunately pip 20.2 (the most recent release at the time of writing) breaks
compatibility with PyPy, thereby causing Travis CI builds of py2deb to fail as
well. For details please refer to https://github.com/pypa/pip/issues/8653.
"""

import pip
import platform
import subprocess

from distutils.version import LooseVersion

if platform.python_implementation() == 'PyPy':
    installed_release = LooseVersion(pip.__version__)
    known_bad_release = LooseVersion('20.2')
    if installed_release >= known_bad_release:
        # Given that pip is broken, we can't use it to downgrade itself!
        # Fortunately setuptools provides easy_install which works fine.
        subprocess.check_call(['easy_install', 'pip < 20.2'])

Prompt:
Fix flake8 "violations" in new PyPy compensation script

"""
Downgrade to pip < 20.2 when running on PyPy because pip 20.2 (the most recent
release at the time of writing) breaks compatibility with PyPy, thereby causing
Travis CI builds of py2deb to fail as well. For more details please refer to
https://github.com/pypa/pip/issues/8653.
"""

import pip
import platform
import subprocess

from distutils.version import LooseVersion

if platform.python_implementation() == 'PyPy':
    installed_release = LooseVersion(pip.__version__)
    known_bad_release = LooseVersion('20.2')
    if installed_release >= known_bad_release:
        # Given that pip is broken, we can't use it to downgrade itself!
        # Fortunately setuptools provides easy_install which works fine.
        subprocess.check_call(['easy_install', 'pip < 20.2'])


from distutils.core import setup
setup(name = "bitey",
            description="Bitcode Import Tool",
            long_description = """
Bitey allows LLVM bitcode to be directly imported into Python as
an high performance extension module without the need for writing wrappers.
""",
            license="""BSD""",
            version = "0.0",
            author = "David Beazley",
            author_email = "dave@dabeaz.com",
            maintainer = "David Beazley",
            maintainer_email = "dave@dabeaz.com",
            url = "https://github.com/dabeaz/bitey/",
            packages = ['bitey'],
            classifiers = [
              'Programming Language :: Python :: 2',
              'Programming Language :: Python :: 3',
              ]
            )

Add trove classifier for Python 3

Add trove classifier for Python 3

Response:
<INSERT> 'Programming Language :: Python :: 3',
              <INSERT_END> <|endoftext|> from distutils.core import setup
setup(name = "bitey",
            description="Bitcode Import Tool",
            long_description = """
Bitey allows LLVM bitcode to be directly imported into Python as
an high performance extension module without the need for writing wrappers.
""",
            license="""BSD""",
            version = "0.0",
            author = "David Beazley",
            author_email = "dave@dabeaz.com",
            maintainer = "David Beazley",
            maintainer_email = "dave@dabeaz.com",
            url = "https://github.com/dabeaz/bitey/",
            packages = ['bitey'],
            classifiers = [
              'Programming Language :: Python :: 2',
              'Programming Language :: Python :: 3',
              ]
            )

Prompt:
Add trove classifier for Python 3

from distutils.core import setup
setup(name = "bitey",
            description="Bitcode Import Tool",
            long_description = """
Bitey allows LLVM bitcode to be directly imported into Python as
an high performance extension module without the need for writing wrappers.
""",
            license="""BSD""",
            version = "0.0",
            author = "David Beazley",
            author_email = "dave@dabeaz.com",
            maintainer = "David Beazley",
            maintainer_email = "dave@dabeaz.com",
            url = "https://github.com/dabeaz/bitey/",
            packages = ['bitey'],
            classifiers = [
              'Programming Language :: Python :: 2',
              ]
            )


import requests
import os
from .endpoints import *

class UnauthorizedToken(Exception):
    pass

class ReviewsAPI:

    def __init__(self):
        token = os.environ.get('UDACITY_AUTH_TOKEN')
        self.headers = {'Authorization': token, 'Content-Length': '0'}

    def certifications(self):
        try:
            raw_response = requests.get(CERTIFICATIONS_URL, headers=self.headers)
            response = raw_response.json()

            raw_response.raise_for_status()

            certifications_list = [item['project_id'] for item in response if item['status'] == 'certified']
            return certifications_list
        except requests.exceptions.HTTPError:
            raise UnauthorizedToken('Maybe it\'s time to change you token!')

    def request_reviews(self, certifications_list):
        projects = self.__projects(certifications_list)
        return requests.post(SUBMISSION_REQUESTS, json=projects, headers=self.headers)

    # TODO Add support to multi language
    def __projects(self, certifications_list):
        projects_list = []
        for certification in certifications_list:
            projects_list.append({'project_id': certification, 'language': 'pt-br'})
        return {'projects': projects_list}

Response:
<INSERT>
            raw_response.raise_for_status()

 <INSERT_END> <REPLACE_OLD> UnauthorizedToken

 <REPLACE_NEW> UnauthorizedToken('Maybe it\'s time to change you token!')

 <REPLACE_END> <|endoftext|> import requests
import os
from .endpoints import *

class UnauthorizedToken(Exception):
    pass

class ReviewsAPI:

    def __init__(self):
        token = os.environ.get('UDACITY_AUTH_TOKEN')
        self.headers = {'Authorization': token, 'Content-Length': '0'}

    def certifications(self):
        try:
            raw_response = requests.get(CERTIFICATIONS_URL, headers=self.headers)
            response = raw_response.json()

            raw_response.raise_for_status()

            certifications_list = [item['project_id'] for item in response if item['status'] == 'certified']
            return certifications_list
        except requests.exceptions.HTTPError:
            raise UnauthorizedToken('Maybe it\'s time to change you token!')

    def request_reviews(self, certifications_list):
        projects = self.__projects(certifications_list)
        return requests.post(SUBMISSION_REQUESTS, json=projects, headers=self.headers)

    # TODO Add support to multi language
    def __projects(self, certifications_list):
        projects_list = []
        for certification in certifications_list:
            projects_list.append({'project_id': certification, 'language': 'pt-br'})
        return {'projects': projects_list}

Prompt:
Raise exception if connection not succeed and customize error message

import requests
import os
from .endpoints import *

class UnauthorizedToken(Exception):
    pass

class ReviewsAPI:

    def __init__(self):
        token = os.environ.get('UDACITY_AUTH_TOKEN')
        self.headers = {'Authorization': token, 'Content-Length': '0'}

    def certifications(self):
        try:
            raw_response = requests.get(CERTIFICATIONS_URL, headers=self.headers)
            response = raw_response.json()
            certifications_list = [item['project_id'] for item in response if item['status'] == 'certified']
            return certifications_list
        except requests.exceptions.HTTPError:
            raise UnauthorizedToken

    def request_reviews(self, certifications_list):
        projects = self.__projects(certifications_list)
        return requests.post(SUBMISSION_REQUESTS, json=projects, headers=self.headers)

    # TODO Add support to multi language
    def __projects(self, certifications_list):
        projects_list = []
        for certification in certifications_list:
            projects_list.append({'project_id': certification, 'language': 'pt-br'})
        return {'projects': projects_list}


"""
Definition of the plugin.
"""
from django.apps import apps
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool

default_blog_model = 'blog_tools.BlogPost'
icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model)
BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1))

if icekit_blog_model != default_blog_model:
    @plugin_pool.register
    class BlogPostPlugin(ContentPlugin):
        model = apps.get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.BlogPostItem'))
        category = _('Blog')
        render_template = 'icekit/plugins/post/default.html'
        raw_id_fields = ['post', ]

Response:
<DELETE> django.db.models.loading import get_model
from <DELETE_END> <REPLACE_OLD> get_model(getattr(settings, <REPLACE_NEW> apps.get_model(getattr(settings, <REPLACE_END> <REPLACE_OLD> 'blog_post.PostItem'))
 <REPLACE_NEW> 'blog_post.BlogPostItem'))
 <REPLACE_END> <|endoftext|> """
Definition of the plugin.
"""
from django.apps import apps
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool

default_blog_model = 'blog_tools.BlogPost'
icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model)
BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1))

if icekit_blog_model != default_blog_model:
    @plugin_pool.register
    class BlogPostPlugin(ContentPlugin):
        model = apps.get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.BlogPostItem'))
        category = _('Blog')
        render_template = 'icekit/plugins/post/default.html'
        raw_id_fields = ['post', ]

Prompt:
Update Blog model and content item matching

"""
Definition of the plugin.
"""
from django.apps import apps
from django.conf import settings
from django.db.models.loading import get_model
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool

default_blog_model = 'blog_tools.BlogPost'
icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL', default_blog_model)
BLOG_MODEL = apps.get_model(*icekit_blog_model.rsplit('.', 1))

if icekit_blog_model != default_blog_model:
    @plugin_pool.register
    class BlogPostPlugin(ContentPlugin):
        model = get_model(getattr(settings, 'ICEKIT_BLOG_CONTENT_ITEM', 'blog_post.PostItem'))
        category = _('Blog')
        render_template = 'icekit/plugins/post/default.html'
        raw_id_fields = ['post', ]


"""Development automation."""

import nox

def _install_this_editable(session, *, extras=None):
    if extras is None:
        extras = []

    session.install("flit")
    session.run(
        "flit",
        "install",
        "-s",
        "--deps=production",
        "--extras",
        ",".join(extras),
        silent=True,
    )

@nox.session
def lint(session):
    session.install("pre-commit")
    session.run("pre-commit", "run", "--all-files", *session.posargs)

@nox.session(python=["3.6", "3.7", "3.8"])
def test(session):
    _install_this_editable(session, extras=["test"])

    default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"]
    args = session.posargs or default_args

    session.run("pytest", *args)

@nox.session
def docs(session):
    _install_this_editable(session, extras=["docs"])
    session.run("sphinx-build", "-b", "html", "docs/", "build/docs")

@nox.session(name="docs-live")
def docs_live(session):
    _install_this_editable(session, extras=["docs"])
    session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")

Add docs-live to perform demo-runs

Add docs-live to perform demo-runs

Response:
<INSERT> "build/docs")

@nox.session(name="docs-live")
def docs_live(session):
    _install_this_editable(session, extras=["docs"])
    session.run("sphinx-autobuild", "-b", "html", "docs/", <INSERT_END> <|endoftext|> """Development automation."""

import nox

def _install_this_editable(session, *, extras=None):
    if extras is None:
        extras = []

    session.install("flit")
    session.run(
        "flit",
        "install",
        "-s",
        "--deps=production",
        "--extras",
        ",".join(extras),
        silent=True,
    )

@nox.session
def lint(session):
    session.install("pre-commit")
    session.run("pre-commit", "run", "--all-files", *session.posargs)

@nox.session(python=["3.6", "3.7", "3.8"])
def test(session):
    _install_this_editable(session, extras=["test"])

    default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"]
    args = session.posargs or default_args

    session.run("pytest", *args)

@nox.session
def docs(session):
    _install_this_editable(session, extras=["docs"])
    session.run("sphinx-build", "-b", "html", "docs/", "build/docs")

@nox.session(name="docs-live")
def docs_live(session):
    _install_this_editable(session, extras=["docs"])
    session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")

Prompt:
Add docs-live to perform demo-runs

"""Development automation."""

import nox

def _install_this_editable(session, *, extras=None):
    if extras is None:
        extras = []

    session.install("flit")
    session.run(
        "flit",
        "install",
        "-s",
        "--deps=production",
        "--extras",
        ",".join(extras),
        silent=True,
    )

@nox.session
def lint(session):
    session.install("pre-commit")
    session.run("pre-commit", "run", "--all-files", *session.posargs)

@nox.session(python=["3.6", "3.7", "3.8"])
def test(session):
    _install_this_editable(session, extras=["test"])

    default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"]
    args = session.posargs or default_args

    session.run("pytest", *args)

@nox.session
def docs(session):
    _install_this_editable(session, extras=["docs"])
    session.run("sphinx-build", "-b", "html", "docs/", "build/docs")


from __future__ import print_function

import difflib
import pprint

import sys

def p(*args):
    """A helper for printing to stderr"""
    print(file=sys.stderr, *args)

def equal_arg(arg1, arg2):
    """Return True if the args are equal, False otherwise

    If the arguments aren't equal under ==, return True, otherwise
    return False and try to output to stderr a diff of the
    pretty-printed objects."""

    if arg1 == arg2:
        return True

    # This is more or less taken from assertDictEqual in
    # django/utils/unittest/case.py:
    args1_lines = pprint.pformat(arg1).splitlines()
    args2_lines = pprint.pformat(arg2).splitlines()
    diff = difflib.ndiff(args1_lines, args2_lines)

    p("Found the following differences: ====================================")
    for line in diff:
        p(line)
    p("=====================================================================")

    return False

def equal_call_args(args1, args2):
    """Return True if two sequences of arguments are equal

    Otherwise return False and output a diff of the first non-equal
    arguments to stderr."""
    if len(args1) != len(args2):
        message = "The argument lists were different lengths: {0} and {1}"
        p(message.format(len(args1), len(args2)))

    for i, arg1 in enumerate(args1):
        if not equal_arg(arg1, args2[i]):
            return False

    return True

Add equal_call_args for helpful diffs of args

This is particularly useful because mock's assert_called_with produces
really unhelpful output if the the expectation doesn't match.

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import print_function

import difflib
import pprint

import sys

def p(*args):
    """A helper for printing to stderr"""
    print(file=sys.stderr, *args)

def equal_arg(arg1, arg2):
    """Return True if the args are equal, False otherwise

    If the arguments aren't equal under ==, return True, otherwise
    return False and try to output to stderr a diff of the
    pretty-printed objects."""

    if arg1 == arg2:
        return True

    # This is more or less taken from assertDictEqual in
    # django/utils/unittest/case.py:
    args1_lines = pprint.pformat(arg1).splitlines()
    args2_lines = pprint.pformat(arg2).splitlines()
    diff = difflib.ndiff(args1_lines, args2_lines)

    p("Found the following differences: ====================================")
    for line in diff:
        p(line)
    p("=====================================================================")

    return False

def equal_call_args(args1, args2):
    """Return True if two sequences of arguments are equal

    Otherwise return False and output a diff of the first non-equal
    arguments to stderr."""
    if len(args1) != len(args2):
        message = "The argument lists were different lengths: {0} and {1}"
        p(message.format(len(args1), len(args2)))

    for i, arg1 in enumerate(args1):
        if not equal_arg(arg1, args2[i]):
            return False

    return True
 <REPLACE_END> <|endoftext|> from __future__ import print_function

import difflib
import pprint

import sys

def p(*args):
    """A helper for printing to stderr"""
    print(file=sys.stderr, *args)

def equal_arg(arg1, arg2):
    """Return True if the args are equal, False otherwise

    If the arguments aren't equal under ==, return True, otherwise
    return False and try to output to stderr a diff of the
    pretty-printed objects."""

    if arg1 == arg2:
        return True

    # This is more or less taken from assertDictEqual in
    # django/utils/unittest/case.py:
    args1_lines = pprint.pformat(arg1).splitlines()
    args2_lines = pprint.pformat(arg2).splitlines()
    diff = difflib.ndiff(args1_lines, args2_lines)

    p("Found the following differences: ====================================")
    for line in diff:
        p(line)
    p("=====================================================================")

    return False

def equal_call_args(args1, args2):
    """Return True if two sequences of arguments are equal

    Otherwise return False and output a diff of the first non-equal
    arguments to stderr."""
    if len(args1) != len(args2):
        message = "The argument lists were different lengths: {0} and {1}"
        p(message.format(len(args1), len(args2)))

    for i, arg1 in enumerate(args1):
        if not equal_arg(arg1, args2[i]):
            return False

    return True

Prompt:
Add equal_call_args for helpful diffs of args

This is particularly useful because mock's assert_called_with produces
really unhelpful output if the the expectation doesn't match.


import sys
sys.path.insert(1, "../../../")
import h2o

def cupMediumGBM(ip,port):
  # Connect to h2o
  h2o.init(ip,port)

  train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv"))
  test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv"))

  train["TARGET_B"] = train["TARGET_B"].asfactor()

  # Train H2O GBM Model:
  train_cols = train.names()
  for c in ['C1', "TARGET_D", "TARGET_B", "CONTROLN"]:
    train_cols.remove(c)
  model = h2o.gbm(x=train[train_cols], y=train["TARGET_B"], distribution = "bernoulli", ntrees = 5)

if __name__ == "__main__":
  h2o.run_test(sys.argv, cupMediumGBM)

Response:
<REPLACE_OLD> ['', <REPLACE_NEW> ['C1', <REPLACE_END> <|endoftext|> import sys
sys.path.insert(1, "../../../")
import h2o

def cupMediumGBM(ip,port):
  # Connect to h2o
  h2o.init(ip,port)

  train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv"))
  test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv"))

  train["TARGET_B"] = train["TARGET_B"].asfactor()

  # Train H2O GBM Model:
  train_cols = train.names()
  for c in ['C1', "TARGET_D", "TARGET_B", "CONTROLN"]:
    train_cols.remove(c)
  model = h2o.gbm(x=train[train_cols], y=train["TARGET_B"], distribution = "bernoulli", ntrees = 5)

if __name__ == "__main__":
  h2o.run_test(sys.argv, cupMediumGBM)

Prompt:
Update test for new column naming rules.  Remove '' as a name and call column 'C1'

import sys
sys.path.insert(1, "../../../")
import h2o

def cupMediumGBM(ip,port):
  # Connect to h2o
  h2o.init(ip,port)

  train = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98LRN_z.csv"))
  test = h2o.import_frame(path=h2o.locate("bigdata/laptop/usecases/cup98VAL_z.csv"))

  train["TARGET_B"] = train["TARGET_B"].asfactor()

  # Train H2O GBM Model:
  train_cols = train.names()
  for c in ['', "TARGET_D", "TARGET_B", "CONTROLN"]:
    train_cols.remove(c)
  model = h2o.gbm(x=train[train_cols], y=train["TARGET_B"], distribution = "bernoulli", ntrees = 5)

if __name__ == "__main__":
  h2o.run_test(sys.argv, cupMediumGBM)


import numpy as np
from ..centroid_resid import get_obs_slot_residuals

def test_multi_ai():
    # obsid 15175 has two aspect intervals
    dyags, yt, dzags, zt = get_obs_slot_residuals(15175, 4)
    assert np.all(np.abs(dyags) < 3)
    assert np.all(np.abs(dzags) < 6)

def test_obc_centroids():
    dyags, yt, dzags, zt = get_obs_slot_residuals(15175, 5, centroid_source='obc')
    assert np.all(np.abs(dyags) < 6)
    assert np.all(np.abs(dzags) < 3)

def test_obc():
    dyags, yt, dzags, zt = get_obs_slot_residuals(15175, 6, att_source='obc', centroid_source='obc')
    assert np.all(np.abs(dyags) < 4.5)
    assert np.all(np.abs(dzags) < 5.5)

Response:
<REPLACE_OLD> dzags <REPLACE_NEW> yt, dzags, zt <REPLACE_END> <REPLACE_OLD> dzags <REPLACE_NEW> yt, dzags, zt <REPLACE_END> <REPLACE_OLD> dzags <REPLACE_NEW> yt, dzags, zt <REPLACE_END> <|endoftext|> import numpy as np
from ..centroid_resid import get_obs_slot_residuals

def test_multi_ai():
    # obsid 15175 has two aspect intervals
    dyags, yt, dzags, zt = get_obs_slot_residuals(15175, 4)
    assert np.all(np.abs(dyags) < 3)
    assert np.all(np.abs(dzags) < 6)

def test_obc_centroids():
    dyags, yt, dzags, zt = get_obs_slot_residuals(15175, 5, centroid_source='obc')
    assert np.all(np.abs(dyags) < 6)
    assert np.all(np.abs(dzags) < 3)

def test_obc():
    dyags, yt, dzags, zt = get_obs_slot_residuals(15175, 6, att_source='obc', centroid_source='obc')
    assert np.all(np.abs(dyags) < 4.5)
    assert np.all(np.abs(dzags) < 5.5)

Prompt:
Update tests using helper method for new API

import numpy as np
from ..centroid_resid import get_obs_slot_residuals

def test_multi_ai():
    # obsid 15175 has two aspect intervals
    dyags, dzags = get_obs_slot_residuals(15175, 4)
    assert np.all(np.abs(dyags) < 3)
    assert np.all(np.abs(dzags) < 6)

def test_obc_centroids():
    dyags, dzags = get_obs_slot_residuals(15175, 5, centroid_source='obc')
    assert np.all(np.abs(dyags) < 6)
    assert np.all(np.abs(dzags) < 3)

def test_obc():
    dyags, dzags = get_obs_slot_residuals(15175, 6, att_source='obc', centroid_source='obc')
    assert np.all(np.abs(dyags) < 4.5)
    assert np.all(np.abs(dzags) < 5.5)


from django.conf import settings
import os
import os.path
import time
import re
from celery.task import task

@task
def cleanup_temp_tif_files(age=7200):
    temp_dir = settings.DATASET_DOWNLOAD_DIR
    cutoff = time.time() - age
    t_files = os.listdir(temp_dir)
    for t_file in t_files:
        if re.search('.zip$', t_file):
            path = os.path.join(temp_dir, t_file)
            if os.path.getctime(path) < cutoff:
                try:
                    os.remove(path)
                except OSError:
                    pass

Update GeoTIFF cleanup to cleanup .zip

Update GeoTIFF cleanup to cleanup .zip

Response:
<REPLACE_OLD> re.search('.tif$', <REPLACE_NEW> re.search('.zip$', <REPLACE_END> <|endoftext|> from django.conf import settings
import os
import os.path
import time
import re
from celery.task import task

@task
def cleanup_temp_tif_files(age=7200):
    temp_dir = settings.DATASET_DOWNLOAD_DIR
    cutoff = time.time() - age
    t_files = os.listdir(temp_dir)
    for t_file in t_files:
        if re.search('.zip$', t_file):
            path = os.path.join(temp_dir, t_file)
            if os.path.getctime(path) < cutoff:
                try:
                    os.remove(path)
                except OSError:
                    pass

Prompt:
Update GeoTIFF cleanup to cleanup .zip

from django.conf import settings
import os
import os.path
import time
import re
from celery.task import task

@task
def cleanup_temp_tif_files(age=7200):
    temp_dir = settings.DATASET_DOWNLOAD_DIR
    cutoff = time.time() - age
    t_files = os.listdir(temp_dir)
    for t_file in t_files:
        if re.search('.tif$', t_file):
            path = os.path.join(temp_dir, t_file)
            if os.path.getctime(path) < cutoff:
                try:
                    os.remove(path)
                except OSError:
                    pass


import os, socket, sys, struct, getopt

def sendfile(filename, ip):
	statinfo = os.stat(filename)
	fbiinfo = struct.pack('!q', statinfo.st_size)
	with open(filename, 'rb') as f:
		sock = socket.socket()
		sock.connect((ip, 5000))
		sock.send(fbiinfo)
		while True:
			chunk = f.read(16384)
			if not chunk:
				break  # EOF
			sock.sendall(chunk)
		sock.close()

def show_usage_exit():
	print('sendfile.py -f <inputfile> -i <ip address>')
	sys.exit(2)

def main(argv):
	filename = None
	ip = None
	try:
		opts, args = getopt.getopt(argv, "hf:i:")
	except getopt.GetoptError:
		show_usage_exit()
	for opt, arg in opts:
		if opt == '-h':
			show_usage_exit()
		elif opt in ("-f", "--file"):
			filename = arg
		elif opt in ("-i", "--ip"):
			ip = arg
	if not (filename and ip):
		show_usage_exit()
	sendfile(filename, ip)

if __name__ == "__main__":
	main(sys.argv[1:])

Add script for network CIA installation using FBI

Response:
<INSERT> import os, socket, sys, struct, getopt

def sendfile(filename, ip):
	statinfo = os.stat(filename)
	fbiinfo = struct.pack('!q', statinfo.st_size)
	with open(filename, 'rb') as f:
		sock = socket.socket()
		sock.connect((ip, 5000))
		sock.send(fbiinfo)
		while True:
			chunk = f.read(16384)
			if not chunk:
				break <INSERT_END> <INSERT> # EOF
			sock.sendall(chunk)
		sock.close()

def show_usage_exit():
	print('sendfile.py -f <inputfile> -i <ip address>')
	sys.exit(2)

def main(argv):
	filename = None
	ip = None
	try:
		opts, args = getopt.getopt(argv, "hf:i:")
	except getopt.GetoptError:
		show_usage_exit()
	for opt, arg in opts:
		if opt == '-h':
			show_usage_exit()
		elif opt in ("-f", "--file"):
			filename = arg
		elif opt in ("-i", "--ip"):
			ip = arg
	if not (filename and ip):
		show_usage_exit()
	sendfile(filename, ip)

if __name__ == "__main__":
	main(sys.argv[1:])
 <INSERT_END> <|endoftext|> import os, socket, sys, struct, getopt

def sendfile(filename, ip):
	statinfo = os.stat(filename)
	fbiinfo = struct.pack('!q', statinfo.st_size)
	with open(filename, 'rb') as f:
		sock = socket.socket()
		sock.connect((ip, 5000))
		sock.send(fbiinfo)
		while True:
			chunk = f.read(16384)
			if not chunk:
				break  # EOF
			sock.sendall(chunk)
		sock.close()

def show_usage_exit():
	print('sendfile.py -f <inputfile> -i <ip address>')
	sys.exit(2)

def main(argv):
	filename = None
	ip = None
	try:
		opts, args = getopt.getopt(argv, "hf:i:")
	except getopt.GetoptError:
		show_usage_exit()
	for opt, arg in opts:
		if opt == '-h':
			show_usage_exit()
		elif opt in ("-f", "--file"):
			filename = arg
		elif opt in ("-i", "--ip"):
			ip = arg
	if not (filename and ip):
		show_usage_exit()
	sendfile(filename, ip)

if __name__ == "__main__":
	main(sys.argv[1:])

Prompt: Add script for network CIA installation using FBI


import staticconf

CLUSTERMAN_YAML_FILE_PATH = '/nail/srv/configs/clusterman.yaml'
CLUSTERMAN_METRICS_YAML_FILE_PATH = '/nail/srv/configs/clusterman_metrics.yaml'

def get_clusterman_metrics():
    try:
        import clusterman_metrics
        clusterman_yaml = CLUSTERMAN_YAML_FILE_PATH
        staticconf.YamlConfiguration(CLUSTERMAN_METRICS_YAML_FILE_PATH, namespace='clusterman_metrics')
    except (ImportError, FileNotFoundError):
        # our cluster autoscaler is not currently open source, sorry!
        clusterman_metrics = None
        clusterman_yaml = None

    return clusterman_metrics, clusterman_yaml

Fix regression in manpages build

Fix regression in manpages build

Response:
<REPLACE_OLD> ImportError:
 <REPLACE_NEW> (ImportError, FileNotFoundError):
 <REPLACE_END> <|endoftext|> import staticconf

CLUSTERMAN_YAML_FILE_PATH = '/nail/srv/configs/clusterman.yaml'
CLUSTERMAN_METRICS_YAML_FILE_PATH = '/nail/srv/configs/clusterman_metrics.yaml'

def get_clusterman_metrics():
    try:
        import clusterman_metrics
        clusterman_yaml = CLUSTERMAN_YAML_FILE_PATH
        staticconf.YamlConfiguration(CLUSTERMAN_METRICS_YAML_FILE_PATH, namespace='clusterman_metrics')
    except (ImportError, FileNotFoundError):
        # our cluster autoscaler is not currently open source, sorry!
        clusterman_metrics = None
        clusterman_yaml = None

    return clusterman_metrics, clusterman_yaml

Prompt:
Fix regression in manpages build

import staticconf

CLUSTERMAN_YAML_FILE_PATH = '/nail/srv/configs/clusterman.yaml'
CLUSTERMAN_METRICS_YAML_FILE_PATH = '/nail/srv/configs/clusterman_metrics.yaml'

def get_clusterman_metrics():
    try:
        import clusterman_metrics
        clusterman_yaml = CLUSTERMAN_YAML_FILE_PATH
        staticconf.YamlConfiguration(CLUSTERMAN_METRICS_YAML_FILE_PATH, namespace='clusterman_metrics')
    except ImportError:
        # our cluster autoscaler is not currently open source, sorry!
        clusterman_metrics = None
        clusterman_yaml = None

    return clusterman_metrics, clusterman_yaml


from evaluate_user import evaluate_user

from Tkinter import *
from ScrolledText import ScrolledText
from ttk import Frame, Button, Label, Style
import re

class EvaluatorWindow(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.parent.title("Twitter Judge")
        self.style = Style()
        self.style.theme_use("default")

        output_frame = Frame(self, relief = RIDGE, borderwidth = 1)
        output_frame.pack(anchor = N, fill = BOTH, expand = True)

        output_text = ScrolledText(output_frame)
        self.output_text = output_text
        output_text.pack(fill = BOTH, expand = True)

        input_frame = Frame(self, height = 32)
        input_frame.pack(anchor = S, fill = X, expand = False)

        user_label = Label(input_frame, text = "Enter username:")
        user_label.pack(side = LEFT)
        judge_button = Button(input_frame, text = "Judge!", command = lambda: judge(user_entry.get(), self))
        judge_button.pack(side = RIGHT)
        user_entry = Entry(input_frame)
        user_entry.pack(fill = X, padx = 5, pady = 5, expand = True)

        self.pack(fill = BOTH, expand = True)

    # Write results to the output as if this is an open file
    def write(self, output):
        self.output_text.insert(INSERT, output)
        self.output_text.see('insert')
        self.output_text.update()
        return len(output)

def judge(user_id, output_file):
    # strip away the '@' if the user included it
    user_id = re.sub('@','', user_id)
    # Notify the user if the attempt failed for any reason
    if user_id != 'exit' and evaluate_user(user_id, output_file) == 1:
        print("An error occured.\n")

def main():

    window = Tk()
    window.geometry("450x600")
    app = EvaluatorWindow(window)
    window.mainloop()

if __name__ == "__main__":
    main()

Response:
<REPLACE_OLD> evaluate_user

def main():
 <REPLACE_NEW> evaluate_user

from Tkinter import *
from ScrolledText import ScrolledText
from ttk import Frame, Button, Label, Style
import re

class EvaluatorWindow(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.parent.title("Twitter Judge")
        self.style = Style()
        self.style.theme_use("default")

        output_frame = Frame(self, relief = RIDGE, borderwidth = 1)
        output_frame.pack(anchor = N, fill = BOTH, expand = True)

        output_text = ScrolledText(output_frame)
        self.output_text = output_text
        output_text.pack(fill = BOTH, expand = True)

        input_frame = Frame(self, height = 32)
        input_frame.pack(anchor = S, fill = X, expand = False)

        user_label = Label(input_frame, text = "Enter username:")
        user_label.pack(side = LEFT)
        judge_button = Button(input_frame, text = "Judge!", command = lambda: judge(user_entry.get(), self))
        judge_button.pack(side = RIGHT)
        user_entry = Entry(input_frame)
        user_entry.pack(fill = X, padx = 5, pady = 5, expand = True)

        self.pack(fill = BOTH, expand = True)

    # Write results to the output as if this is an open file
    def write(self, output):
        self.output_text.insert(INSERT, output)
        self.output_text.see('insert')
        self.output_text.update()
        return len(output)

def judge(user_id, output_file):
    # strip away the '@' if the user included it
 <REPLACE_END> <REPLACE_OLD> ""
    while user_id != 'exit':
        user_id = raw_input("Enter <REPLACE_NEW> re.sub('@','', user_id)
    # Notify the <REPLACE_END> <REPLACE_OLD> id: ")
     <REPLACE_NEW> if the attempt failed for any reason
 <REPLACE_END> <REPLACE_OLD> evaluate_user(user_id) <REPLACE_NEW> evaluate_user(user_id, output_file) <REPLACE_END> <REPLACE_OLD>     print("Cannot evaluate user.\n")

if <REPLACE_NEW> print("An error occured.\n")

def main():

    window = Tk()
    window.geometry("450x600")
    app = EvaluatorWindow(window)
    window.mainloop()

if <REPLACE_END> <|endoftext|> from evaluate_user import evaluate_user

from Tkinter import *
from ScrolledText import ScrolledText
from ttk import Frame, Button, Label, Style
import re

class EvaluatorWindow(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.parent.title("Twitter Judge")
        self.style = Style()
        self.style.theme_use("default")

        output_frame = Frame(self, relief = RIDGE, borderwidth = 1)
        output_frame.pack(anchor = N, fill = BOTH, expand = True)

        output_text = ScrolledText(output_frame)
        self.output_text = output_text
        output_text.pack(fill = BOTH, expand = True)

        input_frame = Frame(self, height = 32)
        input_frame.pack(anchor = S, fill = X, expand = False)

        user_label = Label(input_frame, text = "Enter username:")
        user_label.pack(side = LEFT)
        judge_button = Button(input_frame, text = "Judge!", command = lambda: judge(user_entry.get(), self))
        judge_button.pack(side = RIGHT)
        user_entry = Entry(input_frame)
        user_entry.pack(fill = X, padx = 5, pady = 5, expand = True)

        self.pack(fill = BOTH, expand = True)

    # Write results to the output as if this is an open file
    def write(self, output):
        self.output_text.insert(INSERT, output)
        self.output_text.see('insert')
        self.output_text.update()
        return len(output)

def judge(user_id, output_file):
    # strip away the '@' if the user included it
    user_id = re.sub('@','', user_id)
    # Notify the user if the attempt failed for any reason
    if user_id != 'exit' and evaluate_user(user_id, output_file) == 1:
        print("An error occured.\n")

def main():

    window = Tk()
    window.geometry("450x600")
    app = EvaluatorWindow(window)
    window.mainloop()

if __name__ == "__main__":
    main()

Prompt:
Replace line endings with whitespace instead of deleting them.

from evaluate_user import evaluate_user

def main():
    user_id = ""
    while user_id != 'exit':
        user_id = raw_input("Enter user id: ")
        if user_id != 'exit' and evaluate_user(user_id) == 1:
            print("Cannot evaluate user.\n")

if __name__ == "__main__":
    main()


from expects import expect, equal
from primestg.report import Report
from ast import literal_eval

with description('Report S06 example'):
    with before.all:

        self.data_filenames = [
            'spec/data/S06.xml',
            'spec/data/S06_with_error.xml',
            # 'spec/data/S06_empty.xml'
        ]

        self.report = []
        for data_filename in self.data_filenames:
            with open(data_filename) as data_file:
                self.report.append(Report(data_file))

    with it('generates the expected results for the whole report'):

        result_filenames = []
        warnings = []
        for data_filename in self.data_filenames:
            result_filenames.append('{}_result.txt'.format(data_filename))

        for key, result_filename in enumerate(result_filenames):
            result = []
            with open(result_filename) as result_file:
                result_string = result_file.read()
                expected_result = literal_eval(result_string)
            for cnc in self.report[key].concentrators:
                if cnc.meters:
                    for meter in cnc.meters:
                        for value in meter.values:
                            result.append(value)
                        warnings.append(meter.warnings)

            print('Result: {} \n Expected result: {} \n Warnings: {}'.format(
                result, expected_result, warnings))

            expect(result).to(equal(expected_result))
        expected_warnings = [[], ["ERROR: Cnc(CIR4621704174), "
                                  "Meter(ZIV42553686). Thrown exception: "
                                  "object of type 'NoneType' has no len()"], []]
        expect(warnings).to(equal(expected_warnings))

Response:
<INSERT> 'spec/data/S06_with_error.xml',
            <INSERT_END> <INSERT> warnings = []
        <INSERT_END> <INSERT> result = []
            <INSERT_END> <REPLACE_OLD> literal_eval(result_string)

        result = self.report[key].values
 <REPLACE_NEW> literal_eval(result_string)
            for cnc in self.report[key].concentrators:
                if cnc.meters:
                    for meter in cnc.meters:
                        for value in meter.values:
                            result.append(value)
                        warnings.append(meter.warnings)

            print('Result: {} \n Expected result: {} \n Warnings: {}'.format(
                result, expected_result, warnings))

     <REPLACE_END> <REPLACE_OLD> # result_filename = '{}_result.txt'.format(self.data_filename)
        #
        # with open(result_filename) as result_file:
        #     result_string = result_file.read()
        #     self.expected_result = literal_eval(result_string)
        #
        # result = self.report.values
        #
        # expect(result).to(equal(self.expected_result))
 <REPLACE_NEW> expected_warnings = [[], ["ERROR: Cnc(CIR4621704174), "
                                  "Meter(ZIV42553686). Thrown exception: "
                                  "object of type 'NoneType' has no len()"], []]
        expect(warnings).to(equal(expected_warnings))
 <REPLACE_END> <|endoftext|> from expects import expect, equal
from primestg.report import Report
from ast import literal_eval

with description('Report S06 example'):
    with before.all:

        self.data_filenames = [
            'spec/data/S06.xml',
            'spec/data/S06_with_error.xml',
            # 'spec/data/S06_empty.xml'
        ]

        self.report = []
        for data_filename in self.data_filenames:
            with open(data_filename) as data_file:
                self.report.append(Report(data_file))

    with it('generates the expected results for the whole report'):

        result_filenames = []
        warnings = []
        for data_filename in self.data_filenames:
            result_filenames.append('{}_result.txt'.format(data_filename))

        for key, result_filename in enumerate(result_filenames):
            result = []
            with open(result_filename) as result_file:
                result_string = result_file.read()
                expected_result = literal_eval(result_string)
            for cnc in self.report[key].concentrators:
                if cnc.meters:
                    for meter in cnc.meters:
                        for value in meter.values:
                            result.append(value)
                        warnings.append(meter.warnings)

            print('Result: {} \n Expected result: {} \n Warnings: {}'.format(
                result, expected_result, warnings))

            expect(result).to(equal(expected_result))
        expected_warnings = [[], ["ERROR: Cnc(CIR4621704174), "
                                  "Meter(ZIV42553686). Thrown exception: "
                                  "object of type 'NoneType' has no len()"], []]
        expect(warnings).to(equal(expected_warnings))

Prompt:
TEST for correct an with errors S06 report

from expects import expect, equal
from primestg.report import Report
from ast import literal_eval

with description('Report S06 example'):
    with before.all:

        self.data_filenames = [
            'spec/data/S06.xml',
            # 'spec/data/S06_empty.xml'
        ]

        self.report = []
        for data_filename in self.data_filenames:
            with open(data_filename) as data_file:
                self.report.append(Report(data_file))

    with it('generates the expected results for the whole report'):

        result_filenames = []
        for data_filename in self.data_filenames:
            result_filenames.append('{}_result.txt'.format(data_filename))

        for key, result_filename in enumerate(result_filenames):
            with open(result_filename) as result_file:
                result_string = result_file.read()
                expected_result = literal_eval(result_string)

        result = self.report[key].values
        expect(result).to(equal(expected_result))
        # result_filename = '{}_result.txt'.format(self.data_filename)
        #
        # with open(result_filename) as result_file:
        #     result_string = result_file.read()
        #     self.expected_result = literal_eval(result_string)
        #
        # result = self.report.values
        #
        # expect(result).to(equal(self.expected_result))


"""Download genome files from the NCBI"""
from .config import (
    SUPPORTED_TAXONOMIC_GROUPS,
    NgdConfig
)
from .core import (
    args_download,
    download,
    argument_parser,
)

__version__ = '0.2.9'
__all__ = [
    'download',
    'args_download',
    'SUPPORTED_TAXONOMIC_GROUPS',
    'NgdConfig',
    'argument_parser'
]

Bump version number to 0.2.9

Response:
<REPLACE_OLD> '0.2.8'
__all__ <REPLACE_NEW> '0.2.9'
__all__ <REPLACE_END> <|endoftext|> """Download genome files from the NCBI"""
from .config import (
    SUPPORTED_TAXONOMIC_GROUPS,
    NgdConfig
)
from .core import (
    args_download,
    download,
    argument_parser,
)

__version__ = '0.2.9'
__all__ = [
    'download',
    'args_download',
    'SUPPORTED_TAXONOMIC_GROUPS',
    'NgdConfig',
    'argument_parser'
]

Prompt:
Bump version number to 0.2.9

Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>

"""Download genome files from the NCBI"""
from .config import (
    SUPPORTED_TAXONOMIC_GROUPS,
    NgdConfig
)
from .core import (
    args_download,
    download,
    argument_parser,
)

__version__ = '0.2.8'
__all__ = [
    'download',
    'args_download',
    'SUPPORTED_TAXONOMIC_GROUPS',
    'NgdConfig',
    'argument_parser'
]


import pytest

from catinabox import cattery, mccattery

@pytest.fixture(params=[
    cattery.Cattery,
    mccattery.McCattery
])
def cattery_fixture(request):
    return request.param()

###########################################################################
# add_cats
###########################################################################

def test__add_cats__succeeds(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy", "Snookums"])
    assert cattery_fixture.cats == ["Fluffy", "Snookums"]
    assert cattery_fixture.num_cats == 2

###########################################################################
# remove_cat
###########################################################################

def test__remove_cat__succeeds(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy", "Junior"])
    cattery_fixture.remove_cat("Fluffy")
    assert cattery_fixture.cats == ["Junior"]
    assert cattery_fixture.num_cats == 1

def test__remove_cat__no_cats__fails(cattery_fixture):
    with pytest.raises(cattery.CatNotFound):
        cattery_fixture.remove_cat("Fluffles")

def test__remove_cat__cat_not_in_cattery__fails(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy"])
    with pytest.raises(cattery.CatNotFound):
        cattery_fixture.remove_cat("Snookums")

Response:
<REPLACE_OLD> cattery

class TestCattery(object):

 <REPLACE_NEW> cattery, mccattery

@pytest.fixture(params=[
 <REPLACE_END> <REPLACE_OLD> ###########################################################################
 <REPLACE_NEW> cattery.Cattery,
 <REPLACE_END> <REPLACE_OLD> # add_cats
 <REPLACE_NEW> mccattery.McCattery
])
def cattery_fixture(request):
 <REPLACE_END> <REPLACE_OLD> ###########################################################################

 <REPLACE_NEW> return request.param()

###########################################################################
# add_cats
###########################################################################

def test__add_cats__succeeds(cattery_fixture):
 <REPLACE_END> <REPLACE_OLD> def test__add_cats__succeeds(self):
        c = cattery.Cattery()
     <REPLACE_NEW> cattery_fixture.add_cats(["Fluffy", "Snookums"])
 <REPLACE_END> <REPLACE_OLD> c

    ###########################################################################
    # remove_cat
    ###########################################################################

    def test__remove_cat__succeeds(self):
        c = cattery.Cattery()
     <REPLACE_NEW> cattery_fixture.cats == ["Fluffy", "Snookums"]
 <REPLACE_END> <REPLACE_OLD> c

 <REPLACE_NEW> cattery_fixture.num_cats == 2

###########################################################################
# remove_cat
###########################################################################

def test__remove_cat__succeeds(cattery_fixture):
 <REPLACE_END> <REPLACE_OLD> def test__remove_cat__no_cats__fails(self):
 <REPLACE_NEW> cattery_fixture.add_cats(["Fluffy", "Junior"])
 <REPLACE_END> <REPLACE_OLD>     c = cattery.Cattery()
     <REPLACE_NEW> cattery_fixture.remove_cat("Fluffy")
 <REPLACE_END> <REPLACE_OLD> c

 <REPLACE_NEW> cattery_fixture.cats == ["Junior"]
 <REPLACE_END> <REPLACE_OLD> def test__remove_cat__cat_not_in_cattery__fails(self):
        c = cattery.Cattery()
        c.add_cats(["Fluffy"])
     <REPLACE_NEW> assert cattery_fixture.num_cats == 1

def test__remove_cat__no_cats__fails(cattery_fixture):
 <REPLACE_END> <INSERT> cattery_fixture.remove_cat("Fluffles")

def test__remove_cat__cat_not_in_cattery__fails(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy"])
    with pytest.raises(cattery.CatNotFound):
 <INSERT_END> <REPLACE_OLD> c.remove_cat("Snookums")
 <REPLACE_NEW>    cattery_fixture.remove_cat("Snookums")
 <REPLACE_END> <|endoftext|> import pytest

from catinabox import cattery, mccattery

@pytest.fixture(params=[
    cattery.Cattery,
    mccattery.McCattery
])
def cattery_fixture(request):
    return request.param()

###########################################################################
# add_cats
###########################################################################

def test__add_cats__succeeds(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy", "Snookums"])
    assert cattery_fixture.cats == ["Fluffy", "Snookums"]
    assert cattery_fixture.num_cats == 2

###########################################################################
# remove_cat
###########################################################################

def test__remove_cat__succeeds(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy", "Junior"])
    cattery_fixture.remove_cat("Fluffy")
    assert cattery_fixture.cats == ["Junior"]
    assert cattery_fixture.num_cats == 1

def test__remove_cat__no_cats__fails(cattery_fixture):
    with pytest.raises(cattery.CatNotFound):
        cattery_fixture.remove_cat("Fluffles")

def test__remove_cat__cat_not_in_cattery__fails(cattery_fixture):
    cattery_fixture.add_cats(["Fluffy"])
    with pytest.raises(cattery.CatNotFound):
        cattery_fixture.remove_cat("Snookums")

Prompt:
Add full tests for mccattery and cattery

import pytest

from catinabox import cattery

class TestCattery(object):

    ###########################################################################
    # add_cats
    ###########################################################################

    def test__add_cats__succeeds(self):
        c = cattery.Cattery()
        assert c

    ###########################################################################
    # remove_cat
    ###########################################################################

    def test__remove_cat__succeeds(self):
        c = cattery.Cattery()
        assert c

    def test__remove_cat__no_cats__fails(self):
        c = cattery.Cattery()
        assert c

    def test__remove_cat__cat_not_in_cattery__fails(self):
        c = cattery.Cattery()
        c.add_cats(["Fluffy"])
        with pytest.raises(cattery.CatNotFound):
            c.remove_cat("Snookums")


# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    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 django.conf.urls import patterns
from django.conf.urls import url

from openstack_dashboard.dashboards.project.images.snapshots import views

urlpatterns = patterns(
    '',
    url(r'^(?P<instance_id>[^/]+)/create/$',
        views.CreateView.as_view(),
        name='create')
)

Response:
<REPLACE_OLD> url(r'^(?P<instance_id>[^/]+)/create',
 <REPLACE_NEW> url(r'^(?P<instance_id>[^/]+)/create/$',
 <REPLACE_END> <|endoftext|> # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    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 django.conf.urls import patterns
from django.conf.urls import url

from openstack_dashboard.dashboards.project.images.snapshots import views

urlpatterns = patterns(
    '',
    url(r'^(?P<instance_id>[^/]+)/create/$',
        views.CreateView.as_view(),
        name='create')
)

Prompt:
Fix too loose url regex for snapshot creation

Current regex '^(?P<instance_id>[^/]+)/create' for url
projects/images/<instance-id>/create will match all urls start with 'create' by
mistake. The '$' added will make sure the regex only match 'create' as expect.

Change-Id: I9f180d8d904d15e9458513f39b1e4719ac6800a3
Closes-Bug: #1477822

# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    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 django.conf.urls import patterns
from django.conf.urls import url

from openstack_dashboard.dashboards.project.images.snapshots import views

urlpatterns = patterns(
    '',
    url(r'^(?P<instance_id>[^/]+)/create',
        views.CreateView.as_view(),
        name='create')
)


import logging
import mock
import unittest

from mock import patch

from svc_monitor.svc_monitor import SvcMonitor
from pysandesh.sandesh_base import Sandesh

class Arguments(object):
    def __init__(self):
        self.disc_server_ip = None
        self.disc_server_port = None
        self.collectors = None
        self.http_server_port = 0
        self.log_local = None
        self.log_category = None
        self.log_level = None
        self.log_file = '/var/log/contrail/svc_monitor.log'
        self.use_syslog = False
        self.syslog_facility = Sandesh._DEFAULT_SYSLOG_FACILITY
        self.cluster_id = None

class SvcMonitorInitTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    @patch('pysandesh.sandesh_base.Sandesh')
    @patch.object(SvcMonitor, '_cassandra_init')
    def test_init_monitor(self, sandesh_mock, cassandra_init_mock):
        logging.debug("init")
        self._api_client = mock.Mock()
        arguments = Arguments()
        with patch.object(logging.handlers, 'RotatingFileHandler'):
            self._svc_monitor = SvcMonitor(self._api_client, arguments)

Response:
<REPLACE_OLD> Sandesh._DEFAULT_SYSLOG_FACILITY

class <REPLACE_NEW> Sandesh._DEFAULT_SYSLOG_FACILITY
        self.cluster_id = None

class <REPLACE_END> <|endoftext|> import logging
import mock
import unittest

from mock import patch

from svc_monitor.svc_monitor import SvcMonitor
from pysandesh.sandesh_base import Sandesh

class Arguments(object):
    def __init__(self):
        self.disc_server_ip = None
        self.disc_server_port = None
        self.collectors = None
        self.http_server_port = 0
        self.log_local = None
        self.log_category = None
        self.log_level = None
        self.log_file = '/var/log/contrail/svc_monitor.log'
        self.use_syslog = False
        self.syslog_facility = Sandesh._DEFAULT_SYSLOG_FACILITY
        self.cluster_id = None

class SvcMonitorInitTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    @patch('pysandesh.sandesh_base.Sandesh')
    @patch.object(SvcMonitor, '_cassandra_init')
    def test_init_monitor(self, sandesh_mock, cassandra_init_mock):
        logging.debug("init")
        self._api_client = mock.Mock()
        arguments = Arguments()
        with patch.object(logging.handlers, 'RotatingFileHandler'):
            self._svc_monitor = SvcMonitor(self._api_client, arguments)

Prompt:
Fix svc_monitor tests by adding a missing arg

This commit d318b73fbab8f0c200c71adf642968a624a7db29
introduced a cluster_id arg but this arg is not
initialized in the test file.

Change-Id: I770e5f2c949afd408b8906439e711e7f619afa57

import logging
import mock
import unittest

from mock import patch

from svc_monitor.svc_monitor import SvcMonitor
from pysandesh.sandesh_base import Sandesh

class Arguments(object):
    def __init__(self):
        self.disc_server_ip = None
        self.disc_server_port = None
        self.collectors = None
        self.http_server_port = 0
        self.log_local = None
        self.log_category = None
        self.log_level = None
        self.log_file = '/var/log/contrail/svc_monitor.log'
        self.use_syslog = False
        self.syslog_facility = Sandesh._DEFAULT_SYSLOG_FACILITY

class SvcMonitorInitTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    @patch('pysandesh.sandesh_base.Sandesh')
    @patch.object(SvcMonitor, '_cassandra_init')
    def test_init_monitor(self, sandesh_mock, cassandra_init_mock):
        logging.debug("init")
        self._api_client = mock.Mock()
        arguments = Arguments()
        with patch.object(logging.handlers, 'RotatingFileHandler'):
            self._svc_monitor = SvcMonitor(self._api_client, arguments)


from os import environ
from urllib2 import urlopen

from flask import Flask, json, jsonify
app = Flask(__name__)

from hip import get_ranking_array

url = 'http://open.mapquestapi.com/directions/v2/route'
params = '?key={apikey}&ambiguities=ignore&routeType=pedestrian'
rel = url + params + '&from={flat},{flng}&to={tlat},{tlng}'

@app.route("/route/<from_lat>,<from_lng>/<to_lat>,<to_lng>")
def route(from_lat, from_lng, to_lat, to_lng):
    resp = urlopen(rel.format(apikey=environ['MAPQUEST_API_KEY'],
                   flat=from_lat, flng=from_lng, tlat=to_lat, tlng=to_lng))

    route = json.loads(resp.read().decode("utf-8"))
    coords = [(man['startPoint']['lat'], man['startPoint']['lng'])
              for leg in route['route']['legs']
              for man in leg['maneuvers']]
    hip_rank, total_rank = get_ranking_array(coords)
    return jsonify(route=route, hip_rank=list(hip_rank), total_rank=total_rank)

if __name__ == "__main__":
    app.run(debug=environ.get('FLASK_DEBUG', False))

Return route, hip rank and total rank

Return route, hip rank and total rank

Response:
<REPLACE_OLD> make_response
app <REPLACE_NEW> jsonify
app <REPLACE_END> <REPLACE_OLD> Flask(__name__)

url <REPLACE_NEW> Flask(__name__)

from hip import get_ranking_array

url <REPLACE_END> <REPLACE_OLD> get_coords(from_lat, <REPLACE_NEW> route(from_lat, <REPLACE_END> <REPLACE_OLD> resp_dict <REPLACE_NEW> route <REPLACE_END> <REPLACE_OLD> res <REPLACE_NEW> coords <REPLACE_END> <INSERT>    <INSERT_END> <REPLACE_OLD> resp_dict['route']['legs']
 <REPLACE_NEW> route['route']['legs']
    <REPLACE_END> <INSERT> hip_rank, total_rank = get_ranking_array(coords)
    <INSERT_END> <REPLACE_OLD> make_response(json.dumps(res))

if <REPLACE_NEW> jsonify(route=route, hip_rank=list(hip_rank), total_rank=total_rank)

if <REPLACE_END> <|endoftext|> from os import environ
from urllib2 import urlopen

from flask import Flask, json, jsonify
app = Flask(__name__)

from hip import get_ranking_array

url = 'http://open.mapquestapi.com/directions/v2/route'
params = '?key={apikey}&ambiguities=ignore&routeType=pedestrian'
rel = url + params + '&from={flat},{flng}&to={tlat},{tlng}'

@app.route("/route/<from_lat>,<from_lng>/<to_lat>,<to_lng>")
def route(from_lat, from_lng, to_lat, to_lng):
    resp = urlopen(rel.format(apikey=environ['MAPQUEST_API_KEY'],
                   flat=from_lat, flng=from_lng, tlat=to_lat, tlng=to_lng))

    route = json.loads(resp.read().decode("utf-8"))
    coords = [(man['startPoint']['lat'], man['startPoint']['lng'])
              for leg in route['route']['legs']
              for man in leg['maneuvers']]
    hip_rank, total_rank = get_ranking_array(coords)
    return jsonify(route=route, hip_rank=list(hip_rank), total_rank=total_rank)

if __name__ == "__main__":
    app.run(debug=environ.get('FLASK_DEBUG', False))

Prompt:
Return route, hip rank and total rank

from os import environ
from urllib2 import urlopen

from flask import Flask, json, make_response
app = Flask(__name__)

url = 'http://open.mapquestapi.com/directions/v2/route'
params = '?key={apikey}&ambiguities=ignore&routeType=pedestrian'
rel = url + params + '&from={flat},{flng}&to={tlat},{tlng}'

@app.route("/route/<from_lat>,<from_lng>/<to_lat>,<to_lng>")
def get_coords(from_lat, from_lng, to_lat, to_lng):
    resp = urlopen(rel.format(apikey=environ['MAPQUEST_API_KEY'],
                   flat=from_lat, flng=from_lng, tlat=to_lat, tlng=to_lng))

    resp_dict = json.loads(resp.read().decode("utf-8"))
    res = [(man['startPoint']['lat'], man['startPoint']['lng'])
           for leg in resp_dict['route']['legs']
           for man in leg['maneuvers']]
    return make_response(json.dumps(res))

if __name__ == "__main__":
    app.run(debug=environ.get('FLASK_DEBUG', False))


"""Setup file to Not Another Neuroimaging Slicer

"""

from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.abspath(path.join(here, 'README.md'))) as f:
    long_description = f.read()

setup(
    name='qipype',
    version='3.2',
    description='nipype interfaces to QUantitative Imaging Tools',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/spinicist/quit',
    author='Tobias Wood',
    author_email='tobias@spinicist.org.uk',
    py_modules=['qipype'],
    install_requires=['nipype>=1.2.3',
                      'nibabel>=2.5.1'],
    python_requires='>=3',
    license='MPL',
    classifiers=['Topic :: Scientific/Engineering :: Physics',
                 'Programming Language :: Python :: 3',
                 ],
    keywords='neuroimaging mri',
    packages=find_packages()
)

Response:
<REPLACE_OLD> version='0.3',
 <REPLACE_NEW> version='3.2',
 <REPLACE_END> <|endoftext|> """Setup file to Not Another Neuroimaging Slicer

"""

from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.abspath(path.join(here, 'README.md'))) as f:
    long_description = f.read()

setup(
    name='qipype',
    version='3.2',
    description='nipype interfaces to QUantitative Imaging Tools',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/spinicist/quit',
    author='Tobias Wood',
    author_email='tobias@spinicist.org.uk',
    py_modules=['qipype'],
    install_requires=['nipype>=1.2.3',
                      'nibabel>=2.5.1'],
    python_requires='>=3',
    license='MPL',
    classifiers=['Topic :: Scientific/Engineering :: Physics',
                 'Programming Language :: Python :: 3',
                 ],
    keywords='neuroimaging mri',
    packages=find_packages()
)

Prompt:
Make qipype and QUIT version numbers match

"""Setup file to Not Another Neuroimaging Slicer

"""

from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.abspath(path.join(here, 'README.md'))) as f:
    long_description = f.read()

setup(
    name='qipype',
    version='0.3',
    description='nipype interfaces to QUantitative Imaging Tools',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/spinicist/quit',
    author='Tobias Wood',
    author_email='tobias@spinicist.org.uk',
    py_modules=['qipype'],
    install_requires=['nipype>=1.2.3',
                      'nibabel>=2.5.1'],
    python_requires='>=3',
    license='MPL',
    classifiers=['Topic :: Scientific/Engineering :: Physics',
                 'Programming Language :: Python :: 3',
                 ],
    keywords='neuroimaging mri',
    packages=find_packages()
)


Add test for ping endpoint

Add test for ping endpoint

Response:
<INSERT> from flask.ext.resty import Api
import pytest

# -----------------------------------------------------------------------------

@pytest.fixture(autouse=True)
def routes(app):
 <INSERT_END> <INSERT>   api = Api(app, '/api')
    api.add_ping('/ping')

# -----------------------------------------------------------------------------

def test_ping(client):
    response = client.get('/ping')
    assert response.status_code == 200
    assert not response.data
 <INSERT_END> <|endoftext|> from flask.ext.resty import Api
import pytest

# -----------------------------------------------------------------------------

@pytest.fixture(autouse=True)
def routes(app):
    api = Api(app, '/api')
    api.add_ping('/ping')

# -----------------------------------------------------------------------------

def test_ping(client):
    response = client.get('/ping')
    assert response.status_code == 200
    assert not response.data

Prompt: Add test for ping endpoint


# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.

from astropy.tests.pytest_plugins import *

## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
# enable_deprecations_as_exceptions()

## Uncomment and customize the following lines to add/remove entries
## from the list of packages for which version numbers are displayed
## when running the tests
# PYTEST_HEADER_MODULES['scikit-image'] = 'skimage'
# del PYTEST_HEADER_MODULES['h5py']

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

## Uncomment and customize the following lines to add/remove entries
## from the list of packages for which version numbers are displayed
## when running the tests
# PYTEST_HEADER_MODULES['scikit-image'] = 'skimage'
# del PYTEST_HEADER_MODULES['h5py']
 <REPLACE_END> <|endoftext|> # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.

from astropy.tests.pytest_plugins import *

## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
# enable_deprecations_as_exceptions()

## Uncomment and customize the following lines to add/remove entries
## from the list of packages for which version numbers are displayed
## when running the tests
# PYTEST_HEADER_MODULES['scikit-image'] = 'skimage'
# del PYTEST_HEADER_MODULES['h5py']

Prompt:
Add note about adding/removing packages to/from pytest header
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.

from astropy.tests.pytest_plugins import *

## Uncomment the following line to treat all DeprecationWarnings as
## exceptions
# enable_deprecations_as_exceptions()


import os
import logging
import logging.config

LOG_CONFIG = {
    'version': 1,
    'formatters': {
        'standard': {'format': 'voltron: [%(levelname)s] %(message)s'}
    },
    'handlers': {
        'default': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        }
    },
    'loggers': {
        'voltron': {
            'handlers': ['default'],
            'level': 'INFO',
            'propogate': True,
        }
    }
}

VOLTRON_DIR = os.path.expanduser('~/.voltron/')
VOLTRON_CONFIG = os.path.join(VOLTRON_DIR, 'config')

def configure_logging():
    logging.config.dictConfig(LOG_CONFIG)
    log = logging.getLogger('voltron')
    return log

# Python 3 shims
if not hasattr(__builtins__, "xrange"):
    xrange = range

Create some shims for py3k

Create some shims for py3k

Response:
<REPLACE_OLD> log
 <REPLACE_NEW> log

# Python 3 shims
if not hasattr(__builtins__, "xrange"):
    xrange = range
 <REPLACE_END> <|endoftext|> import os
import logging
import logging.config

LOG_CONFIG = {
    'version': 1,
    'formatters': {
        'standard': {'format': 'voltron: [%(levelname)s] %(message)s'}
    },
    'handlers': {
        'default': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        }
    },
    'loggers': {
        'voltron': {
            'handlers': ['default'],
            'level': 'INFO',
            'propogate': True,
        }
    }
}

VOLTRON_DIR = os.path.expanduser('~/.voltron/')
VOLTRON_CONFIG = os.path.join(VOLTRON_DIR, 'config')

def configure_logging():
    logging.config.dictConfig(LOG_CONFIG)
    log = logging.getLogger('voltron')
    return log

# Python 3 shims
if not hasattr(__builtins__, "xrange"):
    xrange = range

Prompt:
Create some shims for py3k

import os
import logging
import logging.config

LOG_CONFIG = {
    'version': 1,
    'formatters': {
        'standard': {'format': 'voltron: [%(levelname)s] %(message)s'}
    },
    'handlers': {
        'default': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        }
    },
    'loggers': {
        'voltron': {
            'handlers': ['default'],
            'level': 'INFO',
            'propogate': True,
        }
    }
}

VOLTRON_DIR = os.path.expanduser('~/.voltron/')
VOLTRON_CONFIG = os.path.join(VOLTRON_DIR, 'config')

def configure_logging():
    logging.config.dictConfig(LOG_CONFIG)
    log = logging.getLogger('voltron')
    return log


#!/usr/bin/env python
import sys

if sys.argv.__len__() < 3:
    print "Usage :  Enter time needed for each portion of the code"
    print "    % overhead <advance> <exchange> <regrid>"
    sys.exit();

a = float(sys.argv[1])
e = float(sys.argv[2])
r = float(sys.argv[3])

o = r + e + a

print " "
# print "%40s %6.1f%%" % ("Overhead as percentage of ADVANCE",100.0*o/a)
# print "%40s %6.1f%%" % ("Overhead as percentage of total",100.0*o/(a + o))
print "%40s %6.1f%%" % ("ADVANCE as percentage of total",100.0*a/o)
print "%40s %6.1f%%" % ("EXCHANGE as percentage of total",100.0*e/o)
print "%40s %6.1f%%" % ("REGRID as percentage of total",100.0*r/o)
print " "

print "Grid advances take %5.2f times as long as exchange and regridding" % (a/o)
print " "

Response:
<REPLACE_OLD> e

print <REPLACE_NEW> e + a

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

if sys.argv.__len__() < 3:
    print "Usage :  Enter time needed for each portion of the code"
    print "    % overhead <advance> <exchange> <regrid>"
    sys.exit();

a = float(sys.argv[1])
e = float(sys.argv[2])
r = float(sys.argv[3])

o = r + e + a

print " "
# print "%40s %6.1f%%" % ("Overhead as percentage of ADVANCE",100.0*o/a)
# print "%40s %6.1f%%" % ("Overhead as percentage of total",100.0*o/(a + o))
print "%40s %6.1f%%" % ("ADVANCE as percentage of total",100.0*a/o)
print "%40s %6.1f%%" % ("EXCHANGE as percentage of total",100.0*e/o)
print "%40s %6.1f%%" % ("REGRID as percentage of total",100.0*r/o)
print " "

print "Grid advances take %5.2f times as long as exchange and regridding" % (a/o)
print " "

Prompt:
Make everything a percentage of the total

#!/usr/bin/env python
import sys

if sys.argv.__len__() < 3:
    print "Usage :  Enter time needed for each portion of the code"
    print "    % overhead <advance> <exchange> <regrid>"
    sys.exit();

a = float(sys.argv[1])
e = float(sys.argv[2])
r = float(sys.argv[3])

o = r + e

print " "
# print "%40s %6.1f%%" % ("Overhead as percentage of ADVANCE",100.0*o/a)
# print "%40s %6.1f%%" % ("Overhead as percentage of total",100.0*o/(a + o))
print "%40s %6.1f%%" % ("ADVANCE as percentage of total",100.0*a/o)
print "%40s %6.1f%%" % ("EXCHANGE as percentage of total",100.0*e/o)
print "%40s %6.1f%%" % ("REGRID as percentage of total",100.0*r/o)
print " "

print "Grid advances take %5.2f times as long as exchange and regridding" % (a/o)
print " "


import argparse
import logging
import sys

from . import commands

parser = argparse.ArgumentParser(description="Cobe control")
parser.add_argument("-b", "--brain", default="cobe.brain")
parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--instatrace", metavar="FILE",
                    help="log performance statistics to FILE")

subparsers = parser.add_subparsers(title="Commands")
commands.ConsoleCommand.add_subparser(subparsers)
commands.InitCommand.add_subparser(subparsers)
commands.LearnCommand.add_subparser(subparsers)
commands.LearnIrcLogCommand.add_subparser(subparsers)

def main():
    args = parser.parse_args()

    formatter = logging.Formatter("%(levelname)s: %(message)s")
    console = logging.StreamHandler()
    console.setFormatter(formatter)
    logging.root.addHandler(console)

    if args.debug:
        logging.root.setLevel(logging.DEBUG)
    else:
        logging.root.setLevel(logging.INFO)

    if args.instatrace:
        instatrace.Instatrace().init(args.instatrace)

    try:
        args.run(args)
    except KeyboardInterrupt:
        print
        sys.exit(1)

if __name__ == "__main__":
    main()

Response:
<REPLACE_OLD> help=argparse.SUPPRESS)

subparsers <REPLACE_NEW> help=argparse.SUPPRESS)
parser.add_argument("--instatrace", metavar="FILE",
                    help="log performance statistics to FILE")

subparsers <REPLACE_END> <INSERT> if args.instatrace:
        instatrace.Instatrace().init(args.instatrace)

    <INSERT_END> <|endoftext|> import argparse
import logging
import sys

from . import commands

parser = argparse.ArgumentParser(description="Cobe control")
parser.add_argument("-b", "--brain", default="cobe.brain")
parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--instatrace", metavar="FILE",
                    help="log performance statistics to FILE")

subparsers = parser.add_subparsers(title="Commands")
commands.ConsoleCommand.add_subparser(subparsers)
commands.InitCommand.add_subparser(subparsers)
commands.LearnCommand.add_subparser(subparsers)
commands.LearnIrcLogCommand.add_subparser(subparsers)

def main():
    args = parser.parse_args()

    formatter = logging.Formatter("%(levelname)s: %(message)s")
    console = logging.StreamHandler()
    console.setFormatter(formatter)
    logging.root.addHandler(console)

    if args.debug:
        logging.root.setLevel(logging.DEBUG)
    else:
        logging.root.setLevel(logging.INFO)

    if args.instatrace:
        instatrace.Instatrace().init(args.instatrace)

    try:
        args.run(args)
    except KeyboardInterrupt:
        print
        sys.exit(1)

if __name__ == "__main__":
    main()

Prompt:
Add a command line argument for enabling instatrace globally

import argparse
import logging
import sys

from . import commands

parser = argparse.ArgumentParser(description="Cobe control")
parser.add_argument("-b", "--brain", default="cobe.brain")
parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS)

subparsers = parser.add_subparsers(title="Commands")
commands.ConsoleCommand.add_subparser(subparsers)
commands.InitCommand.add_subparser(subparsers)
commands.LearnCommand.add_subparser(subparsers)
commands.LearnIrcLogCommand.add_subparser(subparsers)

def main():
    args = parser.parse_args()

    formatter = logging.Formatter("%(levelname)s: %(message)s")
    console = logging.StreamHandler()
    console.setFormatter(formatter)
    logging.root.addHandler(console)

    if args.debug:
        logging.root.setLevel(logging.DEBUG)
    else:
        logging.root.setLevel(logging.INFO)

    try:
        args.run(args)
    except KeyboardInterrupt:
        print
        sys.exit(1)

if __name__ == "__main__":
    main()


#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT

"""Exports the Stylint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Stylint(NodeLinter):

    """Provides an interface to stylint."""

    cmd = 'stylint @ *'
    defaults = {
        'selector': 'source.stylus, source.stylus.embedded.html',
        '--ignore=,': '',
        '--warn=,': '',
        '--error=,': ''
    }
    regex = r'''(?xi)
        # Comments show example output for each line of a Stylint warning
        # /path/to/file/example.styl
        ^.*$\s*
        # 177:24  colors  warning  hexidecimal color should be a variable
        # 177:24  warning  hexidecimal color should be a variable  colors
        # 177  warning  hexidecimal color should be a variable  colors
        ^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
    '''
    multiline = True
    error_stream = util.STREAM_STDOUT
    tempfile_suffix = 'styl'
    config_file = ('--config', '.stylintrc', '~')

Response:
<DELETE> text.html.vue, <DELETE_END> <|endoftext|> #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT

"""Exports the Stylint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Stylint(NodeLinter):

    """Provides an interface to stylint."""

    cmd = 'stylint @ *'
    defaults = {
        'selector': 'source.stylus, source.stylus.embedded.html',
        '--ignore=,': '',
        '--warn=,': '',
        '--error=,': ''
    }
    regex = r'''(?xi)
        # Comments show example output for each line of a Stylint warning
        # /path/to/file/example.styl
        ^.*$\s*
        # 177:24  colors  warning  hexidecimal color should be a variable
        # 177:24  warning  hexidecimal color should be a variable  colors
        # 177  warning  hexidecimal color should be a variable  colors
        ^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
    '''
    multiline = True
    error_stream = util.STREAM_STDOUT
    tempfile_suffix = 'styl'
    config_file = ('--config', '.stylintrc', '~')

Prompt:
Remove vue from selectors and just use embedded html
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT

"""Exports the Stylint plugin class."""

from SublimeLinter.lint import NodeLinter, util

class Stylint(NodeLinter):

    """Provides an interface to stylint."""

    cmd = 'stylint @ *'
    defaults = {
        'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html',
        '--ignore=,': '',
        '--warn=,': '',
        '--error=,': ''
    }
    regex = r'''(?xi)
        # Comments show example output for each line of a Stylint warning
        # /path/to/file/example.styl
        ^.*$\s*
        # 177:24  colors  warning  hexidecimal color should be a variable
        # 177:24  warning  hexidecimal color should be a variable  colors
        # 177  warning  hexidecimal color should be a variable  colors
        ^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
    '''
    multiline = True
    error_stream = util.STREAM_STDOUT
    tempfile_suffix = 'styl'
    config_file = ('--config', '.stylintrc', '~')


"""Cloud configuration."""

class Config(object):
    """Cloud configuration helper."""
    __singleton = None

    def __init__(self, connection):
        """Initializer."""
        self.connection = connection

    @classmethod
    def from_settings(cls):
        """Create configuration from Django settings or environment."""
        from cloud_browser.app_settings import settings
        from django.core.exceptions import ImproperlyConfigured

        conn = None
        if conn is None:
            # Try Rackspace
            account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
            secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
            servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
            if (account and secret_key):
                from cloud_browser.cloud.rackspace import RackspaceConnection
                conn = RackspaceConnection(account, secret_key, servicenet)

        if not conn:
            raise ImproperlyConfigured("No suitable credentials found.")

        return cls(conn)

    @classmethod
    def singleton(cls):
        """Get singleton object."""
        if cls.__singleton is None:
            cls.__singleton = cls.from_settings()
        return cls.__singleton

Response:
<REPLACE_OLD> configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection

class <REPLACE_NEW> configuration."""

class <REPLACE_END> <DELETE>    conn_cls = RackspaceConnection
 <DELETE_END> <INSERT> conn = None
        if conn is None:
            # Try Rackspace
            <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> settings.CLOUD_BROWSER_RACKSPACE_SERVICENET

 <REPLACE_NEW> settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
     <REPLACE_END> <DELETE> not <DELETE_END> <INSERT>                from cloud_browser.cloud.rackspace import RackspaceConnection
                conn = RackspaceConnection(account, secret_key, servicenet)

        if not conn:
 <INSERT_END> <DELETE> conn = cls.conn_cls(account, secret_key, servicenet)
        <DELETE_END> <|endoftext|> """Cloud configuration."""

class Config(object):
    """Cloud configuration helper."""
    __singleton = None

    def __init__(self, connection):
        """Initializer."""
        self.connection = connection

    @classmethod
    def from_settings(cls):
        """Create configuration from Django settings or environment."""
        from cloud_browser.app_settings import settings
        from django.core.exceptions import ImproperlyConfigured

        conn = None
        if conn is None:
            # Try Rackspace
            account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
            secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
            servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET
            if (account and secret_key):
                from cloud_browser.cloud.rackspace import RackspaceConnection
                conn = RackspaceConnection(account, secret_key, servicenet)

        if not conn:
            raise ImproperlyConfigured("No suitable credentials found.")

        return cls(conn)

    @classmethod
    def singleton(cls):
        """Get singleton object."""
        if cls.__singleton is None:
            cls.__singleton = cls.from_settings()
        return cls.__singleton

Prompt:
Config: Refactor to allow different connection class bindings.

"""Cloud configuration."""
from cloud_browser.cloud.rackspace import RackspaceConnection

class Config(object):
    """Cloud configuration helper."""
    conn_cls = RackspaceConnection
    __singleton = None

    def __init__(self, connection):
        """Initializer."""
        self.connection = connection

    @classmethod
    def from_settings(cls):
        """Create configuration from Django settings or environment."""
        from cloud_browser.app_settings import settings
        from django.core.exceptions import ImproperlyConfigured

        account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT
        secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY
        servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET

        if not (account and secret_key):
            raise ImproperlyConfigured("No suitable credentials found.")

        conn = cls.conn_cls(account, secret_key, servicenet)
        return cls(conn)

    @classmethod
    def singleton(cls):
        """Get singleton object."""
        if cls.__singleton is None:
            cls.__singleton = cls.from_settings()
        return cls.__singleton


import os
import sys
import sphinx_rtd_theme

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.insert(0, os.path.abspath("../.."))

import django
django.setup()

project = "django-postgres-extra"
copyright = "2019, Sector Labs"
author = "Sector Labs"
extensions = [
    "sphinx_rtd_theme",
    "sphinx.ext.intersphinx",
    "sphinx.ext.autodoc",
    "sphinx.ext.coverage",
    "sphinx.ext.napoleon",
]
templates_path = ["_templates"]
exclude_patterns = []
html_theme = "sphinx_rtd_theme"
intersphinx_mapping = {
    "django": ("https://docs.djangoproject.com/en/stable/", "https://docs.djangoproject.com/en/stable/_objects/"),
}

Response:
<REPLACE_OLD> ("https://docs.djangoproject.com/en/2.2/", "https://docs.djangoproject.com/en/2.2/_objects/"),
}
 <REPLACE_NEW> ("https://docs.djangoproject.com/en/stable/", "https://docs.djangoproject.com/en/stable/_objects/"),
}
 <REPLACE_END> <|endoftext|> import os
import sys
import sphinx_rtd_theme

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.insert(0, os.path.abspath("../.."))

import django
django.setup()

project = "django-postgres-extra"
copyright = "2019, Sector Labs"
author = "Sector Labs"
extensions = [
    "sphinx_rtd_theme",
    "sphinx.ext.intersphinx",
    "sphinx.ext.autodoc",
    "sphinx.ext.coverage",
    "sphinx.ext.napoleon",
]
templates_path = ["_templates"]
exclude_patterns = []
html_theme = "sphinx_rtd_theme"
intersphinx_mapping = {
    "django": ("https://docs.djangoproject.com/en/stable/", "https://docs.djangoproject.com/en/stable/_objects/"),
}

Prompt:
Use 'stable' Django version for intersphinx

This will ensure documentation references always point at the latest version.
import os
import sys
import sphinx_rtd_theme

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.insert(0, os.path.abspath("../.."))

import django
django.setup()

project = "django-postgres-extra"
copyright = "2019, Sector Labs"
author = "Sector Labs"
extensions = [
    "sphinx_rtd_theme",
    "sphinx.ext.intersphinx",
    "sphinx.ext.autodoc",
    "sphinx.ext.coverage",
    "sphinx.ext.napoleon",
]
templates_path = ["_templates"]
exclude_patterns = []
html_theme = "sphinx_rtd_theme"
intersphinx_mapping = {
    "django": ("https://docs.djangoproject.com/en/2.2/", "https://docs.djangoproject.com/en/2.2/_objects/"),
}