#!/usr/bin/env python

import os
import rospy
from sound_play.msg import SoundRequest
from sound_play.libsoundplay import SoundClient
from std_msgs.msg import String
import urllib

tts_cmd = (
  'wget -q -U "Mozilla/5.0" -O -
  "http://translate.google.com/translate_tts?tl=en-uk&q={}" > /tmp/speech.mp3'
)
sox_cmd = 'sox /tmp/speech.mp3 /tmp/speech.wav'

class ChatbotSpeaker:
  def __init__(self):
    rospy.init_node('chatbot_speaker')
    self._client = SoundClient()
    rospy.Subscriber('chatbot_responses', String, self._response_callback)
    rospy.spin()

  def _response_callback(self, data):
    query = urllib.quote(data.data)
    os.system(tts_cmd.format(query))
    os.system(sox_cmd)
    self._client.playWave('/tmp/speech.wav')

def main():
  speaker = ChatbotSpeaker()

if __name__ == '__main__':
  main()

Response:
<INSERT> os
import <INSERT_END> <REPLACE_OLD> String

class <REPLACE_NEW> String
import urllib

tts_cmd = (
  'wget -q -U "Mozilla/5.0" -O -
  "http://translate.google.com/translate_tts?tl=en-uk&q={}" > /tmp/speech.mp3'
)
sox_cmd = 'sox /tmp/speech.mp3 /tmp/speech.wav'

class <REPLACE_END> <REPLACE_OLD> self._client.say(data.data)

def <REPLACE_NEW> query = urllib.quote(data.data)
    os.system(tts_cmd.format(query))
    os.system(sox_cmd)
    self._client.playWave('/tmp/speech.wav')

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

import os
import rospy
from sound_play.msg import SoundRequest
from sound_play.libsoundplay import SoundClient
from std_msgs.msg import String
import urllib

tts_cmd = (
  'wget -q -U "Mozilla/5.0" -O -
  "http://translate.google.com/translate_tts?tl=en-uk&q={}" > /tmp/speech.mp3'
)
sox_cmd = 'sox /tmp/speech.mp3 /tmp/speech.wav'

class ChatbotSpeaker:
  def __init__(self):
    rospy.init_node('chatbot_speaker')
    self._client = SoundClient()
    rospy.Subscriber('chatbot_responses', String, self._response_callback)
    rospy.spin()

  def _response_callback(self, data):
    query = urllib.quote(data.data)
    os.system(tts_cmd.format(query))
    os.system(sox_cmd)
    self._client.playWave('/tmp/speech.wav')

def main():
  speaker = ChatbotSpeaker()

if __name__ == '__main__':
  main()

Prompt:
Use Google Translate API to get a female TTS

#!/usr/bin/env python

import rospy
from sound_play.msg import SoundRequest
from sound_play.libsoundplay import SoundClient
from std_msgs.msg import String

class ChatbotSpeaker:
  def __init__(self):
    rospy.init_node('chatbot_speaker')
    self._client = SoundClient()
    rospy.Subscriber('chatbot_responses', String, self._response_callback)
    rospy.spin()

  def _response_callback(self, data):
    self._client.say(data.data)

def main():
  speaker = ChatbotSpeaker()

if __name__ == '__main__':
  main()


from conans import ConanFile, CMake, tools

class LibWFUTConan(ConanFile):
    name = "libwfut"
    version = "0.2.4"
    license = "GPL-2.0+"
    author = "Erik Ogenvik <erik@ogenvik.org>"
    homepage = "https://www.worldforge.org"
    url = "https://github.com/worldforge/libwfut"
    description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
    topics = ("mmorpg", "worldforge")
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [False, True], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}
    generators = "cmake"
    requires = ["sigc++/2.10.0@worldforge/stable",
                "zlib/1.2.11",
                "libcurl/7.66.0@worldforge/stable"]

    scm = {
        "type": "git",
        "url": "https://github.com/worldforge/libwfut.git",
        "revision": "auto"
    }

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder=".")
        cmake.build()
        cmake.install()

    def package_info(self):
        self.cpp_info.libs = tools.collect_libs(self)
        self.cpp_info.includedirs = ["include/wfut-0.2"]

    def package(self):
        pass

Build with PIC by default.

Build with PIC by default.

Response:
<REPLACE_OLD> True]}
 <REPLACE_NEW> True], "fPIC": [True, False]}
 <REPLACE_END> <REPLACE_OLD> False}
 <REPLACE_NEW> False, "fPIC": True}
 <REPLACE_END> <|endoftext|> from conans import ConanFile, CMake, tools

class LibWFUTConan(ConanFile):
    name = "libwfut"
    version = "0.2.4"
    license = "GPL-2.0+"
    author = "Erik Ogenvik <erik@ogenvik.org>"
    homepage = "https://www.worldforge.org"
    url = "https://github.com/worldforge/libwfut"
    description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
    topics = ("mmorpg", "worldforge")
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [False, True], "fPIC": [True, False]}
    default_options = {"shared": False, "fPIC": True}
    generators = "cmake"
    requires = ["sigc++/2.10.0@worldforge/stable",
                "zlib/1.2.11",
                "libcurl/7.66.0@worldforge/stable"]

    scm = {
        "type": "git",
        "url": "https://github.com/worldforge/libwfut.git",
        "revision": "auto"
    }

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder=".")
        cmake.build()
        cmake.install()

    def package_info(self):
        self.cpp_info.libs = tools.collect_libs(self)
        self.cpp_info.includedirs = ["include/wfut-0.2"]

    def package(self):
        pass

Prompt:
Build with PIC by default.

from conans import ConanFile, CMake, tools

class LibWFUTConan(ConanFile):
    name = "libwfut"
    version = "0.2.4"
    license = "GPL-2.0+"
    author = "Erik Ogenvik <erik@ogenvik.org>"
    homepage = "https://www.worldforge.org"
    url = "https://github.com/worldforge/libwfut"
    description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
    topics = ("mmorpg", "worldforge")
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [False, True]}
    default_options = {"shared": False}
    generators = "cmake"
    requires = ["sigc++/2.10.0@worldforge/stable",
                "zlib/1.2.11",
                "libcurl/7.66.0@worldforge/stable"]

    scm = {
        "type": "git",
        "url": "https://github.com/worldforge/libwfut.git",
        "revision": "auto"
    }

    def build(self):
        cmake = CMake(self)
        cmake.configure(source_folder=".")
        cmake.build()
        cmake.install()

    def package_info(self):
        self.cpp_info.libs = tools.collect_libs(self)
        self.cpp_info.includedirs = ["include/wfut-0.2"]

    def package(self):
        pass


from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect

from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService

def index(request):
  meetups = Meetup.objects.all()
  meetup_presenters = [MeetupService(meetup).get_decorated_meetup() for meetup in meetups]

  return render(request, 'index.html', {"meetups": meetup_presenters})

Response:
<REPLACE_OLD> []
  <REPLACE_NEW> [MeetupService(meetup).get_decorated_meetup() <REPLACE_END> <REPLACE_OLD> meetups:
    service = MeetupService(meetup)
    meetup_presenters.append(service.get_decorated_meetup())
 <REPLACE_NEW> meetups]

 <REPLACE_END> <|endoftext|> from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect

from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService

def index(request):
  meetups = Meetup.objects.all()
  meetup_presenters = [MeetupService(meetup).get_decorated_meetup() for meetup in meetups]

  return render(request, 'index.html', {"meetups": meetup_presenters})

Prompt:
Use list comprehension to generate MeetupPresentor list in index view

from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect

from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService

def index(request):
  meetups = Meetup.objects.all()
  meetup_presenters = []
  for meetup in meetups:
    service = MeetupService(meetup)
    meetup_presenters.append(service.get_decorated_meetup())
  return render(request, 'index.html', {"meetups": meetup_presenters})


name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'

class BeetleError(Exception):
    def __init__(self, page=None):
        self.page = page

Response:
<REPLACE_OLD> pass
 <REPLACE_NEW> def __init__(self, page=None):
        self.page = page
 <REPLACE_END> <|endoftext|> name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'

class BeetleError(Exception):
    def __init__(self, page=None):
        self.page = page

Prompt:
Allow the BeetleError class to take a page object as an argument

name = 'beetle'
version = '0.4.1-dev'
project_url = 'https://github.com/cknv/beetle'

class BeetleError(Exception):
    pass


# -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': "Audit Log",
    'version': "9.0.1.0.0",
    'author': "ABF OSIELL,Odoo Community Association (OCA)",
    'license': "AGPL-3",
    'website': "http://www.osiell.com",
    'category': "Tools",
    'depends': [
        'base',
    ],
    'data': [
        'security/ir.model.access.csv',
        'data/ir_cron.xml',
        'views/auditlog_view.xml',
        'views/http_session_view.xml',
        'views/http_request_view.xml',
    ],
    'images': [],
    'application': True,
    'installable': True,
}

Response:
<REPLACE_OLD> True,
    'pre_init_hook': 'pre_init_hook',
}
 <REPLACE_NEW> True,
}
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': "Audit Log",
    'version': "9.0.1.0.0",
    'author': "ABF OSIELL,Odoo Community Association (OCA)",
    'license': "AGPL-3",
    'website': "http://www.osiell.com",
    'category': "Tools",
    'depends': [
        'base',
    ],
    'data': [
        'security/ir.model.access.csv',
        'data/ir_cron.xml',
        'views/auditlog_view.xml',
        'views/http_session_view.xml',
        'views/http_request_view.xml',
    ],
    'images': [],
    'application': True,
    'installable': True,
}

Prompt:
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more

# -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': "Audit Log",
    'version': "9.0.1.0.0",
    'author': "ABF OSIELL,Odoo Community Association (OCA)",
    'license': "AGPL-3",
    'website': "http://www.osiell.com",
    'category': "Tools",
    'depends': [
        'base',
    ],
    'data': [
        'security/ir.model.access.csv',
        'data/ir_cron.xml',
        'views/auditlog_view.xml',
        'views/http_session_view.xml',
        'views/http_request_view.xml',
    ],
    'images': [],
    'application': True,
    'installable': True,
    'pre_init_hook': 'pre_init_hook',
}


BOOK_PRICE = 8

def _group_price(size):
    discounts = [0, .05, .1, .2, .25]
    if not (0 < size <= 5):
        raise ValueError('size must be in 1..' + len(discounts))
    return BOOK_PRICE * size * (1 - discounts[size - 1])

def calculate_total(books, price_so_far=0.):
    if not books:
        return price_so_far

    groups = list(set(books))
    min_price = float('inf')

    for i in range(len(groups)):

        remaining_books = books[:]

        for v in groups[:i + 1]:
            remaining_books.remove(v)

        price = calculate_total(remaining_books,
                                price_so_far + _group_price(i + 1))
        min_price = min(min_price, price)

    return min_price

Use book price constant in calculation

Response:
<REPLACE_OLD> 8 <REPLACE_NEW> BOOK_PRICE <REPLACE_END> <|endoftext|> BOOK_PRICE = 8

def _group_price(size):
    discounts = [0, .05, .1, .2, .25]
    if not (0 < size <= 5):
        raise ValueError('size must be in 1..' + len(discounts))
    return BOOK_PRICE * size * (1 - discounts[size - 1])

def calculate_total(books, price_so_far=0.):
    if not books:
        return price_so_far

    groups = list(set(books))
    min_price = float('inf')

    for i in range(len(groups)):

        remaining_books = books[:]

        for v in groups[:i + 1]:
            remaining_books.remove(v)

        price = calculate_total(remaining_books,
                                price_so_far + _group_price(i + 1))
        min_price = min(min_price, price)

    return min_price

Prompt:
book-store: Use book price constant in calculation

BOOK_PRICE = 8

def _group_price(size):
    discounts = [0, .05, .1, .2, .25]
    if not (0 < size <= 5):
        raise ValueError('size must be in 1..' + len(discounts))
    return 8 * size * (1 - discounts[size - 1])

def calculate_total(books, price_so_far=0.):
    if not books:
        return price_so_far

    groups = list(set(books))
    min_price = float('inf')

    for i in range(len(groups)):

        remaining_books = books[:]

        for v in groups[:i + 1]:
            remaining_books.remove(v)

        price = calculate_total(remaining_books,
                                price_so_far + _group_price(i + 1))
        min_price = min(min_price, price)

    return min_price


# Python
import os

# django-setuptest
import setuptest

TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']

class TestSuite(setuptest.SetupTestSuite):

    def __init__(self, *args, **kwargs):
        os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()
        super(TestSuite, self).__init__(*args, **kwargs)

    def resolve_packages(self):
        packages = super(TestSuite, self).resolve_packages()
        for test_app in TEST_APPS:
            if test_app not in packages:
                packages.append(test_app)
        return packages

Response:
<REPLACE_OLD> TestSuite(setuptest.SetupTestSuite):
 <REPLACE_NEW> TestSuite(setuptest.SetupTestSuite):

 <REPLACE_END> <REPLACE_OLD>
 <REPLACE_NEW> def __init__(self, *args, **kwargs):
        os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()
        super(TestSuite, self).__init__(*args, **kwargs)

 <REPLACE_END> <REPLACE_OLD> packages
 <REPLACE_NEW> packages

         <REPLACE_END> <|endoftext|> # Python
import os

# django-setuptest
import setuptest

TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']

class TestSuite(setuptest.SetupTestSuite):

    def __init__(self, *args, **kwargs):
        os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()
        super(TestSuite, self).__init__(*args, **kwargs)

    def resolve_packages(self):
        packages = super(TestSuite, self).resolve_packages()
        for test_app in TEST_APPS:
            if test_app not in packages:
                packages.append(test_app)
        return packages

Prompt:
Fix to allow tests with South migrations to run.

# Python
import os

# django-setuptest
import setuptest

TEST_APPS = ['sortedm2m_tests', 'sortedm2m_field', 'sortedm2m_form', 'south_support']

class TestSuite(setuptest.SetupTestSuite):

    def resolve_packages(self):
        packages = super(TestSuite, self).resolve_packages()
        for test_app in TEST_APPS:
            if test_app not in packages:
                packages.append(test_app)
        return packages


"""
CartoDB Services Python Library

See:
https://github.com/CartoDB/geocoder-api
"""

from setuptools import setup, find_packages

setup(
    name='cartodb_services',

    version='0.6.2',

    description='CartoDB Services API Python Library',

    url='https://github.com/CartoDB/dataservices-api',

    author='Data Services Team - CartoDB',
    author_email='dataservices@cartodb.com',

    license='MIT',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Mapping comunity',
        'Topic :: Maps :: Mapping Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
    ],

    keywords='maps api mapping tools geocoder routing',

    packages=find_packages(exclude=['contrib', 'docs', 'tests']),

    extras_require={
        'dev': ['unittest'],
        'test': ['unittest', 'nose', 'mockredispy', 'mock'],
    }
)

Update url of pip package

Update url of pip package

Response:
<REPLACE_OLD> url='https://github.com/CartoDB/geocoder-api',

 <REPLACE_NEW> url='https://github.com/CartoDB/dataservices-api',

 <REPLACE_END> <|endoftext|> """
CartoDB Services Python Library

See:
https://github.com/CartoDB/geocoder-api
"""

from setuptools import setup, find_packages

setup(
    name='cartodb_services',

    version='0.6.2',

    description='CartoDB Services API Python Library',

    url='https://github.com/CartoDB/dataservices-api',

    author='Data Services Team - CartoDB',
    author_email='dataservices@cartodb.com',

    license='MIT',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Mapping comunity',
        'Topic :: Maps :: Mapping Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
    ],

    keywords='maps api mapping tools geocoder routing',

    packages=find_packages(exclude=['contrib', 'docs', 'tests']),

    extras_require={
        'dev': ['unittest'],
        'test': ['unittest', 'nose', 'mockredispy', 'mock'],
    }
)

Prompt:
Update url of pip package

"""
CartoDB Services Python Library

See:
https://github.com/CartoDB/geocoder-api
"""

from setuptools import setup, find_packages

setup(
    name='cartodb_services',

    version='0.6.2',

    description='CartoDB Services API Python Library',

    url='https://github.com/CartoDB/geocoder-api',

    author='Data Services Team - CartoDB',
    author_email='dataservices@cartodb.com',

    license='MIT',

    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Mapping comunity',
        'Topic :: Maps :: Mapping Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
    ],

    keywords='maps api mapping tools geocoder routing',

    packages=find_packages(exclude=['contrib', 'docs', 'tests']),

    extras_require={
        'dev': ['unittest'],
        'test': ['unittest', 'nose', 'mockredispy', 'mock'],
    }
)


import pytest

from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive

@pytest.fixture
def mock_api(mocker):
    mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
    mocker.patch('bcbio.distributed.objectstore.Http')
    mocker.patch('bcbio.distributed.objectstore.build')
    mocker.patch('bcbio.distributed.objectstore.http')
    yield None

def test_create_google_drive_service(mock_api):
    service = GoogleDrive()
    assert service

def test_creates_http_auth(mock_api):
    GoogleDrive()
    objectstore.ServiceAccountCredentials.from_json_keyfile_name\
        .assert_called_once_with(
            GoogleDrive.GOOGLE_API_KEY_FILE, scopes=GoogleDrive.SCOPES)

def test_api_scope_includes_google_drive(mock_api):
    drive_scope = 'https://www.googleapis.com/auth/drive'
    assert drive_scope in GoogleDrive.SCOPES

def test_filename_with_json_key_is_present(mock_api):
    assert GoogleDrive.GOOGLE_API_KEY_FILE
    assert GoogleDrive.GOOGLE_API_KEY_FILE.endswith('.json')

Response:
<REPLACE_OLD> GoogleDrive.SCOPES
 <REPLACE_NEW> GoogleDrive.SCOPES

def test_filename_with_json_key_is_present(mock_api):
    assert GoogleDrive.GOOGLE_API_KEY_FILE
    assert GoogleDrive.GOOGLE_API_KEY_FILE.endswith('.json')
 <REPLACE_END> <|endoftext|> import pytest

from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive

@pytest.fixture
def mock_api(mocker):
    mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
    mocker.patch('bcbio.distributed.objectstore.Http')
    mocker.patch('bcbio.distributed.objectstore.build')
    mocker.patch('bcbio.distributed.objectstore.http')
    yield None

def test_create_google_drive_service(mock_api):
    service = GoogleDrive()
    assert service

def test_creates_http_auth(mock_api):
    GoogleDrive()
    objectstore.ServiceAccountCredentials.from_json_keyfile_name\
        .assert_called_once_with(
            GoogleDrive.GOOGLE_API_KEY_FILE, scopes=GoogleDrive.SCOPES)

def test_api_scope_includes_google_drive(mock_api):
    drive_scope = 'https://www.googleapis.com/auth/drive'
    assert drive_scope in GoogleDrive.SCOPES

def test_filename_with_json_key_is_present(mock_api):
    assert GoogleDrive.GOOGLE_API_KEY_FILE
    assert GoogleDrive.GOOGLE_API_KEY_FILE.endswith('.json')

Prompt:
Test json file with api key is in API service class

import pytest

from bcbio.distributed import objectstore
from bcbio.distributed.objectstore import GoogleDrive

@pytest.fixture
def mock_api(mocker):
    mocker.patch('bcbio.distributed.objectstore.ServiceAccountCredentials')
    mocker.patch('bcbio.distributed.objectstore.Http')
    mocker.patch('bcbio.distributed.objectstore.build')
    mocker.patch('bcbio.distributed.objectstore.http')
    yield None

def test_create_google_drive_service(mock_api):
    service = GoogleDrive()
    assert service

def test_creates_http_auth(mock_api):
    GoogleDrive()
    objectstore.ServiceAccountCredentials.from_json_keyfile_name\
        .assert_called_once_with(
            GoogleDrive.GOOGLE_API_KEY_FILE, scopes=GoogleDrive.SCOPES)

def test_api_scope_includes_google_drive(mock_api):
    drive_scope = 'https://www.googleapis.com/auth/drive'
    assert drive_scope in GoogleDrive.SCOPES


def key_exists(search_key, inputed_dict):
    '''
    Given a search key which is dot notated
    return wether or not that key exists in a dictionary
    '''
    num_levels = search_key.split(".")
    if len(num_levels) == 0:
        return False
    current_pointer = inputed_dict
    for updated_key in num_levels:
        if current_pointer is None:
            return False
        if updated_key == num_levels[-1]:
            return updated_key in current_pointer
        if updated_key in current_pointer:
            current_pointer = current_pointer[updated_key]
        else:
            return False

Add more error handling to key exists

Add more error handling to key exists

Response:
<INSERT> current_pointer is None:
            return False
        if <INSERT_END> <|endoftext|>
def key_exists(search_key, inputed_dict):
    '''
    Given a search key which is dot notated
    return wether or not that key exists in a dictionary
    '''
    num_levels = search_key.split(".")
    if len(num_levels) == 0:
        return False
    current_pointer = inputed_dict
    for updated_key in num_levels:
        if current_pointer is None:
            return False
        if updated_key == num_levels[-1]:
            return updated_key in current_pointer
        if updated_key in current_pointer:
            current_pointer = current_pointer[updated_key]
        else:
            return False

Prompt:
Add more error handling to key exists

def key_exists(search_key, inputed_dict):
    '''
    Given a search key which is dot notated
    return wether or not that key exists in a dictionary
    '''
    num_levels = search_key.split(".")
    if len(num_levels) == 0:
        return False
    current_pointer = inputed_dict
    for updated_key in num_levels:
        if updated_key == num_levels[-1]:
            return updated_key in current_pointer
        if updated_key in current_pointer:
            current_pointer = current_pointer[updated_key]
        else:
            return False


import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *

class TestBERT(unittest.TestCase):

    def test_init(self):
        trainer = BERTTrainer()

    def test_train(self):
        output_dir = 'test_{}'.format(str(int(time.time())))
        trainer = BERTTrainer(output_dir=output_dir)
        print(trainer.bert_model_hub)
        data = pd.DataFrame({
            'abstract': ['test one', 'test two', 'test three'] * 5,
            'section': ['U.S.', 'Arts', 'U.S.'] * 5,
        })
        data_column = 'abstract'
        label_column = 'section'

        train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
        trainer.train(train_features, label_list)
        results = trainer.test(test_features)
        print('Evaluation results:', results)

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

Print eval results in test

Print eval results in test

Response:
<REPLACE_OLD> trainer.test(test_features)

if <REPLACE_NEW> results = trainer.test(test_features)
        print('Evaluation results:', results)

if <REPLACE_END> <|endoftext|> import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *

class TestBERT(unittest.TestCase):

    def test_init(self):
        trainer = BERTTrainer()

    def test_train(self):
        output_dir = 'test_{}'.format(str(int(time.time())))
        trainer = BERTTrainer(output_dir=output_dir)
        print(trainer.bert_model_hub)
        data = pd.DataFrame({
            'abstract': ['test one', 'test two', 'test three'] * 5,
            'section': ['U.S.', 'Arts', 'U.S.'] * 5,
        })
        data_column = 'abstract'
        label_column = 'section'

        train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
        trainer.train(train_features, label_list)
        results = trainer.test(test_features)
        print('Evaluation results:', results)

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

Prompt:
Print eval results in test

import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *

class TestBERT(unittest.TestCase):

    def test_init(self):
        trainer = BERTTrainer()

    def test_train(self):
        output_dir = 'test_{}'.format(str(int(time.time())))
        trainer = BERTTrainer(output_dir=output_dir)
        print(trainer.bert_model_hub)
        data = pd.DataFrame({
            'abstract': ['test one', 'test two', 'test three'] * 5,
            'section': ['U.S.', 'Arts', 'U.S.'] * 5,
        })
        data_column = 'abstract'
        label_column = 'section'

        train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
        trainer.train(train_features, label_list)
        trainer.test(test_features)

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


class OdkCalculate:
    def __init__(self, row):
        self.row = row

    def to_html(self, *args, **kwargs):
        return ""

    def to_text(self, *args, **kwargs):
        return ""

    def __repr__(self):
        return '<OdkCalculate {}>'.format(self.row['name'])

Update signature of to_text and to_html

Update signature of to_text and to_html

Response:
<REPLACE_OLD> to_html(self):
 <REPLACE_NEW> to_html(self, *args, **kwargs):
 <REPLACE_END> <REPLACE_OLD> to_text(self):
 <REPLACE_NEW> to_text(self, *args, **kwargs):
 <REPLACE_END> <|endoftext|> class OdkCalculate:
    def __init__(self, row):
        self.row = row

    def to_html(self, *args, **kwargs):
        return ""

    def to_text(self, *args, **kwargs):
        return ""

    def __repr__(self):
        return '<OdkCalculate {}>'.format(self.row['name'])

Prompt:
Update signature of to_text and to_html

class OdkCalculate:
    def __init__(self, row):
        self.row = row

    def to_html(self):
        return ""

    def to_text(self):
        return ""

    def __repr__(self):
        return '<OdkCalculate {}>'.format(self.row['name'])


import discord
import asyncio
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True)
requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True)

args = parser.parse_args()

client = discord.Client()

@client.event
async def on_ready():
    print('Connection successful.')
    print('Your ID: ' + client.user.id)
    target = open(args.output, 'w')
    print(args.output, 'has been opened.')

    messageCount = 0
    channel = discord.Object(id=args.channel)

    print("Scraping messages... Don't send any messages while scraping!")
    with tqdm(leave=True,unit=' messages') as scraped:
        async for msg in client.logs_from(channel, 10000000000):
            line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content)
            line = line.encode('utf-8')
            toWrite = "{}".format(line)
            target.write(toWrite)
            target.write("\n")
            messageCount += 1
            scraped.update(1)
    print('-----')
    print('Scraping complete.')

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

client.run(usertoken,bot=False)

Response:
<REPLACE_OLD> complete.')

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

client.run('email', 'password')
 <REPLACE_NEW> complete.')

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

client.run(usertoken,bot=False)
 <REPLACE_END> <|endoftext|> import discord
import asyncio
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True)
requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True)

args = parser.parse_args()

client = discord.Client()

@client.event
async def on_ready():
    print('Connection successful.')
    print('Your ID: ' + client.user.id)
    target = open(args.output, 'w')
    print(args.output, 'has been opened.')

    messageCount = 0
    channel = discord.Object(id=args.channel)

    print("Scraping messages... Don't send any messages while scraping!")
    with tqdm(leave=True,unit=' messages') as scraped:
        async for msg in client.logs_from(channel, 10000000000):
            line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content)
            line = line.encode('utf-8')
            toWrite = "{}".format(line)
            target.write(toWrite)
            target.write("\n")
            messageCount += 1
            scraped.update(1)
    print('-----')
    print('Scraping complete.')

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

client.run(usertoken,bot=False)

Prompt:
Update to use token instead of email+pass

import discord
import asyncio
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser(description='Discord channel scraper')
requiredNamed = parser.add_argument_group('Required arguments:')
requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True)
requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True)

args = parser.parse_args()

client = discord.Client()

@client.event
async def on_ready():
    print('Connection successful.')
    print('Your ID: ' + client.user.id)
    target = open(args.output, 'w')
    print(args.output, 'has been opened.')

    messageCount = 0
    channel = discord.Object(id=args.channel)

    print("Scraping messages... Don't send any messages while scraping!")
    with tqdm(leave=True,unit=' messages') as scraped:
        async for msg in client.logs_from(channel, 10000000000):
            line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content)
            line = line.encode('utf-8')
            toWrite = "{}".format(line)
            target.write(toWrite)
            target.write("\n")
            messageCount += 1
            scraped.update(1)
    print('-----')
    print('Scraping complete.')

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

client.run('email', 'password')


"""A virtual serial port data source."""
from __future__ import absolute_import

import logging

from .base import BytestreamDataSource, DataSourceError

LOG = logging.getLogger(__name__)

try:
    import serial
except ImportError:
    LOG.debug("serial library not installed, can't use serial interface")

class SerialDataSource(BytestreamDataSource):
    """A data source reading from a serial port, which could be implemented
    with a USB to Serial or Bluetooth adapter.
    """
    DEFAULT_PORT = "/dev/ttyUSB0"
    DEFAULT_BAUDRATE = 115200

    def __init__(self, callback=None, port=None, baudrate=None):
        """Initialize a connection to the serial device.

        Kwargs:
            port - optionally override the default virtual COM port
            baudrate - optionally override the default baudrate

        Raises:
            DataSourceError if the serial device cannot be opened.
        """
        super(SerialDataSource, self).__init__(callback)
        port = port or self.DEFAULT_PORT
        baudrate = baudrate or self.DEFAULT_BAUDRATE
        try:
            self.device = serial.Serial(port, baudrate, rtscts=True)
        except serial.SerialException as e:
            raise DataSourceError("Unable to open serial device at port "
                    "%s: %s" % (port, e))
        else:
            LOG.debug("Opened serial device at %s", port)

    def _read(self):
        return self.device.readline()

Response:
<REPLACE_OLD> logging

try:
 <REPLACE_NEW> logging

from .base import BytestreamDataSource, DataSourceError

LOG = logging.getLogger(__name__)

try:
 <REPLACE_END> <REPLACE_OLD> interface")

from .base import BytestreamDataSource, DataSourceError

LOG = logging.getLogger(__name__)

class <REPLACE_NEW> interface")

class <REPLACE_END> <|endoftext|> """A virtual serial port data source."""
from __future__ import absolute_import

import logging

from .base import BytestreamDataSource, DataSourceError

LOG = logging.getLogger(__name__)

try:
    import serial
except ImportError:
    LOG.debug("serial library not installed, can't use serial interface")

class SerialDataSource(BytestreamDataSource):
    """A data source reading from a serial port, which could be implemented
    with a USB to Serial or Bluetooth adapter.
    """
    DEFAULT_PORT = "/dev/ttyUSB0"
    DEFAULT_BAUDRATE = 115200

    def __init__(self, callback=None, port=None, baudrate=None):
        """Initialize a connection to the serial device.

        Kwargs:
            port - optionally override the default virtual COM port
            baudrate - optionally override the default baudrate

        Raises:
            DataSourceError if the serial device cannot be opened.
        """
        super(SerialDataSource, self).__init__(callback)
        port = port or self.DEFAULT_PORT
        baudrate = baudrate or self.DEFAULT_BAUDRATE
        try:
            self.device = serial.Serial(port, baudrate, rtscts=True)
        except serial.SerialException as e:
            raise DataSourceError("Unable to open serial device at port "
                    "%s: %s" % (port, e))
        else:
            LOG.debug("Opened serial device at %s", port)

    def _read(self):
        return self.device.readline()

Prompt:
Make sure LOG is defined before using it.

"""A virtual serial port data source."""
from __future__ import absolute_import

import logging

try:
    import serial
except ImportError:
    LOG.debug("serial library not installed, can't use serial interface")

from .base import BytestreamDataSource, DataSourceError

LOG = logging.getLogger(__name__)

class SerialDataSource(BytestreamDataSource):
    """A data source reading from a serial port, which could be implemented
    with a USB to Serial or Bluetooth adapter.
    """
    DEFAULT_PORT = "/dev/ttyUSB0"
    DEFAULT_BAUDRATE = 115200

    def __init__(self, callback=None, port=None, baudrate=None):
        """Initialize a connection to the serial device.

        Kwargs:
            port - optionally override the default virtual COM port
            baudrate - optionally override the default baudrate

        Raises:
            DataSourceError if the serial device cannot be opened.
        """
        super(SerialDataSource, self).__init__(callback)
        port = port or self.DEFAULT_PORT
        baudrate = baudrate or self.DEFAULT_BAUDRATE
        try:
            self.device = serial.Serial(port, baudrate, rtscts=True)
        except serial.SerialException as e:
            raise DataSourceError("Unable to open serial device at port "
                    "%s: %s" % (port, e))
        else:
            LOG.debug("Opened serial device at %s", port)

    def _read(self):
        return self.device.readline()


import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max

def fix_updated(apps, _):
    Proposal = apps.get_model("proposal", "Proposal")
    proposals = Proposal.objects.annotate(published=Max("documents__published"))
    for proposal in proposals:
        if proposal.published:
            proposal.updated = proposal.published
            proposal.save()

class Migration(migrations.Migration):
    dependencies = [
        ('proposal', '0033_non_null_started'),
    ]

    operations = [
        migrations.RunPython(fix_updated),
    ]

Set proposal updated date to the mod date of most recent Document

Response:
<INSERT> import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max

def fix_updated(apps, _):
 <INSERT_END> <INSERT>   Proposal = apps.get_model("proposal", "Proposal")
    proposals = Proposal.objects.annotate(published=Max("documents__published"))
    for proposal in proposals:
        if proposal.published:
            proposal.updated = proposal.published
            proposal.save()

class Migration(migrations.Migration):
    dependencies = [
        ('proposal', '0033_non_null_started'),
    ]

    operations = [
        migrations.RunPython(fix_updated),
    ]
 <INSERT_END> <|endoftext|> import django.contrib.gis.db.models.fields
from django.db import migrations
from django.contrib.gis.db.models import Max

def fix_updated(apps, _):
    Proposal = apps.get_model("proposal", "Proposal")
    proposals = Proposal.objects.annotate(published=Max("documents__published"))
    for proposal in proposals:
        if proposal.published:
            proposal.updated = proposal.published
            proposal.save()

class Migration(migrations.Migration):
    dependencies = [
        ('proposal', '0033_non_null_started'),
    ]

    operations = [
        migrations.RunPython(fix_updated),
    ]

Prompt: Set proposal updated date to the mod date of most recent Document


from __future__ import unicode_literals

import pytest

from cassandra_migrate.cql import CqlSplitter

@pytest.mark.parametrize('cql,statements', [
    # Two statements, with whitespace
    ('''
     CREATE TABLE hello;
     CREATE TABLE world;
     ''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Two statements, no whitespace
    ('''CREATE TABLE hello;CREATE TABLE world;''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Two statements, with line and block comments
    ('''
     // comment
     -- comment
     CREATE TABLE hello;
     /* comment; comment
      */
     CREATE TABLE world;
     ''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Statements with semicolons inside strings
    ('''
     CREATE TABLE 'hello;';
     CREATE TABLE "world;"
     ''',
     ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']),
    # Double-dollar-sign quoted strings, as reported in PR #24
    ('INSERT INTO test (test) VALUES '
     '($$Pesky semicolon here ;Hello$$);',
     ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"])
])
def test_cql_split(cql, statements):
    result = CqlSplitter.split(cql.strip())
    assert result == statements

Response:
<REPLACE_OLD> "world;"'])
])
def <REPLACE_NEW> "world;"']),
    # Double-dollar-sign quoted strings, as reported in PR #24
    ('INSERT INTO test (test) VALUES '
     '($$Pesky semicolon here ;Hello$$);',
     ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"])
])
def <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

import pytest

from cassandra_migrate.cql import CqlSplitter

@pytest.mark.parametrize('cql,statements', [
    # Two statements, with whitespace
    ('''
     CREATE TABLE hello;
     CREATE TABLE world;
     ''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Two statements, no whitespace
    ('''CREATE TABLE hello;CREATE TABLE world;''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Two statements, with line and block comments
    ('''
     // comment
     -- comment
     CREATE TABLE hello;
     /* comment; comment
      */
     CREATE TABLE world;
     ''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Statements with semicolons inside strings
    ('''
     CREATE TABLE 'hello;';
     CREATE TABLE "world;"
     ''',
     ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"']),
    # Double-dollar-sign quoted strings, as reported in PR #24
    ('INSERT INTO test (test) VALUES '
     '($$Pesky semicolon here ;Hello$$);',
     ["INSERT INTO test (test) VALUES ($$Pesky semicolon here ;Hello$$)"])
])
def test_cql_split(cql, statements):
    result = CqlSplitter.split(cql.strip())
    assert result == statements

Prompt:
Add CQL-splitting test case for double-dollar-sign strings

from __future__ import unicode_literals

import pytest

from cassandra_migrate.cql import CqlSplitter

@pytest.mark.parametrize('cql,statements', [
    # Two statements, with whitespace
    ('''
     CREATE TABLE hello;
     CREATE TABLE world;
     ''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Two statements, no whitespace
    ('''CREATE TABLE hello;CREATE TABLE world;''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Two statements, with line and block comments
    ('''
     // comment
     -- comment
     CREATE TABLE hello;
     /* comment; comment
      */
     CREATE TABLE world;
     ''',
     ['CREATE TABLE hello', 'CREATE TABLE world']),
    # Statements with semicolons inside strings
    ('''
     CREATE TABLE 'hello;';
     CREATE TABLE "world;"
     ''',
     ["CREATE TABLE 'hello;'", 'CREATE TABLE "world;"'])
])
def test_cql_split(cql, statements):
    result = CqlSplitter.split(cql.strip())
    assert result == statements


from distutils.version import StrictVersion
from distutils.msvccompiler import get_build_version
from sys import maxsize
from SCons.Script import AddOption, GetOption
from path import path
import subprocess

def generate(env):
    """Add Builders and construction variables to the Environment."""
    if not 'conda' in env['TOOLS'][:-1]:
      env.Tool('system')
      SYSTEM = env['SYSTEM']

      def Conda(sources=[], channels=['statiskit', 'conda-forge']):
        if len(sources) == 0:
            if SYSTEM == 'win':
                sources = [recipe for recipe in path(env.Dir('.').srcnode().abspath).walkdirs() if (recipe/'meta.yaml').exists() and (recipe/'bld.bat').exists()]
            else:
                sources = [recipe for recipe in path(env.Dir('.').srcnode().abspath).walkdirs() if (recipe/'meta.yaml').exists() and (recipe/'build.sh').exists()]
            for source in sources
        targets = []
      if SYSTEM == 'win':
        env['SHLIBSUFFIX'] = '.pyd'
        env['TARGET_ARCH'] = 'x86_64' if ARCH == '64' else 'x86'
        AddOption('--msvc-version',
                      dest    = 'msvc-version',
                      type    = 'string',
                      nargs   = 1,
                      action  = 'store',
                      help    = 'MSVC version',
                      default = str(get_build_version()))
        env['MSVC_VERSION'] = GetOption('msvc-version')
      env.Tool('default')
      env.Tool('prefix')
      if SYSTEM == 'win':
        env.AppendUnique(CCFLAGS=['/O2',
                                  '/Ob2',
                                  '/MD',
                                  '/GR',
                                  '/EHsc',
                                  '/Gy',
                                  '/GF',
                                  '/GA'],
                         CPPDEFINES=['WIN32',
                                     'UNICODE'])
        env.PrependUnique(CPPPATH=['$PREFIX\include'])
        env.PrependUnique(LIBPATH=['$PREFIX\lib',
                                   '$PREFIX\..\libs'])
      else:
        env.PrependUnique(CPPPATH=['$PREFIX/include'],
                          LIBPATH=['$PREFIX/lib'],
                          CFLAGS=["-x", "c", "-std=c11"],
                          CXXFLAGS=["-x", "c++", "-std=c++11"])
        if ARCH == '32':
          env.AppendUnique(CCFLAGS=['-m32'])
        if SYSTEM == 'osx':
          env.AppendUnique(CCFLAGS=['-ferror-limit=0'],
                           CXXFLAGS=['-stdlib=libc++'])
        else:
          env.AppendUnique(CCFLAGS=['-fmax-errors=0',
                                    '-Wl,--no-undefined',
                                    '-fvisibility=hidden'],
                           CPPDEFINES=['_GLIBCXX_USE_CXX11_ABI=1'])

def exists(env):
    return 1

Add Conda Tool for SCons

Add Conda Tool for SCons

Response:
<REPLACE_OLD>  <REPLACE_NEW> from distutils.version import StrictVersion
from distutils.msvccompiler import get_build_version
from sys import maxsize
from SCons.Script import AddOption, GetOption
from path import path
import subprocess

def generate(env):
    """Add Builders and construction variables to the Environment."""
    if not 'conda' in env['TOOLS'][:-1]:
      env.Tool('system')
      SYSTEM = env['SYSTEM']

      def Conda(sources=[], channels=['statiskit', 'conda-forge']):
        if len(sources) == 0:
            if SYSTEM == 'win':
                sources = [recipe for recipe in path(env.Dir('.').srcnode().abspath).walkdirs() if (recipe/'meta.yaml').exists() and (recipe/'bld.bat').exists()]
            else:
                sources = [recipe for recipe in path(env.Dir('.').srcnode().abspath).walkdirs() if (recipe/'meta.yaml').exists() and (recipe/'build.sh').exists()]
            for source in sources
        targets = []
      if SYSTEM == 'win':
        env['SHLIBSUFFIX'] = '.pyd'
        env['TARGET_ARCH'] = 'x86_64' if ARCH == '64' else 'x86'
        AddOption('--msvc-version',
                      dest    = 'msvc-version',
                      type    = 'string',
                      nargs   = 1,
                      action  = 'store',
                      help    = 'MSVC version',
                      default = str(get_build_version()))
        env['MSVC_VERSION'] = GetOption('msvc-version')
      env.Tool('default')
      env.Tool('prefix')
      if SYSTEM == 'win':
        env.AppendUnique(CCFLAGS=['/O2',
                                  '/Ob2',
                                  '/MD',
                                  '/GR',
                                  '/EHsc',
                                  '/Gy',
                                  '/GF',
                                  '/GA'],
                         CPPDEFINES=['WIN32',
                                     'UNICODE'])
        env.PrependUnique(CPPPATH=['$PREFIX\include'])
        env.PrependUnique(LIBPATH=['$PREFIX\lib',
                                   '$PREFIX\..\libs'])
      else:
        env.PrependUnique(CPPPATH=['$PREFIX/include'],
                          LIBPATH=['$PREFIX/lib'],
                          CFLAGS=["-x", "c", "-std=c11"],
                          CXXFLAGS=["-x", "c++", "-std=c++11"])
        if ARCH == '32':
          env.AppendUnique(CCFLAGS=['-m32'])
        if SYSTEM == 'osx':
          env.AppendUnique(CCFLAGS=['-ferror-limit=0'],
                           CXXFLAGS=['-stdlib=libc++'])
        else:
          env.AppendUnique(CCFLAGS=['-fmax-errors=0',
                                    '-Wl,--no-undefined',
                                    '-fvisibility=hidden'],
                           CPPDEFINES=['_GLIBCXX_USE_CXX11_ABI=1'])

def exists(env):
    return 1
 <REPLACE_END> <|endoftext|> from distutils.version import StrictVersion
from distutils.msvccompiler import get_build_version
from sys import maxsize
from SCons.Script import AddOption, GetOption
from path import path
import subprocess

def generate(env):
    """Add Builders and construction variables to the Environment."""
    if not 'conda' in env['TOOLS'][:-1]:
      env.Tool('system')
      SYSTEM = env['SYSTEM']

      def Conda(sources=[], channels=['statiskit', 'conda-forge']):
        if len(sources) == 0:
            if SYSTEM == 'win':
                sources = [recipe for recipe in path(env.Dir('.').srcnode().abspath).walkdirs() if (recipe/'meta.yaml').exists() and (recipe/'bld.bat').exists()]
            else:
                sources = [recipe for recipe in path(env.Dir('.').srcnode().abspath).walkdirs() if (recipe/'meta.yaml').exists() and (recipe/'build.sh').exists()]
            for source in sources
        targets = []
      if SYSTEM == 'win':
        env['SHLIBSUFFIX'] = '.pyd'
        env['TARGET_ARCH'] = 'x86_64' if ARCH == '64' else 'x86'
        AddOption('--msvc-version',
                      dest    = 'msvc-version',
                      type    = 'string',
                      nargs   = 1,
                      action  = 'store',
                      help    = 'MSVC version',
                      default = str(get_build_version()))
        env['MSVC_VERSION'] = GetOption('msvc-version')
      env.Tool('default')
      env.Tool('prefix')
      if SYSTEM == 'win':
        env.AppendUnique(CCFLAGS=['/O2',
                                  '/Ob2',
                                  '/MD',
                                  '/GR',
                                  '/EHsc',
                                  '/Gy',
                                  '/GF',
                                  '/GA'],
                         CPPDEFINES=['WIN32',
                                     'UNICODE'])
        env.PrependUnique(CPPPATH=['$PREFIX\include'])
        env.PrependUnique(LIBPATH=['$PREFIX\lib',
                                   '$PREFIX\..\libs'])
      else:
        env.PrependUnique(CPPPATH=['$PREFIX/include'],
                          LIBPATH=['$PREFIX/lib'],
                          CFLAGS=["-x", "c", "-std=c11"],
                          CXXFLAGS=["-x", "c++", "-std=c++11"])
        if ARCH == '32':
          env.AppendUnique(CCFLAGS=['-m32'])
        if SYSTEM == 'osx':
          env.AppendUnique(CCFLAGS=['-ferror-limit=0'],
                           CXXFLAGS=['-stdlib=libc++'])
        else:
          env.AppendUnique(CCFLAGS=['-fmax-errors=0',
                                    '-Wl,--no-undefined',
                                    '-fvisibility=hidden'],
                           CPPDEFINES=['_GLIBCXX_USE_CXX11_ABI=1'])

def exists(env):
    return 1

Prompt: Add Conda Tool for SCons


# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-11 08:38
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('rtei', '0002_auto_20190109_1413'),
    ]

    operations = [
        migrations.AddField(
            model_name='rteidocument',
            name='file_size',
            field=models.PositiveIntegerField(editable=False, null=True),
        ),
    ]

Add rteidocument file size migration

Add rteidocument file size migration

(apply 3rd)

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-11 08:38
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('rtei', '0002_auto_20190109_1413'),
    ]

    operations = [
        migrations.AddField(
            model_name='rteidocument',
            name='file_size',
            field=models.PositiveIntegerField(editable=False, null=True),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-11 08:38
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('rtei', '0002_auto_20190109_1413'),
    ]

    operations = [
        migrations.AddField(
            model_name='rteidocument',
            name='file_size',
            field=models.PositiveIntegerField(editable=False, null=True),
        ),
    ]

Prompt:
Add rteidocument file size migration

(apply 3rd)


""" Testing gitwash dumper
"""

from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call

from nose.tools import assert_true, assert_equal, assert_raises

_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None

def setup():
    global TMPDIR
    TMPDIR = mkdtemp()

def teardown():
    shutil.rmtree(TMPDIR)

def test_dumper():
    call([EXE_PTH,
          TMPDIR,
          'my_project'])

TEST - setup teardown for test

TEST - setup teardown for test

Response:
<REPLACE_OLD> assert_raises

def <REPLACE_NEW> assert_raises

_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None

def setup():
    global TMPDIR
    TMPDIR = mkdtemp()

def teardown():
    shutil.rmtree(TMPDIR)

def <REPLACE_END> <REPLACE_OLD> downpath, _ = psplit(dirname(__file__))
    exe_pth = pjoin(downpath, 'gitwash_dumper.py')
    tmpdir = mkdtemp()
    try:
        call([exe_pth,
 <REPLACE_NEW> call([EXE_PTH,
 <REPLACE_END> <REPLACE_OLD>     tmpdir,
 <REPLACE_NEW> TMPDIR,
 <REPLACE_END> <REPLACE_OLD>     'my_project'])
    finally:
        shutil.rmtree(tmpdir)

 <REPLACE_NEW> 'my_project'])

 <REPLACE_END> <|endoftext|> """ Testing gitwash dumper
"""

from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call

from nose.tools import assert_true, assert_equal, assert_raises

_downpath, _ = psplit(dirname(__file__))
EXE_PTH = pjoin(_downpath, 'gitwash_dumper.py')
TMPDIR = None

def setup():
    global TMPDIR
    TMPDIR = mkdtemp()

def teardown():
    shutil.rmtree(TMPDIR)

def test_dumper():
    call([EXE_PTH,
          TMPDIR,
          'my_project'])

Prompt:
TEST - setup teardown for test

""" Testing gitwash dumper
"""

from os.path import join as pjoin, dirname, split as psplit
import shutil
from tempfile import mkdtemp
from subprocess import call

from nose.tools import assert_true, assert_equal, assert_raises

def test_dumper():
    downpath, _ = psplit(dirname(__file__))
    exe_pth = pjoin(downpath, 'gitwash_dumper.py')
    tmpdir = mkdtemp()
    try:
        call([exe_pth,
              tmpdir,
              'my_project'])
    finally:
        shutil.rmtree(tmpdir)


class AddResponseHeader:
    def process_response(self, req, resp, resource):
        resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
        resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
        resp.set_header('Access-Control-Allow-Headers', 'Content-Type')

components = [AddResponseHeader()]

Fix API access control headers

Fix API access control headers

Response:
<REPLACE_OLD> 'http://localhost:8000')

components <REPLACE_NEW> 'http://localhost:8000')
        resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
        resp.set_header('Access-Control-Allow-Headers', 'Content-Type')

components <REPLACE_END> <|endoftext|> class AddResponseHeader:
    def process_response(self, req, resp, resource):
        resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
        resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
        resp.set_header('Access-Control-Allow-Headers', 'Content-Type')

components = [AddResponseHeader()]

Prompt:
Fix API access control headers

class AddResponseHeader:
    def process_response(self, req, resp, resource):
        resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')

components = [AddResponseHeader()]


import os
from datetime import datetime

class Result:
    def __init__(self, directory):
        date = datetime.fromtimestamp(time())
        name = '%d-%d-%d_%d-%d-%d' % (datetime.year,
                                      datetime.month,
                                      datetime.day,
                                      datetime.hour,
                                      datetime.minute,
                                      datetime.second)
        self.file = File(directory, name)

class File:
    def __init__(self, directory, name):
        if not os.path.exists(directory):
            os.makedirs(directory)
        self.path = os.path.join(directory, name)
        if not os.path.exists(self.path):
            open(self.path, 'a').close()

    def write_line(self, text):
        stream = open(self.path, 'w')
        stream.write('%s\n' % text)
        stream.close()

Create Result class with file

Create Result class with file

Response:
<REPLACE_OLD>  <REPLACE_NEW> import os
from datetime import datetime

class Result:
    def __init__(self, directory):
        date = datetime.fromtimestamp(time())
        name = '%d-%d-%d_%d-%d-%d' % (datetime.year,
                                      datetime.month,
                                      datetime.day,
                                      datetime.hour,
                                      datetime.minute,
                                      datetime.second)
        self.file = File(directory, name)

class File:
    def __init__(self, directory, name):
        if not os.path.exists(directory):
            os.makedirs(directory)
        self.path = os.path.join(directory, name)
        if not os.path.exists(self.path):
            open(self.path, 'a').close()

    def write_line(self, text):
        stream = open(self.path, 'w')
        stream.write('%s\n' % text)
        stream.close()
 <REPLACE_END> <|endoftext|> import os
from datetime import datetime

class Result:
    def __init__(self, directory):
        date = datetime.fromtimestamp(time())
        name = '%d-%d-%d_%d-%d-%d' % (datetime.year,
                                      datetime.month,
                                      datetime.day,
                                      datetime.hour,
                                      datetime.minute,
                                      datetime.second)
        self.file = File(directory, name)

class File:
    def __init__(self, directory, name):
        if not os.path.exists(directory):
            os.makedirs(directory)
        self.path = os.path.join(directory, name)
        if not os.path.exists(self.path):
            open(self.path, 'a').close()

    def write_line(self, text):
        stream = open(self.path, 'w')
        stream.write('%s\n' % text)
        stream.close()

Prompt: Create Result class with file


import random
class Die(object):
    def __init__(self, sides = 6):
        self.sides = sides
        self.held = False
        self.die_face = 1
    def change_held(self, held):
        self.held = held
    def roll_die(self):
        if (self.held == False):
            self.die_face = random.randint(1, self.sides)
        else:
            pass
    def get_die_face(self):
        return self.die_face

class DiceBag(object):
    def __init__(self):
        self.dice = []
        self.dice_roll = []
    def add_die_obj(self, die_obj):
        self.dice.append(die_obj)
    def remove_die(self, die_obj):
        self.dice.remove(die_obj)
    def remove_die_index(self, index):
        del self.dice[index]
    def add_die_notation(self, standard_die_notation):
        lst_notation = standard_die_notation.split("d")
        for i in int(lst_notation[0]):
            die1 = Die(int(lst_notation[1]))
            self.dice.append(die1)
    def roll_all(self):
        for obj in self.dice:
            obj.roll_die()
            self.dice_roll.append(obj.get_die_face())
    def get_dice_roll(self):
        return self.dice_roll

Add get dice roll function

Add get dice roll function

Response:
<INSERT>    def get_dice_roll(self):
        return self.dice_roll
 <INSERT_END> <|endoftext|> import random
class Die(object):
    def __init__(self, sides = 6):
        self.sides = sides
        self.held = False
        self.die_face = 1
    def change_held(self, held):
        self.held = held
    def roll_die(self):
        if (self.held == False):
            self.die_face = random.randint(1, self.sides)
        else:
            pass
    def get_die_face(self):
        return self.die_face

class DiceBag(object):
    def __init__(self):
        self.dice = []
        self.dice_roll = []
    def add_die_obj(self, die_obj):
        self.dice.append(die_obj)
    def remove_die(self, die_obj):
        self.dice.remove(die_obj)
    def remove_die_index(self, index):
        del self.dice[index]
    def add_die_notation(self, standard_die_notation):
        lst_notation = standard_die_notation.split("d")
        for i in int(lst_notation[0]):
            die1 = Die(int(lst_notation[1]))
            self.dice.append(die1)
    def roll_all(self):
        for obj in self.dice:
            obj.roll_die()
            self.dice_roll.append(obj.get_die_face())
    def get_dice_roll(self):
        return self.dice_roll

Prompt:
Add get dice roll function

import random
class Die(object):
    def __init__(self, sides = 6):
        self.sides = sides
        self.held = False
        self.die_face = 1
    def change_held(self, held):
        self.held = held
    def roll_die(self):
        if (self.held == False):
            self.die_face = random.randint(1, self.sides)
        else:
            pass
    def get_die_face(self):
        return self.die_face

class DiceBag(object):
    def __init__(self):
        self.dice = []
        self.dice_roll = []
    def add_die_obj(self, die_obj):
        self.dice.append(die_obj)
    def remove_die(self, die_obj):
        self.dice.remove(die_obj)
    def remove_die_index(self, index):
        del self.dice[index]
    def add_die_notation(self, standard_die_notation):
        lst_notation = standard_die_notation.split("d")
        for i in int(lst_notation[0]):
            die1 = Die(int(lst_notation[1]))
            self.dice.append(die1)
    def roll_all(self):
        for obj in self.dice:
            obj.roll_die()
            self.dice_roll.append(obj.get_die_face())


from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView

from oidc_provider.models import UserConsent, Client

@login_required
def list_consents(request):
    # if a revoke request was done, process it
    revoke = request.POST.get('revoke', None)
    if revoke is not None:
        consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke)
        if consent:
            revoked_client = consent[0].client
            consent[0].delete()
            messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name))
        else:
            client = Client.objects.filter(client_id=revoke)
            if client:
                messages.error(request, "You have no consent for client \"{}\".".format(client[0].name))
            else:
                messages.error(request, "Unknown client.")
    # render the result
    consents = UserConsent.objects.filter(user=request.user)
    return render(request, 'list_consents.html', {
        'consents': consents
    })

class ProfileView(LoginRequiredMixin, TemplateView):
    template_name = 'profile.html'

Response:
<REPLACE_OLD> ProfileView(TemplateView, LoginRequiredMixin):
 <REPLACE_NEW> ProfileView(LoginRequiredMixin, TemplateView):
 <REPLACE_END> <|endoftext|> from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView

from oidc_provider.models import UserConsent, Client

@login_required
def list_consents(request):
    # if a revoke request was done, process it
    revoke = request.POST.get('revoke', None)
    if revoke is not None:
        consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke)
        if consent:
            revoked_client = consent[0].client
            consent[0].delete()
            messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name))
        else:
            client = Client.objects.filter(client_id=revoke)
            if client:
                messages.error(request, "You have no consent for client \"{}\".".format(client[0].name))
            else:
                messages.error(request, "Unknown client.")
    # render the result
    consents = UserConsent.objects.filter(user=request.user)
    return render(request, 'list_consents.html', {
        'consents': consents
    })

class ProfileView(LoginRequiredMixin, TemplateView):
    template_name = 'profile.html'

Prompt:
Fix access restriction to /accounts/profile/

LoginRequiredMixin needs to come first for it to be applied. Otherwise,
/accounts/profile/ is accessible even when the user is not
authenticated.

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView

from oidc_provider.models import UserConsent, Client

@login_required
def list_consents(request):
    # if a revoke request was done, process it
    revoke = request.POST.get('revoke', None)
    if revoke is not None:
        consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke)
        if consent:
            revoked_client = consent[0].client
            consent[0].delete()
            messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name))
        else:
            client = Client.objects.filter(client_id=revoke)
            if client:
                messages.error(request, "You have no consent for client \"{}\".".format(client[0].name))
            else:
                messages.error(request, "Unknown client.")
    # render the result
    consents = UserConsent.objects.filter(user=request.user)
    return render(request, 'list_consents.html', {
        'consents': consents
    })

class ProfileView(TemplateView, LoginRequiredMixin):
    template_name = 'profile.html'


from bst import BinarySearchTree

nodes = [5, 4, 8, 3, 43, 22, 7, 74, 2]

def test_insert_nodes():
    """size of tree equal to number of values inserted"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.size() == 9

def test_contains_node():
    """expected nodes in tree"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.contains(74)
    assert b.contains(2)
    assert b.contains(5)
    assert b.contains(43)
    assert not b.contains(103)

def test_balance():
    """balance updated when node added"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.balance() == 0
    b.insert(90)
    assert b.balance() == -1

def test_depth():
    """depth updated as nodes added"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.depth() == 4
    b.insert(90)
    assert b.depth() == 5

def test_size():
    """size on empty and when populated"""
    b = BinarySearchTree()
    assert b.size() == 0
    for n in nodes:
        b.insert(n)
    assert b.size() == 9

def test_root():
    """check tree's root and child nodes"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.root.val == 5
    assert b.root.left.val == 4
    assert b.root.right.val == 8

Add tests for binary search tree

Add tests for binary search tree

Response:
<REPLACE_OLD>  <REPLACE_NEW> from bst import BinarySearchTree

nodes = [5, 4, 8, 3, 43, 22, 7, 74, 2]

def test_insert_nodes():
    """size of tree equal to number of values inserted"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.size() == 9

def test_contains_node():
    """expected nodes in tree"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.contains(74)
    assert b.contains(2)
    assert b.contains(5)
    assert b.contains(43)
    assert not b.contains(103)

def test_balance():
    """balance updated when node added"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.balance() == 0
    b.insert(90)
    assert b.balance() == -1

def test_depth():
    """depth updated as nodes added"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.depth() == 4
    b.insert(90)
    assert b.depth() == 5

def test_size():
    """size on empty and when populated"""
    b = BinarySearchTree()
    assert b.size() == 0
    for n in nodes:
        b.insert(n)
    assert b.size() == 9

def test_root():
    """check tree's root and child nodes"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.root.val == 5
    assert b.root.left.val == 4
    assert b.root.right.val == 8
 <REPLACE_END> <|endoftext|> from bst import BinarySearchTree

nodes = [5, 4, 8, 3, 43, 22, 7, 74, 2]

def test_insert_nodes():
    """size of tree equal to number of values inserted"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.size() == 9

def test_contains_node():
    """expected nodes in tree"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.contains(74)
    assert b.contains(2)
    assert b.contains(5)
    assert b.contains(43)
    assert not b.contains(103)

def test_balance():
    """balance updated when node added"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.balance() == 0
    b.insert(90)
    assert b.balance() == -1

def test_depth():
    """depth updated as nodes added"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.depth() == 4
    b.insert(90)
    assert b.depth() == 5

def test_size():
    """size on empty and when populated"""
    b = BinarySearchTree()
    assert b.size() == 0
    for n in nodes:
        b.insert(n)
    assert b.size() == 9

def test_root():
    """check tree's root and child nodes"""
    b = BinarySearchTree()
    for n in nodes:
        b.insert(n)
    assert b.root.val == 5
    assert b.root.left.val == 4
    assert b.root.right.val == 8

Prompt: Add tests for binary search tree


from logger import logger
from seriesly import Seriesly

from perfrunner.settings import StatsSettings

def main():
    s = Seriesly(StatsSettings.SERIESLY)
    for db in s.list_dbs():
        logger.info('Compacting {}'.format(db))
        result = s[db].compact()
        logger.info('Compaction finished: {}'.format(result))

if __name__ == '__main__':
    main()

Update reference to Seriesly hostname

Response:
<REPLACE_OLD> Seriesly(StatsSettings.SERIESLY['host'])
 <REPLACE_NEW> Seriesly(StatsSettings.SERIESLY)
 <REPLACE_END> <|endoftext|> from logger import logger
from seriesly import Seriesly

from perfrunner.settings import StatsSettings

def main():
    s = Seriesly(StatsSettings.SERIESLY)
    for db in s.list_dbs():
        logger.info('Compacting {}'.format(db))
        result = s[db].compact()
        logger.info('Compaction finished: {}'.format(result))

if __name__ == '__main__':
    main()

Prompt:
Update reference to Seriesly hostname

Change-Id: I03eb6b3551e21d6987f15ec236c40546b312e663
Reviewed-on: http://review.couchbase.org/71447
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>

from logger import logger
from seriesly import Seriesly

from perfrunner.settings import StatsSettings

def main():
    s = Seriesly(StatsSettings.SERIESLY['host'])
    for db in s.list_dbs():
        logger.info('Compacting {}'.format(db))
        result = s[db].compact()
        logger.info('Compaction finished: {}'.format(result))

if __name__ == '__main__':
    main()


from logging import getLogger
from pkg_resources import get_distribution

from django import apps

log = getLogger(__name__)

class AppConfig(apps.AppConfig):
    name = "axes"
    initialized = False

    @classmethod
    def initialize(cls):
        """
        Initialize Axes logging and show version information.

        This method is re-entrant and can be called multiple times.
        It displays version information exactly once at application startup.
        """

        if cls.initialized:
            return
        cls.initialized = True

        # Only import settings, checks, and signals one time after Django has been initialized
        from axes.conf import settings  # noqa
        from axes import checks, signals  # noqa

        # Skip startup log messages if Axes is not set to verbose
        if settings.AXES_VERBOSE:
            log.info("AXES: BEGIN LOG")
            log.info(
                "AXES: Using django-axes version %s",
                get_distribution("django-axes").version,
            )

            if settings.AXES_ONLY_USER_FAILURES:
                log.info("AXES: blocking by username only.")
            elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
                log.info("AXES: blocking by combination of username and IP.")
            elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
                log.info("AXES: blocking by username or IP.")
            else:
                log.info("AXES: blocking by IP only.")

    def ready(self):
        self.initialize()

Add QA skip for import ordering

Add QA skip for import ordering

Response:
<REPLACE_OLD> settings
 <REPLACE_NEW> settings  # noqa
 <REPLACE_END> <|endoftext|> from logging import getLogger
from pkg_resources import get_distribution

from django import apps

log = getLogger(__name__)

class AppConfig(apps.AppConfig):
    name = "axes"
    initialized = False

    @classmethod
    def initialize(cls):
        """
        Initialize Axes logging and show version information.

        This method is re-entrant and can be called multiple times.
        It displays version information exactly once at application startup.
        """

        if cls.initialized:
            return
        cls.initialized = True

        # Only import settings, checks, and signals one time after Django has been initialized
        from axes.conf import settings  # noqa
        from axes import checks, signals  # noqa

        # Skip startup log messages if Axes is not set to verbose
        if settings.AXES_VERBOSE:
            log.info("AXES: BEGIN LOG")
            log.info(
                "AXES: Using django-axes version %s",
                get_distribution("django-axes").version,
            )

            if settings.AXES_ONLY_USER_FAILURES:
                log.info("AXES: blocking by username only.")
            elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
                log.info("AXES: blocking by combination of username and IP.")
            elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
                log.info("AXES: blocking by username or IP.")
            else:
                log.info("AXES: blocking by IP only.")

    def ready(self):
        self.initialize()

Prompt:
Add QA skip for import ordering
from logging import getLogger
from pkg_resources import get_distribution

from django import apps

log = getLogger(__name__)

class AppConfig(apps.AppConfig):
    name = "axes"
    initialized = False

    @classmethod
    def initialize(cls):
        """
        Initialize Axes logging and show version information.

        This method is re-entrant and can be called multiple times.
        It displays version information exactly once at application startup.
        """

        if cls.initialized:
            return
        cls.initialized = True

        # Only import settings, checks, and signals one time after Django has been initialized
        from axes.conf import settings
        from axes import checks, signals  # noqa

        # Skip startup log messages if Axes is not set to verbose
        if settings.AXES_VERBOSE:
            log.info("AXES: BEGIN LOG")
            log.info(
                "AXES: Using django-axes version %s",
                get_distribution("django-axes").version,
            )

            if settings.AXES_ONLY_USER_FAILURES:
                log.info("AXES: blocking by username only.")
            elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
                log.info("AXES: blocking by combination of username and IP.")
            elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
                log.info("AXES: blocking by username or IP.")
            else:
                log.info("AXES: blocking by IP only.")

    def ready(self):
        self.initialize()


import subprocess
import datetime
import pytz
import urllib2
from ingest_from_rucsoundings import RAOB
import psycopg2

POSTGIS = psycopg2.connect(database='postgis', host='iemdb')

def conv( raw):
    if float(raw) < -9998:
        return None
    return float(raw)

sts = datetime.datetime(1946,1,1)
ets = datetime.datetime(1990,1,1)
interval = datetime.timedelta(days=1)
now = sts
while now < ets:
    print now
    uri = now.strftime("http://mtarchive.geol.iastate.edu/%Y/%m/%d/gempak/upperair/%Y%m%d_upa.gem")
    try:
        data = urllib2.urlopen(uri).read()
        o = open('data.gem', 'wb')
        o.write(data)
        o.close()
    except Exception, exp:
        print exp
        now += interval
        continue

    o = open('fn', 'w')
    o.write("""
SNFILE=data.gem
AREA=DSET
DATTIM=ALL
SNPARM=TMPC;DWPC;HGHT;DRCT;SKNT
LEVELS=ALL
 VCOORD   = PRES
 OUTPUT   = T
 MRGDAT   = YES
run

exit
""")
    o.close()
    p = subprocess.Popen("snlist < fn", stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, shell=True)
    data = p.stdout.read()
    myraob = None
    for line in data.split("\n"):
        if line.strip()[:4] == 'STID':

            if myraob is not None:
                print str(myraob)
                txn = POSTGIS.cursor()
                myraob.database_save(txn)
                txn.close()
                POSTGIS.commit()
                myraob = None
            tokens = line.strip().split()
            myraob = RAOB()
            myraob.station = tokens[2]
            valid = datetime.datetime.strptime("19"+tokens[-1], '%Y%m%d/%H%M')
            myraob.valid = valid.replace(tzinfo=pytz.timezone("UTC"))
        if line.find(".") > 0 and line.find("=") == -1 and line.find("PRES") == -1:
            tokens = line.strip().split()
            if len(tokens) < 6:
                continue
            myraob.profile.append({'levelcode': None,
                                'pressure': float(tokens[0]),
                                'height': conv(float(tokens[3])),
                                'tmpc': conv(float(tokens[1])),
                                'dwpc': conv(float(tokens[2])),
                                'drct': conv(float(tokens[4])),
                                'smps': myraob.conv_speed(tokens[5]),
                                'ts': None,
                                'bearing': None,
                                'range': None
                                })

    now += interval

Add script to process mtarchive's sounding archive

Response:
<REPLACE_OLD>  <REPLACE_NEW> import subprocess
import datetime
import pytz
import urllib2
from ingest_from_rucsoundings import RAOB
import psycopg2

POSTGIS = psycopg2.connect(database='postgis', host='iemdb')

def conv( raw):
    if float(raw) < -9998:
        return None
    return float(raw)

sts = datetime.datetime(1946,1,1)
ets = datetime.datetime(1990,1,1)
interval = datetime.timedelta(days=1)
now = sts
while now < ets:
    print now
    uri = now.strftime("http://mtarchive.geol.iastate.edu/%Y/%m/%d/gempak/upperair/%Y%m%d_upa.gem")
    try:
        data = urllib2.urlopen(uri).read()
        o = open('data.gem', 'wb')
        o.write(data)
        o.close()
    except Exception, exp:
        print exp
        now += interval
        continue

    o = open('fn', 'w')
    o.write("""
SNFILE=data.gem
AREA=DSET
DATTIM=ALL
SNPARM=TMPC;DWPC;HGHT;DRCT;SKNT
LEVELS=ALL
 VCOORD   = PRES
 OUTPUT   = T
 MRGDAT   = YES
run

exit
""")
    o.close()
    p = subprocess.Popen("snlist < fn", stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, shell=True)
    data = p.stdout.read()
    myraob = None
    for line in data.split("\n"):
        if line.strip()[:4] == 'STID':

            if myraob is not None:
                print str(myraob)
                txn = POSTGIS.cursor()
                myraob.database_save(txn)
                txn.close()
                POSTGIS.commit()
                myraob = None
            tokens = line.strip().split()
            myraob = RAOB()
            myraob.station = tokens[2]
            valid = datetime.datetime.strptime("19"+tokens[-1], '%Y%m%d/%H%M')
            myraob.valid = valid.replace(tzinfo=pytz.timezone("UTC"))
        if line.find(".") > 0 and line.find("=") == -1 and line.find("PRES") == -1:
            tokens = line.strip().split()
            if len(tokens) < 6:
                continue
            myraob.profile.append({'levelcode': None,
                                'pressure': float(tokens[0]),
                                'height': conv(float(tokens[3])),
                                'tmpc': conv(float(tokens[1])),
                                'dwpc': conv(float(tokens[2])),
                                'drct': conv(float(tokens[4])),
                                'smps': myraob.conv_speed(tokens[5]),
                                'ts': None,
                                'bearing': None,
                                'range': None
                                })

    now += interval

 <REPLACE_END> <|endoftext|> import subprocess
import datetime
import pytz
import urllib2
from ingest_from_rucsoundings import RAOB
import psycopg2

POSTGIS = psycopg2.connect(database='postgis', host='iemdb')

def conv( raw):
    if float(raw) < -9998:
        return None
    return float(raw)

sts = datetime.datetime(1946,1,1)
ets = datetime.datetime(1990,1,1)
interval = datetime.timedelta(days=1)
now = sts
while now < ets:
    print now
    uri = now.strftime("http://mtarchive.geol.iastate.edu/%Y/%m/%d/gempak/upperair/%Y%m%d_upa.gem")
    try:
        data = urllib2.urlopen(uri).read()
        o = open('data.gem', 'wb')
        o.write(data)
        o.close()
    except Exception, exp:
        print exp
        now += interval
        continue

    o = open('fn', 'w')
    o.write("""
SNFILE=data.gem
AREA=DSET
DATTIM=ALL
SNPARM=TMPC;DWPC;HGHT;DRCT;SKNT
LEVELS=ALL
 VCOORD   = PRES
 OUTPUT   = T
 MRGDAT   = YES
run

exit
""")
    o.close()
    p = subprocess.Popen("snlist < fn", stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, shell=True)
    data = p.stdout.read()
    myraob = None
    for line in data.split("\n"):
        if line.strip()[:4] == 'STID':

            if myraob is not None:
                print str(myraob)
                txn = POSTGIS.cursor()
                myraob.database_save(txn)
                txn.close()
                POSTGIS.commit()
                myraob = None
            tokens = line.strip().split()
            myraob = RAOB()
            myraob.station = tokens[2]
            valid = datetime.datetime.strptime("19"+tokens[-1], '%Y%m%d/%H%M')
            myraob.valid = valid.replace(tzinfo=pytz.timezone("UTC"))
        if line.find(".") > 0 and line.find("=") == -1 and line.find("PRES") == -1:
            tokens = line.strip().split()
            if len(tokens) < 6:
                continue
            myraob.profile.append({'levelcode': None,
                                'pressure': float(tokens[0]),
                                'height': conv(float(tokens[3])),
                                'tmpc': conv(float(tokens[1])),
                                'dwpc': conv(float(tokens[2])),
                                'drct': conv(float(tokens[4])),
                                'smps': myraob.conv_speed(tokens[5]),
                                'ts': None,
                                'bearing': None,
                                'range': None
                                })

    now += interval

Prompt: Add script to process mtarchive's sounding archive


import os, shutil, tempfile
from bl.file import File
from bl.string import String

class Text(File):

    def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
        File.__init__(self, fn=fn, encoding=encoding, **args)
        if text is not None:
            self.text = text
        elif fn is not None and os.path.exists(fn):
            self.text = String(self.read().decode(encoding))
        else:
            self.text = String("")

    def write(self, fn=None, text=None, encoding='UTF-8', **args):
        try:
            data = (text or self.text or '').encode(encoding)
        except:
            data = (text or self.text or '').encode()
        File.write(self, fn=fn, data=data, **args)

Response:
<DELETE> data=None, <DELETE_END> <DELETE> if data is None:
            <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <|endoftext|>
import os, shutil, tempfile
from bl.file import File
from bl.string import String

class Text(File):

    def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
        File.__init__(self, fn=fn, encoding=encoding, **args)
        if text is not None:
            self.text = text
        elif fn is not None and os.path.exists(fn):
            self.text = String(self.read().decode(encoding))
        else:
            self.text = String("")

    def write(self, fn=None, text=None, encoding='UTF-8', **args):
        try:
            data = (text or self.text or '').encode(encoding)
        except:
            data = (text or self.text or '').encode()
        File.write(self, fn=fn, data=data, **args)

Prompt:
Revert "allow to write Text with raw data"

This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.

import os, shutil, tempfile
from bl.file import File
from bl.string import String

class Text(File):

    def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
        File.__init__(self, fn=fn, encoding=encoding, **args)
        if text is not None:
            self.text = text
        elif fn is not None and os.path.exists(fn):
            self.text = String(self.read().decode(encoding))
        else:
            self.text = String("")

    def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
        if data is None:
            try:
                data = (text or self.text or '').encode(encoding)
            except:
                data = (text or self.text or '').encode()
        File.write(self, fn=fn, data=data, **args)


# encoding: utf-8

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

from __future__ import print_function, unicode_literals

import pytest
from simplesqlite import set_log_level, set_logger

logbook = pytest.importorskip("logbook", minversion="0.12.3")

import logbook  # isort:skip

class Test_set_logger(object):
    @pytest.mark.parametrize(["value"], [[True], [False]])
    def test_smoke(self, value):
        set_logger(value)

class Test_set_log_level(object):
    @pytest.mark.parametrize(
        ["value"],
        [
            [logbook.CRITICAL],
            [logbook.ERROR],
            [logbook.WARNING],
            [logbook.NOTICE],
            [logbook.INFO],
            [logbook.DEBUG],
            [logbook.TRACE],
            [logbook.NOTSET],
        ],
    )
    def test_smoke(self, value):
        set_log_level(value)

    @pytest.mark.parametrize(
        ["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
    )
    def test_exception(self, value, expected):
        with pytest.raises(expected):
            set_log_level(value)

Update skip condition for tests

Update skip condition for tests

Response:
<REPLACE_OLD> minversion="1.1.0")

import <REPLACE_NEW> minversion="0.12.3")

import <REPLACE_END> <|endoftext|> # encoding: utf-8

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

from __future__ import print_function, unicode_literals

import pytest
from simplesqlite import set_log_level, set_logger

logbook = pytest.importorskip("logbook", minversion="0.12.3")

import logbook  # isort:skip

class Test_set_logger(object):
    @pytest.mark.parametrize(["value"], [[True], [False]])
    def test_smoke(self, value):
        set_logger(value)

class Test_set_log_level(object):
    @pytest.mark.parametrize(
        ["value"],
        [
            [logbook.CRITICAL],
            [logbook.ERROR],
            [logbook.WARNING],
            [logbook.NOTICE],
            [logbook.INFO],
            [logbook.DEBUG],
            [logbook.TRACE],
            [logbook.NOTSET],
        ],
    )
    def test_smoke(self, value):
        set_log_level(value)

    @pytest.mark.parametrize(
        ["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
    )
    def test_exception(self, value, expected):
        with pytest.raises(expected):
            set_log_level(value)

Prompt:
Update skip condition for tests

# encoding: utf-8

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

from __future__ import print_function, unicode_literals

import pytest
from simplesqlite import set_log_level, set_logger

logbook = pytest.importorskip("logbook", minversion="1.1.0")

import logbook  # isort:skip

class Test_set_logger(object):
    @pytest.mark.parametrize(["value"], [[True], [False]])
    def test_smoke(self, value):
        set_logger(value)

class Test_set_log_level(object):
    @pytest.mark.parametrize(
        ["value"],
        [
            [logbook.CRITICAL],
            [logbook.ERROR],
            [logbook.WARNING],
            [logbook.NOTICE],
            [logbook.INFO],
            [logbook.DEBUG],
            [logbook.TRACE],
            [logbook.NOTSET],
        ],
    )
    def test_smoke(self, value):
        set_log_level(value)

    @pytest.mark.parametrize(
        ["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
    )
    def test_exception(self, value, expected):
        with pytest.raises(expected):
            set_log_level(value)


# Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>

import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
    os.path.join(app.root_path, app.name + '.db'))

db = SQLAlchemy(app)
migrate = Migrate(app, db)

#class MyModel(db.Model):
#    id = db.Column(db.Integer, primary_key=True)
#    # Quickref:
#    # types: Integer, String(L), Text, DateTime, ForeignKey('table.col')
#    # keywords: primary_key, nullable, unique, default
#    # rels: db.relationship('OtherModel', backref=db.backref('mymodels'))
#
#
#    def __init__(self, ...):
#        pass
#
#
#    def __str__(self):
#        return self.name
#
#
#    def __repr__(self):
#        return '<{} {!r}>'.format(self.__class__.__name__, self.id)

Response:
<REPLACE_OLD> flask.ext.sqlalchemy <REPLACE_NEW> flask_sqlalchemy <REPLACE_END> <INSERT> flask_migrate import Migrate
from <INSERT_END> <REPLACE_OLD> SQLAlchemy(app)

#class <REPLACE_NEW> SQLAlchemy(app)
migrate = Migrate(app, db)

#class <REPLACE_END> <|endoftext|> # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>

import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
    os.path.join(app.root_path, app.name + '.db'))

db = SQLAlchemy(app)
migrate = Migrate(app, db)

#class MyModel(db.Model):
#    id = db.Column(db.Integer, primary_key=True)
#    # Quickref:
#    # types: Integer, String(L), Text, DateTime, ForeignKey('table.col')
#    # keywords: primary_key, nullable, unique, default
#    # rels: db.relationship('OtherModel', backref=db.backref('mymodels'))
#
#
#    def __init__(self, ...):
#        pass
#
#
#    def __str__(self):
#        return self.name
#
#
#    def __repr__(self):
#        return '<{} {!r}>'.format(self.__class__.__name__, self.id)

Prompt:
Use newer package import syntax for Flask

# Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>

import os, os.path
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from {{PROJECTNAME}} import app

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
    os.path.join(app.root_path, app.name + '.db'))

db = SQLAlchemy(app)

#class MyModel(db.Model):
#    id = db.Column(db.Integer, primary_key=True)
#    # Quickref:
#    # types: Integer, String(L), Text, DateTime, ForeignKey('table.col')
#    # keywords: primary_key, nullable, unique, default
#    # rels: db.relationship('OtherModel', backref=db.backref('mymodels'))
#
#
#    def __init__(self, ...):
#        pass
#
#
#    def __str__(self):
#        return self.name
#
#
#    def __repr__(self):
#        return '<{} {!r}>'.format(self.__class__.__name__, self.id)


# There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
                'WebOb>=1.2b3',
                ]

import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()

requires = [
    'pyramid',
    'SQLAlchemy',
    'transaction',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'zope.sqlalchemy',
    'waitress',
    'py-bcrypt',
    ]

setup(name='uptrack',
      version='0.0',
      description='uptrack',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='Mathieu Bridon',
      author_email='mathieu.bridon@network-box.com',
      url='',
      license='AGPLv3+',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='uptrack',
      install_requires=requires,
      entry_points="""\
      [paste.app_factory]
      main = uptrack:main
      [console_scripts]
      uptrack-initdb = uptrack.scripts.initializedb:main
      """,
      )

Rename the DB initialization script

Response:
<REPLACE_OLD> initialize_uptrack_db <REPLACE_NEW> uptrack-initdb <REPLACE_END> <|endoftext|> # There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
                'WebOb>=1.2b3',
                ]

import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()

requires = [
    'pyramid',
    'SQLAlchemy',
    'transaction',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'zope.sqlalchemy',
    'waitress',
    'py-bcrypt',
    ]

setup(name='uptrack',
      version='0.0',
      description='uptrack',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='Mathieu Bridon',
      author_email='mathieu.bridon@network-box.com',
      url='',
      license='AGPLv3+',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='uptrack',
      install_requires=requires,
      entry_points="""\
      [paste.app_factory]
      main = uptrack:main
      [console_scripts]
      uptrack-initdb = uptrack.scripts.initializedb:main
      """,
      )

Prompt:
scripts: Rename the DB initialization script

We'll have other scripts, prefixing them all by the app name will be
nicer to admins.

# There is a conflict with older versions on EL 6
__requires__ = ['PasteDeploy>=1.5.0',
                'WebOb>=1.2b3',
                ]

import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
CHANGES = open(os.path.join(here, 'CHANGES')).read()

requires = [
    'pyramid',
    'SQLAlchemy',
    'transaction',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'zope.sqlalchemy',
    'waitress',
    'py-bcrypt',
    ]

setup(name='uptrack',
      version='0.0',
      description='uptrack',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='Mathieu Bridon',
      author_email='mathieu.bridon@network-box.com',
      url='',
      license='AGPLv3+',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='uptrack',
      install_requires=requires,
      entry_points="""\
      [paste.app_factory]
      main = uptrack:main
      [console_scripts]
      initialize_uptrack_db = uptrack.scripts.initializedb:main
      """,
      )