import time

def _tail_print(e):
    print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))

def get_events(conn, stackname):
    """Get the events in batches and return in chronological order"""
    next = None
    event_list = []
    while 1:
        events = conn.describe_stack_events(stackname, next)
        event_list.append(events)
        if events.next_token is None:
            break
        next = events.next_token
        time.sleep(1)
    return reversed(sum(event_list, []))

def tail(conn, stack_name, log_func=_tail_print, sleep_time=5):
    """Show and then tail the event log"""
    # First dump the full list of events in chronological order and keep
    # track of the events we've seen already
    seen = set()
    initial_events = get_events(conn, stack_name)
    for e in initial_events:
        log_func(e)
        seen.add(e.event_id)

    # Now keep looping through and dump the new events
    while 1:
        events = get_events(conn, stack_name)
        for e in events:
            if e.event_id not in seen:
                log_func(e)
            seen.add(e.event_id)
        time.sleep(sleep_time)

Response:
<REPLACE_OLD> get_events(conn, stackname):
    """Get the events in batches and return in chronological order"""
    next = None
    event_list = []
    while 1:
        events = conn.describe_stack_events(stackname, next)
        event_list.append(events)
        if events.next_token is None:
            break
        next = events.next_token
        time.sleep(1)
    return reversed(sum(event_list, []))

def tail(conn, stack_name):
    """Show and then tail the event log"""
    def tail_print(e):
     <REPLACE_NEW> _tail_print(e):
 <REPLACE_END> <REPLACE_OLD> e.event_id))

 <REPLACE_NEW> e.event_id))

def get_events(conn, stackname):
    """Get the events in batches and return in chronological order"""
    next = None
    event_list = []
    while 1:
        events = conn.describe_stack_events(stackname, next)
        event_list.append(events)
        if events.next_token is None:
            break
        next = events.next_token
        time.sleep(1)
    return reversed(sum(event_list, []))

def tail(conn, stack_name, log_func=_tail_print, sleep_time=5):
    """Show and then tail the event log"""
 <REPLACE_END> <REPLACE_OLD> tail_print(e)
 <REPLACE_NEW> log_func(e)
 <REPLACE_END> <REPLACE_OLD> tail_print(e)
 <REPLACE_NEW> log_func(e)
 <REPLACE_END> <REPLACE_OLD> time.sleep(5)
 <REPLACE_NEW> time.sleep(sleep_time)
 <REPLACE_END> <|endoftext|> import time

def _tail_print(e):
    print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))

def get_events(conn, stackname):
    """Get the events in batches and return in chronological order"""
    next = None
    event_list = []
    while 1:
        events = conn.describe_stack_events(stackname, next)
        event_list.append(events)
        if events.next_token is None:
            break
        next = events.next_token
        time.sleep(1)
    return reversed(sum(event_list, []))

def tail(conn, stack_name, log_func=_tail_print, sleep_time=5):
    """Show and then tail the event log"""
    # First dump the full list of events in chronological order and keep
    # track of the events we've seen already
    seen = set()
    initial_events = get_events(conn, stack_name)
    for e in initial_events:
        log_func(e)
        seen.add(e.event_id)

    # Now keep looping through and dump the new events
    while 1:
        events = get_events(conn, stack_name)
        for e in events:
            if e.event_id not in seen:
                log_func(e)
            seen.add(e.event_id)
        time.sleep(sleep_time)

Prompt:
Support a custom logging function and sleep time within tail

import time

def get_events(conn, stackname):
    """Get the events in batches and return in chronological order"""
    next = None
    event_list = []
    while 1:
        events = conn.describe_stack_events(stackname, next)
        event_list.append(events)
        if events.next_token is None:
            break
        next = events.next_token
        time.sleep(1)
    return reversed(sum(event_list, []))

def tail(conn, stack_name):
    """Show and then tail the event log"""
    def tail_print(e):
        print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))

    # First dump the full list of events in chronological order and keep
    # track of the events we've seen already
    seen = set()
    initial_events = get_events(conn, stack_name)
    for e in initial_events:
        tail_print(e)
        seen.add(e.event_id)

    # Now keep looping through and dump the new events
    while 1:
        events = get_events(conn, stack_name)
        for e in events:
            if e.event_id not in seen:
                tail_print(e)
            seen.add(e.event_id)
        time.sleep(5)


"""Representation filters for API"""

from flask import make_response, current_app
from bson.json_util import dumps

def output_bson(data, code, headers=None):
    """Makes Flask response with a JSON encoded body.

    Response items are serialized from MongoDB BSON objects to
    JSON compatible format.

    Modified from module `flask_restful.representations.json`

    """

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', True)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp

Response:
<REPLACE_OLD> BSON <REPLACE_NEW> JSON <REPLACE_END> <REPLACE_OLD> body

 <REPLACE_NEW> body.

 <REPLACE_END> <REPLACE_OLD> Copied <REPLACE_NEW> Response items are serialized from MongoDB BSON objects to
    JSON compatible format.

    Modified <REPLACE_END> <|endoftext|> """Representation filters for API"""

from flask import make_response, current_app
from bson.json_util import dumps

def output_bson(data, code, headers=None):
    """Makes Flask response with a JSON encoded body.

    Response items are serialized from MongoDB BSON objects to
    JSON compatible format.

    Modified from module `flask_restful.representations.json`

    """

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', True)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp

Prompt:
Correct JSON/BSON terminology in docstrings

"""Representation filters for API"""

from flask import make_response, current_app
from bson.json_util import dumps

def output_bson(data, code, headers=None):
    """Makes Flask response with a BSON encoded body

    Copied from module `flask_restful.representations.json`

    """

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', True)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


from django.conf.urls import patterns, include
from django.views.generic import TemplateView
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(
    # Prefix
    '',

    (r'^admin/', include(admin.site.urls)),
    (r'^api/', include('blimp.router')),

    (r'', include('blimp.users.urls')),

    # Catch all URL
    (r'^.*/$', TemplateView.as_view(template_name='index.html'))
)

Response:
<REPLACE_OLD> (r'^', <REPLACE_NEW> (r'^.*/$', <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include
from django.views.generic import TemplateView
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(
    # Prefix
    '',

    (r'^admin/', include(admin.site.urls)),
    (r'^api/', include('blimp.router')),

    (r'', include('blimp.users.urls')),

    # Catch all URL
    (r'^.*/$', TemplateView.as_view(template_name='index.html'))
)

Prompt:
Fix catch all URL to allow APPEND_SLASH to work
from django.conf.urls import patterns, include
from django.views.generic import TemplateView
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(
    # Prefix
    '',

    (r'^admin/', include(admin.site.urls)),
    (r'^api/', include('blimp.router')),

    (r'', include('blimp.users.urls')),

    # Catch all URL
    (r'^', TemplateView.as_view(template_name='index.html'))
)


from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField

csrf = CsrfProtect()

class Submission(Form):
    submission = StringField('Submission URL')
    comments = BooleanField('Include comments')
    comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
    email = StringField('Kindle email address')
    kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])

class Subreddit(Form):
    subreddit = StringField('Subreddit')
    comments = BooleanField('Include comments')
    comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
    time = SelectField('Time period',
                       choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
                                ('hour', 'hour')])
    limit = IntegerField('Number of posts')
    email = StringField('Kindle email address')
    kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])

Make numbers the default comments style

Make numbers the default comments style

Response:
<REPLACE_OLD> choices=[('quotes', 'quotes'), ('numbers', 'numbers')])
 <REPLACE_NEW> choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
 <REPLACE_END> <REPLACE_OLD> choices=[('quotes', 'quotes'), ('numbers', 'numbers')])
 <REPLACE_NEW> choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
 <REPLACE_END> <|endoftext|> from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField

csrf = CsrfProtect()

class Submission(Form):
    submission = StringField('Submission URL')
    comments = BooleanField('Include comments')
    comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
    email = StringField('Kindle email address')
    kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])

class Subreddit(Form):
    subreddit = StringField('Subreddit')
    comments = BooleanField('Include comments')
    comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')])
    time = SelectField('Time period',
                       choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
                                ('hour', 'hour')])
    limit = IntegerField('Number of posts')
    email = StringField('Kindle email address')
    kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])

Prompt:
Make numbers the default comments style

from flask_wtf import Form
from flask_wtf.csrf import CsrfProtect
from wtforms import StringField, IntegerField, SelectField, BooleanField

csrf = CsrfProtect()

class Submission(Form):
    submission = StringField('Submission URL')
    comments = BooleanField('Include comments')
    comments_style = SelectField('Comments style', choices=[('quotes', 'quotes'), ('numbers', 'numbers')])
    email = StringField('Kindle email address')
    kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])

class Subreddit(Form):
    subreddit = StringField('Subreddit')
    comments = BooleanField('Include comments')
    comments_style = SelectField('Comments style', choices=[('quotes', 'quotes'), ('numbers', 'numbers')])
    time = SelectField('Time period',
                       choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'),
                                ('hour', 'hour')])
    limit = IntegerField('Number of posts')
    email = StringField('Kindle email address')
    kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])


"""
Test the top-level Kafka Streams class
"""

import pytest

from winton_kafka_streams import kafka_config
from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError
from winton_kafka_streams.kafka_streams import KafkaStreams
from winton_kafka_streams.processor.processor import BaseProcessor
from winton_kafka_streams.processor.topology import TopologyBuilder

class MyTestProcessor(BaseProcessor):
    pass

def test__given__stream_already_started__when__call_start_again__then__raise_error():
    kafka_config.NUM_STREAM_THREADS = 0
    topology_builder = TopologyBuilder()

    topology_builder.source('my-source', ['my-input-topic-1'])
    topology_builder.processor('my-processor', MyTestProcessor, 'my-source')
    topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor')

    topology = topology_builder.build()

    kafka_streams = KafkaStreams(topology, kafka_config)
    kafka_streams.start()

    with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'):
        kafka_streams.start()

Use more Pythonic name for test.

Use more Pythonic name for test.

Response:
<REPLACE_OLD> test_Given_StreamAlreadyStarted_When_CallStartAgain_Then_RaiseError():
 <REPLACE_NEW> test__given__stream_already_started__when__call_start_again__then__raise_error():
 <REPLACE_END> <|endoftext|> """
Test the top-level Kafka Streams class
"""

import pytest

from winton_kafka_streams import kafka_config
from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError
from winton_kafka_streams.kafka_streams import KafkaStreams
from winton_kafka_streams.processor.processor import BaseProcessor
from winton_kafka_streams.processor.topology import TopologyBuilder

class MyTestProcessor(BaseProcessor):
    pass

def test__given__stream_already_started__when__call_start_again__then__raise_error():
    kafka_config.NUM_STREAM_THREADS = 0
    topology_builder = TopologyBuilder()

    topology_builder.source('my-source', ['my-input-topic-1'])
    topology_builder.processor('my-processor', MyTestProcessor, 'my-source')
    topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor')

    topology = topology_builder.build()

    kafka_streams = KafkaStreams(topology, kafka_config)
    kafka_streams.start()

    with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'):
        kafka_streams.start()

Prompt:
Use more Pythonic name for test.

"""
Test the top-level Kafka Streams class
"""

import pytest

from winton_kafka_streams import kafka_config
from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError
from winton_kafka_streams.kafka_streams import KafkaStreams
from winton_kafka_streams.processor.processor import BaseProcessor
from winton_kafka_streams.processor.topology import TopologyBuilder

class MyTestProcessor(BaseProcessor):
    pass

def test_Given_StreamAlreadyStarted_When_CallStartAgain_Then_RaiseError():
    kafka_config.NUM_STREAM_THREADS = 0
    topology_builder = TopologyBuilder()

    topology_builder.source('my-source', ['my-input-topic-1'])
    topology_builder.processor('my-processor', MyTestProcessor, 'my-source')
    topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor')

    topology = topology_builder.build()

    kafka_streams = KafkaStreams(topology, kafka_config)
    kafka_streams.start()

    with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'):
        kafka_streams.start()


import logging
import time

from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist

logger = logging.getLogger('backends.base')

class BaseBackend(object):
    current_playlist = None
    library = None
    playback = None
    stored_playlists = None
    uri_handlers = []

class BaseCurrentPlaylistController(object):
    def __init__(self, backend):
        self.backend = backend

    def add(self, track, at_position=None):
        raise NotImplementedError

class BasePlaybackController(object):
    PAUSED = 'paused'
    PLAYING = 'playing'
    STOPPED = 'stopped'

    def __init__(self, backend):
        self.backend = backend
        self.state = self.STOPPED
        self.current_track = None
        self.playlist_position = None

    def play(self, id=None, position=None):
        raise NotImplementedError

    def next(self):
        raise NotImplementedError

Response:
<REPLACE_OLD> backend

class <REPLACE_NEW> backend

    def add(self, track, at_position=None):
        raise NotImplementedError

class <REPLACE_END> <|endoftext|> import logging
import time

from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist

logger = logging.getLogger('backends.base')

class BaseBackend(object):
    current_playlist = None
    library = None
    playback = None
    stored_playlists = None
    uri_handlers = []

class BaseCurrentPlaylistController(object):
    def __init__(self, backend):
        self.backend = backend

    def add(self, track, at_position=None):
        raise NotImplementedError

class BasePlaybackController(object):
    PAUSED = 'paused'
    PLAYING = 'playing'
    STOPPED = 'stopped'

    def __init__(self, backend):
        self.backend = backend
        self.state = self.STOPPED
        self.current_track = None
        self.playlist_position = None

    def play(self, id=None, position=None):
        raise NotImplementedError

    def next(self):
        raise NotImplementedError

Prompt:
Add add method to BaseCurrentPlaylistController

import logging
import time

from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist

logger = logging.getLogger('backends.base')

class BaseBackend(object):
    current_playlist = None
    library = None
    playback = None
    stored_playlists = None
    uri_handlers = []

class BaseCurrentPlaylistController(object):
    def __init__(self, backend):
        self.backend = backend

class BasePlaybackController(object):
    PAUSED = 'paused'
    PLAYING = 'playing'
    STOPPED = 'stopped'

    def __init__(self, backend):
        self.backend = backend
        self.state = self.STOPPED
        self.current_track = None
        self.playlist_position = None

    def play(self, id=None, position=None):
        raise NotImplementedError

    def next(self):
        raise NotImplementedError


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

UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0

INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)

UINT256_MAX = 2 ** 256 - 1

# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'

MINUTE_SEC = 60
MINUTE_MS = 60 * 1000

NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6

# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200

Response:
<REPLACE_OLD> 1

ROPSTEN_REGISTRY_ADDRESS <REPLACE_NEW> 1

# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS <REPLACE_END> <REPLACE_OLD> 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS <REPLACE_NEW> 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS <REPLACE_END> <REPLACE_OLD> '524b7dcacac3055bd42fc03b006e9fdcb607e2be'

MINUTE_SEC <REPLACE_NEW> 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'

MINUTE_SEC <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0

INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)

UINT256_MAX = 2 ** 256 - 1

# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'

MINUTE_SEC = 60
MINUTE_MS = 60 * 1000

NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6

# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200

Prompt:
Update pre-deployed Ropsten contract addresses
# -*- coding: utf-8 -*-

UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0

INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)

UINT256_MAX = 2 ** 256 - 1

ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'

MINUTE_SEC = 60
MINUTE_MS = 60 * 1000

NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6

# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200


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

from smaug.tests.fullstack import smaug_base

class ProvidersTest(smaug_base.SmaugBaseTest):
    """Test Providers operation"""
    provider_id = u"cf56bd3e-97a7-4078-b6d5-f36246333fd9"

    def test_providers_list(self):
        provider_res = self.smaug_client.providers.list()
        self.assertEqual(1, len(provider_res))

    def test_provider_get(self):
        provider_res = self.smaug_client.providers.get(self.provider_id)
        self.assertEqual("OS Infra Provider", provider_res.name)

Add fullstack tests of the resource providers

Change-Id: Ie4f769de3060fdb279320637ba965d5b452e2a2d
Closes-Bug: #1578889

Response:
<INSERT> # 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
#
# <INSERT_END> <INSERT>     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from smaug.tests.fullstack import smaug_base

class ProvidersTest(smaug_base.SmaugBaseTest):
    """Test Providers operation"""
    provider_id = u"cf56bd3e-97a7-4078-b6d5-f36246333fd9"

    def test_providers_list(self):
        provider_res = self.smaug_client.providers.list()
        self.assertEqual(1, len(provider_res))

    def test_provider_get(self):
        provider_res = self.smaug_client.providers.get(self.provider_id)
        self.assertEqual("OS Infra Provider", provider_res.name)
 <INSERT_END> <|endoftext|> # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from smaug.tests.fullstack import smaug_base

class ProvidersTest(smaug_base.SmaugBaseTest):
    """Test Providers operation"""
    provider_id = u"cf56bd3e-97a7-4078-b6d5-f36246333fd9"

    def test_providers_list(self):
        provider_res = self.smaug_client.providers.list()
        self.assertEqual(1, len(provider_res))

    def test_provider_get(self):
        provider_res = self.smaug_client.providers.get(self.provider_id)
        self.assertEqual("OS Infra Provider", provider_res.name)

Prompt:
Add fullstack tests of the resource providers

Change-Id: Ie4f769de3060fdb279320637ba965d5b452e2a2d
Closes-Bug: #1578889


# IPython log file
# See https://stackoverflow.com/questions/62135639/mcp-geometrics-for-calculating-marketsheds/62144556
import numpy as np
from scipy import sparse
from skimage import graph
from skimage.graph import _mcp

image = np.array([[1, 1, 2, 2], [2, 1, 1, 3], [3, 2, 1, 2], [2, 2, 2, 1]])
mcp = graph.MCP_Geometric(image)
destinations = [[0, 0], [3, 3]]
costs, traceback = mcp.find_costs(destinations)
offsets = _mcp.make_offsets(2, True)
indices = np.indices(traceback.shape)
offsets.append([0, 0])
offsets_arr = np.array(offsets)
offset_to_neighbor = offsets_arr[traceback]
neighbor_index = indices - offset_to_neighbor.transpose((2, 0, 1))
ids = np.arange(traceback.size).reshape(image.shape)
neighbor_ids = np.ravel_multi_index(tuple(neighbor_index), traceback.shape)
g = sparse.coo_matrix((
    np.ones(traceback.size),
    (ids.flat, neighbor_ids.flat),
)).tocsr()
basins = sparse.csgraph.connected_components(g)[1].reshape((4, 4))
print(basins)

Add link to SO question

Add link to SO question

Response:
<REPLACE_OLD> file
import <REPLACE_NEW> file
# See https://stackoverflow.com/questions/62135639/mcp-geometrics-for-calculating-marketsheds/62144556
import <REPLACE_END> <|endoftext|> # IPython log file
# See https://stackoverflow.com/questions/62135639/mcp-geometrics-for-calculating-marketsheds/62144556
import numpy as np
from scipy import sparse
from skimage import graph
from skimage.graph import _mcp

image = np.array([[1, 1, 2, 2], [2, 1, 1, 3], [3, 2, 1, 2], [2, 2, 2, 1]])
mcp = graph.MCP_Geometric(image)
destinations = [[0, 0], [3, 3]]
costs, traceback = mcp.find_costs(destinations)
offsets = _mcp.make_offsets(2, True)
indices = np.indices(traceback.shape)
offsets.append([0, 0])
offsets_arr = np.array(offsets)
offset_to_neighbor = offsets_arr[traceback]
neighbor_index = indices - offset_to_neighbor.transpose((2, 0, 1))
ids = np.arange(traceback.size).reshape(image.shape)
neighbor_ids = np.ravel_multi_index(tuple(neighbor_index), traceback.shape)
g = sparse.coo_matrix((
    np.ones(traceback.size),
    (ids.flat, neighbor_ids.flat),
)).tocsr()
basins = sparse.csgraph.connected_components(g)[1].reshape((4, 4))
print(basins)

Prompt:
Add link to SO question

# IPython log file
import numpy as np
from scipy import sparse
from skimage import graph
from skimage.graph import _mcp

image = np.array([[1, 1, 2, 2], [2, 1, 1, 3], [3, 2, 1, 2], [2, 2, 2, 1]])
mcp = graph.MCP_Geometric(image)
destinations = [[0, 0], [3, 3]]
costs, traceback = mcp.find_costs(destinations)
offsets = _mcp.make_offsets(2, True)
indices = np.indices(traceback.shape)
offsets.append([0, 0])
offsets_arr = np.array(offsets)
offset_to_neighbor = offsets_arr[traceback]
neighbor_index = indices - offset_to_neighbor.transpose((2, 0, 1))
ids = np.arange(traceback.size).reshape(image.shape)
neighbor_ids = np.ravel_multi_index(tuple(neighbor_index), traceback.shape)
g = sparse.coo_matrix((
    np.ones(traceback.size),
    (ids.flat, neighbor_ids.flat),
)).tocsr()
basins = sparse.csgraph.connected_components(g)[1].reshape((4, 4))
print(basins)


def buildsys_build_state_change(config, message):
    """ Buildsys: build changed state (started, failed, finished)

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.build.state.change')

def buildsys_package_list_change(config, message):
    """ Buildsys: Package list changed

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.package.list.change')

def buildsys_repo_done(config, message):
    """ Buildsys: Building a repo has finished

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.repo.done')

def buildsys_repo_init(config, message):
    """ Buildsys: Building a repo has started

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.repo.init')

def buildsys_tag(config, message):
    """ Buildsys: A package has been tagged

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.tag')

def buildsys_untag(config, message):
    """ Buildsys: A package has been untagged

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.untag')

Add filters for the buildsystem messages

Response:
<INSERT>

def buildsys_build_state_change(config, message):
 <INSERT_END> <INSERT>   """ Buildsys: build changed state (started, failed, finished)

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.build.state.change')

def buildsys_package_list_change(config, message):
    """ Buildsys: Package list changed

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.package.list.change')

def buildsys_repo_done(config, message):
    """ Buildsys: Building a repo has finished

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.repo.done')

def buildsys_repo_init(config, message):
    """ Buildsys: Building a repo has started

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.repo.init')

def buildsys_tag(config, message):
    """ Buildsys: A package has been tagged

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.tag')

def buildsys_untag(config, message):
    """ Buildsys: A package has been untagged

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.untag')
 <INSERT_END> <|endoftext|>

def buildsys_build_state_change(config, message):
    """ Buildsys: build changed state (started, failed, finished)

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.build.state.change')

def buildsys_package_list_change(config, message):
    """ Buildsys: Package list changed

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.package.list.change')

def buildsys_repo_done(config, message):
    """ Buildsys: Building a repo has finished

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.repo.done')

def buildsys_repo_init(config, message):
    """ Buildsys: Building a repo has started

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.repo.init')

def buildsys_tag(config, message):
    """ Buildsys: A package has been tagged

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.tag')

def buildsys_untag(config, message):
    """ Buildsys: A package has been untagged

    TODO description for the web interface goes here
    """
    return message['topic'].endswith('buildsys.untag')

Prompt: Add filters for the buildsystem messages


from flask import Flask, request
from pprint import pprint
import json

app = Flask(__name__)
lastCommit = "No recorded commits!"

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/latest")
def latest():
  return lastCommit

@app.route("/update", methods=["POST"])
def update():
  payload = json.dumps(request.form['payload'])
  lastCommit = payload['commits'][0]['message']
  return ""

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)

Add code to show last commit message

Add code to show last commit message

Response:
<REPLACE_OLD> GitHub"

@app.route("/update", <REPLACE_NEW> GitHub"

@app.route("/latest")
def latest():
  return lastCommit

@app.route("/update", <REPLACE_END> <REPLACE_OLD> print <REPLACE_NEW> payload = <REPLACE_END> <REPLACE_OLD> return

if <REPLACE_NEW> lastCommit = payload['commits'][0]['message']
  return ""

if <REPLACE_END> <|endoftext|> from flask import Flask, request
from pprint import pprint
import json

app = Flask(__name__)
lastCommit = "No recorded commits!"

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/latest")
def latest():
  return lastCommit

@app.route("/update", methods=["POST"])
def update():
  payload = json.dumps(request.form['payload'])
  lastCommit = payload['commits'][0]['message']
  return ""

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)

Prompt:
Add code to show last commit message

from flask import Flask, request
from pprint import pprint
import json

app = Flask(__name__)
lastCommit = "No recorded commits!"

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/update", methods=["POST"])
def update():
  print json.dumps(request.form['payload'])
  return

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)


"""This module provides SQL Server specific fields for Django models."""
from django.db.models import AutoField, ForeignKey, IntegerField
from django.forms import ValidationError

class BigAutoField(AutoField):
    """A bigint IDENTITY field"""
    def get_internal_type(self):
        return "BigAutoField"

    def to_python(self, value):
        if value is None:
            return value
        try:
            return long(value)
        except (TypeError, ValueError):
            raise ValidationError(
                _("This value must be an long."))

    def get_db_prep_value(self, value):
        if value is None:
            return None
        return long(value)

class BigForeignKey(ForeignKey):
    """A ForeignKey field that points to a BigAutoField or BigIntegerField"""
    def db_type(self):
        return BigIntegerField().db_type()

class BigIntegerField(IntegerField):
    """A BigInteger field, until Django ticket #399 lands (if ever.)"""
    def get_internal_type(self):
        return "BigIntegerField"

    def to_python(self, value):
        if value is None:
            return value
        try:
            return long(value)
        except (TypeError, ValueError):
            raise ValidationError(
                _("This value must be an long."))

    def get_db_prep_value(self, value):
        if value is None:
            return None
        return long(value)

Response:
<REPLACE_OLD> IntegerField

class <REPLACE_NEW> IntegerField
from django.forms import ValidationError

class <REPLACE_END> <REPLACE_OLD> exceptions.ValidationError(
 <REPLACE_NEW> ValidationError(
 <REPLACE_END> <REPLACE_OLD> exceptions.ValidationError(
 <REPLACE_NEW> ValidationError(
 <REPLACE_END> <|endoftext|> """This module provides SQL Server specific fields for Django models."""
from django.db.models import AutoField, ForeignKey, IntegerField
from django.forms import ValidationError

class BigAutoField(AutoField):
    """A bigint IDENTITY field"""
    def get_internal_type(self):
        return "BigAutoField"

    def to_python(self, value):
        if value is None:
            return value
        try:
            return long(value)
        except (TypeError, ValueError):
            raise ValidationError(
                _("This value must be an long."))

    def get_db_prep_value(self, value):
        if value is None:
            return None
        return long(value)

class BigForeignKey(ForeignKey):
    """A ForeignKey field that points to a BigAutoField or BigIntegerField"""
    def db_type(self):
        return BigIntegerField().db_type()

class BigIntegerField(IntegerField):
    """A BigInteger field, until Django ticket #399 lands (if ever.)"""
    def get_internal_type(self):
        return "BigIntegerField"

    def to_python(self, value):
        if value is None:
            return value
        try:
            return long(value)
        except (TypeError, ValueError):
            raise ValidationError(
                _("This value must be an long."))

    def get_db_prep_value(self, value):
        if value is None:
            return None
        return long(value)

Prompt:
Fix import error for custom Field validation

"""This module provides SQL Server specific fields for Django models."""
from django.db.models import AutoField, ForeignKey, IntegerField

class BigAutoField(AutoField):
    """A bigint IDENTITY field"""
    def get_internal_type(self):
        return "BigAutoField"

    def to_python(self, value):
        if value is None:
            return value
        try:
            return long(value)
        except (TypeError, ValueError):
            raise exceptions.ValidationError(
                _("This value must be an long."))

    def get_db_prep_value(self, value):
        if value is None:
            return None
        return long(value)

class BigForeignKey(ForeignKey):
    """A ForeignKey field that points to a BigAutoField or BigIntegerField"""
    def db_type(self):
        return BigIntegerField().db_type()

class BigIntegerField(IntegerField):
    """A BigInteger field, until Django ticket #399 lands (if ever.)"""
    def get_internal_type(self):
        return "BigIntegerField"

    def to_python(self, value):
        if value is None:
            return value
        try:
            return long(value)
        except (TypeError, ValueError):
            raise exceptions.ValidationError(
                _("This value must be an long."))

    def get_db_prep_value(self, value):
        if value is None:
            return None
        return long(value)


"""Tests for foamPy."""

from .core import *
from .dictionaries import *
from .types import *
from .foil import *

def test_load_all_torque_drag():
    """Test the `load_all_torque_drag` function."""
    t, torque, drag = load_all_torque_drag(casedir="test")
    assert t.max() == 4.0

Response:
<REPLACE_OLD> """
Tests <REPLACE_NEW> """Tests <REPLACE_END> <REPLACE_OLD> foamPy.
"""

from <REPLACE_NEW> foamPy."""

from <REPLACE_END> <REPLACE_OLD> *
 <REPLACE_NEW> *

def test_load_all_torque_drag():
    """Test the `load_all_torque_drag` function."""
    t, torque, drag = load_all_torque_drag(casedir="test")
    assert t.max() == 4.0
 <REPLACE_END> <|endoftext|> """Tests for foamPy."""

from .core import *
from .dictionaries import *
from .types import *
from .foil import *

def test_load_all_torque_drag():
    """Test the `load_all_torque_drag` function."""
    t, torque, drag = load_all_torque_drag(casedir="test")
    assert t.max() == 4.0

Prompt:
Add test for loading all torque and drag data

"""
Tests for foamPy.
"""

from .core import *
from .dictionaries import *
from .types import *
from .foil import *


# -*- encoding: utf-8 -*-
# JN 2016-02-16

"""
Plot a spectrum from the first 1000 records of data
"""
import sys
import scipy.signal as sig
import matplotlib.pyplot as mpl

from combinato import NcsFile, DefaultFilter

def plot_spectrum(fname):
    fid = NcsFile(fname)
    rawdata = fid.read(0, 1000)
    data = rawdata * (1e6 * fid.header['ADBitVolts'])
    fs = 1/fid.timestep
    my_filter = DefaultFilter(fid.timestep)
    filt_data = my_filter.filter_extract(data)
    [f, p] = sig.welch(data, fs, nperseg=32768)
    [f_filt, p_filt] = sig.welch(filt_data, fs, nperseg=32768)

    fig = mpl.figure()
    plot = fig.add_subplot(1, 1, 1)
    plot.plot(f, p, label='Unfiltered')
    plot.plot(f_filt, p_filt, label='Filtered')

    plot.set_yscale('log')
    plot.legend()
    plot.set_ylabel(r'$\mu\mathrm{V}^2/\mathrm{Hz}$')
    plot.set_xlabel(r'$\mathrm{Hz}$')

def main():
    plot_spectrum(sys.argv[1])
    mpl.show()

if __name__ == '__main__':
    main()

Add small plot of power spectral density

Response:
<INSERT> # -*- encoding: utf-8 -*-
# JN 2016-02-16

"""
Plot a spectrum from the first 1000 records of data
"""
import sys
import scipy.signal as sig
import matplotlib.pyplot as mpl

from combinato import NcsFile, DefaultFilter

def plot_spectrum(fname):
 <INSERT_END> <INSERT>   fid = NcsFile(fname)
    rawdata = fid.read(0, 1000)
    data = rawdata * (1e6 * fid.header['ADBitVolts'])
    fs = 1/fid.timestep
    my_filter = DefaultFilter(fid.timestep)
    filt_data = my_filter.filter_extract(data)
    [f, p] = sig.welch(data, fs, nperseg=32768)
    [f_filt, p_filt] = sig.welch(filt_data, fs, nperseg=32768)

    fig = mpl.figure()
    plot = fig.add_subplot(1, 1, 1)
    plot.plot(f, p, label='Unfiltered')
    plot.plot(f_filt, p_filt, label='Filtered')

    plot.set_yscale('log')
    plot.legend()
    plot.set_ylabel(r'$\mu\mathrm{V}^2/\mathrm{Hz}$')
    plot.set_xlabel(r'$\mathrm{Hz}$')

def main():
    plot_spectrum(sys.argv[1])
    mpl.show()

if __name__ == '__main__':
    main()
 <INSERT_END> <|endoftext|> # -*- encoding: utf-8 -*-
# JN 2016-02-16

"""
Plot a spectrum from the first 1000 records of data
"""
import sys
import scipy.signal as sig
import matplotlib.pyplot as mpl

from combinato import NcsFile, DefaultFilter

def plot_spectrum(fname):
    fid = NcsFile(fname)
    rawdata = fid.read(0, 1000)
    data = rawdata * (1e6 * fid.header['ADBitVolts'])
    fs = 1/fid.timestep
    my_filter = DefaultFilter(fid.timestep)
    filt_data = my_filter.filter_extract(data)
    [f, p] = sig.welch(data, fs, nperseg=32768)
    [f_filt, p_filt] = sig.welch(filt_data, fs, nperseg=32768)

    fig = mpl.figure()
    plot = fig.add_subplot(1, 1, 1)
    plot.plot(f, p, label='Unfiltered')
    plot.plot(f_filt, p_filt, label='Filtered')

    plot.set_yscale('log')
    plot.legend()
    plot.set_ylabel(r'$\mu\mathrm{V}^2/\mathrm{Hz}$')
    plot.set_xlabel(r'$\mathrm{Hz}$')

def main():
    plot_spectrum(sys.argv[1])
    mpl.show()

if __name__ == '__main__':
    main()

Prompt: Add small plot of power spectral density


#i = 0
#numbers = []

#while i < 6:
#    print "At the top i is %d" % i
#    numbers.append(i)
#
#    i += 1
#    print "Numbers now: ", numbers
#    print "At the bottom i is %d" % i
#
#
#print "The numbers: "
#
#for num in numbers:
#    print num

#Study Drills
print "What's the limit of the list?"
a = int(raw_input("> "))

def list_numbers(a):
    """This function might add numbers to a list?"""
    i = 0
    numbers = []

    while i < a:
        print "At the top i is %d" % i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

    print "The numbers: "

    for num in numbers:
        print num

    return

list_numbers(a)

Response:
<REPLACE_OLD> raw_input("> ")

def <REPLACE_NEW> int(raw_input("> "))

def <REPLACE_END> <|endoftext|> #i = 0
#numbers = []

#while i < 6:
#    print "At the top i is %d" % i
#    numbers.append(i)
#
#    i += 1
#    print "Numbers now: ", numbers
#    print "At the bottom i is %d" % i
#
#
#print "The numbers: "
#
#for num in numbers:
#    print num

#Study Drills
print "What's the limit of the list?"
a = int(raw_input("> "))

def list_numbers(a):
    """This function might add numbers to a list?"""
    i = 0
    numbers = []

    while i < a:
        print "At the top i is %d" % i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

    print "The numbers: "

    for num in numbers:
        print num

    return

list_numbers(a)

Prompt:
Fix that crazy error that would cause enless looping...

#i = 0
#numbers = []

#while i < 6:
#    print "At the top i is %d" % i
#    numbers.append(i)
#
#    i += 1
#    print "Numbers now: ", numbers
#    print "At the bottom i is %d" % i
#
#
#print "The numbers: "
#
#for num in numbers:
#    print num

#Study Drills
print "What's the limit of the list?"
a = raw_input("> ")

def list_numbers(a):
    """This function might add numbers to a list?"""
    i = 0
    numbers = []

    while i < a:
        print "At the top i is %d" % i
        numbers.append(i)

        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

    print "The numbers: "

    for num in numbers:
        print num

    return

list_numbers(a)


from settings_common import *

PACKAGE_VERSION = "0.5"

DEBUG = TEMPLATE_DEBUG = True

DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp')

SERVE_STATIC_FILES = True

# the following is an idea from https://code.djangoproject.com/wiki/SplitSettings
# We have both local settings and common settings. They are used as follows:
# - common settings are shared data between normal settings and unit test settings
# - local settings are used on productive servers to keep the local
#   settings such as db passwords, etc out of version control
try:
    from settings_local import *
except ImportError:
    pass

if SERVE_STATIC_FILES:
    INSTALLED_APPS += ('django.contrib.staticfiles',)

Response:
<REPLACE_OLD> pass
 <REPLACE_NEW> pass

if SERVE_STATIC_FILES:
    INSTALLED_APPS += ('django.contrib.staticfiles',)
 <REPLACE_END> <|endoftext|> from settings_common import *

PACKAGE_VERSION = "0.5"

DEBUG = TEMPLATE_DEBUG = True

DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp')

SERVE_STATIC_FILES = True

# the following is an idea from https://code.djangoproject.com/wiki/SplitSettings
# We have both local settings and common settings. They are used as follows:
# - common settings are shared data between normal settings and unit test settings
# - local settings are used on productive servers to keep the local
#   settings such as db passwords, etc out of version control
try:
    from settings_local import *
except ImportError:
    pass

if SERVE_STATIC_FILES:
    INSTALLED_APPS += ('django.contrib.staticfiles',)

Prompt:
Use django.contrib.staticfiles when running locally

so that the admin interface uses the proper css when running on the
dev machine

from settings_common import *

PACKAGE_VERSION = "0.5"

DEBUG = TEMPLATE_DEBUG = True

DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp')

SERVE_STATIC_FILES = True

# the following is an idea from https://code.djangoproject.com/wiki/SplitSettings
# We have both local settings and common settings. They are used as follows:
# - common settings are shared data between normal settings and unit test settings
# - local settings are used on productive servers to keep the local
#   settings such as db passwords, etc out of version control
try:
    from settings_local import *
except ImportError:
    pass


#!/usr/bin/env python

'''Checks processes'''

#===============================================================================
# Import modules
#===============================================================================

# Standard Library
import os
import subprocess
import logging

# Third party modules

# Application modules

#===============================================================================
# Check script is running
#===============================================================================
def is_running(script_name):

    '''Checks list of processes for script name and filters out lines with the
    PID and parent PID. Returns a TRUE if other script with the same name is
    found running.'''

    try:
        logger = logging.getLogger('root')

        cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
        cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout,
                                stdout=subprocess.PIPE)
        cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout,
                                stdout=subprocess.PIPE)
        cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout,
                                stdout=subprocess.PIPE)
        cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout,
                                stdout=subprocess.PIPE)

        other_script_found = cmd5.communicate()[0]

        if other_script_found:
            logger.info('Script already runnning. Exiting...')
            logger.info(other_script_found)
            return True

        return False

    except Exception, e:
        logger.error('System check failed ({error_v}). Exiting...'.format(
            error_v=e))
        return True

Response:
<REPLACE_OLD> logger.error('Script <REPLACE_NEW> logger.info('Script <REPLACE_END> <REPLACE_OLD> logger.error(other_script_found)
 <REPLACE_NEW> logger.info(other_script_found)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

'''Checks processes'''

#===============================================================================
# Import modules
#===============================================================================

# Standard Library
import os
import subprocess
import logging

# Third party modules

# Application modules

#===============================================================================
# Check script is running
#===============================================================================
def is_running(script_name):

    '''Checks list of processes for script name and filters out lines with the
    PID and parent PID. Returns a TRUE if other script with the same name is
    found running.'''

    try:
        logger = logging.getLogger('root')

        cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
        cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout,
                                stdout=subprocess.PIPE)
        cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout,
                                stdout=subprocess.PIPE)
        cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout,
                                stdout=subprocess.PIPE)
        cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout,
                                stdout=subprocess.PIPE)

        other_script_found = cmd5.communicate()[0]

        if other_script_found:
            logger.info('Script already runnning. Exiting...')
            logger.info(other_script_found)
            return True

        return False

    except Exception, e:
        logger.error('System check failed ({error_v}). Exiting...'.format(
            error_v=e))
        return True

Prompt:
Downgrade script already running to info

#!/usr/bin/env python

'''Checks processes'''

#===============================================================================
# Import modules
#===============================================================================

# Standard Library
import os
import subprocess
import logging

# Third party modules

# Application modules

#===============================================================================
# Check script is running
#===============================================================================
def is_running(script_name):

    '''Checks list of processes for script name and filters out lines with the
    PID and parent PID. Returns a TRUE if other script with the same name is
    found running.'''

    try:
        logger = logging.getLogger('root')

        cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
        cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout,
                                stdout=subprocess.PIPE)
        cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout,
                                stdout=subprocess.PIPE)
        cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout,
                                stdout=subprocess.PIPE)
        cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout,
                                stdout=subprocess.PIPE)

        other_script_found = cmd5.communicate()[0]

        if other_script_found:
            logger.error('Script already runnning. Exiting...')
            logger.error(other_script_found)
            return True

        return False

    except Exception, e:
        logger.error('System check failed ({error_v}). Exiting...'.format(
            error_v=e))
        return True


# -*- coding: utf8 -*-

from __future__ import unicode_literals
from __future__ import absolute_import

from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404

from ..models import CustomTag

register = template.Library()

@register.assignment_tag
def get_obj_list(app, model, obj):
    '''
    Return list of all objects of type app.model tagged with a tag pointing to
    obj (an object in the db, e.g. Person, Family, ...).
    '''

    try:
        return get_model(app, model).objects.filter(
                tags__slug='%s.%s-%d' % (
                    obj._meta.app_label, obj._meta.model_name, obj.id))
    except:
        return []

@register.assignment_tag
def get_tag_list(app, model, tag):
    '''
    Return list of all objects of type app.model tagged with the tag "tag".
    '''

    try:
        return get_model(app, model).objects.filter(tags__slug='%s' % tag)
    except:
        return []

@register.filter
def as_tag_text(slug):
    try:
        tag = CustomTag.objects.get(slug=slug)
        return tag.as_tag_text()
    except ObjectDoesNotExist:
        raise Http404

Response:
<INSERT> django.core.exceptions import ObjectDoesNotExist
from <INSERT_END> <REPLACE_OLD> get_model

from <REPLACE_NEW> get_model
from django.http import Http404

from <REPLACE_END> <INSERT> try:
        <INSERT_END> <INSERT>     <INSERT_END> <INSERT>    except ObjectDoesNotExist:
        raise Http404

 <INSERT_END> <|endoftext|> # -*- coding: utf8 -*-

from __future__ import unicode_literals
from __future__ import absolute_import

from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404

from ..models import CustomTag

register = template.Library()

@register.assignment_tag
def get_obj_list(app, model, obj):
    '''
    Return list of all objects of type app.model tagged with a tag pointing to
    obj (an object in the db, e.g. Person, Family, ...).
    '''

    try:
        return get_model(app, model).objects.filter(
                tags__slug='%s.%s-%d' % (
                    obj._meta.app_label, obj._meta.model_name, obj.id))
    except:
        return []

@register.assignment_tag
def get_tag_list(app, model, tag):
    '''
    Return list of all objects of type app.model tagged with the tag "tag".
    '''

    try:
        return get_model(app, model).objects.filter(tags__slug='%s' % tag)
    except:
        return []

@register.filter
def as_tag_text(slug):
    try:
        tag = CustomTag.objects.get(slug=slug)
        return tag.as_tag_text()
    except ObjectDoesNotExist:
        raise Http404

Prompt:
Fix server error in tag search for non-existing tag.

# -*- coding: utf8 -*-

from __future__ import unicode_literals
from __future__ import absolute_import

from django import template
from django.db.models.loading import get_model

from ..models import CustomTag

register = template.Library()

@register.assignment_tag
def get_obj_list(app, model, obj):
    '''
    Return list of all objects of type app.model tagged with a tag pointing to
    obj (an object in the db, e.g. Person, Family, ...).
    '''

    try:
        return get_model(app, model).objects.filter(
                tags__slug='%s.%s-%d' % (
                    obj._meta.app_label, obj._meta.model_name, obj.id))
    except:
        return []

@register.assignment_tag
def get_tag_list(app, model, tag):
    '''
    Return list of all objects of type app.model tagged with the tag "tag".
    '''

    try:
        return get_model(app, model).objects.filter(tags__slug='%s' % tag)
    except:
        return []

@register.filter
def as_tag_text(slug):
    tag = CustomTag.objects.get(slug=slug)
    return tag.as_tag_text()


#! /usr/bin/env python

import sys
import re
import yaml

FILE = sys.argv[1]
YAML = sys.argv[2]
TYPE = sys.argv[3]

header = open(YAML, "r")
text = open(FILE, "r")
copy = open(FILE+"_NEW", "wt")

docs = yaml.load_all(header)

for doc in docs:
    if not doc == None:
        if 'figure' in doc.keys():
            for line in text:
                mfig = False
                for f in doc['figure']:
                    my_regex = r"^!\{" + re.escape(f['id']) + r"\}$"
                    if re.search(my_regex, line, re.IGNORECASE):
                        mfig = True
                        if TYPE == 'preprint':
                            ftype = "figure"
                            fwidth = "\\columnwidth"
                            if "wide" in f.keys():
                                ftype = "figure*"
                                fwidth = "\\textwidth"
                            copy.write("\n\\begin{" + ftype + "}[bt]\n")
                            copy.write("\t\\centering\n")
                            copy.write("\t\\includegraphics[width=" + fwidth + "]{" + f['file'] + "}\n")
                            copy.write("\t\\caption{" + f['caption'] + "}\n")
                            copy.write("\t\\label{" + f['id'] + "}\n")
                            copy.write("\\end{" + ftype + "}\n\n")
                if not mfig:
                    copy.write(line)

header.close()
text.close()
copy.close()

Make the python script silent

Make the python script silent

Response:
<DELETE> print line
                        <DELETE_END> <DELETE> print f
                            <DELETE_END> <|endoftext|> #! /usr/bin/env python

import sys
import re
import yaml

FILE = sys.argv[1]
YAML = sys.argv[2]
TYPE = sys.argv[3]

header = open(YAML, "r")
text = open(FILE, "r")
copy = open(FILE+"_NEW", "wt")

docs = yaml.load_all(header)

for doc in docs:
    if not doc == None:
        if 'figure' in doc.keys():
            for line in text:
                mfig = False
                for f in doc['figure']:
                    my_regex = r"^!\{" + re.escape(f['id']) + r"\}$"
                    if re.search(my_regex, line, re.IGNORECASE):
                        mfig = True
                        if TYPE == 'preprint':
                            ftype = "figure"
                            fwidth = "\\columnwidth"
                            if "wide" in f.keys():
                                ftype = "figure*"
                                fwidth = "\\textwidth"
                            copy.write("\n\\begin{" + ftype + "}[bt]\n")
                            copy.write("\t\\centering\n")
                            copy.write("\t\\includegraphics[width=" + fwidth + "]{" + f['file'] + "}\n")
                            copy.write("\t\\caption{" + f['caption'] + "}\n")
                            copy.write("\t\\label{" + f['id'] + "}\n")
                            copy.write("\\end{" + ftype + "}\n\n")
                if not mfig:
                    copy.write(line)

header.close()
text.close()
copy.close()

Prompt:
Make the python script silent

#! /usr/bin/env python

import sys
import re
import yaml

FILE = sys.argv[1]
YAML = sys.argv[2]
TYPE = sys.argv[3]

header = open(YAML, "r")
text = open(FILE, "r")
copy = open(FILE+"_NEW", "wt")

docs = yaml.load_all(header)

for doc in docs:
    if not doc == None:
        if 'figure' in doc.keys():
            for line in text:
                mfig = False
                for f in doc['figure']:
                    my_regex = r"^!\{" + re.escape(f['id']) + r"\}$"
                    if re.search(my_regex, line, re.IGNORECASE):
                        mfig = True
                        print line
                        if TYPE == 'preprint':
                            ftype = "figure"
                            fwidth = "\\columnwidth"
                            if "wide" in f.keys():
                                ftype = "figure*"
                                fwidth = "\\textwidth"
                            copy.write("\n\\begin{" + ftype + "}[bt]\n")
                            copy.write("\t\\centering\n")
                            print f
                            copy.write("\t\\includegraphics[width=" + fwidth + "]{" + f['file'] + "}\n")
                            copy.write("\t\\caption{" + f['caption'] + "}\n")
                            copy.write("\t\\label{" + f['id'] + "}\n")
                            copy.write("\\end{" + ftype + "}\n\n")
                if not mfig:
                    copy.write(line)

header.close()
text.close()
copy.close()


#!/usr/bin/env python
#

import argparse
import os
import syslog

parser = argparse.ArgumentParser(
	description='Syslog messages as read from a pipe')

parser.add_argument('-i', '--ident',
	help='Use the given identifier for syslogging',
	required=True)
parser.add_argument('pipe', help='Pipe file to read log records from')
args = parser.parse_args()

syslog.openlog(args.ident, 0)

if not os.path.exists(args.pipe):
	os.mkfifo(args.pipe)

while os.path.exists(args.pipe):
	f = open(args.pipe, 'r')

	for l in f:
		syslog.syslog(l)

	f.close()

syslog.closelog()

Add a Python program which reads from a pipe and writes the data it gets to syslog.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
#

import argparse
import os
import syslog

parser = argparse.ArgumentParser(
	description='Syslog messages as read from a pipe')

parser.add_argument('-i', '--ident',
	help='Use the given identifier for syslogging',
	required=True)
parser.add_argument('pipe', help='Pipe file to read log records from')
args = parser.parse_args()

syslog.openlog(args.ident, 0)

if not os.path.exists(args.pipe):
	os.mkfifo(args.pipe)

while os.path.exists(args.pipe):
	f = open(args.pipe, 'r')

	for l in f:
		syslog.syslog(l)

	f.close()

syslog.closelog()
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#

import argparse
import os
import syslog

parser = argparse.ArgumentParser(
	description='Syslog messages as read from a pipe')

parser.add_argument('-i', '--ident',
	help='Use the given identifier for syslogging',
	required=True)
parser.add_argument('pipe', help='Pipe file to read log records from')
args = parser.parse_args()

syslog.openlog(args.ident, 0)

if not os.path.exists(args.pipe):
	os.mkfifo(args.pipe)

while os.path.exists(args.pipe):
	f = open(args.pipe, 'r')

	for l in f:
		syslog.syslog(l)

	f.close()

syslog.closelog()

Prompt:
Add a Python program which reads from a pipe and writes the data it gets
to syslog.


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

from openfisca_web_api.loader.parameters import walk_node
from openfisca_core.parameters import ParameterNode, Scale

def test_amount_scale():
    parameters = []
    metadata = {'location':'foo', 'version':'1', 'repository_url':'foo'}
    root_node = ParameterNode(data = {})
    amount_scale_data = {'brackets':[{'amount':{'2014-01-01':{'value':0}},'threshold':{'2014-01-01':{'value':1}}}]}
    scale = Scale('scale', amount_scale_data, 'foo')
    root_node.children['scale'] = scale
    walk_node(root_node, parameters, [], metadata)
    assert parameters == [{'description': None, 'id': 'scale', 'metadata': {}, 'source': 'foo/blob/1', 'brackets': {'2014-01-01': {1: 0}}}]

Add unit tests for AmountTaxScale serialization

Response:
<INSERT> # -*- coding: utf-8 -*-

from openfisca_web_api.loader.parameters import walk_node
from openfisca_core.parameters import ParameterNode, Scale

def test_amount_scale():
 <INSERT_END> <INSERT>   parameters = []
    metadata = {'location':'foo', 'version':'1', 'repository_url':'foo'}
    root_node = ParameterNode(data = {})
    amount_scale_data = {'brackets':[{'amount':{'2014-01-01':{'value':0}},'threshold':{'2014-01-01':{'value':1}}}]}
    scale = Scale('scale', amount_scale_data, 'foo')
    root_node.children['scale'] = scale
    walk_node(root_node, parameters, [], metadata)
    assert parameters == [{'description': None, 'id': 'scale', 'metadata': {}, 'source': 'foo/blob/1', 'brackets': {'2014-01-01': {1: 0}}}]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

from openfisca_web_api.loader.parameters import walk_node
from openfisca_core.parameters import ParameterNode, Scale

def test_amount_scale():
    parameters = []
    metadata = {'location':'foo', 'version':'1', 'repository_url':'foo'}
    root_node = ParameterNode(data = {})
    amount_scale_data = {'brackets':[{'amount':{'2014-01-01':{'value':0}},'threshold':{'2014-01-01':{'value':1}}}]}
    scale = Scale('scale', amount_scale_data, 'foo')
    root_node.children['scale'] = scale
    walk_node(root_node, parameters, [], metadata)
    assert parameters == [{'description': None, 'id': 'scale', 'metadata': {}, 'source': 'foo/blob/1', 'brackets': {'2014-01-01': {1: 0}}}]

Prompt: Add unit tests for AmountTaxScale serialization


from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject

class Event(DictionaryObject):
    pass

class Update(Event):
    def __init__(self, update, is_pending):
        super().__init__()
        self.update = update
        self.is_pending = is_pending

class Action:
    def __init__(self):
        pass

    def get_name(self):
        return self.__class__.__name__

    def setup(self, api: Api, config: Config, state: State, cache: Cache):
        self.api = api
        self.config = config
        self.state = state
        self.cache = cache
        self.post_setup()

    def post_setup(self):
        pass

    def process(self, event):
        pass

class ActionGroup(Action):
    def __init__(self, *actions):
        super().__init__()
        self.actions = list(actions)

    def add(self, *actions):
        self.actions.extend(actions)

    def setup(self, *args):
        self.for_each(lambda action: action.setup(*args))
        super().setup(*args)

    def process(self, event):
        self.for_each(lambda action: action.process(event._copy()))

    def for_each(self, func):
        for action in self.actions:
            func(action)

class IntermediateAction(ActionGroup):
    def __init__(self):
        super().__init__()

    def then(self, *next_actions):
        self.add(*next_actions)
        return self

    def _continue(self, event):
        super().process(event)

Response:
<REPLACE_OLD> map(func, self.actions)

class <REPLACE_NEW> for action in self.actions:
            func(action)

class <REPLACE_END> <|endoftext|> from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject

class Event(DictionaryObject):
    pass

class Update(Event):
    def __init__(self, update, is_pending):
        super().__init__()
        self.update = update
        self.is_pending = is_pending

class Action:
    def __init__(self):
        pass

    def get_name(self):
        return self.__class__.__name__

    def setup(self, api: Api, config: Config, state: State, cache: Cache):
        self.api = api
        self.config = config
        self.state = state
        self.cache = cache
        self.post_setup()

    def post_setup(self):
        pass

    def process(self, event):
        pass

class ActionGroup(Action):
    def __init__(self, *actions):
        super().__init__()
        self.actions = list(actions)

    def add(self, *actions):
        self.actions.extend(actions)

    def setup(self, *args):
        self.for_each(lambda action: action.setup(*args))
        super().setup(*args)

    def process(self, event):
        self.for_each(lambda action: action.process(event._copy()))

    def for_each(self, func):
        for action in self.actions:
            func(action)

class IntermediateAction(ActionGroup):
    def __init__(self):
        super().__init__()

    def then(self, *next_actions):
        self.add(*next_actions)
        return self

    def _continue(self, event):
        super().process(event)

Prompt:
Fix for_each incorrectly using lazy map operator

from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject

class Event(DictionaryObject):
    pass

class Update(Event):
    def __init__(self, update, is_pending):
        super().__init__()
        self.update = update
        self.is_pending = is_pending

class Action:
    def __init__(self):
        pass

    def get_name(self):
        return self.__class__.__name__

    def setup(self, api: Api, config: Config, state: State, cache: Cache):
        self.api = api
        self.config = config
        self.state = state
        self.cache = cache
        self.post_setup()

    def post_setup(self):
        pass

    def process(self, event):
        pass

class ActionGroup(Action):
    def __init__(self, *actions):
        super().__init__()
        self.actions = list(actions)

    def add(self, *actions):
        self.actions.extend(actions)

    def setup(self, *args):
        self.for_each(lambda action: action.setup(*args))
        super().setup(*args)

    def process(self, event):
        self.for_each(lambda action: action.process(event._copy()))

    def for_each(self, func):
        map(func, self.actions)

class IntermediateAction(ActionGroup):
    def __init__(self):
        super().__init__()

    def then(self, *next_actions):
        self.add(*next_actions)
        return self

    def _continue(self, event):
        super().process(event)


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

# Blitz speed reading trainer add-on for Anki
#
# Copyright (C) 2016  Jakub Szypulka, Dave Shifflett
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from anki.hooks import addHook
from aqt.reviewer import Reviewer
import time

start_time = None

def onShowQuestion():
    global start_time
    start_time = time.time()

addHook('showQuestion', onShowQuestion)

def myDefaultEase(self):
    elapsed_time = time.time() - start_time
    if elapsed_time < 2:
        return 3
    if elapsed_time < 5:
        return 2
    else:
        return 1

Reviewer._defaultEase = myDefaultEase

Increase time limits to 2 and 5 seconds

Increase time limits to 2 and 5 seconds

Response:
<REPLACE_OLD> 1:
 <REPLACE_NEW> 2:
 <REPLACE_END> <REPLACE_OLD> 3:
 <REPLACE_NEW> 5:
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

# Blitz speed reading trainer add-on for Anki
#
# Copyright (C) 2016  Jakub Szypulka, Dave Shifflett
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from anki.hooks import addHook
from aqt.reviewer import Reviewer
import time

start_time = None

def onShowQuestion():
    global start_time
    start_time = time.time()

addHook('showQuestion', onShowQuestion)

def myDefaultEase(self):
    elapsed_time = time.time() - start_time
    if elapsed_time < 2:
        return 3
    if elapsed_time < 5:
        return 2
    else:
        return 1

Reviewer._defaultEase = myDefaultEase

Prompt:
Increase time limits to 2 and 5 seconds

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

# Blitz speed reading trainer add-on for Anki
#
# Copyright (C) 2016  Jakub Szypulka, Dave Shifflett
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from anki.hooks import addHook
from aqt.reviewer import Reviewer
import time

start_time = None

def onShowQuestion():
    global start_time
    start_time = time.time()

addHook('showQuestion', onShowQuestion)

def myDefaultEase(self):
    elapsed_time = time.time() - start_time
    if elapsed_time < 1:
        return 3
    if elapsed_time < 3:
        return 2
    else:
        return 1

Reviewer._defaultEase = myDefaultEase


#!/usr/bin/env python

from tabulate import tabulate
from mlbgame import injury
import dateutil.parser
from datetime import datetime

team_id = 117 # Houston Astros
i = injury.Injury(team_id)
injuries = []

for inj in i.injuries:
    team = inj.team_name
    injury = ['{0}, {1} ({2})'.format(inj.name_last, inj.name_first,
        inj.position), inj.insert_ts, inj.injury_status, inj.due_back,
        inj.injury_desc, inj.injury_update]
    injuries.append(injury)
print tabulate(injuries, headers=[team, 'Updated', 'Status', 'Due Back',
    'Injury', 'Notes'])
print
print 'Last Updated: %s' % i.last_update

"""
"""

Add example for injury class

Add example for injury class

Response:
<INSERT> #!/usr/bin/env python

from tabulate import tabulate
from mlbgame import injury
import dateutil.parser
from datetime import datetime

team_id = 117 # Houston Astros
i = injury.Injury(team_id)
injuries = []

for inj in i.injuries:
 <INSERT_END> <INSERT>   team = inj.team_name
    injury = ['{0}, {1} ({2})'.format(inj.name_last, inj.name_first,
        inj.position), inj.insert_ts, inj.injury_status, inj.due_back,
        inj.injury_desc, inj.injury_update]
    injuries.append(injury)
print tabulate(injuries, headers=[team, 'Updated', 'Status', 'Due Back',
    'Injury', 'Notes'])
print
print 'Last Updated: %s' % i.last_update

"""
"""
 <INSERT_END> <|endoftext|> #!/usr/bin/env python

from tabulate import tabulate
from mlbgame import injury
import dateutil.parser
from datetime import datetime

team_id = 117 # Houston Astros
i = injury.Injury(team_id)
injuries = []

for inj in i.injuries:
    team = inj.team_name
    injury = ['{0}, {1} ({2})'.format(inj.name_last, inj.name_first,
        inj.position), inj.insert_ts, inj.injury_status, inj.due_back,
        inj.injury_desc, inj.injury_update]
    injuries.append(injury)
print tabulate(injuries, headers=[team, 'Updated', 'Status', 'Due Back',
    'Injury', 'Notes'])
print
print 'Last Updated: %s' % i.last_update

"""
"""

Prompt: Add example for injury class


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

import codecs

from setuptools import setup

with codecs.open('README.rst', encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='syslog2IRC',
    version='0.8',
    description='A proxy to forward syslog messages to IRC',
    long_description=long_description,
    url='http://homework.nwsnet.de/releases/c474/#syslog2irc',
    author='Jochen Kupperschmidt',
    author_email='homework@nwsnet.de',
    license='MIT',
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Communications :: Chat :: Internet Relay Chat',
        'Topic :: Internet',
        'Topic :: System :: Logging',
        'Topic :: System :: Monitoring',
        'Topic :: System :: Networking :: Monitoring',
        'Topic :: System :: Systems Administration',
    ],
)

Response:
<REPLACE_OLD> from <REPLACE_NEW> # -*- coding: utf-8 -*-

import codecs

from <REPLACE_END> <REPLACE_OLD> setup

setup(
 <REPLACE_NEW> setup

with codecs.open('README.rst', encoding='utf-8') as f:
    long_description = f.read()

setup(
 <REPLACE_END> <INSERT> long_description=long_description,
    <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

import codecs

from setuptools import setup

with codecs.open('README.rst', encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='syslog2IRC',
    version='0.8',
    description='A proxy to forward syslog messages to IRC',
    long_description=long_description,
    url='http://homework.nwsnet.de/releases/c474/#syslog2irc',
    author='Jochen Kupperschmidt',
    author_email='homework@nwsnet.de',
    license='MIT',
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Communications :: Chat :: Internet Relay Chat',
        'Topic :: Internet',
        'Topic :: System :: Logging',
        'Topic :: System :: Monitoring',
        'Topic :: System :: Networking :: Monitoring',
        'Topic :: System :: Systems Administration',
    ],
)

Prompt:
Include README content as long description.

from setuptools import setup

setup(
    name='syslog2IRC',
    version='0.8',
    description='A proxy to forward syslog messages to IRC',
    url='http://homework.nwsnet.de/releases/c474/#syslog2irc',
    author='Jochen Kupperschmidt',
    author_email='homework@nwsnet.de',
    license='MIT',
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Communications :: Chat :: Internet Relay Chat',
        'Topic :: Internet',
        'Topic :: System :: Logging',
        'Topic :: System :: Monitoring',
        'Topic :: System :: Networking :: Monitoring',
        'Topic :: System :: Systems Administration',
    ],
)


#!/usr/bin/python2
import LogUncaught, ConfigParser, logging, PushBullet, os
from time import localtime, strftime

sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')

# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)

# Logger Formatter
sbLFORMAT = logging.Formatter('[%(asctime)s | %(levelname)s] - %(message)s')
sbLFH.setFormatter(sbLFORMAT)

# Logger
sbLogger = logging.getLogger("serverbackup_logger")
sbLogger.setLevel(logging.DEBUG)
sbLogger.addHandler(sbLFH)

sbLogger.info("Script has begun")

sbLocation = sbConfig.get('ServerBackup', 'backup_location')
databasePass = sbConfig.get('Database', 'password')
lbLocation = sbConfig.get('LogBackup', 'backup_location')
date = strftime("%m_%d_%Y_%H_%M_%S", localtime())
sbFolder = sbLocation + "backup_" + date + "/"

os.makedirs(sbFolder)

if not os.path.exists(sbFolder):
   message = "Folder, \"%s\", couldn't be made" % sbFolder
   sbLogger.critical(message)
   PushBullet.sendPushNote({'id':PushBullet.getPushDevicesIds(), 'title':"Server Backup Error", 'message':message})
   exit(message)

Response:
<REPLACE_OLD> os

sbConfig <REPLACE_NEW> PushBullet, os
from time import localtime, strftime

sbConfig <REPLACE_END> <DELETE>  <DELETE_END> <REPLACE_OLD> 'backup_location')

 <REPLACE_NEW> 'backup_location')
date = strftime("%m_%d_%Y_%H_%M_%S", localtime())
sbFolder = sbLocation + "backup_" + date + "/"

os.makedirs(sbFolder)

if not os.path.exists(sbFolder):
   message = "Folder, \"%s\", couldn't be made" % sbFolder
   sbLogger.critical(message)
   PushBullet.sendPushNote({'id':PushBullet.getPushDevicesIds(), 'title':"Server Backup Error", 'message':message})
   exit(message) <REPLACE_END> <|endoftext|> #!/usr/bin/python2
import LogUncaught, ConfigParser, logging, PushBullet, os
from time import localtime, strftime

sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')

# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)

# Logger Formatter
sbLFORMAT = logging.Formatter('[%(asctime)s | %(levelname)s] - %(message)s')
sbLFH.setFormatter(sbLFORMAT)

# Logger
sbLogger = logging.getLogger("serverbackup_logger")
sbLogger.setLevel(logging.DEBUG)
sbLogger.addHandler(sbLFH)

sbLogger.info("Script has begun")

sbLocation = sbConfig.get('ServerBackup', 'backup_location')
databasePass = sbConfig.get('Database', 'password')
lbLocation = sbConfig.get('LogBackup', 'backup_location')
date = strftime("%m_%d_%Y_%H_%M_%S", localtime())
sbFolder = sbLocation + "backup_" + date + "/"

os.makedirs(sbFolder)

if not os.path.exists(sbFolder):
   message = "Folder, \"%s\", couldn't be made" % sbFolder
   sbLogger.critical(message)
   PushBullet.sendPushNote({'id':PushBullet.getPushDevicesIds(), 'title':"Server Backup Error", 'message':message})
   exit(message)

Prompt:
Backup directory is made, and a notification is sent and logged if the directory doesn't exist

#!/usr/bin/python2
import LogUncaught, ConfigParser, logging, os

sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')

# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)

# Logger Formatter
sbLFORMAT = logging.Formatter('[%(asctime)s | %(levelname)s]  - %(message)s')
sbLFH.setFormatter(sbLFORMAT)

# Logger
sbLogger = logging.getLogger("serverbackup_logger")
sbLogger.setLevel(logging.DEBUG)
sbLogger.addHandler(sbLFH)

sbLogger.info("Script has begun")

sbLocation = sbConfig.get('ServerBackup', 'backup_location')
databasePass = sbConfig.get('Database', 'password')
lbLocation = sbConfig.get('LogBackup', 'backup_location')


#!/usr/bin/env python2.6
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""

import sys
import py_compile
import re

def main(args=None):
    """Except for the custom dfile, this is stolen directly from py_compile.

    Compile all of the given filename arguments.  This custom version
    replaces /ms/dev in the path with /ms/dist to match our environment usage.

    """
    if args is None:
        args = sys.argv[1:]
    dev_re = re.compile(r'/ms/dev/(?P<meta>[^/]+)/(?P<proj>[^/]+)'
                        r'/(?P<release>[^/]+)/install/(?P<path>.*)')
    for filename in args:
        try:
            m = dev_re.match(filename)
            if m:
                dfile = "/ms/dist/%(meta)s/PROJ/%(proj)s" \
                        "/%(release)s/%(path)s" % m.groupdict()
            else:
                dfile = filename
            py_compile.compile(filename, dfile=dfile, doraise=True)
        except py_compile.PyCompileError, e:
            sys.stderr.write(e.msg)

if __name__ == "__main__":
    main()

Update shebang to use /usr/bin/env.

Response:
<REPLACE_OLD> #!/ms/dist/python/PROJ/core/2.5.2-1/bin/python
# <REPLACE_NEW> #!/usr/bin/env python2.6
# <REPLACE_END> <|endoftext|> #!/usr/bin/env python2.6
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""

import sys
import py_compile
import re

def main(args=None):
    """Except for the custom dfile, this is stolen directly from py_compile.

    Compile all of the given filename arguments.  This custom version
    replaces /ms/dev in the path with /ms/dist to match our environment usage.

    """
    if args is None:
        args = sys.argv[1:]
    dev_re = re.compile(r'/ms/dev/(?P<meta>[^/]+)/(?P<proj>[^/]+)'
                        r'/(?P<release>[^/]+)/install/(?P<path>.*)')
    for filename in args:
        try:
            m = dev_re.match(filename)
            if m:
                dfile = "/ms/dist/%(meta)s/PROJ/%(proj)s" \
                        "/%(release)s/%(path)s" % m.groupdict()
            else:
                dfile = filename
            py_compile.compile(filename, dfile=dfile, doraise=True)
        except py_compile.PyCompileError, e:
            sys.stderr.write(e.msg)

if __name__ == "__main__":
    main()

Prompt:
Update shebang to use /usr/bin/env.

Remove the /ms/dist reference.

#!/ms/dist/python/PROJ/core/2.5.2-1/bin/python
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""

import sys
import py_compile
import re

def main(args=None):
    """Except for the custom dfile, this is stolen directly from py_compile.

    Compile all of the given filename arguments.  This custom version
    replaces /ms/dev in the path with /ms/dist to match our environment usage.

    """
    if args is None:
        args = sys.argv[1:]
    dev_re = re.compile(r'/ms/dev/(?P<meta>[^/]+)/(?P<proj>[^/]+)'
                        r'/(?P<release>[^/]+)/install/(?P<path>.*)')
    for filename in args:
        try:
            m = dev_re.match(filename)
            if m:
                dfile = "/ms/dist/%(meta)s/PROJ/%(proj)s" \
                        "/%(release)s/%(path)s" % m.groupdict()
            else:
                dfile = filename
            py_compile.compile(filename, dfile=dfile, doraise=True)
        except py_compile.PyCompileError, e:
            sys.stderr.write(e.msg)

if __name__ == "__main__":
    main()


if alert['resource'].startswith('R1'):
    alert['service'] = [ 'R1' ]
elif alert['resource'].startswith('R2'):
    alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
    alert['service'] = [ 'ContentAPI' ]
elif alert['resource'].startswith('frontend'):
    alert['service'] = [ 'Frontend' ]
elif 'flexible' in alert['resource'].lower():
    alert['service'] = [ 'FlexibleContent' ]
elif alert['resource'].startswith('Identity'):
    alert['service'] = [ 'Identity' ]
elif alert['resource'].startswith('Mobile'):
    alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Android'):
    alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('iOS'):
    alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Soulmates'):
    alert['service'] = [ 'Soulmates' ]
elif alert['resource'].startswith('Microapps'):
    alert['service'] = [ 'MicroApp' ]
elif alert['resource'].startswith('Mutualisation'):
    alert['service'] = [ 'Mutualisation' ]
elif alert['resource'].startswith('Ophan'):
    alert['service'] = [ 'Ophan' ]
else:
    alert['service'] = [ 'Unknown' ]

Add more service lookups for Deploys

Add more service lookups for Deploys

Response:
<REPLACE_OLD> 'r2' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('R1'):
    alert['service'] = [ 'R1' ]
elif alert['resource'].startswith('R2'):
 <REPLACE_END> <INSERT> alert['resource'].startswith('frontend'):
    alert['service'] = [ 'Frontend' ]
elif <INSERT_END> <REPLACE_OLD> 'frontend' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('Identity'):
 <REPLACE_END> <REPLACE_OLD> 'Frontend' <REPLACE_NEW> 'Identity' <REPLACE_END> <REPLACE_OLD> 'mobile' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('Mobile'):
 <REPLACE_END> <REPLACE_OLD> 'android' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('Android'):
 <REPLACE_END> <REPLACE_OLD> 'ios' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('iOS'):
 <REPLACE_END> <REPLACE_OLD> 'identity' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('Soulmates'):
 <REPLACE_END> <REPLACE_OLD> 'Identity' <REPLACE_NEW> 'Soulmates' <REPLACE_END> <REPLACE_OLD> 'microapps' in alert['resource'].lower():
 <REPLACE_NEW> alert['resource'].startswith('Microapps'):
 <REPLACE_END> <INSERT> ]
elif alert['resource'].startswith('Mutualisation'):
    alert['service'] = [ 'Mutualisation' ]
elif alert['resource'].startswith('Ophan'):
    alert['service'] = [ 'Ophan' <INSERT_END> <|endoftext|>
if alert['resource'].startswith('R1'):
    alert['service'] = [ 'R1' ]
elif alert['resource'].startswith('R2'):
    alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
    alert['service'] = [ 'ContentAPI' ]
elif alert['resource'].startswith('frontend'):
    alert['service'] = [ 'Frontend' ]
elif 'flexible' in alert['resource'].lower():
    alert['service'] = [ 'FlexibleContent' ]
elif alert['resource'].startswith('Identity'):
    alert['service'] = [ 'Identity' ]
elif alert['resource'].startswith('Mobile'):
    alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Android'):
    alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('iOS'):
    alert['service'] = [ 'Mobile' ]
elif alert['resource'].startswith('Soulmates'):
    alert['service'] = [ 'Soulmates' ]
elif alert['resource'].startswith('Microapps'):
    alert['service'] = [ 'MicroApp' ]
elif alert['resource'].startswith('Mutualisation'):
    alert['service'] = [ 'Mutualisation' ]
elif alert['resource'].startswith('Ophan'):
    alert['service'] = [ 'Ophan' ]
else:
    alert['service'] = [ 'Unknown' ]

Prompt:
Add more service lookups for Deploys

if 'r2' in alert['resource'].lower():
    alert['service'] = [ 'R2' ]
elif 'content-api' in alert['resource'].lower():
    alert['service'] = [ 'ContentAPI' ]
elif 'flexible' in alert['resource'].lower():
    alert['service'] = [ 'FlexibleContent' ]
elif 'frontend' in alert['resource'].lower():
    alert['service'] = [ 'Frontend' ]
elif 'mobile' in alert['resource'].lower():
    alert['service'] = [ 'Mobile' ]
elif 'android' in alert['resource'].lower():
    alert['service'] = [ 'Mobile' ]
elif 'ios' in alert['resource'].lower():
    alert['service'] = [ 'Mobile' ]
elif 'identity' in alert['resource'].lower():
    alert['service'] = [ 'Identity' ]
elif 'microapps' in alert['resource'].lower():
    alert['service'] = [ 'MicroApp' ]
else:
    alert['service'] = [ 'Unknown' ]


#!/usr/bin/env python
#
# This example shows how to read and write mesh files using the low-level ViennaGrid
# wrapper for Python (viennagrid.wrapper).

from __future__ import print_function

# In this example, we will set up a domain of triangles in the cartesian 3D
# space from the contents of a Netgen mesh file.
#
# For that purpose, we need to define a domain and, eventually, also a segmentation
# (in case we want to read segmentation data from the mesh file), and we need the
# Netgen reader function, too.
#
# (Notice that the 'read_netgen' function and all other I/O functions
# work with any type of domain and segmentation without name change.)

from viennagrid.wrapper import TriangularCartesian3D_Domain as Domain
from viennagrid.wrapper import TriangularCartesian3D_Segmentation as Segmentation
from viennagrid.wrapper import read_netgen

# In case we want to read only the domain information from the mesh file, we would
# just create an empty domain and call the Netgen reader on it with the file path
# where the mesh file can be found.

domain = Domain()
read_netgen('../data/half-trigate.mesh', domain)

# In case we want to read not only the domain information, but also the segmentation
# information from the mesh file, we would have to create an empty domain and an
# empty segmentation on that domain, and then call the Netgen reader.

domain = Domain()
segmentation = Segmentation(domain)
read_netgen('../data/half-trigate.mesh', domain, segmentation)

Write an example of the use of the Netgen reader.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
#
# This example shows how to read and write mesh files using the low-level ViennaGrid
# wrapper for Python (viennagrid.wrapper).

from __future__ import print_function

# In this example, we will set up a domain of triangles in the cartesian 3D
# space from the contents of a Netgen mesh file.
#
# For that purpose, we need to define a domain and, eventually, also a segmentation
# (in case we want to read segmentation data from the mesh file), and we need the
# Netgen reader function, too.
#
# (Notice that the 'read_netgen' function and all other I/O functions
# work with any type of domain and segmentation without name change.)

from viennagrid.wrapper import TriangularCartesian3D_Domain as Domain
from viennagrid.wrapper import TriangularCartesian3D_Segmentation as Segmentation
from viennagrid.wrapper import read_netgen

# In case we want to read only the domain information from the mesh file, we would
# just create an empty domain and call the Netgen reader on it with the file path
# where the mesh file can be found.

domain = Domain()
read_netgen('../data/half-trigate.mesh', domain)

# In case we want to read not only the domain information, but also the segmentation
# information from the mesh file, we would have to create an empty domain and an
# empty segmentation on that domain, and then call the Netgen reader.

domain = Domain()
segmentation = Segmentation(domain)
read_netgen('../data/half-trigate.mesh', domain, segmentation)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# This example shows how to read and write mesh files using the low-level ViennaGrid
# wrapper for Python (viennagrid.wrapper).

from __future__ import print_function

# In this example, we will set up a domain of triangles in the cartesian 3D
# space from the contents of a Netgen mesh file.
#
# For that purpose, we need to define a domain and, eventually, also a segmentation
# (in case we want to read segmentation data from the mesh file), and we need the
# Netgen reader function, too.
#
# (Notice that the 'read_netgen' function and all other I/O functions
# work with any type of domain and segmentation without name change.)

from viennagrid.wrapper import TriangularCartesian3D_Domain as Domain
from viennagrid.wrapper import TriangularCartesian3D_Segmentation as Segmentation
from viennagrid.wrapper import read_netgen

# In case we want to read only the domain information from the mesh file, we would
# just create an empty domain and call the Netgen reader on it with the file path
# where the mesh file can be found.

domain = Domain()
read_netgen('../data/half-trigate.mesh', domain)

# In case we want to read not only the domain information, but also the segmentation
# information from the mesh file, we would have to create an empty domain and an
# empty segmentation on that domain, and then call the Netgen reader.

domain = Domain()
segmentation = Segmentation(domain)
read_netgen('../data/half-trigate.mesh', domain, segmentation)

Prompt: Write an example of the use of the Netgen reader.