# Copyright 2014  Emmanuele Bassi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import sys
import re

NUMBER_REGEX = re.compile(r'([0-9])([a-z])')

def to_camel_case(text):
    # We only care about Graphene types
    if not text.startswith('graphene_') and not text.endswith('_t'):
        return text

    res = []
    for token in text[:-2].split('_'):
        uc_token = token.title()

	# We need to do this for types like graphene_point3d_t, which
	# need to be transformed into GraphenePoint3D, not GraphenePoint3d
        matches = NUMBER_REGEX.match(uc_token)
        if matches and matches.group(2):
            uc_token = ''.join([matches.group(1), matches.group(2).title])

        res.append(uc_token)

    return ''.join(res)

if __name__ == '__main__':
    in_text = sys.stdin.read()
    sys.stdout.write(to_camel_case(in_text))

Response:
<REPLACE_OLD> import <REPLACE_NEW> # Copyright 2014  Emmanuele Bassi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import <REPLACE_END> <|endoftext|> # Copyright 2014  Emmanuele Bassi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import sys
import re

NUMBER_REGEX = re.compile(r'([0-9])([a-z])')

def to_camel_case(text):
    # We only care about Graphene types
    if not text.startswith('graphene_') and not text.endswith('_t'):
        return text

    res = []
    for token in text[:-2].split('_'):
        uc_token = token.title()

	# We need to do this for types like graphene_point3d_t, which
	# need to be transformed into GraphenePoint3D, not GraphenePoint3d
        matches = NUMBER_REGEX.match(uc_token)
        if matches and matches.group(2):
            uc_token = ''.join([matches.group(1), matches.group(2).title])

        res.append(uc_token)

    return ''.join(res)

if __name__ == '__main__':
    in_text = sys.stdin.read()
    sys.stdout.write(to_camel_case(in_text))

Prompt:
Add licensing to the introspection filter

It's a small utility script, but it's better to have a license for it
anyway.

import sys
import re

NUMBER_REGEX = re.compile(r'([0-9])([a-z])')

def to_camel_case(text):
    # We only care about Graphene types
    if not text.startswith('graphene_') and not text.endswith('_t'):
        return text

    res = []
    for token in text[:-2].split('_'):
        uc_token = token.title()

	# We need to do this for types like graphene_point3d_t, which
	# need to be transformed into GraphenePoint3D, not GraphenePoint3d
        matches = NUMBER_REGEX.match(uc_token)
        if matches and matches.group(2):
            uc_token = ''.join([matches.group(1), matches.group(2).title])

        res.append(uc_token)

    return ''.join(res)

if __name__ == '__main__':
    in_text = sys.stdin.read()
    sys.stdout.write(to_camel_case(in_text))


class Solution(object):
    def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        timePoints = map(lambda x:int(x.split(':')[0]) * 60 + int(x.split(':')[1]), timePoints)
        MINUTES_IN_A_DAY = 24 * 60
        timePoints.sort()
        m = timePoints[0] + MINUTES_IN_A_DAY - timePoints[-1]
        it1, it2 = iter(timePoints), iter(timePoints)
        it2.next()
        return min(m, min(t2 - t1 for (t1, t2) in zip(it1, it2)))

Add py solution for 539. Minimum Time Difference

539. Minimum Time Difference: https://leetcode.com/problems/minimum-time-difference/

Response:
<INSERT> class Solution(object):
 <INSERT_END> <INSERT>   def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        timePoints = map(lambda x:int(x.split(':')[0]) * 60 + int(x.split(':')[1]), timePoints)
        MINUTES_IN_A_DAY = 24 * 60
        timePoints.sort()
        m = timePoints[0] + MINUTES_IN_A_DAY - timePoints[-1]
        it1, it2 = iter(timePoints), iter(timePoints)
        it2.next()
        return min(m, min(t2 - t1 for (t1, t2) in zip(it1, it2)))
 <INSERT_END> <|endoftext|> class Solution(object):
    def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        timePoints = map(lambda x:int(x.split(':')[0]) * 60 + int(x.split(':')[1]), timePoints)
        MINUTES_IN_A_DAY = 24 * 60
        timePoints.sort()
        m = timePoints[0] + MINUTES_IN_A_DAY - timePoints[-1]
        it1, it2 = iter(timePoints), iter(timePoints)
        it2.next()
        return min(m, min(t2 - t1 for (t1, t2) in zip(it1, it2)))

Prompt:
Add py solution for 539. Minimum Time Difference

539. Minimum Time Difference: https://leetcode.com/problems/minimum-time-difference/


__author__ = 'max'

import gpxpy
import pandas as pd

def parse_gpx(gpx_file_name):
    return gpxpy.parse(gpx_file_name)

def data_frame_for_track_segment(segment):
    seg_dict = {}

    for point in segment.points:
        seg_dict[point.time] = [point.latitude, point.longitude,
                                point.elevation, point.speed]
    seg_frame = pd.DataFrame(data=seg_dict)
    # Switch columns and rows s.t. timestamps are rows and gps data columns.
    seg_frame = seg_frame.T
    seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
    return seg_frame

def track_segment_mapping(track):
    segments = [data_frame_for_track_segment(segment)
                for segment in track.segments]
    return segments

def pandas_data_frame_for_gpx(gpx):
    tracks_frames = [track_segment_mapping(track) for track in gpx.tracks]
    # Create a hierarchical DataFrame by unstacking.
    tracks_frame = pd.DataFrame(tracks_frames)
    unstacked_frame = tracks_frame.unstack()
    unstacked_frame.index.name = 'tracks'
    assert gpx.name
    d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T
    d_frame.index.name = 'name'
    return d_frame

Response:
<REPLACE_OLD> (data_frame_for_track_segment(segment)
 <REPLACE_NEW> [data_frame_for_track_segment(segment)
 <REPLACE_END> <REPLACE_OLD> track.segments)
 <REPLACE_NEW> track.segments]
 <REPLACE_END> <REPLACE_OLD> (track_segment_mapping(track) <REPLACE_NEW> [track_segment_mapping(track) <REPLACE_END> <REPLACE_OLD> gpx.tracks)
 <REPLACE_NEW> gpx.tracks]
 <REPLACE_END> <|endoftext|> __author__ = 'max'

import gpxpy
import pandas as pd

def parse_gpx(gpx_file_name):
    return gpxpy.parse(gpx_file_name)

def data_frame_for_track_segment(segment):
    seg_dict = {}

    for point in segment.points:
        seg_dict[point.time] = [point.latitude, point.longitude,
                                point.elevation, point.speed]
    seg_frame = pd.DataFrame(data=seg_dict)
    # Switch columns and rows s.t. timestamps are rows and gps data columns.
    seg_frame = seg_frame.T
    seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
    return seg_frame

def track_segment_mapping(track):
    segments = [data_frame_for_track_segment(segment)
                for segment in track.segments]
    return segments

def pandas_data_frame_for_gpx(gpx):
    tracks_frames = [track_segment_mapping(track) for track in gpx.tracks]
    # Create a hierarchical DataFrame by unstacking.
    tracks_frame = pd.DataFrame(tracks_frames)
    unstacked_frame = tracks_frame.unstack()
    unstacked_frame.index.name = 'tracks'
    assert gpx.name
    d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T
    d_frame.index.name = 'name'
    return d_frame

Prompt:
Return to list generator to enable pandas cmd output

__author__ = 'max'

import gpxpy
import pandas as pd

def parse_gpx(gpx_file_name):
    return gpxpy.parse(gpx_file_name)

def data_frame_for_track_segment(segment):
    seg_dict = {}

    for point in segment.points:
        seg_dict[point.time] = [point.latitude, point.longitude,
                                point.elevation, point.speed]
    seg_frame = pd.DataFrame(data=seg_dict)
    # Switch columns and rows s.t. timestamps are rows and gps data columns.
    seg_frame = seg_frame.T
    seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed']
    return seg_frame

def track_segment_mapping(track):
    segments = (data_frame_for_track_segment(segment)
                for segment in track.segments)
    return segments

def pandas_data_frame_for_gpx(gpx):
    tracks_frames = (track_segment_mapping(track) for track in gpx.tracks)
    # Create a hierarchical DataFrame by unstacking.
    tracks_frame = pd.DataFrame(tracks_frames)
    unstacked_frame = tracks_frame.unstack()
    unstacked_frame.index.name = 'tracks'
    assert gpx.name
    d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T
    d_frame.index.name = 'name'
    return d_frame


from functools import wraps
from time import time

from django_statsd.clients import statsd

class UnauthorizedException(Exception):
    """Failure to log into the email server."""
    pass

class NewsletterException(Exception):
    """Error when trying to talk to the the email server."""

    def __init__(self, msg=None, error_code=None, status_code=None):
        self.error_code = error_code
        self.status_code = status_code
        super(NewsletterException, self).__init__(msg)

class NewsletterNoResultsException(NewsletterException):
    """
    No results were returned from the mail server (but the request
    didn't report any errors)
    """
    pass

def get_timer_decorator(prefix):
    """
    Decorator for timing and counting requests to the API
    """
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            starttime = time()

            def record_timing():
                totaltime = int((time() - starttime) * 1000)
                statsd.timing(prefix + '.timing', totaltime)
                statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
                statsd.incr(prefix + '.count')
                statsd.incr(prefix + '.{}.count'.format(f.__name__))

            try:
                resp = f(*args, **kwargs)
            except NewsletterException:
                record_timing()
                raise

            record_timing()
            return resp

        return wrapped

    return decorator

Response:
<REPLACE_OLD> time()
            e = None
            try:
                resp = f(*args, **kwargs)
            except NewsletterException as e:  # noqa
                pass
            except Exception:
                raise

 <REPLACE_NEW> time()

            def record_timing():
     <REPLACE_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> '.{}.count'.format(f.__name__))
            if e:
                raise
            else:
     <REPLACE_NEW> '.{}.count'.format(f.__name__))

            try:
                resp = f(*args, **kwargs)
            except NewsletterException:
                record_timing()
                raise

            record_timing()
 <REPLACE_END> <|endoftext|> from functools import wraps
from time import time

from django_statsd.clients import statsd

class UnauthorizedException(Exception):
    """Failure to log into the email server."""
    pass

class NewsletterException(Exception):
    """Error when trying to talk to the the email server."""

    def __init__(self, msg=None, error_code=None, status_code=None):
        self.error_code = error_code
        self.status_code = status_code
        super(NewsletterException, self).__init__(msg)

class NewsletterNoResultsException(NewsletterException):
    """
    No results were returned from the mail server (but the request
    didn't report any errors)
    """
    pass

def get_timer_decorator(prefix):
    """
    Decorator for timing and counting requests to the API
    """
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            starttime = time()

            def record_timing():
                totaltime = int((time() - starttime) * 1000)
                statsd.timing(prefix + '.timing', totaltime)
                statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
                statsd.incr(prefix + '.count')
                statsd.incr(prefix + '.{}.count'.format(f.__name__))

            try:
                resp = f(*args, **kwargs)
            except NewsletterException:
                record_timing()
                raise

            record_timing()
            return resp

        return wrapped

    return decorator

Prompt:
Refactor the timing decorator to be less confusing

Also means that we don't have to ignore a flake8 error.

from functools import wraps
from time import time

from django_statsd.clients import statsd

class UnauthorizedException(Exception):
    """Failure to log into the email server."""
    pass

class NewsletterException(Exception):
    """Error when trying to talk to the the email server."""

    def __init__(self, msg=None, error_code=None, status_code=None):
        self.error_code = error_code
        self.status_code = status_code
        super(NewsletterException, self).__init__(msg)

class NewsletterNoResultsException(NewsletterException):
    """
    No results were returned from the mail server (but the request
    didn't report any errors)
    """
    pass

def get_timer_decorator(prefix):
    """
    Decorator for timing and counting requests to the API
    """
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            starttime = time()
            e = None
            try:
                resp = f(*args, **kwargs)
            except NewsletterException as e:  # noqa
                pass
            except Exception:
                raise

            totaltime = int((time() - starttime) * 1000)
            statsd.timing(prefix + '.timing', totaltime)
            statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
            statsd.incr(prefix + '.count')
            statsd.incr(prefix + '.{}.count'.format(f.__name__))
            if e:
                raise
            else:
                return resp

        return wrapped

    return decorator


from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api

def index(request):
    uid = request.COOKIES.get("uid")
    data = None
    if not uid:
        uid, _ = api.create_new_user()
    else:
        data = api.get_saved_cities(uid)

    response = render_to_response(
        "homepage/index.html",
        {"saved_cities": data},
        context_instance=RequestContext(request)
    )

    expires = datetime.utcnow() + timedelta(days=180)
    response.set_cookie("uid", uid, expires=expires)

    return response

Fix create user in homepage view.

Response:
<INSERT> data = None
    <INSERT_END> <REPLACE_OLD> data <REPLACE_NEW> _ <REPLACE_END> <|endoftext|> from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api

def index(request):
    uid = request.COOKIES.get("uid")
    data = None
    if not uid:
        uid, _ = api.create_new_user()
    else:
        data = api.get_saved_cities(uid)

    response = render_to_response(
        "homepage/index.html",
        {"saved_cities": data},
        context_instance=RequestContext(request)
    )

    expires = datetime.utcnow() + timedelta(days=180)
    response.set_cookie("uid", uid, expires=expires)

    return response

Prompt:
Fix create user in homepage view.

api.create_new_user is returning the newly created user record, so we can't pass that as data to the template.

from datetime import datetime, timedelta
from django.shortcuts import render_to_response
from django.template import RequestContext
import api

def index(request):
    uid = request.COOKIES.get("uid")
    if not uid:
        uid, data = api.create_new_user()
    else:
        data = api.get_saved_cities(uid)

    response = render_to_response(
        "homepage/index.html",
        {"saved_cities": data},
        context_instance=RequestContext(request)
    )

    expires = datetime.utcnow() + timedelta(days=180)
    response.set_cookie("uid", uid, expires=expires)

    return response


# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import ValidationError
import stdnum.ar
import logging
_logger = logging.getLogger(__name__)

def validate_cbu(cbu):
    try:
        return stdnum.ar.cbu.validate(cbu)
    except Exception as error:
        msg = _("Argentinian CBU was not validated: %s" % repr(error))
        _logger.log(25, msg)
        raise ValidationError(msg)

class ResPartnerBank(models.Model):

    _inherit = 'res.partner.bank'

    @api.model
    def _get_supported_account_types(self):
        """ Add new account type named cbu used in Argentina """
        res = super()._get_supported_account_types()
        res.append(('cbu', _('CBU')))
        return res

    @api.model
    def retrieve_acc_type(self, acc_number):
        try:
            validate_cbu(acc_number)
        except Exception:
            return super().retrieve_acc_type(acc_number)
        return 'cbu'

Response:
<REPLACE_OLD> _
import stdnum.ar.cbu

def <REPLACE_NEW> _
from odoo.exceptions import ValidationError
import stdnum.ar
import logging
_logger = logging.getLogger(__name__)

def <REPLACE_END> <REPLACE_OLD> return stdnum.ar.cbu.validate(cbu)

class <REPLACE_NEW> try:
        return stdnum.ar.cbu.validate(cbu)
    except Exception as error:
        msg = _("Argentinian CBU was not validated: %s" % repr(error))
        _logger.log(25, msg)
        raise ValidationError(msg)

class <REPLACE_END> <|endoftext|> # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import ValidationError
import stdnum.ar
import logging
_logger = logging.getLogger(__name__)

def validate_cbu(cbu):
    try:
        return stdnum.ar.cbu.validate(cbu)
    except Exception as error:
        msg = _("Argentinian CBU was not validated: %s" % repr(error))
        _logger.log(25, msg)
        raise ValidationError(msg)

class ResPartnerBank(models.Model):

    _inherit = 'res.partner.bank'

    @api.model
    def _get_supported_account_types(self):
        """ Add new account type named cbu used in Argentina """
        res = super()._get_supported_account_types()
        res.append(('cbu', _('CBU')))
        return res

    @api.model
    def retrieve_acc_type(self, acc_number):
        try:
            validate_cbu(acc_number)
        except Exception:
            return super().retrieve_acc_type(acc_number)
        return 'cbu'

Prompt:
[FIX] l10n_ar: Fix ImportError: No module named 'stdnum.ar.cbu'

Since stdnum.ar.cbu is not available in odoo saas enviroment because is
using an old version of stdnum package, we add a try exept in order to
catch this and manage the error properly which is raise an exception and
leave a message in the log telling the user that the cbu was not able to
validate.

closes odoo/odoo#40383

X-original-commit: 25d483fc3fc05fd47c72c3d96c02fed12b998b0d
Signed-off-by: Josse Colpaert <1f46e7f017caa89a77c9557ed26b800e8d5d7700@openerp.com>

# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
import stdnum.ar.cbu

def validate_cbu(cbu):
    return stdnum.ar.cbu.validate(cbu)

class ResPartnerBank(models.Model):

    _inherit = 'res.partner.bank'

    @api.model
    def _get_supported_account_types(self):
        """ Add new account type named cbu used in Argentina """
        res = super()._get_supported_account_types()
        res.append(('cbu', _('CBU')))
        return res

    @api.model
    def retrieve_acc_type(self, acc_number):
        try:
            validate_cbu(acc_number)
        except Exception:
            return super().retrieve_acc_type(acc_number)
        return 'cbu'


from __future__ import absolute_import

def check(header, convention=None, dimensions=[0, 1]):

    ix = dimensions[0] + 1
    iy = dimensions[1] + 1

    ctypex = header['CTYPE%i' % ix]
    crvaly = header['CRVAL%i' % iy]

    # Check for CRVAL2!=0 for CAR projection
    if ctypex[4:] == '-CAR' and crvaly != 0:

        if convention in ['wells', 'calabretta']:
            if convention == 'wells':
                try:
                    crpixy = header['CRPIX%i' % iy]
                    cdelty = header['CDELT%i' % iy]
                except:
                    raise Exception("Need CDELT to be present for wells convention")
                crpixy = crpixy - crvaly / cdelty
                header.update('CRPIX%i' % iy, crpixy)
                header.update('CRVAL%i' % iy, 0.0)
            else:
                pass
        else:
            raise Exception('''WARNING: projection is Plate Caree (-CAR) and
            CRVAL2 is not zero. This can be intepreted either according to
            Wells (1981) or Calabretta (2002). The former defines the
            projection as rectilinear regardless of the value of CRVAL2,
            whereas the latter defines the projection as rectilinear only when
            CRVAL2 is zero. You will need to specify the convention to assume
            by setting either convention='wells' or convention='calabretta'
            when initializing the FITSFigure instance. ''')

    return header

Response:
<DELETE> iy]
    crpixy = header['CRPIX%i' % iy]
    cdelty = header['CDELT%i' % <DELETE_END> <INSERT>                try:
                    crpixy = header['CRPIX%i' % iy]
                    cdelty = header['CDELT%i' % iy]
                except:
                    raise Exception("Need CDELT to be present for wells convention")
 <INSERT_END> <|endoftext|> from __future__ import absolute_import

def check(header, convention=None, dimensions=[0, 1]):

    ix = dimensions[0] + 1
    iy = dimensions[1] + 1

    ctypex = header['CTYPE%i' % ix]
    crvaly = header['CRVAL%i' % iy]

    # Check for CRVAL2!=0 for CAR projection
    if ctypex[4:] == '-CAR' and crvaly != 0:

        if convention in ['wells', 'calabretta']:
            if convention == 'wells':
                try:
                    crpixy = header['CRPIX%i' % iy]
                    cdelty = header['CDELT%i' % iy]
                except:
                    raise Exception("Need CDELT to be present for wells convention")
                crpixy = crpixy - crvaly / cdelty
                header.update('CRPIX%i' % iy, crpixy)
                header.update('CRVAL%i' % iy, 0.0)
            else:
                pass
        else:
            raise Exception('''WARNING: projection is Plate Caree (-CAR) and
            CRVAL2 is not zero. This can be intepreted either according to
            Wells (1981) or Calabretta (2002). The former defines the
            projection as rectilinear regardless of the value of CRVAL2,
            whereas the latter defines the projection as rectilinear only when
            CRVAL2 is zero. You will need to specify the convention to assume
            by setting either convention='wells' or convention='calabretta'
            when initializing the FITSFigure instance. ''')

    return header

Prompt:
Fix check for Wells/Calabretta convention
from __future__ import absolute_import

def check(header, convention=None, dimensions=[0, 1]):

    ix = dimensions[0] + 1
    iy = dimensions[1] + 1

    ctypex = header['CTYPE%i' % ix]
    crvaly = header['CRVAL%i' % iy]
    crpixy = header['CRPIX%i' % iy]
    cdelty = header['CDELT%i' % iy]

    # Check for CRVAL2!=0 for CAR projection
    if ctypex[4:] == '-CAR' and crvaly != 0:

        if convention in ['wells', 'calabretta']:
            if convention == 'wells':
                crpixy = crpixy - crvaly / cdelty
                header.update('CRPIX%i' % iy, crpixy)
                header.update('CRVAL%i' % iy, 0.0)
            else:
                pass
        else:
            raise Exception('''WARNING: projection is Plate Caree (-CAR) and
            CRVAL2 is not zero. This can be intepreted either according to
            Wells (1981) or Calabretta (2002). The former defines the
            projection as rectilinear regardless of the value of CRVAL2,
            whereas the latter defines the projection as rectilinear only when
            CRVAL2 is zero. You will need to specify the convention to assume
            by setting either convention='wells' or convention='calabretta'
            when initializing the FITSFigure instance. ''')

    return header


from distutils.core import setup

import sisdb

setup (
    name='sisdb',
    version=sisdb.VERSION,
    description='SIS ORM like library',
    packages=['sisdb'],
    install_requires=['sispy >= 0.3.0']
)

Update to require sispy instead of sis

Update to require sispy instead of sis

Response:
<REPLACE_OLD> install_requires=['sis <REPLACE_NEW> install_requires=['sispy <REPLACE_END> <|endoftext|> from distutils.core import setup

import sisdb

setup (
    name='sisdb',
    version=sisdb.VERSION,
    description='SIS ORM like library',
    packages=['sisdb'],
    install_requires=['sispy >= 0.3.0']
)

Prompt:
Update to require sispy instead of sis
from distutils.core import setup

import sisdb

setup (
    name='sisdb',
    version=sisdb.VERSION,
    description='SIS ORM like library',
    packages=['sisdb'],
    install_requires=['sis >= 0.3.0']
)


import os
from os import path
import glob
import json
import subprocess

class Snippet(object):

    def __init__(self, config, username, snippet_id):
        self.config = config
        self.username = username
        self.snippet_id = snippet_id

        repo_parent = path.join(self.config.get('snippet_home'), username)
        self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0]

    @staticmethod
    def clone(url, clone_to):
        #TODO: Add log line for notifying user.
        # subprocess.DEVNULL
        subprocess.call(['git', 'clone', url, clone_to])

    @staticmethod
    def pull(repo_dir):
        # TODO: Add log line for notifying user.
        subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull'])

    def get_files(self):
        """ Return files of snippet """

        metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
        with open(metadata_file, 'r') as f:
            data = json.loads(f.read())

            for item in data['values']:
                if item['id'] != self.snippet_id:
                    continue

                return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]

Add doc string to Snippet.get_files

Add doc string to Snippet.get_files

Response:
<INSERT> """ Return files of snippet """

        <INSERT_END> <|endoftext|> import os
from os import path
import glob
import json
import subprocess

class Snippet(object):

    def __init__(self, config, username, snippet_id):
        self.config = config
        self.username = username
        self.snippet_id = snippet_id

        repo_parent = path.join(self.config.get('snippet_home'), username)
        self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0]

    @staticmethod
    def clone(url, clone_to):
        #TODO: Add log line for notifying user.
        # subprocess.DEVNULL
        subprocess.call(['git', 'clone', url, clone_to])

    @staticmethod
    def pull(repo_dir):
        # TODO: Add log line for notifying user.
        subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull'])

    def get_files(self):
        """ Return files of snippet """

        metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
        with open(metadata_file, 'r') as f:
            data = json.loads(f.read())

            for item in data['values']:
                if item['id'] != self.snippet_id:
                    continue

                return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]

Prompt:
Add doc string to Snippet.get_files

import os
from os import path
import glob
import json
import subprocess

class Snippet(object):

    def __init__(self, config, username, snippet_id):
        self.config = config
        self.username = username
        self.snippet_id = snippet_id

        repo_parent = path.join(self.config.get('snippet_home'), username)
        self.repo_path = glob.glob(path.join(repo_parent, '*{}'.format(self.snippet_id)))[0]

    @staticmethod
    def clone(url, clone_to):
        #TODO: Add log line for notifying user.
        # subprocess.DEVNULL
        subprocess.call(['git', 'clone', url, clone_to])

    @staticmethod
    def pull(repo_dir):
        # TODO: Add log line for notifying user.
        subprocess.call(['git', '--git-dir={}/.git'.format(repo_dir), 'pull'])

    def get_files(self):
        metadata_file = path.join(self.config.get('snippet_home'), 'metadata.json')
        with open(metadata_file, 'r') as f:
            data = json.loads(f.read())

            for item in data['values']:
                if item['id'] != self.snippet_id:
                    continue

                return [f for f in os.listdir(self.repo_path) if path.isfile(path.join(self.repo_path, f))]


import os.path

from nose2.tests._common import FunctionalTestCase

class TestCoverage(FunctionalTestCase):
    def test_run(self):
        proc = self.runIn(
            'scenario/test_with_module',
            '-v',
            '--with-coverage',
            '--coverage=lib/'
        )
        STATS = '           8      5    38%'

        stdout, stderr = proc.communicate()
        self.assertTestRunOutputMatches(
            proc,
            stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
        self.assertTestRunOutputMatches(
            proc,
            stderr='TOTAL      ' + STATS)

Fix regex matching coverage output

Response:
<REPLACE_OLD> 'mod1').replace('\\', <REPLACE_NEW> 'mod1.py').replace('\\', <REPLACE_END> <INSERT>    <INSERT_END> <|endoftext|> import os.path

from nose2.tests._common import FunctionalTestCase

class TestCoverage(FunctionalTestCase):
    def test_run(self):
        proc = self.runIn(
            'scenario/test_with_module',
            '-v',
            '--with-coverage',
            '--coverage=lib/'
        )
        STATS = '           8      5    38%'

        stdout, stderr = proc.communicate()
        self.assertTestRunOutputMatches(
            proc,
            stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
        self.assertTestRunOutputMatches(
            proc,
            stderr='TOTAL      ' + STATS)

Prompt:
Fix regex matching coverage output

The coverage library now returns the file extensions.

import os.path

from nose2.tests._common import FunctionalTestCase

class TestCoverage(FunctionalTestCase):
    def test_run(self):
        proc = self.runIn(
            'scenario/test_with_module',
            '-v',
            '--with-coverage',
            '--coverage=lib/'
        )
        STATS = '           8      5    38%'

        stdout, stderr = proc.communicate()
        self.assertTestRunOutputMatches(
            proc,
            stderr=os.path.join('lib', 'mod1').replace('\\', r'\\') + STATS)
        self.assertTestRunOutputMatches(
            proc,
            stderr='TOTAL   ' + STATS)


from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql

from radar.database import db
from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship
from radar.models.logs import log_changes

class Form(db.Model):
    __tablename__ = 'forms'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    data = Column(postgresql.JSONB, nullable=False)

@log_changes
class Entry(db.Model, MetaModelMixin):
    __tablename__ = 'entries'

    id = uuid_pk_column()

    patient_id = patient_id_column()
    patient = patient_relationship('entries')

    form_id = Column(Integer, ForeignKey('forms.id'), nullable=False)
    form = relationship('Form')

    data = Column(postgresql.JSONB, nullable=False)

Index('entries_patient_idx', Entry.patient_id)

class GroupForm(db.Model):
    __tablename__ = 'group_forms'

    id = Column(Integer, primary_key=True)

    group_id = Column(Integer, ForeignKey('groups.id'), nullable=False)
    group = relationship('Group')

    form_id = Column(Integer, ForeignKey('forms.id'), nullable=False)
    form = relationship('Form')

Add index on patient id

Add index on patient id

Response:
<REPLACE_OLD> nullable=False)

class <REPLACE_NEW> nullable=False)

Index('entries_patient_idx', Entry.patient_id)

class <REPLACE_END> <|endoftext|> from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql

from radar.database import db
from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship
from radar.models.logs import log_changes

class Form(db.Model):
    __tablename__ = 'forms'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    data = Column(postgresql.JSONB, nullable=False)

@log_changes
class Entry(db.Model, MetaModelMixin):
    __tablename__ = 'entries'

    id = uuid_pk_column()

    patient_id = patient_id_column()
    patient = patient_relationship('entries')

    form_id = Column(Integer, ForeignKey('forms.id'), nullable=False)
    form = relationship('Form')

    data = Column(postgresql.JSONB, nullable=False)

Index('entries_patient_idx', Entry.patient_id)

class GroupForm(db.Model):
    __tablename__ = 'group_forms'

    id = Column(Integer, primary_key=True)

    group_id = Column(Integer, ForeignKey('groups.id'), nullable=False)
    group = relationship('Group')

    form_id = Column(Integer, ForeignKey('forms.id'), nullable=False)
    form = relationship('Form')

Prompt:
Add index on patient id

from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql

from radar.database import db
from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship
from radar.models.logs import log_changes

class Form(db.Model):
    __tablename__ = 'forms'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    data = Column(postgresql.JSONB, nullable=False)

@log_changes
class Entry(db.Model, MetaModelMixin):
    __tablename__ = 'entries'

    id = uuid_pk_column()

    patient_id = patient_id_column()
    patient = patient_relationship('entries')

    form_id = Column(Integer, ForeignKey('forms.id'), nullable=False)
    form = relationship('Form')

    data = Column(postgresql.JSONB, nullable=False)

class GroupForm(db.Model):
    __tablename__ = 'group_forms'

    id = Column(Integer, primary_key=True)

    group_id = Column(Integer, ForeignKey('groups.id'), nullable=False)
    group = relationship('Group')

    form_id = Column(Integer, ForeignKey('forms.id'), nullable=False)
    form = relationship('Form')


import sqlite3
import urllib2
import xml.etree.ElementTree as ET

MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'

def main():
	conn = sqlite3.connect('everdi.db')
	cur = conn.cursor()

	# Get all items used in current BlueprintInstances
	cur.execute("""
SELECT DISTINCT c.item_id
FROM blueprints_blueprintcomponent c
  INNER JOIN blueprints_blueprintinstance AS bi
    ON c.blueprint_id = bi.blueprint_id
""")
	rows = cur.fetchall()

	for i in range(0, len(rows), 20):
		url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20]))
		f = urllib2.urlopen(url)
		data = f.read()
		f.close()
		#open('data.txt', 'w').write(data)
		#data = open('data.txt').read()

		root = ET.fromstring(data)
		for t in root.findall('marketstat/type'):
			typeid = t.get('id')
			sell_median = t.find('sell/median').text
			buy_median = t.find('buy/median').text

			cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))

		conn.commit()

if __name__ == '__main__':
	main()

Response:
<REPLACE_OLD> 'http://api.eve-central.com/api/marketstat?hours=24&%s'

ITEMS = [
	34, # Tritanium
	35, # Pyerite
	36, # Mexallon
	37, # Isogen
	38, # Nocxium
	39, # Zydrine
	40, # Megacyte
	11399, # Morphite
]

def <REPLACE_NEW> 'http://api.eve-central.com/api/marketstat?hours=24&%s'

def <REPLACE_END> <REPLACE_OLD> conn.cursor()

	url <REPLACE_NEW> conn.cursor()

	# Get all items used in current BlueprintInstances
	cur.execute("""
SELECT DISTINCT c.item_id
FROM blueprints_blueprintcomponent c
  INNER JOIN blueprints_blueprintinstance AS bi
    ON c.blueprint_id = bi.blueprint_id
""")
	rows = cur.fetchall()

	for i in range(0, len(rows), 20):
		url <REPLACE_END> <REPLACE_OLD> i <REPLACE_NEW> item <REPLACE_END> <REPLACE_OLD> i <REPLACE_NEW> item <REPLACE_END> <REPLACE_OLD> ITEMS))
	f <REPLACE_NEW> rows[i:i+20]))
		f <REPLACE_END> <REPLACE_OLD> urllib2.urlopen(url)
	data <REPLACE_NEW> urllib2.urlopen(url)
		data <REPLACE_END> <REPLACE_OLD> f.read()
	f.close()
	#open('data.txt', 'w').write(data)
	#data <REPLACE_NEW> f.read()
		f.close()
		#open('data.txt', 'w').write(data)
		#data <REPLACE_END> <REPLACE_OLD> open('data.txt').read()

	root <REPLACE_NEW> open('data.txt').read()

		root <REPLACE_END> <REPLACE_OLD> ET.fromstring(data)
	for <REPLACE_NEW> ET.fromstring(data)
		for <REPLACE_END> <REPLACE_OLD> root.findall('marketstat/type'):
		typeid <REPLACE_NEW> root.findall('marketstat/type'):
			typeid <REPLACE_END> <REPLACE_OLD> t.get('id')
		sell_median <REPLACE_NEW> t.get('id')
			sell_median <REPLACE_END> <REPLACE_OLD> t.find('sell/median').text
		buy_median <REPLACE_NEW> t.find('sell/median').text
			buy_median <REPLACE_END> <REPLACE_OLD> t.find('buy/median').text

		cur.execute('UPDATE <REPLACE_NEW> t.find('buy/median').text

			cur.execute('UPDATE <REPLACE_END> <REPLACE_OLD> typeid))

	conn.commit()

if <REPLACE_NEW> typeid))

		conn.commit()

if <REPLACE_END> <|endoftext|> import sqlite3
import urllib2
import xml.etree.ElementTree as ET

MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'

def main():
	conn = sqlite3.connect('everdi.db')
	cur = conn.cursor()

	# Get all items used in current BlueprintInstances
	cur.execute("""
SELECT DISTINCT c.item_id
FROM blueprints_blueprintcomponent c
  INNER JOIN blueprints_blueprintinstance AS bi
    ON c.blueprint_id = bi.blueprint_id
""")
	rows = cur.fetchall()

	for i in range(0, len(rows), 20):
		url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20]))
		f = urllib2.urlopen(url)
		data = f.read()
		f.close()
		#open('data.txt', 'w').write(data)
		#data = open('data.txt').read()

		root = ET.fromstring(data)
		for t in root.findall('marketstat/type'):
			typeid = t.get('id')
			sell_median = t.find('sell/median').text
			buy_median = t.find('buy/median').text

			cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))

		conn.commit()

if __name__ == '__main__':
	main()

Prompt:
Update prices for all BlueprintInstances we currently have

import sqlite3
import urllib2
import xml.etree.ElementTree as ET

MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'

ITEMS = [
	34, # Tritanium
	35, # Pyerite
	36, # Mexallon
	37, # Isogen
	38, # Nocxium
	39, # Zydrine
	40, # Megacyte
	11399, # Morphite
]

def main():
	conn = sqlite3.connect('everdi.db')
	cur = conn.cursor()

	url = MARKET_URL % ('&'.join('typeid=%s' % i for i in ITEMS))
	f = urllib2.urlopen(url)
	data = f.read()
	f.close()
	#open('data.txt', 'w').write(data)
	#data = open('data.txt').read()

	root = ET.fromstring(data)
	for t in root.findall('marketstat/type'):
		typeid = t.get('id')
		sell_median = t.find('sell/median').text
		buy_median = t.find('buy/median').text

		cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))

	conn.commit()

if __name__ == '__main__':
	main()


import re

from bs4 import BeautifulSoup

import cfscrape

def nplstatus():
    scraper = cfscrape.create_scraper()
    data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
    soup = BeautifulSoup(data, 'html.parser')
    raw_status = soup.find_all(class_='register_linklabel')[2].span
    return not raw_status

def latest_version():
    scraper = cfscrape.create_scraper()
    data = scraper.get('http://teamspeak.com/downloads').content
    soup = BeautifulSoup(data, 'html.parser')

    def search(search_string):
        return soup.find_all(text=re.compile(search_string))[0].parent.\
                find(class_='version').text

    def clean(s):
        return s.replace('\n', '').strip()
    return clean(search(r'Client\ 64\-bit')), \
        clean(search(r'Server\ 64\-bit'))

Clean string returned by website

Response:
<REPLACE_OLD> find(class_='version').text
 <REPLACE_NEW> find(class_='version').text

    def clean(s):
     <REPLACE_END> <REPLACE_OLD> search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')
 <REPLACE_NEW> s.replace('\n', '').strip()
    return clean(search(r'Client\ 64\-bit')), \
        clean(search(r'Server\ 64\-bit'))
 <REPLACE_END> <|endoftext|> import re

from bs4 import BeautifulSoup

import cfscrape

def nplstatus():
    scraper = cfscrape.create_scraper()
    data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
    soup = BeautifulSoup(data, 'html.parser')
    raw_status = soup.find_all(class_='register_linklabel')[2].span
    return not raw_status

def latest_version():
    scraper = cfscrape.create_scraper()
    data = scraper.get('http://teamspeak.com/downloads').content
    soup = BeautifulSoup(data, 'html.parser')

    def search(search_string):
        return soup.find_all(text=re.compile(search_string))[0].parent.\
                find(class_='version').text

    def clean(s):
        return s.replace('\n', '').strip()
    return clean(search(r'Client\ 64\-bit')), \
        clean(search(r'Server\ 64\-bit'))

Prompt:
Clean string returned by website

=> remove newline-characters and strip

import re

from bs4 import BeautifulSoup

import cfscrape

def nplstatus():
    scraper = cfscrape.create_scraper()
    data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
    soup = BeautifulSoup(data, 'html.parser')
    raw_status = soup.find_all(class_='register_linklabel')[2].span
    return not raw_status

def latest_version():
    scraper = cfscrape.create_scraper()
    data = scraper.get('http://teamspeak.com/downloads').content
    soup = BeautifulSoup(data, 'html.parser')

    def search(search_string):
        return soup.find_all(text=re.compile(search_string))[0].parent.\
                find(class_='version').text
    return search(r'Client\ 64\-bit'), search(r'Server\ 64\-bit')


'''
Created on Feb 21, 2013

@author: raybesiga
'''

from django.core.management.base import BaseCommand
from education.models import reschedule_teacher_weekly_polls
from optparse import OptionParser, make_option

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option("-g", "--group", dest="group"),
    )
    def handle(self, **options):
        if not options['group']:
            group = raw_input('For which group? -- Teachers, SMC, Head Teachers, All:')
        else:
            group = options['group']
        group = None if options['group'] == 'All' else group
        reschedule_teacher_weekly_polls(grp=group)
        self.stdout.write('')
        self.stdout.write('Done')

Add new reschedule teacher weekly poll

Add new reschedule teacher weekly poll

Response:
<INSERT> '''
Created on Feb 21, 2013

@author: raybesiga
'''

from django.core.management.base import BaseCommand
from education.models import reschedule_teacher_weekly_polls
from optparse import OptionParser, make_option

class Command(BaseCommand):
 <INSERT_END> <INSERT>
    option_list = BaseCommand.option_list + (
        make_option("-g", "--group", dest="group"),
    )
    def handle(self, **options):
        if not options['group']:
            group = raw_input('For which group? -- Teachers, SMC, Head Teachers, All:')
        else:
            group = options['group']
        group = None if options['group'] == 'All' else group
        reschedule_teacher_weekly_polls(grp=group)
        self.stdout.write('')
        self.stdout.write('Done')
 <INSERT_END> <|endoftext|> '''
Created on Feb 21, 2013

@author: raybesiga
'''

from django.core.management.base import BaseCommand
from education.models import reschedule_teacher_weekly_polls
from optparse import OptionParser, make_option

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option("-g", "--group", dest="group"),
    )
    def handle(self, **options):
        if not options['group']:
            group = raw_input('For which group? -- Teachers, SMC, Head Teachers, All:')
        else:
            group = options['group']
        group = None if options['group'] == 'All' else group
        reschedule_teacher_weekly_polls(grp=group)
        self.stdout.write('')
        self.stdout.write('Done')

Prompt: Add new reschedule teacher weekly poll


# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = True
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = True

Response:
<INSERT> True
CALENDAR_MECHANISM = <INSERT_END> <|endoftext|> # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = True
MEMCACHE_MECHANISM = True
CALENDAR_MECHANISM = True

Prompt:
Enable Calendar integration on App Engine deployments

# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com

APP_ENGINE = True
ENABLE_JASMINE = False
LOGIN_MANAGER = 'ggrc.login.appengine'
FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer'
# Cannot access filesystem on AppEngine or when using SDK
AUTOBUILD_ASSETS = False
SQLALCHEMY_RECORD_QUERIES = True
MEMCACHE_MECHANISM = True


import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils

class ScriptBase:

    def __init__(self, config_file=None):
        self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
        self.name = self.__class__.__name__
        self.ts = get_ts()
        if config_file:
            boto.config.read(config_file)

    def notify(self, subject, body=''):
        boto.utils.notify(subject, body)

    def mkdir(self, path):
        if not os.path.isdir(path):
            try:
                os.mkdir(path)
            except:
                boto.log.error('Error creating directory: %s' % path)

    def umount(self, path):
        if os.path.ismount(path):
            self.run('umount %s' % path)

    def run(self, command, notify=True, exit_on_error=False, cwd=None):
        self.last_command = ShellCommand(command, cwd=cwd)
        if self.last_command.status != 0:
            boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
            if notify:
                self.notify('Error encountered', \
                        'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
                        (command, self.last_command.output))
            if exit_on_error:
                sys.exit(-1)
        return self.last_command.status

    def main(self):
        pass

Response:
<REPLACE_OLD> cwd)
 <REPLACE_NEW> cwd=cwd)
 <REPLACE_END> <|endoftext|> import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils

class ScriptBase:

    def __init__(self, config_file=None):
        self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
        self.name = self.__class__.__name__
        self.ts = get_ts()
        if config_file:
            boto.config.read(config_file)

    def notify(self, subject, body=''):
        boto.utils.notify(subject, body)

    def mkdir(self, path):
        if not os.path.isdir(path):
            try:
                os.mkdir(path)
            except:
                boto.log.error('Error creating directory: %s' % path)

    def umount(self, path):
        if os.path.ismount(path):
            self.run('umount %s' % path)

    def run(self, command, notify=True, exit_on_error=False, cwd=None):
        self.last_command = ShellCommand(command, cwd=cwd)
        if self.last_command.status != 0:
            boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
            if notify:
                self.notify('Error encountered', \
                        'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
                        (command, self.last_command.output))
            if exit_on_error:
                sys.exit(-1)
        return self.last_command.status

    def main(self):
        pass

Prompt:
Add missing argument specification for cwd argument.

import os
import sys
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils

class ScriptBase:

    def __init__(self, config_file=None):
        self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
        self.name = self.__class__.__name__
        self.ts = get_ts()
        if config_file:
            boto.config.read(config_file)

    def notify(self, subject, body=''):
        boto.utils.notify(subject, body)

    def mkdir(self, path):
        if not os.path.isdir(path):
            try:
                os.mkdir(path)
            except:
                boto.log.error('Error creating directory: %s' % path)

    def umount(self, path):
        if os.path.ismount(path):
            self.run('umount %s' % path)

    def run(self, command, notify=True, exit_on_error=False, cwd=None):
        self.last_command = ShellCommand(command, cwd)
        if self.last_command.status != 0:
            boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
            if notify:
                self.notify('Error encountered', \
                        'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
                        (command, self.last_command.output))
            if exit_on_error:
                sys.exit(-1)
        return self.last_command.status

    def main(self):
        pass


from landlab import VoronoiDelaunayGrid  # , RasterModelGrid
from landlab.components.flow_routing.route_flow_dn import FlowRouter
from landlab.components.stream_power.stream_power import StreamPowerEroder
import numpy as np

x, y = np.random.rand(50), np.random.rand(50)
mg = VoronoiDelaunayGrid(x,y)
#mg = RasterModelGrid(4,5)

mg.add_field('node', 'topographic__elevation', mg.node_x, copy=True)

fr = FlowRouter(mg)
spe = StreamPowerEroder(mg, 'drive_sp_params.txt')

for i in xrange(100):
    fr.route_flow()
    spe.erode(1.)

Test driver for Voronoi stream power

Test driver for Voronoi stream power

What it says on the tin. Very simple.

Response:
<INSERT> from landlab import VoronoiDelaunayGrid <INSERT_END> <INSERT> # , RasterModelGrid
from landlab.components.flow_routing.route_flow_dn import FlowRouter
from landlab.components.stream_power.stream_power import StreamPowerEroder
import numpy as np

x, y = np.random.rand(50), np.random.rand(50)
mg = VoronoiDelaunayGrid(x,y)
#mg = RasterModelGrid(4,5)

mg.add_field('node', 'topographic__elevation', mg.node_x, copy=True)

fr = FlowRouter(mg)
spe = StreamPowerEroder(mg, 'drive_sp_params.txt')

for i in xrange(100):
    fr.route_flow()
    spe.erode(1.)
 <INSERT_END> <|endoftext|> from landlab import VoronoiDelaunayGrid  # , RasterModelGrid
from landlab.components.flow_routing.route_flow_dn import FlowRouter
from landlab.components.stream_power.stream_power import StreamPowerEroder
import numpy as np

x, y = np.random.rand(50), np.random.rand(50)
mg = VoronoiDelaunayGrid(x,y)
#mg = RasterModelGrid(4,5)

mg.add_field('node', 'topographic__elevation', mg.node_x, copy=True)

fr = FlowRouter(mg)
spe = StreamPowerEroder(mg, 'drive_sp_params.txt')

for i in xrange(100):
    fr.route_flow()
    spe.erode(1.)

Prompt:
Test driver for Voronoi stream power

What it says on the tin. Very simple.


from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin

class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
	Type = Gio.BusType

	def __init__(self, type, timeout=1000):
		self.con = Gio.bus_get_sync(type, None)
		self.timeout = timeout

	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_value, traceback):
		self.con = None

def SystemBus():
	return Bus(Bus.Type.SYSTEM)

def SessionBus():
	return Bus(Bus.Type.SESSION)

if __name__ == "__main__":
	import sys
	title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
	message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'

	bus = SessionBus()
	notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
	notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
	# [""] is not required, but makes us compatible with Gnome 2030.

Increase the default timeout to 1s.

Increase the default timeout to 1s.

Response:
<REPLACE_OLD> timeout=10):
		self.con <REPLACE_NEW> timeout=1000):
		self.con <REPLACE_END> <|endoftext|> from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin

class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
	Type = Gio.BusType

	def __init__(self, type, timeout=1000):
		self.con = Gio.bus_get_sync(type, None)
		self.timeout = timeout

	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_value, traceback):
		self.con = None

def SystemBus():
	return Bus(Bus.Type.SYSTEM)

def SessionBus():
	return Bus(Bus.Type.SESSION)

if __name__ == "__main__":
	import sys
	title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
	message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'

	bus = SessionBus()
	notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
	notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
	# [""] is not required, but makes us compatible with Gnome 2030.

Prompt:
Increase the default timeout to 1s.

from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin

class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
	Type = Gio.BusType

	def __init__(self, type, timeout=10):
		self.con = Gio.bus_get_sync(type, None)
		self.timeout = timeout

	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_value, traceback):
		self.con = None

def SystemBus():
	return Bus(Bus.Type.SYSTEM)

def SessionBus():
	return Bus(Bus.Type.SESSION)

if __name__ == "__main__":
	import sys
	title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
	message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'

	bus = SessionBus()
	notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
	notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
	# [""] is not required, but makes us compatible with Gnome 2030.


from nose.tools import assert_false
from mock import Mock, PropertyMock, patch
from .models import Photo

def test_dont_access_source():
    """
    Touching the source may trigger an unneeded query.
    See <https://github.com/matthewwithanm/django-imagekit/issues/295>

    """
    pmock = PropertyMock()
    pmock.__get__ = Mock()
    with patch.object(Photo, 'original_image', pmock):
        photo = Photo()  # noqa
        assert_false(pmock.__get__.called)

Add test to illustrate GH-295

Add test to illustrate GH-295

Response:
<INSERT> from nose.tools import assert_false
from mock import Mock, PropertyMock, patch
from .models import Photo

def test_dont_access_source():
 <INSERT_END> <INSERT>   """
    Touching the source may trigger an unneeded query.
    See <https://github.com/matthewwithanm/django-imagekit/issues/295>

    """
    pmock = PropertyMock()
    pmock.__get__ = Mock()
    with patch.object(Photo, 'original_image', pmock):
        photo = Photo()  # noqa
        assert_false(pmock.__get__.called)
 <INSERT_END> <|endoftext|> from nose.tools import assert_false
from mock import Mock, PropertyMock, patch
from .models import Photo

def test_dont_access_source():
    """
    Touching the source may trigger an unneeded query.
    See <https://github.com/matthewwithanm/django-imagekit/issues/295>

    """
    pmock = PropertyMock()
    pmock.__get__ = Mock()
    with patch.object(Photo, 'original_image', pmock):
        photo = Photo()  # noqa
        assert_false(pmock.__get__.called)

Prompt: Add test to illustrate GH-295


from turtle import *

GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"

fillcolor(FARBE)
shape(SHAPE)

def zeichneKerze(brennt):
    pd()
    begin_fill()
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    right(90)
    forward(GROESSE*30)
    back(GROESSE*30)
    left(90)
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    end_fill()
    pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    left(90)
    fd(GROESSE*430)
    pd()
    color("yellow")
    dot(GROESSE*60)
    color("black")
    back(GROESSE*30)
    pu()
    home()

##zeichneKerze(brennt=False) # testweise erstmal nur nicht brennende Kerze
zeichneKerze(True)
hideturtle()

Response:
<REPLACE_OLD> True

fillcolor(FARBE)

def <REPLACE_NEW> True
SHAPE = "turtle"

fillcolor(FARBE)
shape(SHAPE)

def <REPLACE_END> <REPLACE_OLD> Kerze
zeichneKerze(True)
hide()
 <REPLACE_NEW> Kerze
zeichneKerze(True)
hideturtle()
 <REPLACE_END> <|endoftext|> from turtle import *

GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"

fillcolor(FARBE)
shape(SHAPE)

def zeichneKerze(brennt):
    pd()
    begin_fill()
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    right(90)
    forward(GROESSE*30)
    back(GROESSE*30)
    left(90)
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    end_fill()
    pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    left(90)
    fd(GROESSE*430)
    pd()
    color("yellow")
    dot(GROESSE*60)
    color("black")
    back(GROESSE*30)
    pu()
    home()

##zeichneKerze(brennt=False) # testweise erstmal nur nicht brennende Kerze
zeichneKerze(True)
hideturtle()

Prompt:
Resolve NameError, add changeable turtle shape constant.

from turtle import *

GROESSE = 0.5
FARBE = "red"
FAERBEN = True

fillcolor(FARBE)

def zeichneKerze(brennt):
    pd()
    begin_fill()
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    right(90)
    forward(GROESSE*30)
    back(GROESSE*30)
    left(90)
    forward(GROESSE*100)
    left(90)
    forward(GROESSE*400)
    left(90)
    forward(GROESSE*100)
    end_fill()
    pu()
    if brennt:
        zeichneFlamme()

def zeichneFlamme():
    left(90)
    fd(GROESSE*430)
    pd()
    color("yellow")
    dot(GROESSE*60)
    color("black")
    back(GROESSE*30)
    pu()
    home()

##zeichneKerze(brennt=False) # testweise erstmal nur nicht brennende Kerze
zeichneKerze(True)
hide()


from setuptools import setup

long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files.  It optimizes images without changing their look or visual quality
("losslessly").

It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seemless integration with easy_thumbnails app, but can
work with others too.'''

setup(
    author="Marko Samastur",
    author_email="markos@gaivo.net",
    name='image-diet2',
    version='0.7.1',
    description='Remove unnecessary bytes from images',
    long_description=long_description,
    url='https://github.com/samastur/image-diet2/',
    platforms=['OS Independent'],
    license='MIT License',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
        'Topic :: Utilities',
    ],
    install_requires=[
        'pyimagediet>=0.9',
    ],
    include_package_data=True,
    packages=['image_diet'],
    zip_safe=False
)

Use version 0.9 of pyimagediet

Use version 0.9 of pyimagediet

Response:
<REPLACE_OLD> 'pyimagediet>=0.5',
 <REPLACE_NEW> 'pyimagediet>=0.9',
 <REPLACE_END> <|endoftext|> from setuptools import setup

long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files.  It optimizes images without changing their look or visual quality
("losslessly").

It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seemless integration with easy_thumbnails app, but can
work with others too.'''

setup(
    author="Marko Samastur",
    author_email="markos@gaivo.net",
    name='image-diet2',
    version='0.7.1',
    description='Remove unnecessary bytes from images',
    long_description=long_description,
    url='https://github.com/samastur/image-diet2/',
    platforms=['OS Independent'],
    license='MIT License',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
        'Topic :: Utilities',
    ],
    install_requires=[
        'pyimagediet>=0.9',
    ],
    include_package_data=True,
    packages=['image_diet'],
    zip_safe=False
)

Prompt:
Use version 0.9 of pyimagediet

from setuptools import setup

long_description = '''\
image-diet2 is a Django application for removing unnecessary bytes from image
files.  It optimizes images without changing their look or visual quality
("losslessly").

It works on images in JPEG, GIF and PNG formats and will leave others
unchanged. Provides a seemless integration with easy_thumbnails app, but can
work with others too.'''

setup(
    author="Marko Samastur",
    author_email="markos@gaivo.net",
    name='image-diet2',
    version='0.7.1',
    description='Remove unnecessary bytes from images',
    long_description=long_description,
    url='https://github.com/samastur/image-diet2/',
    platforms=['OS Independent'],
    license='MIT License',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
        'Topic :: Utilities',
    ],
    install_requires=[
        'pyimagediet>=0.5',
    ],
    include_package_data=True,
    packages=['image_diet'],
    zip_safe=False
)


import sqlite3

def init(conn):
  c = conn.cursor()
  c.execute(
    '''CREATE TABLE IF NOT EXISTS email_log (
         `id` INTEGER PRIMARY KEY AUTOINCREMENT,
         `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
         `param` TEXT,
         `email` TEXT,
         `stage` INTEGER DEFAULT 0,
         `sender` TEXT,
         `receiver` TEXT,
         `subject` TEXT,
         `date_raw` TEXT,
         `message_id` TEXT,
         `attachments` INTEGER,
         `in_reply_to` TEXT,
         `in_reply_to_id` INTEGER,
         `references` TEXT
       )''')

  c.execute(
    '''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
       ON email_log (message_id)
    ''')

Add index to the message_id column

Add index to the message_id column

Response:
<INSERT>  c.execute(
    '''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
       ON email_log (message_id)
    ''')

 <INSERT_END> <|endoftext|> import sqlite3

def init(conn):
  c = conn.cursor()
  c.execute(
    '''CREATE TABLE IF NOT EXISTS email_log (
         `id` INTEGER PRIMARY KEY AUTOINCREMENT,
         `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
         `param` TEXT,
         `email` TEXT,
         `stage` INTEGER DEFAULT 0,
         `sender` TEXT,
         `receiver` TEXT,
         `subject` TEXT,
         `date_raw` TEXT,
         `message_id` TEXT,
         `attachments` INTEGER,
         `in_reply_to` TEXT,
         `in_reply_to_id` INTEGER,
         `references` TEXT
       )''')

  c.execute(
    '''CREATE INDEX IF NOT EXISTS email_log_idx_message_id
       ON email_log (message_id)
    ''')

Prompt:
Add index to the message_id column

import sqlite3

def init(conn):
  c = conn.cursor()
  c.execute(
    '''CREATE TABLE IF NOT EXISTS email_log (
         `id` INTEGER PRIMARY KEY AUTOINCREMENT,
         `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
         `param` TEXT,
         `email` TEXT,
         `stage` INTEGER DEFAULT 0,
         `sender` TEXT,
         `receiver` TEXT,
         `subject` TEXT,
         `date_raw` TEXT,
         `message_id` TEXT,
         `attachments` INTEGER,
         `in_reply_to` TEXT,
         `in_reply_to_id` INTEGER,
         `references` TEXT
       )''')


from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac

def assemble_cx(stmts, out_file):
    """Return a CX assembler."""
    stmts = ac.filter_belief(stmts, 0.95)
    stmts = ac.filter_top_level(stmts)

    ca = CxAssembler()
    ca.add_statements(stmts)
    model = ca.make_model()
    ca.save_model(out_file)
    return ca

Remove strip context for CX assembly

Remove strip context for CX assembly

Response:
<REPLACE_OLD> ac.filter_top_level(stmts)
    stmts = ac.strip_agent_context(stmts)
 <REPLACE_NEW> ac.filter_top_level(stmts)

 <REPLACE_END> <|endoftext|> from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac

def assemble_cx(stmts, out_file):
    """Return a CX assembler."""
    stmts = ac.filter_belief(stmts, 0.95)
    stmts = ac.filter_top_level(stmts)

    ca = CxAssembler()
    ca.add_statements(stmts)
    model = ca.make_model()
    ca.save_model(out_file)
    return ca

Prompt:
Remove strip context for CX assembly

from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac

def assemble_cx(stmts, out_file):
    """Return a CX assembler."""
    stmts = ac.filter_belief(stmts, 0.95)
    stmts = ac.filter_top_level(stmts)
    stmts = ac.strip_agent_context(stmts)
    ca = CxAssembler()
    ca.add_statements(stmts)
    model = ca.make_model()
    ca.save_model(out_file)
    return ca


# -*- coding: utf-8 -*-
'''Custom decorators.'''

from __future__ import absolute_import
from functools import wraps
from textblob.exceptions import MissingCorpusException

class cached_property(object):
    '''A property that is only computed once per instance and then replaces
    itself with an ordinary attribute. Deleting the attribute resets the
    property.

    Credit to Marcel Hellkamp, author of bottle.py.
    '''

    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, obj, cls):
        if obj is None:
            return self
        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value

def requires_nltk_corpus(func):
    '''Wraps a function that requires an NLTK corpus. If the corpus isn't found,
    raise a MissingCorpusException.
    '''
    @wraps(func)
    def decorated(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except LookupError as err:
            print(err)
            raise MissingCorpusException()
    return decorated

Response:
<INSERT> functools import wraps
from <INSERT_END> <INSERT> @wraps(func)
    <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
'''Custom decorators.'''

from __future__ import absolute_import
from functools import wraps
from textblob.exceptions import MissingCorpusException

class cached_property(object):
    '''A property that is only computed once per instance and then replaces
    itself with an ordinary attribute. Deleting the attribute resets the
    property.

    Credit to Marcel Hellkamp, author of bottle.py.
    '''

    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, obj, cls):
        if obj is None:
            return self
        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value

def requires_nltk_corpus(func):
    '''Wraps a function that requires an NLTK corpus. If the corpus isn't found,
    raise a MissingCorpusException.
    '''
    @wraps(func)
    def decorated(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except LookupError as err:
            print(err)
            raise MissingCorpusException()
    return decorated

Prompt:
Use wraps decorator for requires_nltk_corpus

# -*- coding: utf-8 -*-
'''Custom decorators.'''

from __future__ import absolute_import
from textblob.exceptions import MissingCorpusException

class cached_property(object):
    '''A property that is only computed once per instance and then replaces
    itself with an ordinary attribute. Deleting the attribute resets the
    property.

    Credit to Marcel Hellkamp, author of bottle.py.
    '''

    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, obj, cls):
        if obj is None:
            return self
        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value

def requires_nltk_corpus(func):
    '''Wraps a function that requires an NLTK corpus. If the corpus isn't found,
    raise a MissingCorpusException.
    '''
    def decorated(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except LookupError as err:
            print(err)
            raise MissingCorpusException()
    return decorated


from parcels import Particle, ParticleSet, JITParticle, JITParticleSet
from parcels import NEMOGrid, ParticleFile, AdvectionRK4
from argparse import ArgumentParser

pclasses = {'scipy': (Particle, ParticleSet),
            'jit': (JITParticle, JITParticleSet)}

def moving_eddies(grid, npart, mode='jit', verbose=False):
    """Configuration of a particle set that follows two moving eddies

    :arg grid: :class NEMOGrid: that defines the flow field
    :arg npart: Number of particles to intialise"""

    # Determine particle and set classes according to mode
    ParticleClass, ParticleSetClass = pclasses[mode]

    lon = [3.3, 3.3]
    lat = [46., 47.8]
    pset = ParticleSetClass(2, grid, lon=lon, lat=lat)

    if verbose:
        print("Initial particle positions:")
        for p in pset:
            print(p)

    out = ParticleFile(name="EddyParticle", particleset=pset)
    out.write(pset, 0.)
    current = 0.
    for _ in range(24 * 25):
        pset.execute(AdvectionRK4, time=current,
                     timesteps=12, dt=300.)
        out.write(pset, current)
        current += 3600.

    if verbose:
        print("Final particle positions:")
        for p in pset:
            print(p)

if __name__ == "__main__":
    p = ArgumentParser(description="""
Example of particle advection around an idealised peninsula""")
    p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='jit',
                   help='Execution mode for performing RK4 computation')
    p.add_argument('-p', '--particles', type=int, default=20,
                   help='Number of particles to advect')
    p.add_argument('-v', '--verbose', action='store_true', default=False,
                   help='Print particle information before and after execution')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    args = p.parse_args()

    # Open grid file set
    grid = NEMOGrid.from_file('moving_eddies')

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("moving_eddies(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose)",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        moving_eddies(grid, args.particles, mode=args.mode, verbose=args.verbose)

MovingEddies: Add simple test setup that follows two particles

Response:
<REPLACE_OLD>  <REPLACE_NEW> from parcels import Particle, ParticleSet, JITParticle, JITParticleSet
from parcels import NEMOGrid, ParticleFile, AdvectionRK4
from argparse import ArgumentParser

pclasses = {'scipy': (Particle, ParticleSet),
            'jit': (JITParticle, JITParticleSet)}

def moving_eddies(grid, npart, mode='jit', verbose=False):
    """Configuration of a particle set that follows two moving eddies

    :arg grid: :class NEMOGrid: that defines the flow field
    :arg npart: Number of particles to intialise"""

    # Determine particle and set classes according to mode
    ParticleClass, ParticleSetClass = pclasses[mode]

    lon = [3.3, 3.3]
    lat = [46., 47.8]
    pset = ParticleSetClass(2, grid, lon=lon, lat=lat)

    if verbose:
        print("Initial particle positions:")
        for p in pset:
            print(p)

    out = ParticleFile(name="EddyParticle", particleset=pset)
    out.write(pset, 0.)
    current = 0.
    for _ in range(24 * 25):
        pset.execute(AdvectionRK4, time=current,
                     timesteps=12, dt=300.)
        out.write(pset, current)
        current += 3600.

    if verbose:
        print("Final particle positions:")
        for p in pset:
            print(p)

if __name__ == "__main__":
    p = ArgumentParser(description="""
Example of particle advection around an idealised peninsula""")
    p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='jit',
                   help='Execution mode for performing RK4 computation')
    p.add_argument('-p', '--particles', type=int, default=20,
                   help='Number of particles to advect')
    p.add_argument('-v', '--verbose', action='store_true', default=False,
                   help='Print particle information before and after execution')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    args = p.parse_args()

    # Open grid file set
    grid = NEMOGrid.from_file('moving_eddies')

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("moving_eddies(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose)",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        moving_eddies(grid, args.particles, mode=args.mode, verbose=args.verbose)
 <REPLACE_END> <|endoftext|> from parcels import Particle, ParticleSet, JITParticle, JITParticleSet
from parcels import NEMOGrid, ParticleFile, AdvectionRK4
from argparse import ArgumentParser

pclasses = {'scipy': (Particle, ParticleSet),
            'jit': (JITParticle, JITParticleSet)}

def moving_eddies(grid, npart, mode='jit', verbose=False):
    """Configuration of a particle set that follows two moving eddies

    :arg grid: :class NEMOGrid: that defines the flow field
    :arg npart: Number of particles to intialise"""

    # Determine particle and set classes according to mode
    ParticleClass, ParticleSetClass = pclasses[mode]

    lon = [3.3, 3.3]
    lat = [46., 47.8]
    pset = ParticleSetClass(2, grid, lon=lon, lat=lat)

    if verbose:
        print("Initial particle positions:")
        for p in pset:
            print(p)

    out = ParticleFile(name="EddyParticle", particleset=pset)
    out.write(pset, 0.)
    current = 0.
    for _ in range(24 * 25):
        pset.execute(AdvectionRK4, time=current,
                     timesteps=12, dt=300.)
        out.write(pset, current)
        current += 3600.

    if verbose:
        print("Final particle positions:")
        for p in pset:
            print(p)

if __name__ == "__main__":
    p = ArgumentParser(description="""
Example of particle advection around an idealised peninsula""")
    p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='jit',
                   help='Execution mode for performing RK4 computation')
    p.add_argument('-p', '--particles', type=int, default=20,
                   help='Number of particles to advect')
    p.add_argument('-v', '--verbose', action='store_true', default=False,
                   help='Print particle information before and after execution')
    p.add_argument('--profiling', action='store_true', default=False,
                   help='Print profiling information after run')
    args = p.parse_args()

    # Open grid file set
    grid = NEMOGrid.from_file('moving_eddies')

    if args.profiling:
        from cProfile import runctx
        from pstats import Stats
        runctx("moving_eddies(grid, args.particles, mode=args.mode, \
                              verbose=args.verbose)",
               globals(), locals(), "Profile.prof")
        Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10)
    else:
        moving_eddies(grid, args.particles, mode=args.mode, verbose=args.verbose)

Prompt: MovingEddies: Add simple test setup that follows two particles


from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor

class HiddenModule(XModule):
    def get_html(self):
        if self.system.user_is_staff:
            return u"ERROR: This module is unknown--students will not see it at all"
        else:
            return u""

class HiddenDescriptor(RawDescriptor):
    module_class = HiddenModule

Return unicode string to pass assertion

Response:
<REPLACE_OLD> "ERROR: <REPLACE_NEW> u"ERROR: <REPLACE_END> <REPLACE_OLD> ""

class <REPLACE_NEW> u""

class <REPLACE_END> <|endoftext|> from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor

class HiddenModule(XModule):
    def get_html(self):
        if self.system.user_is_staff:
            return u"ERROR: This module is unknown--students will not see it at all"
        else:
            return u""

class HiddenDescriptor(RawDescriptor):
    module_class = HiddenModule

Prompt:
hidden-module-unicode: Return unicode string to pass assertion

XBlock Fragments expect unicode strings, and fail on an assertion when
it isn't:

```
2013-11-14 07:55:50,774 ERROR 3788 [django.request] base.py:215 - Internal Server Error: /courses/TestU/TST101/now/courseware/41d55c576a574fde99319420228f7f88/5fef5794e34842f4a2d45ebcdeaa9a3a/
Traceback (most recent call last):
  File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 91, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 75, in _cache_controlled
    response = viewfunc(request, *args, **kw)
  File "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware/views.py", line 407, in index
    context['fragment'] = section_module.render('student_view')
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/core.py", line 156, in render
    return self.runtime.render(self, view, context)
  File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 903, in render
    return block.xmodule_runtime.render(to_render, view_name, context)
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/runtime.py", line 356, in render
    frag = view_fn(context)
  File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/seq_module.py", line 77, in student_view
    rendered_child = child.render('student_view', context)
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/core.py", line 156, in render
    return self.runtime.render(self, view, context)
  File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 903, in render
    return block.xmodule_runtime.render(to_render, view_name, context)
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/runtime.py", line 356, in render
    frag = view_fn(context)
  File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/vertical_module.py", line 27, in student_view
    rendered_child = child.render('student_view', context)
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/core.py", line 156, in render
    return self.runtime.render(self, view, context)
  File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 903, in render
    return block.xmodule_runtime.render(to_render, view_name, context)
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/runtime.py", line 356, in render
    frag = view_fn(context)
  File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 464, in student_view
    return Fragment(self.get_html())
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/fragment.py", line 34, in __init__
    self.add_content(content)
  File "/edx/app/edxapp/venvs/edxapp/src/xblock/xblock/fragment.py", line 71, in add_content
    assert isinstance(content, unicode)
AssertionError
```

from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor

class HiddenModule(XModule):
    def get_html(self):
        if self.system.user_is_staff:
            return "ERROR: This module is unknown--students will not see it at all"
        else:
            return ""

class HiddenDescriptor(RawDescriptor):
    module_class = HiddenModule


import os

from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings
from django.utils.functional import empty

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

@override_settings(STATICFILES_DIRS=(os.path.join(os.path.dirname(__file__), 'static'), ))
class QunitTests(StaticLiveServerTestCase):
    """Iteractive tests with selenium."""

    @classmethod
    def setUpClass(cls):
        cls.browser = webdriver.PhantomJS()
        super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super().tearDownClass()

    def setUp(self):
        # Clear the cache versions of the staticfiles finders and storage
        # See https://code.djangoproject.com/ticket/24197
        storage.staticfiles_storage._wrapped = empty
        finders.get_finder.cache_clear()

    def test_qunit(self):
        """Load the QUnit tests and check for failures."""

        self.browser.get(self.live_server_url + settings.STATIC_URL + 'index.html')
        results = WebDriverWait(self.browser, 5).until(
            expected_conditions.visibility_of_element_located((By.ID, 'qunit-testresult')))
        total = int(results.find_element_by_class_name('total').text)
        failed = int(results.find_element_by_class_name('failed').text)
        self.assertTrue(total and not failed, results.text)

Response:
<INSERT> django.contrib.staticfiles import finders, storage
from <INSERT_END> <REPLACE_OLD> override_settings

from <REPLACE_NEW> override_settings
from django.utils.functional import empty

from <REPLACE_END> <INSERT>    def setUp(self):
        # Clear the cache versions of the staticfiles finders and storage
        # See https://code.djangoproject.com/ticket/24197
        storage.staticfiles_storage._wrapped = empty
        finders.get_finder.cache_clear()

 <INSERT_END> <|endoftext|> import os

from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings
from django.utils.functional import empty

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

@override_settings(STATICFILES_DIRS=(os.path.join(os.path.dirname(__file__), 'static'), ))
class QunitTests(StaticLiveServerTestCase):
    """Iteractive tests with selenium."""

    @classmethod
    def setUpClass(cls):
        cls.browser = webdriver.PhantomJS()
        super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super().tearDownClass()

    def setUp(self):
        # Clear the cache versions of the staticfiles finders and storage
        # See https://code.djangoproject.com/ticket/24197
        storage.staticfiles_storage._wrapped = empty
        finders.get_finder.cache_clear()

    def test_qunit(self):
        """Load the QUnit tests and check for failures."""

        self.browser.get(self.live_server_url + settings.STATIC_URL + 'index.html')
        results = WebDriverWait(self.browser, 5).until(
            expected_conditions.visibility_of_element_located((By.ID, 'qunit-testresult')))
        total = int(results.find_element_by_class_name('total').text)
        failed = int(results.find_element_by_class_name('failed').text)
        self.assertTrue(total and not failed, results.text)

Prompt:
Clear global state/caching handled by Django so the test passes when run in the full suite.

import os

from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

@override_settings(STATICFILES_DIRS=(os.path.join(os.path.dirname(__file__), 'static'), ))
class QunitTests(StaticLiveServerTestCase):
    """Iteractive tests with selenium."""

    @classmethod
    def setUpClass(cls):
        cls.browser = webdriver.PhantomJS()
        super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super().tearDownClass()

    def test_qunit(self):
        """Load the QUnit tests and check for failures."""

        self.browser.get(self.live_server_url + settings.STATIC_URL + 'index.html')
        results = WebDriverWait(self.browser, 5).until(
            expected_conditions.visibility_of_element_located((By.ID, 'qunit-testresult')))
        total = int(results.find_element_by_class_name('total').text)
        failed = int(results.find_element_by_class_name('failed').text)
        self.assertTrue(total and not failed, results.text)


from random import random
class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        :type numsSize: int
        """
        self.nums = nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        meet = 0
        choice = None
        for i, n in enumerate(self.nums):
            if n == target:
                meet += 1
                if random() * meet < 1:
                    choice = i
        return choice

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

Add py solution for 398. Random Pick Index

398. Random Pick Index: https://leetcode.com/problems/random-pick-index/

Response:
<REPLACE_OLD>  <REPLACE_NEW> from random import random
class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        :type numsSize: int
        """
        self.nums = nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        meet = 0
        choice = None
        for i, n in enumerate(self.nums):
            if n == target:
                meet += 1
                if random() * meet < 1:
                    choice = i
        return choice

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
 <REPLACE_END> <|endoftext|> from random import random
class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        :type numsSize: int
        """
        self.nums = nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        meet = 0
        choice = None
        for i, n in enumerate(self.nums):
            if n == target:
                meet += 1
                if random() * meet < 1:
                    choice = i
        return choice

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

Prompt:
Add py solution for 398. Random Pick Index

398. Random Pick Index: https://leetcode.com/problems/random-pick-index/


from django.core import serializers
from django.http.response import HttpResponse

from what_meta.models import WhatTorrentGroup

def search_torrent_groups(request, query):
    response = HttpResponse(
        serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
        content_type='text/json',
    )
    response['Access-Control-Allow-Origin'] = '*'
    return response

Support for super simple player.

Support for super simple player.

Response:
<REPLACE_OLD> return <REPLACE_NEW> response = <REPLACE_END> <REPLACE_OLD> content_type='text/plain',
 <REPLACE_NEW> content_type='text/json',
 <REPLACE_END> <INSERT>    response['Access-Control-Allow-Origin'] = '*'
    return response
 <INSERT_END> <|endoftext|> from django.core import serializers
from django.http.response import HttpResponse

from what_meta.models import WhatTorrentGroup

def search_torrent_groups(request, query):
    response = HttpResponse(
        serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
        content_type='text/json',
    )
    response['Access-Control-Allow-Origin'] = '*'
    return response

Prompt:
Support for super simple player.

from django.core import serializers
from django.http.response import HttpResponse

from what_meta.models import WhatTorrentGroup

def search_torrent_groups(request, query):
    return HttpResponse(
        serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)),
        content_type='text/plain',
    )