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

from telemetry.page import test_expectations

# Valid expectation conditions are:
#
# Operating systems:
#     win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
#     linux, chromeos, android
#
# GPU vendors:
#     amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
#     vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.

class PixelExpectations(test_expectations.TestExpectations):
  def SetExpectations(self):
    # Sample Usage:
    # self.Fail('Pixel.Canvas2DRedBox',
    #     ['mac', 'amd', ('nvidia', 0x1234)], bug=123)

    pass

Response:
<DELETE> self.Fail('Pixel.Canvas2DRedBox', bug=371592)
    self.Fail('Pixel.CSS3DBlueBox', bug=371592)
    self.Fail('Pixel.WebGLGreenTriangle', bug=371592)

    <DELETE_END> <|endoftext|> # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.page import test_expectations

# Valid expectation conditions are:
#
# Operating systems:
#     win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
#     linux, chromeos, android
#
# GPU vendors:
#     amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
#     vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.

class PixelExpectations(test_expectations.TestExpectations):
  def SetExpectations(self):
    # Sample Usage:
    # self.Fail('Pixel.Canvas2DRedBox',
    #     ['mac', 'amd', ('nvidia', 0x1234)], bug=123)

    pass

Prompt:
Remove failing expectations for pixel tests.

R=kbr@chromium.org
BUG=252046, 371592
NOTRY=true

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

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270785 0039d316-1c4b-4281-b951-d872f2087c98

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

from telemetry.page import test_expectations

# Valid expectation conditions are:
#
# Operating systems:
#     win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
#     linux, chromeos, android
#
# GPU vendors:
#     amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
#     vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.

class PixelExpectations(test_expectations.TestExpectations):
  def SetExpectations(self):
    # Sample Usage:
    # self.Fail('Pixel.Canvas2DRedBox',
    #     ['mac', 'amd', ('nvidia', 0x1234)], bug=123)

    self.Fail('Pixel.Canvas2DRedBox', bug=371592)
    self.Fail('Pixel.CSS3DBlueBox', bug=371592)
    self.Fail('Pixel.WebGLGreenTriangle', bug=371592)

    pass


from jaeger_client.config import (
    DEFAULT_REPORTING_HOST,
    DEFAULT_REPORTING_PORT,
    DEFAULT_SAMPLING_PORT,
    Config,
)

from microcosm.api import binding, defaults, typed
from microcosm.config.types import boolean

SPAN_NAME = "span_name"

@binding("tracer")
@defaults(
    sample_type="ratelimiting",
    sample_param=typed(int, 10),
    sampling_port=typed(int, DEFAULT_SAMPLING_PORT),
    reporting_port=typed(int, DEFAULT_REPORTING_PORT),
    reporting_host=DEFAULT_REPORTING_HOST,
    logging_enabled=typed(boolean, False),
)
def configure_tracing(graph):
    """
    See https://www.jaegertracing.io/docs/1.12/sampling/ for more info about
    available sampling strategies.

    """
    config = Config(
        config={
            "sampler": {
                "type": graph.config.tracer.sample_type,
                "param": graph.config.tracer.sample_param,
            },
            "local_agent": {
                "sampling_port": graph.config.tracer.sampling_port,
                "reporting_port": graph.config.tracer.reporting_port,
                "reporting_host": graph.config.tracer.reporting_host,
            },
            "logging": graph.config.tracer.logging_enabled,
        },
        service_name=graph.metadata.name,
    )
    return config.initialize_tracer()

Disable jaeger logging by default

Disable jaeger logging by default

Response:
<REPLACE_OLD> typed

SPAN_NAME <REPLACE_NEW> typed
from microcosm.config.types import boolean

SPAN_NAME <REPLACE_END> <REPLACE_OLD> reporting_host=DEFAULT_REPORTING_HOST,
)
def <REPLACE_NEW> reporting_host=DEFAULT_REPORTING_HOST,
    logging_enabled=typed(boolean, False),
)
def <REPLACE_END> <REPLACE_OLD> True,
 <REPLACE_NEW> graph.config.tracer.logging_enabled,
 <REPLACE_END> <|endoftext|> from jaeger_client.config import (
    DEFAULT_REPORTING_HOST,
    DEFAULT_REPORTING_PORT,
    DEFAULT_SAMPLING_PORT,
    Config,
)

from microcosm.api import binding, defaults, typed
from microcosm.config.types import boolean

SPAN_NAME = "span_name"

@binding("tracer")
@defaults(
    sample_type="ratelimiting",
    sample_param=typed(int, 10),
    sampling_port=typed(int, DEFAULT_SAMPLING_PORT),
    reporting_port=typed(int, DEFAULT_REPORTING_PORT),
    reporting_host=DEFAULT_REPORTING_HOST,
    logging_enabled=typed(boolean, False),
)
def configure_tracing(graph):
    """
    See https://www.jaegertracing.io/docs/1.12/sampling/ for more info about
    available sampling strategies.

    """
    config = Config(
        config={
            "sampler": {
                "type": graph.config.tracer.sample_type,
                "param": graph.config.tracer.sample_param,
            },
            "local_agent": {
                "sampling_port": graph.config.tracer.sampling_port,
                "reporting_port": graph.config.tracer.reporting_port,
                "reporting_host": graph.config.tracer.reporting_host,
            },
            "logging": graph.config.tracer.logging_enabled,
        },
        service_name=graph.metadata.name,
    )
    return config.initialize_tracer()

Prompt:
Disable jaeger logging by default

from jaeger_client.config import (
    DEFAULT_REPORTING_HOST,
    DEFAULT_REPORTING_PORT,
    DEFAULT_SAMPLING_PORT,
    Config,
)

from microcosm.api import binding, defaults, typed

SPAN_NAME = "span_name"

@binding("tracer")
@defaults(
    sample_type="ratelimiting",
    sample_param=typed(int, 10),
    sampling_port=typed(int, DEFAULT_SAMPLING_PORT),
    reporting_port=typed(int, DEFAULT_REPORTING_PORT),
    reporting_host=DEFAULT_REPORTING_HOST,
)
def configure_tracing(graph):
    """
    See https://www.jaegertracing.io/docs/1.12/sampling/ for more info about
    available sampling strategies.

    """
    config = Config(
        config={
            "sampler": {
                "type": graph.config.tracer.sample_type,
                "param": graph.config.tracer.sample_param,
            },
            "local_agent": {
                "sampling_port": graph.config.tracer.sampling_port,
                "reporting_port": graph.config.tracer.reporting_port,
                "reporting_host": graph.config.tracer.reporting_host,
            },
            "logging": True,
        },
        service_name=graph.metadata.name,
    )
    return config.initialize_tracer()


from haystack.indexes import *
from haystack import site
from models import Article

class ArticleIndex(SearchIndex):
    name = CharField(model_attr='title')
    text = CharField(document=True, use_template=True)

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Article.objects.active()

site.register(Article, ArticleIndex)

Add search index file - currently search across Articles, extend to search across Categories?

Response:
<INSERT> from haystack.indexes import *
from haystack import site
from models import Article

class ArticleIndex(SearchIndex):
 <INSERT_END> <INSERT>   name = CharField(model_attr='title')
    text = CharField(document=True, use_template=True)

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Article.objects.active()

site.register(Article, ArticleIndex)

 <INSERT_END> <|endoftext|> from haystack.indexes import *
from haystack import site
from models import Article

class ArticleIndex(SearchIndex):
    name = CharField(model_attr='title')
    text = CharField(document=True, use_template=True)

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Article.objects.active()

site.register(Article, ArticleIndex)

Prompt: Add search index file - currently search across Articles, extend to search across Categories?


def includeme(config):
    config.add_route('test.new.routes', '/test/new/routes/{param:[a-z]{1,}}')
    config.add_route('blog.page', '/page/{page_slug}')

Use patterns with explicit length

Use patterns with explicit length

Response:
<REPLACE_OLD> '/test/new/routes/{param:[a-z]+}')
 <REPLACE_NEW> '/test/new/routes/{param:[a-z]{1,}}')
 <REPLACE_END> <|endoftext|> def includeme(config):
    config.add_route('test.new.routes', '/test/new/routes/{param:[a-z]{1,}}')
    config.add_route('blog.page', '/page/{page_slug}')

Prompt:
Use patterns with explicit length

def includeme(config):
    config.add_route('test.new.routes', '/test/new/routes/{param:[a-z]+}')
    config.add_route('blog.page', '/page/{page_slug}')


from cgi import parse_header
import json

from django.http import HttpResponse, Http404

RPC_MARKER = '_rpc'

class Resource(object):

    def __init__(self, request, *args, **kwargs):
        self.request = request
        self.args = args
        self.kwargs = kwargs

    @classmethod
    def as_view(cls):
        def view(request, *args, **kwargs):
            self = cls(request, *args, **kwargs)
            return self.dispatch(request)
        return view

    def dispatch(self, request):
        method = request.META['HTTP_X_RPC_ACTION']
        func = getattr(self, method, None)
        if not getattr(func, RPC_MARKER, True):
            raise Http404

        data = self.get_request_data(request)

        resp = self.execute(func, data)

        return HttpResponse(json.dumps(resp), content_type='application/json')

    def execute(self, handler, data):
        '''Helpful hook to ease wrapping the handler'''
        return handler(**data)

    def get_request_data(self, default=None):
        '''Retrieve data from request'''
        c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', ''))
        if c_type in ['application/json', 'text/json']:
            if not self.request.body:
                return default
            return self.loads(self.request.body)
        if self.request.method == 'GET':
            return self.request.GET
        return self.request.POST

def rpc(view):
    '''Mark a view as accessible via RPC'''
    setattr(view, '_rpc', True)
    return view

Response:
<REPLACE_OLD> func(data)

 <REPLACE_NEW> self.execute(func, data)

 <REPLACE_END> <INSERT>    def execute(self, handler, data):
        '''Helpful hook to ease wrapping the handler'''
        return handler(**data)

 <INSERT_END> <|endoftext|>
from cgi import parse_header
import json

from django.http import HttpResponse, Http404

RPC_MARKER = '_rpc'

class Resource(object):

    def __init__(self, request, *args, **kwargs):
        self.request = request
        self.args = args
        self.kwargs = kwargs

    @classmethod
    def as_view(cls):
        def view(request, *args, **kwargs):
            self = cls(request, *args, **kwargs)
            return self.dispatch(request)
        return view

    def dispatch(self, request):
        method = request.META['HTTP_X_RPC_ACTION']
        func = getattr(self, method, None)
        if not getattr(func, RPC_MARKER, True):
            raise Http404

        data = self.get_request_data(request)

        resp = self.execute(func, data)

        return HttpResponse(json.dumps(resp), content_type='application/json')

    def execute(self, handler, data):
        '''Helpful hook to ease wrapping the handler'''
        return handler(**data)

    def get_request_data(self, default=None):
        '''Retrieve data from request'''
        c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', ''))
        if c_type in ['application/json', 'text/json']:
            if not self.request.body:
                return default
            return self.loads(self.request.body)
        if self.request.method == 'GET':
            return self.request.GET
        return self.request.POST

def rpc(view):
    '''Mark a view as accessible via RPC'''
    setattr(view, '_rpc', True)
    return view

Prompt:
Add execute hook to allow wrapping handler calls

from cgi import parse_header
import json

from django.http import HttpResponse, Http404

RPC_MARKER = '_rpc'

class Resource(object):

    def __init__(self, request, *args, **kwargs):
        self.request = request
        self.args = args
        self.kwargs = kwargs

    @classmethod
    def as_view(cls):
        def view(request, *args, **kwargs):
            self = cls(request, *args, **kwargs)
            return self.dispatch(request)
        return view

    def dispatch(self, request):
        method = request.META['HTTP_X_RPC_ACTION']
        func = getattr(self, method, None)
        if not getattr(func, RPC_MARKER, True):
            raise Http404

        data = self.get_request_data(request)

        resp = func(data)

        return HttpResponse(json.dumps(resp), content_type='application/json')

    def get_request_data(self, default=None):
        '''Retrieve data from request'''
        c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', ''))
        if c_type in ['application/json', 'text/json']:
            if not self.request.body:
                return default
            return self.loads(self.request.body)
        if self.request.method == 'GET':
            return self.request.GET
        return self.request.POST

def rpc(view):
    '''Mark a view as accessible via RPC'''
    setattr(view, '_rpc', True)
    return view


# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

from django.contrib.gis.geos import GEOSGeometry

from django.conf import settings

from apps.modeling.mapshed.calcs import animal_energy_units

ANIMAL_KEYS = settings.GWLFE_CONFIG['AnimalKeys']
ANIMAL_NAMES = settings.GWLFE_DEFAULTS['AnimalName']

ANIMAL_DISPLAY_NAMES = dict(zip(ANIMAL_KEYS, ANIMAL_NAMES))

def animal_population(geojson):
    """
    Given a GeoJSON shape, call MapShed's `animal_energy_units` method
    to calculate the area-weighted county animal population. Returns a
    dictionary to append to the outgoing JSON for analysis results.
    """
    geom = GEOSGeometry(geojson, srid=4326)
    aeu_for_geom = animal_energy_units(geom)[2]
    aeu_return_values = []

    for animal, aeu_value in aeu_for_geom.iteritems():
        aeu_return_values.append({
            'type': ANIMAL_DISPLAY_NAMES[animal],
            'aeu': int(aeu_value),
        })

    return {
        'displayName': 'Animals',
        'name': 'animals',
        'categories': aeu_return_values
    }

Align animal population counts rounding

Response:
<REPLACE_OLD> int(round(aeu_value)),
 <REPLACE_NEW> int(aeu_value),
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

from django.contrib.gis.geos import GEOSGeometry

from django.conf import settings

from apps.modeling.mapshed.calcs import animal_energy_units

ANIMAL_KEYS = settings.GWLFE_CONFIG['AnimalKeys']
ANIMAL_NAMES = settings.GWLFE_DEFAULTS['AnimalName']

ANIMAL_DISPLAY_NAMES = dict(zip(ANIMAL_KEYS, ANIMAL_NAMES))

def animal_population(geojson):
    """
    Given a GeoJSON shape, call MapShed's `animal_energy_units` method
    to calculate the area-weighted county animal population. Returns a
    dictionary to append to the outgoing JSON for analysis results.
    """
    geom = GEOSGeometry(geojson, srid=4326)
    aeu_for_geom = animal_energy_units(geom)[2]
    aeu_return_values = []

    for animal, aeu_value in aeu_for_geom.iteritems():
        aeu_return_values.append({
            'type': ANIMAL_DISPLAY_NAMES[animal],
            'aeu': int(aeu_value),
        })

    return {
        'displayName': 'Animals',
        'name': 'animals',
        'categories': aeu_return_values
    }

Prompt:
Align animal population counts rounding

- round animal population counts down for the frontend "analyze" display to match the MapShed implementation

# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import

from django.contrib.gis.geos import GEOSGeometry

from django.conf import settings

from apps.modeling.mapshed.calcs import animal_energy_units

ANIMAL_KEYS = settings.GWLFE_CONFIG['AnimalKeys']
ANIMAL_NAMES = settings.GWLFE_DEFAULTS['AnimalName']

ANIMAL_DISPLAY_NAMES = dict(zip(ANIMAL_KEYS, ANIMAL_NAMES))

def animal_population(geojson):
    """
    Given a GeoJSON shape, call MapShed's `animal_energy_units` method
    to calculate the area-weighted county animal population. Returns a
    dictionary to append to the outgoing JSON for analysis results.
    """
    geom = GEOSGeometry(geojson, srid=4326)
    aeu_for_geom = animal_energy_units(geom)[2]
    aeu_return_values = []

    for animal, aeu_value in aeu_for_geom.iteritems():
        aeu_return_values.append({
            'type': ANIMAL_DISPLAY_NAMES[animal],
            'aeu': int(round(aeu_value)),
        })

    return {
        'displayName': 'Animals',
        'name': 'animals',
        'categories': aeu_return_values
    }


Response:
<REPLACE_OLD> message,cause=None):
 <REPLACE_NEW> message, cause=None):
 <REPLACE_END> <REPLACE_OLD> self.message  = message
 <REPLACE_NEW> super(MongoctlException, self).__init__(message)
 <REPLACE_END> <REPLACE_OLD> self.cause <REPLACE_NEW> self._cause <REPLACE_END> <REPLACE_OLD> cause

    def __str__(self):
        return self.message <REPLACE_NEW> cause <REPLACE_END> <|endoftext|> __author__ = 'abdul'

###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
    def __init__(self, message, cause=None):
        super(MongoctlException, self).__init__(message)
        self._cause = cause

Prompt:
Remove ref to deprecated "message" property of BaseException

__author__ = 'abdul'

###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
    def __init__(self, message,cause=None):
        self.message  = message
        self.cause = cause

    def __str__(self):
        return self.message


from django.conf.urls import url

from .views import NoticeSettingsView

urlpatterns = [
    url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]

Make compatible with Django 1.9

Make compatible with Django 1.9

Response:
<DELETE> patterns, <DELETE_END> <REPLACE_OLD> patterns(
    "",
 <REPLACE_NEW> [
 <REPLACE_END> <REPLACE_OLD> name="notification_notice_settings"),
)
 <REPLACE_NEW> name="notification_notice_settings"),
]
 <REPLACE_END> <|endoftext|> from django.conf.urls import url

from .views import NoticeSettingsView

urlpatterns = [
    url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]

Prompt:
Make compatible with Django 1.9

from django.conf.urls import patterns, url

from .views import NoticeSettingsView

urlpatterns = patterns(
    "",
    url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)


import os
import shutil
import sys

def fullpath_names(root_dir, file_list):
    """Create a list of fullpath file-name
    """
    fullpath_list = []
    for i in file_list:
        fullpath_list.append(os.path.join(root_dir, i))
    return fullpath_list

def get_files_and_subdirs(root_dir):
    """Return a tuple with all dirs and files inside root_dir
    """
    f, s = [], []
    for (dirpath, dirnames, filenames) in os.walk(root_dir):
        s += fullpath_names(dirpath, dirnames)
        f += fullpath_names(dirpath, filenames)
    return s + f

def escape_space_and_uppercase(file_list):
    """
    Rename files that contains blank spaces or upper letters by dots and
    lower letters
    """
    for i, filename in enumerate(file_list):
        dirname, basename = os.path.split(filename)
        if ' ' in basename or not basename.islower():
            new_name = basename.lower().replace(' ', '.')
            renamed_file = os.path.join(dirname, new_name)
            shutil.move(filename, renamed_file)
            file_list[i] = renamed_file
            print file_list[i]

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'usage: python fix_name.py FOLDER'
    folder = sys.argv[1]
    print 'This program is going to change name of many files.'
    confirm = raw_input('Are you sure to continue? (y/n) ')
    if confirm == 'y':
        dirs_and_files = get_files_and_subdirs(folder)
        escape_space_and_uppercase(dirs_and_files[::-1])
        print 'Done successfully'

Add program to rename files automatically

Response:
<REPLACE_OLD>  <REPLACE_NEW> import os
import shutil
import sys

def fullpath_names(root_dir, file_list):
    """Create a list of fullpath file-name
    """
    fullpath_list = []
    for i in file_list:
        fullpath_list.append(os.path.join(root_dir, i))
    return fullpath_list

def get_files_and_subdirs(root_dir):
    """Return a tuple with all dirs and files inside root_dir
    """
    f, s = [], []
    for (dirpath, dirnames, filenames) in os.walk(root_dir):
        s += fullpath_names(dirpath, dirnames)
        f += fullpath_names(dirpath, filenames)
    return s + f

def escape_space_and_uppercase(file_list):
    """
    Rename files that contains blank spaces or upper letters by dots and
    lower letters
    """
    for i, filename in enumerate(file_list):
        dirname, basename = os.path.split(filename)
        if ' ' in basename or not basename.islower():
            new_name = basename.lower().replace(' ', '.')
            renamed_file = os.path.join(dirname, new_name)
            shutil.move(filename, renamed_file)
            file_list[i] = renamed_file
            print file_list[i]

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'usage: python fix_name.py FOLDER'
    folder = sys.argv[1]
    print 'This program is going to change name of many files.'
    confirm = raw_input('Are you sure to continue? (y/n) ')
    if confirm == 'y':
        dirs_and_files = get_files_and_subdirs(folder)
        escape_space_and_uppercase(dirs_and_files[::-1])
        print 'Done successfully'

 <REPLACE_END> <|endoftext|> import os
import shutil
import sys

def fullpath_names(root_dir, file_list):
    """Create a list of fullpath file-name
    """
    fullpath_list = []
    for i in file_list:
        fullpath_list.append(os.path.join(root_dir, i))
    return fullpath_list

def get_files_and_subdirs(root_dir):
    """Return a tuple with all dirs and files inside root_dir
    """
    f, s = [], []
    for (dirpath, dirnames, filenames) in os.walk(root_dir):
        s += fullpath_names(dirpath, dirnames)
        f += fullpath_names(dirpath, filenames)
    return s + f

def escape_space_and_uppercase(file_list):
    """
    Rename files that contains blank spaces or upper letters by dots and
    lower letters
    """
    for i, filename in enumerate(file_list):
        dirname, basename = os.path.split(filename)
        if ' ' in basename or not basename.islower():
            new_name = basename.lower().replace(' ', '.')
            renamed_file = os.path.join(dirname, new_name)
            shutil.move(filename, renamed_file)
            file_list[i] = renamed_file
            print file_list[i]

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'usage: python fix_name.py FOLDER'
    folder = sys.argv[1]
    print 'This program is going to change name of many files.'
    confirm = raw_input('Are you sure to continue? (y/n) ')
    if confirm == 'y':
        dirs_and_files = get_files_and_subdirs(folder)
        escape_space_and_uppercase(dirs_and_files[::-1])
        print 'Done successfully'

Prompt: Add program to rename files automatically


# Copyright 2018 The pybadge Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Example CI server that serves badges """

from flask import Flask
import pybadges

app = Flask(__name__)

@app.route('/')
def serveBadges():
    # First example
    badge_arg = dict(
        left_text='build',
        right_text='passing',
        right_color='#008000')
    badge = pybadges.badge(**badge_arg)

    # Second example
    secondBadge = pybadges.badge('chat', 'online')
    return badge + "\n" + secondBadge

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

Response:
<INSERT> Copyright 2018 The pybadge Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" <INSERT_END> <REPLACE_OLD> badges

from <REPLACE_NEW> badges """

from <REPLACE_END> <REPLACE_OLD> right_color='#008000'
    )
 <REPLACE_NEW> right_color='#008000')
 <REPLACE_END> <REPLACE_OLD> 'online')

 <REPLACE_NEW> 'online')
 <REPLACE_END> <|endoftext|> # Copyright 2018 The pybadge Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Example CI server that serves badges """

from flask import Flask
import pybadges

app = Flask(__name__)

@app.route('/')
def serveBadges():
    # First example
    badge_arg = dict(
        left_text='build',
        right_text='passing',
        right_color='#008000')
    badge = pybadges.badge(**badge_arg)

    # Second example
    secondBadge = pybadges.badge('chat', 'online')
    return badge + "\n" + secondBadge

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

Prompt:
Add license, right comment and format code

# Example CI server that serves badges

from flask import Flask
import pybadges

app = Flask(__name__)

@app.route('/')
def serveBadges():
    # First example
    badge_arg = dict(
        left_text='build',
        right_text='passing',
        right_color='#008000'
    )
    badge = pybadges.badge(**badge_arg)

    # Second example
    secondBadge = pybadges.badge('chat', 'online')

    return badge + "\n" + secondBadge

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


from ..maps import PreshMap

def test_pop1():
    table = PreshMap()
    table[10] = 20
    table[30] = 25
    assert table[10] == 20
    assert table[30] == 25
    table.pop(30)
    assert table[10] == 20

Add some tests for pop method

Add some tests for pop method

Response:
<INSERT> from ..maps import PreshMap

def test_pop1():
 <INSERT_END> <INSERT>   table = PreshMap()
    table[10] = 20
    table[30] = 25
    assert table[10] == 20
    assert table[30] == 25
    table.pop(30)
    assert table[10] == 20
 <INSERT_END> <|endoftext|> from ..maps import PreshMap

def test_pop1():
    table = PreshMap()
    table[10] = 20
    table[30] = 25
    assert table[10] == 20
    assert table[30] == 25
    table.pop(30)
    assert table[10] == 20

Prompt: Add some tests for pop method


# pylint: disable=missing-docstring, invalid-name, import-error
import pandas as pd

from mltils.encoders import InfrequentValueEncoder

def test_infrequent_value_encoder_1():
    ive = InfrequentValueEncoder()
    assert ive is not None

def test_infrequent_value_encoder_2():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']})
    assert expected.equals(encoded)

def test_infrequent_value_encoder_3():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    assert expected.equals(encoded)

def test_infrequent_value_encoder_4():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    assert expected.equals(encoded)

Response:
<INSERT> expected.equals(encoded)

def test_infrequent_value_encoder_3():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    assert expected.equals(encoded)

def test_infrequent_value_encoder_4():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    assert <INSERT_END> <|endoftext|> # pylint: disable=missing-docstring, invalid-name, import-error
import pandas as pd

from mltils.encoders import InfrequentValueEncoder

def test_infrequent_value_encoder_1():
    ive = InfrequentValueEncoder()
    assert ive is not None

def test_infrequent_value_encoder_2():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']})
    assert expected.equals(encoded)

def test_infrequent_value_encoder_3():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    assert expected.equals(encoded)

def test_infrequent_value_encoder_4():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    assert expected.equals(encoded)

Prompt:
Add more unit tests for InfrequentValueEncoder

# pylint: disable=missing-docstring, invalid-name, import-error
import pandas as pd

from mltils.encoders import InfrequentValueEncoder

def test_infrequent_value_encoder_1():
    ive = InfrequentValueEncoder()
    assert ive is not None

def test_infrequent_value_encoder_2():
    df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']})
    ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq')
    encoded = ive.fit_transform(df)
    expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']})
    assert expected.equals(encoded)


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

from __future__ import absolute_import, unicode_literals

import json
from os import path

class Config(object):
    CACHE_TYPE = 'simple'

    cwd = path.abspath(path.dirname(__file__))
    with open(path.join(cwd, 'me.json')) as me:
        me = json.load(me)
    with open(path.join(cwd, 'modules.json')) as modules:
        modules = json.load(modules)

class DevelopConfig(Config):
    DEBUG = True

class ProductionConfig(Config):
    DEBUG = False

class TestingConfig(Config):
    TESTING = True

Response:
<INSERT>    CACHE_TYPE = 'simple'

 <INSERT_END> <REPLACE_OLD> True
    CACHE_TYPE = 'simple'

class <REPLACE_NEW> True

class <REPLACE_END> <REPLACE_OLD> False
 <REPLACE_NEW> False

class TestingConfig(Config):
    TESTING = True
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

import json
from os import path

class Config(object):
    CACHE_TYPE = 'simple'

    cwd = path.abspath(path.dirname(__file__))
    with open(path.join(cwd, 'me.json')) as me:
        me = json.load(me)
    with open(path.join(cwd, 'modules.json')) as modules:
        modules = json.load(modules)

class DevelopConfig(Config):
    DEBUG = True

class ProductionConfig(Config):
    DEBUG = False

class TestingConfig(Config):
    TESTING = True

Prompt:
Move CACHE_TYPE to Config; add TestingConfig

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

from __future__ import absolute_import, unicode_literals

import json
from os import path

class Config(object):
    cwd = path.abspath(path.dirname(__file__))
    with open(path.join(cwd, 'me.json')) as me:
        me = json.load(me)
    with open(path.join(cwd, 'modules.json')) as modules:
        modules = json.load(modules)

class DevelopConfig(Config):
    DEBUG = True
    CACHE_TYPE = 'simple'

class ProductionConfig(Config):
    DEBUG = False


from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
from UM.Operations.GroupedOperation import GroupedOperation

##  A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
    def __init__(self, node, translation):
        super().__init__()
        self._node = node
        self._transform = node.getLocalTransformation()
        self._position = node.getPosition() + translation
        self._always_merge = True

    def undo(self):
        self._node.setLocalTransformation(self._transform)

    def redo(self):
        self._node.setPosition(self._position)

    def mergeWith(self, other):
        group = GroupedOperation()

        group.addOperation(self)
        group.addOperation(other)

        return group

    def __repr__(self):
        return 'PlatformPhysicsOperation(t = {0})'.format(self._position)

Response:
<REPLACE_OLD> TranslateOperation

## <REPLACE_NEW> TranslateOperation
from UM.Operations.GroupedOperation import GroupedOperation

## <REPLACE_END> <REPLACE_OLD> self._translation <REPLACE_NEW> self._transform <REPLACE_END> <REPLACE_OLD> translation

 <REPLACE_NEW> node.getLocalTransformation()
        self._position = node.getPosition() + translation
        self._always_merge = True

 <REPLACE_END> <REPLACE_OLD> pass

 <REPLACE_NEW> self._node.setLocalTransformation(self._transform)

 <REPLACE_END> <REPLACE_OLD> pass

 <REPLACE_NEW> self._node.setPosition(self._position)

 <REPLACE_END> <REPLACE_OLD> if type(other) is AddSceneNodeOperation:
 <REPLACE_NEW> group = GroupedOperation()

 <REPLACE_END> <INSERT> group.addOperation(self)
 <INSERT_END> <DELETE> other._node.translate(self._translation)
 <DELETE_END> <REPLACE_OLD>  <REPLACE_NEW> group.addOperation(other)

 <REPLACE_END> <REPLACE_OLD> other
 <REPLACE_NEW> group

 <REPLACE_END> <REPLACE_OLD>     elif type(other) is TranslateOperation:
            other._translation += self._translation
     <REPLACE_NEW> def __repr__(self):
 <REPLACE_END> <REPLACE_OLD> other
        else:
            return False

 <REPLACE_NEW> 'PlatformPhysicsOperation(t = {0})'.format(self._position)
 <REPLACE_END> <|endoftext|> from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
from UM.Operations.GroupedOperation import GroupedOperation

##  A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
    def __init__(self, node, translation):
        super().__init__()
        self._node = node
        self._transform = node.getLocalTransformation()
        self._position = node.getPosition() + translation
        self._always_merge = True

    def undo(self):
        self._node.setLocalTransformation(self._transform)

    def redo(self):
        self._node.setPosition(self._position)

    def mergeWith(self, other):
        group = GroupedOperation()

        group.addOperation(self)
        group.addOperation(other)

        return group

    def __repr__(self):
        return 'PlatformPhysicsOperation(t = {0})'.format(self._position)

Prompt:
Use GroupedOperation for merging PlatformPhyisicsOperation

from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation

##  A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
    def __init__(self, node, translation):
        super().__init__()
        self._node = node
        self._translation = translation

    def undo(self):
        pass

    def redo(self):
        pass

    def mergeWith(self, other):
        if type(other) is AddSceneNodeOperation:
            other._node.translate(self._translation)
            return other
        elif type(other) is TranslateOperation:
            other._translation += self._translation
            return other
        else:
            return False


from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^i4p/', include('i4p.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    url(r'^$', direct_to_template, {'template' : 'base.html'}, name="i4p-index"),
    (r'^accounts/', include('registration.backends.default.urls')),
)

Add a name to the index URL

Add a name to the index URL

Response:
<REPLACE_OLD> (r'^$', <REPLACE_NEW> url(r'^$', <REPLACE_END> <REPLACE_OLD> 'base.html'}),
 <REPLACE_NEW> 'base.html'}, name="i4p-index"),
 <REPLACE_END> <|endoftext|> from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^i4p/', include('i4p.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    url(r'^$', direct_to_template, {'template' : 'base.html'}, name="i4p-index"),
    (r'^accounts/', include('registration.backends.default.urls')),
)

Prompt:
Add a name to the index URL

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.views.generic.simple import direct_to_template
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^i4p/', include('i4p.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^$', direct_to_template, {'template' : 'base.html'}),
    (r'^accounts/', include('registration.backends.default.urls')),
)


 # Module of Gaussian Mixture models for python
import megamix.batch
import megamix.online

__all__ = ['batch','online']

Response:
<REPLACE_OLD> python
 <REPLACE_NEW> python
import megamix.batch
import megamix.online
 <REPLACE_END> <|endoftext|>  # Module of Gaussian Mixture models for python
import megamix.batch
import megamix.online

__all__ = ['batch','online']

Prompt:
Solve minor import problems with submodules

 # Module of Gaussian Mixture models for python

__all__ = ['batch','online']


from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework import serializers

from apps.approval.models import CommitteeApplication, CommitteePriority

class CommitteeSerializer(serializers.ModelSerializer):
    group_name = serializers.SerializerMethodField(source='group')

    class Meta(object):
        model = CommitteePriority
        fields = ('group', 'group_name', 'priority')

    def get_group_name(self, instance):
        return instance.group.name

class CommitteeApplicationSerializer(serializers.ModelSerializer):
    committees = CommitteeSerializer(many=True, source='committeepriority_set')

    class Meta(object):
        model = CommitteeApplication
        fields = ('name', 'email', 'application_text', 'prioritized', 'committees')

    def create(self, validated_data):
        committees = validated_data.pop('committeepriority_set')
        application = CommitteeApplication(**validated_data)
        try:
            application.clean()
        except DjangoValidationError as django_error:
            raise serializers.ValidationError(django_error.message)
        application.save()

        for committee in committees:
            CommitteePriority.objects.create(committee_application=application, **committee)

        return CommitteeApplication.objects.get(pk=application.pk)

Response:
<INSERT> django.core.exceptions import ValidationError as DjangoValidationError
from <INSERT_END> <REPLACE_OLD> CommitteeApplication.objects.create(**validated_data)

 <REPLACE_NEW> CommitteeApplication(**validated_data)
        try:
            application.clean()
        except DjangoValidationError as django_error:
            raise serializers.ValidationError(django_error.message)
        application.save()

 <REPLACE_END> <|endoftext|> from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework import serializers

from apps.approval.models import CommitteeApplication, CommitteePriority

class CommitteeSerializer(serializers.ModelSerializer):
    group_name = serializers.SerializerMethodField(source='group')

    class Meta(object):
        model = CommitteePriority
        fields = ('group', 'group_name', 'priority')

    def get_group_name(self, instance):
        return instance.group.name

class CommitteeApplicationSerializer(serializers.ModelSerializer):
    committees = CommitteeSerializer(many=True, source='committeepriority_set')

    class Meta(object):
        model = CommitteeApplication
        fields = ('name', 'email', 'application_text', 'prioritized', 'committees')

    def create(self, validated_data):
        committees = validated_data.pop('committeepriority_set')
        application = CommitteeApplication(**validated_data)
        try:
            application.clean()
        except DjangoValidationError as django_error:
            raise serializers.ValidationError(django_error.message)
        application.save()

        for committee in committees:
            CommitteePriority.objects.create(committee_application=application, **committee)

        return CommitteeApplication.objects.get(pk=application.pk)

Prompt:
Raise DRF ValidationError to get APIException base

from rest_framework import serializers

from apps.approval.models import CommitteeApplication, CommitteePriority

class CommitteeSerializer(serializers.ModelSerializer):
    group_name = serializers.SerializerMethodField(source='group')

    class Meta(object):
        model = CommitteePriority
        fields = ('group', 'group_name', 'priority')

    def get_group_name(self, instance):
        return instance.group.name

class CommitteeApplicationSerializer(serializers.ModelSerializer):
    committees = CommitteeSerializer(many=True, source='committeepriority_set')

    class Meta(object):
        model = CommitteeApplication
        fields = ('name', 'email', 'application_text', 'prioritized', 'committees')

    def create(self, validated_data):
        committees = validated_data.pop('committeepriority_set')
        application = CommitteeApplication.objects.create(**validated_data)

        for committee in committees:
            CommitteePriority.objects.create(committee_application=application, **committee)

        return CommitteeApplication.objects.get(pk=application.pk)


"""Family module for Lingua Libre."""
#
# (C) Pywikibot team, 2021
#
# Distributed under the terms of the MIT license.
#
from pywikibot import family

# The Lingua Libre family
class Family(family.WikimediaFamily):

    """Family class for Lingua Libre.

    *New in version 6.5.*
    """

    name = 'lingualibre'

    langs = {
        'lingualibre': 'lingualibre.org'
    }

    interwiki_forward = 'wikipedia'

    def scriptpath(self, code):
        """Return the script path for this family."""
        return ''

    def interface(self, code):
        """Return 'DataSite'."""
        return 'DataSite'

Response:
<REPLACE_OLD> ''
 <REPLACE_NEW> ''

    def interface(self, code):
        """Return 'DataSite'."""
        return 'DataSite'
 <REPLACE_END> <|endoftext|> """Family module for Lingua Libre."""
#
# (C) Pywikibot team, 2021
#
# Distributed under the terms of the MIT license.
#
from pywikibot import family

# The Lingua Libre family
class Family(family.WikimediaFamily):

    """Family class for Lingua Libre.

    *New in version 6.5.*
    """

    name = 'lingualibre'

    langs = {
        'lingualibre': 'lingualibre.org'
    }

    interwiki_forward = 'wikipedia'

    def scriptpath(self, code):
        """Return the script path for this family."""
        return ''

    def interface(self, code):
        """Return 'DataSite'."""
        return 'DataSite'

Prompt:
Allow to request for item on Lingua Libre

Bug: T286303
Change-Id: Ic0d8824d1bf326f2182fbb64d0cc2ed77f82fd4c

"""Family module for Lingua Libre."""
#
# (C) Pywikibot team, 2021
#
# Distributed under the terms of the MIT license.
#
from pywikibot import family

# The Lingua Libre family
class Family(family.WikimediaFamily):

    """Family class for Lingua Libre.

    *New in version 6.5.*
    """

    name = 'lingualibre'

    langs = {
        'lingualibre': 'lingualibre.org'
    }

    interwiki_forward = 'wikipedia'

    def scriptpath(self, code):
        """Return the script path for this family."""
        return ''


Revert "Change imports to relative."

Response:
<REPLACE_OLD> exit(-1)

import scrub <REPLACE_NEW> exit(-1) <REPLACE_END> <|endoftext|> __version__ = 0.1

import pydarkstar.logutils
import logging

pydarkstar.logutils.setError()

try:
    import sqlalchemy
except ImportError as e:
    logging.exception(e.__class__.__name__)
    logging.error('pip install sqlalchemy')
    exit(-1)

try:
    import pymysql
except ImportError as e:
    logging.exception(e.__class__.__name__)
    logging.error('pip install pymysql')
    exit(-1)

try:
    import bs4
except ImportError as e:
    logging.exception(e.__class__.__name__)
    logging.error('pip install beautifulsoup4')
    exit(-1)

Prompt:
Revert "Change imports to relative."

This reverts commit 9d0990249b7e0e46e38a665cb8c32a1ee435c291.

__version__ = 0.1

import pydarkstar.logutils
import logging

pydarkstar.logutils.setError()

try:
    import sqlalchemy
except ImportError as e:
    logging.exception(e.__class__.__name__)
    logging.error('pip install sqlalchemy')
    exit(-1)

try:
    import pymysql
except ImportError as e:
    logging.exception(e.__class__.__name__)
    logging.error('pip install pymysql')
    exit(-1)

try:
    import bs4
except ImportError as e:
    logging.exception(e.__class__.__name__)
    logging.error('pip install beautifulsoup4')
    exit(-1)

import scrub


import logging
import colorlog

logging.STRONGINFO = logging.INFO + 5
logging.addLevelName(logging.STRONGINFO, 'STRONGINFO')

def logStrongInfo(msg, *args, **kwargs):
    """Log a message with severity 'STRONGINFO' on the root logger. If the logger has
    no handlers, call basicConfig() to add a console handler with a pre-defined
    format."""
    return logging.log(logging.STRONGINFO, msg, *args, **kwargs)

setattr(logging, 'stronginfo', logStrongInfo)

def logStrongInfoMethod(self, msg, *args, **kwargs):
    """Log 'msg % args' with severity 'STRONGINFO'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.stronginfo("Houston, we have a %s", "interesting problem", exc_info=1)
    """
    return self.log(logging.STRONGINFO, msg, *args, **kwargs)

setattr(logging.getLoggerClass(), 'stronginfo', logStrongInfoMethod)

colorlog.default_log_colors['STRONGINFO'] = 'bold_green'

Response:
<REPLACE_OLD> logging.DEBUG <REPLACE_NEW> logging.INFO <REPLACE_END> <|endoftext|> import logging
import colorlog

logging.STRONGINFO = logging.INFO + 5
logging.addLevelName(logging.STRONGINFO, 'STRONGINFO')

def logStrongInfo(msg, *args, **kwargs):
    """Log a message with severity 'STRONGINFO' on the root logger. If the logger has
    no handlers, call basicConfig() to add a console handler with a pre-defined
    format."""
    return logging.log(logging.STRONGINFO, msg, *args, **kwargs)

setattr(logging, 'stronginfo', logStrongInfo)

def logStrongInfoMethod(self, msg, *args, **kwargs):
    """Log 'msg % args' with severity 'STRONGINFO'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.stronginfo("Houston, we have a %s", "interesting problem", exc_info=1)
    """
    return self.log(logging.STRONGINFO, msg, *args, **kwargs)

setattr(logging.getLoggerClass(), 'stronginfo', logStrongInfoMethod)

colorlog.default_log_colors['STRONGINFO'] = 'bold_green'

Prompt:
Correct priority for STRONGINFO log level

import logging
import colorlog

logging.STRONGINFO = logging.DEBUG + 5
logging.addLevelName(logging.STRONGINFO, 'STRONGINFO')

def logStrongInfo(msg, *args, **kwargs):
    """Log a message with severity 'STRONGINFO' on the root logger. If the logger has
    no handlers, call basicConfig() to add a console handler with a pre-defined
    format."""
    return logging.log(logging.STRONGINFO, msg, *args, **kwargs)

setattr(logging, 'stronginfo', logStrongInfo)

def logStrongInfoMethod(self, msg, *args, **kwargs):
    """Log 'msg % args' with severity 'STRONGINFO'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.stronginfo("Houston, we have a %s", "interesting problem", exc_info=1)
    """
    return self.log(logging.STRONGINFO, msg, *args, **kwargs)

setattr(logging.getLoggerClass(), 'stronginfo', logStrongInfoMethod)

colorlog.default_log_colors['STRONGINFO'] = 'bold_green'


import os
import json
import socket

import requests

from flask import request, jsonify, Response, abort

from dadd.worker import app
from dadd.worker.proc import ChildProcess

@app.route('/run/', methods=['POST'])
def run_process():
    proc = ChildProcess(request.json)
    proc.run()
    return jsonify(proc.info())

@app.route('/register/', methods=['POST'])
def register_with_master():
    register(app)
    return jsonify({'message': 'ok'})

def register(host, port):
    sess = requests.Session()

    if 'USERNAME' in app.config and 'PASSWORD' in app.config:
        sess.auth = (app.config['USERNAME'], app.config['PASSWORD'])
    sess.headers = {'content-type': 'application/json'}

    try:
        url = app.config['MASTER_URL'] + '/api/hosts/'
        resp = sess.post(url, data=json.dumps({
            'host': app.config.get('HOSTNAME', socket.getfqdn()),
            'port': port
        }))
        if not resp.ok:
            app.logger.warning('Error registering with master: %s' %
                               app.config['MASTER_URL'])
    except Exception as e:
        app.logger.warning('Connection Error: %s' % e)

@app.route('/logs/<path>', methods=['GET'])
def tail_log(path):
    if os.path.exists(path) and path.startswith('/tmp/'):
        return Response(open(path), content_type='text/plain')
    abort(404)

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

from <REPLACE_NEW> jsonify, Response, abort

from <REPLACE_END> <REPLACE_OLD> socket.getfqdn(), <REPLACE_NEW> app.config.get('HOSTNAME', socket.getfqdn()),
            <REPLACE_END> <REPLACE_OLD> e)
 <REPLACE_NEW> e)

@app.route('/logs/<path>', methods=['GET'])
def tail_log(path):
    if os.path.exists(path) and path.startswith('/tmp/'):
        return Response(open(path), content_type='text/plain')
    abort(404)
 <REPLACE_END> <|endoftext|> import os
import json
import socket

import requests

from flask import request, jsonify, Response, abort

from dadd.worker import app
from dadd.worker.proc import ChildProcess

@app.route('/run/', methods=['POST'])
def run_process():
    proc = ChildProcess(request.json)
    proc.run()
    return jsonify(proc.info())

@app.route('/register/', methods=['POST'])
def register_with_master():
    register(app)
    return jsonify({'message': 'ok'})

def register(host, port):
    sess = requests.Session()

    if 'USERNAME' in app.config and 'PASSWORD' in app.config:
        sess.auth = (app.config['USERNAME'], app.config['PASSWORD'])
    sess.headers = {'content-type': 'application/json'}

    try:
        url = app.config['MASTER_URL'] + '/api/hosts/'
        resp = sess.post(url, data=json.dumps({
            'host': app.config.get('HOSTNAME', socket.getfqdn()),
            'port': port
        }))
        if not resp.ok:
            app.logger.warning('Error registering with master: %s' %
                               app.config['MASTER_URL'])
    except Exception as e:
        app.logger.warning('Connection Error: %s' % e)

@app.route('/logs/<path>', methods=['GET'])
def tail_log(path):
    if os.path.exists(path) and path.startswith('/tmp/'):
        return Response(open(path), content_type='text/plain')
    abort(404)

Prompt:
Allow setting the HOSTNAME reported to the master via an env var; Stub and endpoint for tailing the log of a process assuming you know the path.

I'd like to get this log processing a bit more automatic but I need to
spend more time in Dadd's API.

import json
import socket

import requests

from flask import request, jsonify

from dadd.worker import app
from dadd.worker.proc import ChildProcess

@app.route('/run/', methods=['POST'])
def run_process():
    proc = ChildProcess(request.json)
    proc.run()
    return jsonify(proc.info())

@app.route('/register/', methods=['POST'])
def register_with_master():
    register(app)
    return jsonify({'message': 'ok'})

def register(host, port):
    sess = requests.Session()

    if 'USERNAME' in app.config and 'PASSWORD' in app.config:
        sess.auth = (app.config['USERNAME'], app.config['PASSWORD'])
    sess.headers = {'content-type': 'application/json'}

    try:
        url = app.config['MASTER_URL'] + '/api/hosts/'
        resp = sess.post(url, data=json.dumps({
            'host': socket.getfqdn(), 'port': port
        }))
        if not resp.ok:
            app.logger.warning('Error registering with master: %s' %
                               app.config['MASTER_URL'])
    except Exception as e:
        app.logger.warning('Connection Error: %s' % e)


# Generated by Django 3.1.14 on 2022-03-11 15:06

from django.conf import settings
from django.db import migrations

def forward(apps, schema_editor):
    with schema_editor.connection.cursor() as cursor:
        cursor.execute(
            f"SELECT 1 FROM information_schema.columns WHERE table_name='infrastructure_infrastructure' AND column_name='published'"
        )
        if cursor.fetchone():
            for lang in settings.MODELTRANSLATION_LANGUAGES:
                cursor.execute(
                    f"SELECT 1 FROM information_schema.columns WHERE table_name='infrastructure_infrastructure' AND column_name='published_{lang}'"
                )
                if not cursor.fetchone():
                    cursor.execute(
                        f"ALTER TABLE infrastructure_infrastructure ADD published_{lang} Boolean DEFAULT True;"
                    )

def backward(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('infrastructure', '0027_infrastructure_accessibility'),
    ]

    operations = [
        migrations.RunPython(forward, backward),
    ]

Add migration fix published language

Add migration fix published language

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Generated by Django 3.1.14 on 2022-03-11 15:06

from django.conf import settings
from django.db import migrations

def forward(apps, schema_editor):
    with schema_editor.connection.cursor() as cursor:
        cursor.execute(
            f"SELECT 1 FROM information_schema.columns WHERE table_name='infrastructure_infrastructure' AND column_name='published'"
        )
        if cursor.fetchone():
            for lang in settings.MODELTRANSLATION_LANGUAGES:
                cursor.execute(
                    f"SELECT 1 FROM information_schema.columns WHERE table_name='infrastructure_infrastructure' AND column_name='published_{lang}'"
                )
                if not cursor.fetchone():
                    cursor.execute(
                        f"ALTER TABLE infrastructure_infrastructure ADD published_{lang} Boolean DEFAULT True;"
                    )

def backward(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('infrastructure', '0027_infrastructure_accessibility'),
    ]

    operations = [
        migrations.RunPython(forward, backward),
    ]
 <REPLACE_END> <|endoftext|> # Generated by Django 3.1.14 on 2022-03-11 15:06

from django.conf import settings
from django.db import migrations

def forward(apps, schema_editor):
    with schema_editor.connection.cursor() as cursor:
        cursor.execute(
            f"SELECT 1 FROM information_schema.columns WHERE table_name='infrastructure_infrastructure' AND column_name='published'"
        )
        if cursor.fetchone():
            for lang in settings.MODELTRANSLATION_LANGUAGES:
                cursor.execute(
                    f"SELECT 1 FROM information_schema.columns WHERE table_name='infrastructure_infrastructure' AND column_name='published_{lang}'"
                )
                if not cursor.fetchone():
                    cursor.execute(
                        f"ALTER TABLE infrastructure_infrastructure ADD published_{lang} Boolean DEFAULT True;"
                    )

def backward(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('infrastructure', '0027_infrastructure_accessibility'),
    ]

    operations = [
        migrations.RunPython(forward, backward),
    ]

Prompt: Add migration fix published language


"""An interface to report the status of emulator launches."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import logging
import os
import uuid

class NoOpReporter(object):
  """Captures all device and failure data and throws it away."""

  def __init__(self):
    pass

  def ReportDeviceProperties(self, unused_emu_type, unused_props):
    pass

  def ReportFailure(self, unused_component, unused_details):
    pass

  def ReportToolsUsage(self, unused_namespace, unused_tool_name,
                       unused_runtime_ms, unused_success,
                       unused_total_runtime):
    pass

  def Emit(self):
    pass

def MakeReporter():
  """Creates a reporter instance."""
  return NoOpReporter()

Response:
<REPLACE_OLD> unused_success):
 <REPLACE_NEW> unused_success,
                       unused_total_runtime):
 <REPLACE_END> <|endoftext|> """An interface to report the status of emulator launches."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import logging
import os
import uuid

class NoOpReporter(object):
  """Captures all device and failure data and throws it away."""

  def __init__(self):
    pass

  def ReportDeviceProperties(self, unused_emu_type, unused_props):
    pass

  def ReportFailure(self, unused_component, unused_details):
    pass

  def ReportToolsUsage(self, unused_namespace, unused_tool_name,
                       unused_runtime_ms, unused_success,
                       unused_total_runtime):
    pass

  def Emit(self):
    pass

def MakeReporter():
  """Creates a reporter instance."""
  return NoOpReporter()

Prompt:
Update the reporter interface to even track the total runtime

PiperOrigin-RevId: 160982468

"""An interface to report the status of emulator launches."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import logging
import os
import uuid

class NoOpReporter(object):
  """Captures all device and failure data and throws it away."""

  def __init__(self):
    pass

  def ReportDeviceProperties(self, unused_emu_type, unused_props):
    pass

  def ReportFailure(self, unused_component, unused_details):
    pass

  def ReportToolsUsage(self, unused_namespace, unused_tool_name,
                       unused_runtime_ms, unused_success):
    pass

  def Emit(self):
    pass

def MakeReporter():
  """Creates a reporter instance."""
  return NoOpReporter()


from functools import wraps
from bs4 import BeautifulSoup as bs

from .errors import (
    XMLError, PhoneError, StartTimeError,
    EndTimeError, LifetimeError, SpeedError,
    AlphanameError, TextError, InsufficientFundsError
)

ERROR_MAP = {
    'XMLERROR': XMLError,
    'ERRPHONES': PhoneError,
    'ERRSTARTTIME': StartTimeError,
    'ERRENDTIME': EndTimeError,
    'ERRLIFETIME': LifetimeError,
    'ERRSPEED': SpeedError,
    'ERRALFANAME': AlphanameError,
    'ERRTEXT': TextError,
    'INSUFFICIENTFUNDS': InsufficientFundsError
}

def parse_xml_response(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        res_xml = bs(f(*args, **kwargs), features='lxml-xml')
        state_code = res_xml.message.state['code']
        try:
            raise ERROR_MAP[state_code]
        except KeyError:
            return res_xml
    return wrapper

Fix import of error classes

Fix import of error classes

Response:
<REPLACE_OLD> errors <REPLACE_NEW> .errors <REPLACE_END> <INSERT> (
    <INSERT_END> <REPLACE_OLD> StartTimeError, <REPLACE_NEW> StartTimeError,
    <REPLACE_END> <DELETE>    <DELETE_END> <REPLACE_OLD> InsufficientFundsError

ERROR_MAP <REPLACE_NEW> InsufficientFundsError
)

ERROR_MAP <REPLACE_END> <|endoftext|> from functools import wraps
from bs4 import BeautifulSoup as bs

from .errors import (
    XMLError, PhoneError, StartTimeError,
    EndTimeError, LifetimeError, SpeedError,
    AlphanameError, TextError, InsufficientFundsError
)

ERROR_MAP = {
    'XMLERROR': XMLError,
    'ERRPHONES': PhoneError,
    'ERRSTARTTIME': StartTimeError,
    'ERRENDTIME': EndTimeError,
    'ERRLIFETIME': LifetimeError,
    'ERRSPEED': SpeedError,
    'ERRALFANAME': AlphanameError,
    'ERRTEXT': TextError,
    'INSUFFICIENTFUNDS': InsufficientFundsError
}

def parse_xml_response(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        res_xml = bs(f(*args, **kwargs), features='lxml-xml')
        state_code = res_xml.message.state['code']
        try:
            raise ERROR_MAP[state_code]
        except KeyError:
            return res_xml
    return wrapper

Prompt:
Fix import of error classes

from functools import wraps
from bs4 import BeautifulSoup as bs

from errors import XMLError, PhoneError, StartTimeError, EndTimeError, LifetimeError, SpeedError,
       AlphanameError, TextError, InsufficientFundsError

ERROR_MAP = {
    'XMLERROR': XMLError,
    'ERRPHONES': PhoneError,
    'ERRSTARTTIME': StartTimeError,
    'ERRENDTIME': EndTimeError,
    'ERRLIFETIME': LifetimeError,
    'ERRSPEED': SpeedError,
    'ERRALFANAME': AlphanameError,
    'ERRTEXT': TextError,
    'INSUFFICIENTFUNDS': InsufficientFundsError
}

def parse_xml_response(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        res_xml = bs(f(*args, **kwargs), features='lxml-xml')
        state_code = res_xml.message.state['code']
        try:
            raise ERROR_MAP[state_code]
        except KeyError:
            return res_xml
    return wrapper


import os
import json
from framework.mongo import set_up_storage

from website import settings
from website.project.taxonomies import Subject

from modularodm import Q, storage
from modularodm.exceptions import NoResultsFound, MultipleResultsFound

def update_taxonomies():
    # Flat taxonomy is stored locally, read in here
    with open(
        os.path.join(
            settings.APP_PATH,
            'website', 'static', 'plos_taxonomy.json'
        )
    ) as fp:
        taxonomy = json.load(fp)
        # For now, only PLOS taxonomy is loaded, other types possibly considered in the future
        type = 'plos'
        for subject_path in taxonomy.get('data'):
            subjects = subject_path.split('_')
            text = subjects[-1]

            # Search for parent subject, get id if it exists
            _parent = None
            if len(subjects) > 1:
                try:
                    _parent = Subject.find_one(
                        Q('text', 'eq', subjects[-2]) &
                        Q('type', 'eq', type)
                    )
                except Exception:
                    _parent = None

            parent_id = None
            if _parent:
                parent_id = _parent._id

            try:
                subject = Subject.find_one(
                    Q('text', 'eq', text) &
                    Q('type', 'eq', type)
                )
            except (NoResultsFound, MultipleResultsFound):
                # If subject does not yet exist, create it
                if parent_id:
                    subject = Subject(
                        type=type,
                        text=text,
                        parent_ids=[parent_id],
                    )
                else:
                    subject = Subject(
                        type=type,
                        text=text,
                        parent_ids=[],
                    )
            else:
                # If subject does exist, append parent_id if not already added
                subject.text = text
                subject.type = type
                if parent_id not in subject.parent_ids:
                    subject.parent_ids.append(parent_id)

            subject.save()

if __name__ == '__main__':
    set_up_storage([Subject], storage.MongoStorage)
    update_taxonomies()

Add a script that loads the taxonomies as a standalone thing

Response:
<REPLACE_OLD>  <REPLACE_NEW> import os
import json
from framework.mongo import set_up_storage

from website import settings
from website.project.taxonomies import Subject

from modularodm import Q, storage
from modularodm.exceptions import NoResultsFound, MultipleResultsFound

def update_taxonomies():
    # Flat taxonomy is stored locally, read in here
    with open(
        os.path.join(
            settings.APP_PATH,
            'website', 'static', 'plos_taxonomy.json'
        )
    ) as fp:
        taxonomy = json.load(fp)
        # For now, only PLOS taxonomy is loaded, other types possibly considered in the future
        type = 'plos'
        for subject_path in taxonomy.get('data'):
            subjects = subject_path.split('_')
            text = subjects[-1]

            # Search for parent subject, get id if it exists
            _parent = None
            if len(subjects) > 1:
                try:
                    _parent = Subject.find_one(
                        Q('text', 'eq', subjects[-2]) &
                        Q('type', 'eq', type)
                    )
                except Exception:
                    _parent = None

            parent_id = None
            if _parent:
                parent_id = _parent._id

            try:
                subject = Subject.find_one(
                    Q('text', 'eq', text) &
                    Q('type', 'eq', type)
                )
            except (NoResultsFound, MultipleResultsFound):
                # If subject does not yet exist, create it
                if parent_id:
                    subject = Subject(
                        type=type,
                        text=text,
                        parent_ids=[parent_id],
                    )
                else:
                    subject = Subject(
                        type=type,
                        text=text,
                        parent_ids=[],
                    )
            else:
                # If subject does exist, append parent_id if not already added
                subject.text = text
                subject.type = type
                if parent_id not in subject.parent_ids:
                    subject.parent_ids.append(parent_id)

            subject.save()

if __name__ == '__main__':
    set_up_storage([Subject], storage.MongoStorage)
    update_taxonomies()
 <REPLACE_END> <|endoftext|> import os
import json
from framework.mongo import set_up_storage

from website import settings
from website.project.taxonomies import Subject

from modularodm import Q, storage
from modularodm.exceptions import NoResultsFound, MultipleResultsFound

def update_taxonomies():
    # Flat taxonomy is stored locally, read in here
    with open(
        os.path.join(
            settings.APP_PATH,
            'website', 'static', 'plos_taxonomy.json'
        )
    ) as fp:
        taxonomy = json.load(fp)
        # For now, only PLOS taxonomy is loaded, other types possibly considered in the future
        type = 'plos'
        for subject_path in taxonomy.get('data'):
            subjects = subject_path.split('_')
            text = subjects[-1]

            # Search for parent subject, get id if it exists
            _parent = None
            if len(subjects) > 1:
                try:
                    _parent = Subject.find_one(
                        Q('text', 'eq', subjects[-2]) &
                        Q('type', 'eq', type)
                    )
                except Exception:
                    _parent = None

            parent_id = None
            if _parent:
                parent_id = _parent._id

            try:
                subject = Subject.find_one(
                    Q('text', 'eq', text) &
                    Q('type', 'eq', type)
                )
            except (NoResultsFound, MultipleResultsFound):
                # If subject does not yet exist, create it
                if parent_id:
                    subject = Subject(
                        type=type,
                        text=text,
                        parent_ids=[parent_id],
                    )
                else:
                    subject = Subject(
                        type=type,
                        text=text,
                        parent_ids=[],
                    )
            else:
                # If subject does exist, append parent_id if not already added
                subject.text = text
                subject.type = type
                if parent_id not in subject.parent_ids:
                    subject.parent_ids.append(parent_id)

            subject.save()

if __name__ == '__main__':
    set_up_storage([Subject], storage.MongoStorage)
    update_taxonomies()

Prompt: Add a script that loads the taxonomies as a standalone thing


Change to Unix line endings

REF: Change to Unix line endings

Response:
<REPLACE_OLD> files.

This <REPLACE_NEW> files.

This <REPLACE_END> <REPLACE_OLD> developed
at <REPLACE_NEW> developed
at <REPLACE_END> <REPLACE_OLD> information
for <REPLACE_NEW> information
for <REPLACE_END> <REPLACE_OLD> from
Space".

The <REPLACE_NEW> from
Space".

The <REPLACE_END> <REPLACE_OLD> code
on <REPLACE_NEW> code
on <REPLACE_END> <REPLACE_OLD> basis...

"""
 <REPLACE_NEW> basis...

"""
 <REPLACE_END> <|endoftext|> """Provides convenience utilities for assorted data files.

This package provides a means of organizing the code developed
at UKZN for handling the dataflow and processing of information
for the WRC funded research project K5-1683 "Soil Moisture from
Space".

The interface isn't stable yet so be prepared to update your code
on a regular basis...

"""

Prompt:
REF: Change to Unix line endings

"""Provides convenience utilities for assorted data files.

This package provides a means of organizing the code developed
at UKZN for handling the dataflow and processing of information
for the WRC funded research project K5-1683 "Soil Moisture from
Space".

The interface isn't stable yet so be prepared to update your code
on a regular basis...

"""


import logging

from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual

logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)

class SettingsWithoutPlugins:
    host_name = "TestHost"
    server_name = "TestServer"
    config_file = "server.cfg"
    url = "http://localhost:9000"
    event_poll_period = 0
    full_update_period = 0

    setup_rotation = [
        prl_s4_r2_zolder_casual
    ]

    plugins = []

Set sleep times to zero for tests

Set sleep times to zero for tests

Response:
<REPLACE_OLD> 1
 <REPLACE_NEW> 0
 <REPLACE_END> <REPLACE_OLD> 5

 <REPLACE_NEW> 0

 <REPLACE_END> <|endoftext|> import logging

from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual

logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)

class SettingsWithoutPlugins:
    host_name = "TestHost"
    server_name = "TestServer"
    config_file = "server.cfg"
    url = "http://localhost:9000"
    event_poll_period = 0
    full_update_period = 0

    setup_rotation = [
        prl_s4_r2_zolder_casual
    ]

    plugins = []

Prompt:
Set sleep times to zero for tests

import logging

from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual

logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)

class SettingsWithoutPlugins:
    host_name = "TestHost"
    server_name = "TestServer"
    config_file = "server.cfg"
    url = "http://localhost:9000"
    event_poll_period = 1
    full_update_period = 5

    setup_rotation = [
        prl_s4_r2_zolder_casual
    ]

    plugins = []


from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64
# Note: This name is changed
from .. import bool_ as bool

__all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']

Response:
<REPLACE_OLD> float64, <REPLACE_NEW> float64
# Note: This name is changed
from .. import bool_ as <REPLACE_END> <|endoftext|> from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64
# Note: This name is changed
from .. import bool_ as bool

__all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']

Prompt:
Fix the bool name in the array API namespace

from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool

__all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']


#!/usr/bin/env python

# NOTE: setup.py does NOT install the contents of the library dir
# for you, you should go through "make install" or "make RPMs"
# for that, or manually copy modules over.

import os
import sys

sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup

setup(name='ansible',
      version=__version__,
      description='Minimal SSH command and control',
      author=__author__,
      author_email='michael.dehaan@gmail.com',
      url='http://ansible.github.com/',
      license='GPLv3',
      install_requires=['paramiko', 'jinja2', "PyYAML"],
      package_dir={ 'ansible': 'lib/ansible' },
      packages=[
         'ansible',
         'ansible.inventory',
         'ansible.playbook',
         'ansible.runner',
         'ansible.runner.connection',
      ],
      scripts=[
         'bin/ansible',
         'bin/ansible-playbook',
         'bin/ansible-pull'
      ]
)

Response:
<REPLACE_OLD> 'bin/ansible-playbook'
 <REPLACE_NEW> 'bin/ansible-playbook',
         'bin/ansible-pull'
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

# NOTE: setup.py does NOT install the contents of the library dir
# for you, you should go through "make install" or "make RPMs"
# for that, or manually copy modules over.

import os
import sys

sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup

setup(name='ansible',
      version=__version__,
      description='Minimal SSH command and control',
      author=__author__,
      author_email='michael.dehaan@gmail.com',
      url='http://ansible.github.com/',
      license='GPLv3',
      install_requires=['paramiko', 'jinja2', "PyYAML"],
      package_dir={ 'ansible': 'lib/ansible' },
      packages=[
         'ansible',
         'ansible.inventory',
         'ansible.playbook',
         'ansible.runner',
         'ansible.runner.connection',
      ],
      scripts=[
         'bin/ansible',
         'bin/ansible-playbook',
         'bin/ansible-pull'
      ]
)

Prompt:
Include bin/ansible-pull as part of the sdist in distutils.

#!/usr/bin/env python

# NOTE: setup.py does NOT install the contents of the library dir
# for you, you should go through "make install" or "make RPMs"
# for that, or manually copy modules over.

import os
import sys

sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup

setup(name='ansible',
      version=__version__,
      description='Minimal SSH command and control',
      author=__author__,
      author_email='michael.dehaan@gmail.com',
      url='http://ansible.github.com/',
      license='GPLv3',
      install_requires=['paramiko', 'jinja2', "PyYAML"],
      package_dir={ 'ansible': 'lib/ansible' },
      packages=[
         'ansible',
         'ansible.inventory',
         'ansible.playbook',
         'ansible.runner',
         'ansible.runner.connection',
      ],
      scripts=[
         'bin/ansible',
         'bin/ansible-playbook'
      ]
)


import os
import xlrd
import xlwt

# Assumes the directory with the workbook is relative to the script's location.
directory = 'workbooks/'

workbook = ''
for dirpath, dirnames, filenames in os.walk(directory):
    for files in filenames:
        workbook = (dirpath + files)

'''
Test films include:
Repulsion
The Crying Game
Saint Joan
My LIfe as a Zucchini
'''
# Collects the names of all the films for which individual workbooks need to be
# created.
films = []
wbs = int(input('Number of workbooks to create: '))
for wb in range(0, wbs):
    film = input('Name the film: ')
    films.append(film)

def create_workbook():
    '''Creates a workbook.

    Arguments:
        none

    Returns:
        book = The workbook that was opened.
    '''
    headers = ['First Name', 'Last Name', 'Email', 'Phone', 'Full address']
    book = xlwt.Workbook()
    sheet = book.add_sheet('Contacts')
    column_number = 0
    for header in headers:
        sheet.write(0, column_number, header)
        column_number += 1
    return book

def save_workbook(book, film):
    '''Saves the workbook created in create_workbook().

    Arguments:
        book = The object returned by calling create_workbook().
        film = The name of the film that will part of the workbook's name.

    Returns:
        none
    '''
    book.save('{0} contacts.xls'.format(film))

for film in films:
    save_workbook(create_workbook(), film)

Response:
<INSERT> headers = ['First Name', 'Last Name', 'Email', 'Phone', 'Full address']
    <INSERT_END> <INSERT>    column_number = 0
    for header in headers:
        sheet.write(0, column_number, header)
        column_number += 1
 <INSERT_END> <REPLACE_OLD> contacts'.format(film))

for <REPLACE_NEW> contacts.xls'.format(film))

for <REPLACE_END> <|endoftext|> import os
import xlrd
import xlwt

# Assumes the directory with the workbook is relative to the script's location.
directory = 'workbooks/'

workbook = ''
for dirpath, dirnames, filenames in os.walk(directory):
    for files in filenames:
        workbook = (dirpath + files)

'''
Test films include:
Repulsion
The Crying Game
Saint Joan
My LIfe as a Zucchini
'''
# Collects the names of all the films for which individual workbooks need to be
# created.
films = []
wbs = int(input('Number of workbooks to create: '))
for wb in range(0, wbs):
    film = input('Name the film: ')
    films.append(film)

def create_workbook():
    '''Creates a workbook.

    Arguments:
        none

    Returns:
        book = The workbook that was opened.
    '''
    headers = ['First Name', 'Last Name', 'Email', 'Phone', 'Full address']
    book = xlwt.Workbook()
    sheet = book.add_sheet('Contacts')
    column_number = 0
    for header in headers:
        sheet.write(0, column_number, header)
        column_number += 1
    return book

def save_workbook(book, film):
    '''Saves the workbook created in create_workbook().

    Arguments:
        book = The object returned by calling create_workbook().
        film = The name of the film that will part of the workbook's name.

    Returns:
        none
    '''
    book.save('{0} contacts.xls'.format(film))

for film in films:
    save_workbook(create_workbook(), film)

Prompt:
Add header row to worksheet in workbooks

import os
import xlrd
import xlwt

# Assumes the directory with the workbook is relative to the script's location.
directory = 'workbooks/'

workbook = ''
for dirpath, dirnames, filenames in os.walk(directory):
    for files in filenames:
        workbook = (dirpath + files)

'''
Test films include:
Repulsion
The Crying Game
Saint Joan
My LIfe as a Zucchini
'''
# Collects the names of all the films for which individual workbooks need to be
# created.
films = []
wbs = int(input('Number of workbooks to create: '))
for wb in range(0, wbs):
    film = input('Name the film: ')
    films.append(film)

def create_workbook():
    '''Creates a workbook.

    Arguments:
        none

    Returns:
        book = The workbook that was opened.
    '''
    book = xlwt.Workbook()
    sheet = book.add_sheet('Contacts')
    return book

def save_workbook(book, film):
    '''Saves the workbook created in create_workbook().

    Arguments:
        book = The object returned by calling create_workbook().
        film = The name of the film that will part of the workbook's name.

    Returns:
        none
    '''
    book.save('{0} contacts'.format(film))

for film in films:
    save_workbook(create_workbook(), film)


# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals

from django.db import migrations, OperationalError, ProgrammingError

def fix_fee_product_index(apps, schema_editor):
    try:
        schema_editor.execute(
            'DROP INDEX idx_16977_product_id;'
            'ALTER TABLE cfpb.ratechecker_fee '
            'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
            'ALTER TABLE cfpb.ratechecker_fee '
            'ADD CONSTRAINT idx_16977_product_id '
            'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
        )
    except (ProgrammingError, OperationalError):
        pass

class Migration(migrations.Migration):

    dependencies = [
        ('ratechecker', '0001_initial'),
    ]

    operations = [
        #migrations.RunPython(fix_fee_product_index),
        migrations.AlterUniqueTogether(
            name='fee',
            unique_together=set([]),
        ),
        migrations.RemoveField(
            model_name='fee',
            name='plan',
        ),
        migrations.DeleteModel(
            name='Fee',
        ),
    ]

Response:
<DELETE> table_name = 'cfpb.ratechecker_fee'
    index_name = 'idx_16977_product_id'
    <DELETE_END> <REPLACE_OLD> migrations.RunPython(fix_fee_product_index),
 <REPLACE_NEW> #migrations.RunPython(fix_fee_product_index),
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals

from django.db import migrations, OperationalError, ProgrammingError

def fix_fee_product_index(apps, schema_editor):
    try:
        schema_editor.execute(
            'DROP INDEX idx_16977_product_id;'
            'ALTER TABLE cfpb.ratechecker_fee '
            'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
            'ALTER TABLE cfpb.ratechecker_fee '
            'ADD CONSTRAINT idx_16977_product_id '
            'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
        )
    except (ProgrammingError, OperationalError):
        pass

class Migration(migrations.Migration):

    dependencies = [
        ('ratechecker', '0001_initial'),
    ]

    operations = [
        #migrations.RunPython(fix_fee_product_index),
        migrations.AlterUniqueTogether(
            name='fee',
            unique_together=set([]),
        ),
        migrations.RemoveField(
            model_name='fee',
            name='plan',
        ),
        migrations.DeleteModel(
            name='Fee',
        ),
    ]

Prompt:
Comment out fix_fee_product_index from migration

# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals

from django.db import migrations, OperationalError, ProgrammingError

def fix_fee_product_index(apps, schema_editor):
    table_name = 'cfpb.ratechecker_fee'
    index_name = 'idx_16977_product_id'
    try:
        schema_editor.execute(
            'DROP INDEX idx_16977_product_id;'
            'ALTER TABLE cfpb.ratechecker_fee '
            'DROP CONSTRAINT IF EXISTS idx_16977_product_id;'
            'ALTER TABLE cfpb.ratechecker_fee '
            'ADD CONSTRAINT idx_16977_product_id '
            'UNIQUE (product_id, state_id, lender, single_family, condo, coop);'
        )
    except (ProgrammingError, OperationalError):
        pass

class Migration(migrations.Migration):

    dependencies = [
        ('ratechecker', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(fix_fee_product_index),
        migrations.AlterUniqueTogether(
            name='fee',
            unique_together=set([]),
        ),
        migrations.RemoveField(
            model_name='fee',
            name='plan',
        ),
        migrations.DeleteModel(
            name='Fee',
        ),
    ]


from setuptools import setup, find_packages
import os

scriptnames = ['runElegant.sh',
               'sddsprintdata.sh',
               'renametolower.sh',
               'file2lower.sh',
               'lte2json',
               'json2lte',
               'latticeviewer',
               'lv']

def readme():
    with open('README.rst') as f:
        return f.read()

requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython']

setup(
        name     = "beamline",
        version  = "1.3.6",
        description = "online model package for electron accelerator",
        long_description = readme() + '\n\n',
        author   = "Tong Zhang",
        author_email = "warriorlance@gmail.com",
        platforms = ["Linux"],
        license  = "MIT",
        packages = find_packages(),
        url = "http://archman.github.io/beamline/",
        scripts  = [os.path.join('scripts',sn) for sn in scriptnames],
        requires = requiredpackages,
        install_requires = requiredpackages,
        extras_require = {'sdds': ['sddswhl']},
)

Add wxPython and use install_requires

Response:
<REPLACE_OLD> 'pyepics']

setup(
 <REPLACE_NEW> 'pyepics', 'wxPython']

setup(
 <REPLACE_END> <INSERT> install_requires = requiredpackages,
        <INSERT_END> <|endoftext|> from setuptools import setup, find_packages
import os

scriptnames = ['runElegant.sh',
               'sddsprintdata.sh',
               'renametolower.sh',
               'file2lower.sh',
               'lte2json',
               'json2lte',
               'latticeviewer',
               'lv']

def readme():
    with open('README.rst') as f:
        return f.read()

requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython']

setup(
        name     = "beamline",
        version  = "1.3.6",
        description = "online model package for electron accelerator",
        long_description = readme() + '\n\n',
        author   = "Tong Zhang",
        author_email = "warriorlance@gmail.com",
        platforms = ["Linux"],
        license  = "MIT",
        packages = find_packages(),
        url = "http://archman.github.io/beamline/",
        scripts  = [os.path.join('scripts',sn) for sn in scriptnames],
        requires = requiredpackages,
        install_requires = requiredpackages,
        extras_require = {'sdds': ['sddswhl']},
)

Prompt:
Add wxPython and use install_requires

* Add wxPython as a depenency
* Use `install_requires` so dependencies are installed if one installs this package

from setuptools import setup, find_packages
import os

scriptnames = ['runElegant.sh',
               'sddsprintdata.sh',
               'renametolower.sh',
               'file2lower.sh',
               'lte2json',
               'json2lte',
               'latticeviewer',
               'lv']

def readme():
    with open('README.rst') as f:
        return f.read()

requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics']

setup(
        name     = "beamline",
        version  = "1.3.6",
        description = "online model package for electron accelerator",
        long_description = readme() + '\n\n',
        author   = "Tong Zhang",
        author_email = "warriorlance@gmail.com",
        platforms = ["Linux"],
        license  = "MIT",
        packages = find_packages(),
        url = "http://archman.github.io/beamline/",
        scripts  = [os.path.join('scripts',sn) for sn in scriptnames],
        requires = requiredpackages,
        extras_require = {'sdds': ['sddswhl']},
)


import pyaudio
import wave
import time
import sys
import numpy as np

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

n_bytes_to_test = 1024 * 2 * 6

DEVICE_ID=2

def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    # npdata = np.frombuffer(data, dtype=np.int16)
    # print("len(data): {}, frame_count: {}".format(len(data), frame_count))
    if len(data) < n_bytes_to_test:
        wf.rewind()
        data = wf.readframes(frame_count)
	print("Rewinding")
    return (data, pyaudio.paContinue)

print("Device parameters: {}".format(p.get_device_info_by_index(DEVICE_ID)))

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=48000,
                output_device_index=DEVICE_ID,
                output=True,
                stream_callback=callback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()
wf.close()

p.terminate()

Add support for looping sample

Add support for looping sample

Response:
<REPLACE_OLD> pyaudio.PyAudio()

DEVICE_ID=2

def <REPLACE_NEW> pyaudio.PyAudio()

n_bytes_to_test = 1024 * 2 * 6

DEVICE_ID=2

def <REPLACE_END> <INSERT> # print("len(data): {}, frame_count: {}".format(len(data), frame_count))
    if len(data) < n_bytes_to_test:
        wf.rewind()
        data = wf.readframes(frame_count)
	print("Rewinding")
    <INSERT_END> <REPLACE_OLD> {}".format(p.get_default_output_device_info()))

stream <REPLACE_NEW> {}".format(p.get_device_info_by_index(DEVICE_ID)))

stream <REPLACE_END> <REPLACE_OLD> rate=wf.getframerate(),
 <REPLACE_NEW> rate=48000,
 <REPLACE_END> <|endoftext|> import pyaudio
import wave
import time
import sys
import numpy as np

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

n_bytes_to_test = 1024 * 2 * 6

DEVICE_ID=2

def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    # npdata = np.frombuffer(data, dtype=np.int16)
    # print("len(data): {}, frame_count: {}".format(len(data), frame_count))
    if len(data) < n_bytes_to_test:
        wf.rewind()
        data = wf.readframes(frame_count)
	print("Rewinding")
    return (data, pyaudio.paContinue)

print("Device parameters: {}".format(p.get_device_info_by_index(DEVICE_ID)))

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=48000,
                output_device_index=DEVICE_ID,
                output=True,
                stream_callback=callback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()
wf.close()

p.terminate()

Prompt:
Add support for looping sample

import pyaudio
import wave
import time
import sys
import numpy as np

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

DEVICE_ID=2

def callback(in_data, frame_count, time_info, status):
    data = wf.readframes(frame_count)
    # npdata = np.frombuffer(data, dtype=np.int16)
    return (data, pyaudio.paContinue)

print("Device parameters: {}".format(p.get_default_output_device_info()))

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output_device_index=DEVICE_ID,
                output=True,
                stream_callback=callback)

stream.start_stream()

while stream.is_active():
    time.sleep(0.1)

stream.stop_stream()
stream.close()
wf.close()

p.terminate()


from django.contrib import admin
from models import MuseumObject,FunctionalCategory

class MOAdmin(admin.ModelAdmin):
    fields = ('registration_number','country','description','comment')

    list_display = ('registration_number','country','description','comment')

    list_filter = ('country','functional_category')

    search_fields = ['description','comment']

admin.site.register(MuseumObject, MOAdmin)

admin.site.register(FunctionalCategory)

Enable Django Admin for some of our data

Response:
<INSERT> from django.contrib import admin
from models import MuseumObject,FunctionalCategory

class MOAdmin(admin.ModelAdmin):
 <INSERT_END> <INSERT>   fields = ('registration_number','country','description','comment')

    list_display = ('registration_number','country','description','comment')

    list_filter = ('country','functional_category')

    search_fields = ['description','comment']

admin.site.register(MuseumObject, MOAdmin)

admin.site.register(FunctionalCategory)
 <INSERT_END> <|endoftext|> from django.contrib import admin
from models import MuseumObject,FunctionalCategory

class MOAdmin(admin.ModelAdmin):
    fields = ('registration_number','country','description','comment')

    list_display = ('registration_number','country','description','comment')

    list_filter = ('country','functional_category')

    search_fields = ['description','comment']

admin.site.register(MuseumObject, MOAdmin)

admin.site.register(FunctionalCategory)

Prompt: Enable Django Admin for some of our data