from django.shortcuts import render

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from countylimits.models import CountyLimit

@api_view(['GET'])
def county_limits(request):
    """ Return all counties with their limits per state. """
    if request.method == 'GET':
        package = {'request': {}, 'data': []}
        if 'state' in request.GET:
            state = request.GET['state']
            data = CountyLimit.county_limits_by_state(state)
            if data:
                package['request']['state'] = request.GET['state']
                package['data'] = data
                return Response(package)
            else:
                return Response({'state': 'Invalid state'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'detail': 'Required parameter state is missing'}, status=status.HTTP_400_BAD_REQUEST)

Return 400 when state is invalid

Return 400 when state is invalid

Response:
<INSERT> request.GET['state']
            data = CountyLimit.county_limits_by_state(state)
            if data:
                <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> CountyLimit.county_limits_by_state(state)
 <REPLACE_NEW> data
     <REPLACE_END> <INSERT>            else:
                return Response({'state': 'Invalid state'}, status=status.HTTP_400_BAD_REQUEST)
 <INSERT_END> <|endoftext|> from django.shortcuts import render

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from countylimits.models import CountyLimit

@api_view(['GET'])
def county_limits(request):
    """ Return all counties with their limits per state. """
    if request.method == 'GET':
        package = {'request': {}, 'data': []}
        if 'state' in request.GET:
            state = request.GET['state']
            data = CountyLimit.county_limits_by_state(state)
            if data:
                package['request']['state'] = request.GET['state']
                package['data'] = data
                return Response(package)
            else:
                return Response({'state': 'Invalid state'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'detail': 'Required parameter state is missing'}, status=status.HTTP_400_BAD_REQUEST)

Prompt:
Return 400 when state is invalid

from django.shortcuts import render

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from countylimits.models import CountyLimit

@api_view(['GET'])
def county_limits(request):
    """ Return all counties with their limits per state. """
    if request.method == 'GET':
        package = {'request': {}, 'data': []}
        if 'state' in request.GET:
            state = package['request']['state'] = request.GET['state']
            package['data'] = CountyLimit.county_limits_by_state(state)
            return Response(package)
        else:
            return Response({'detail': 'Required parameter state is missing'}, status=status.HTTP_400_BAD_REQUEST)


# coding=utf-8
import os
import shutil
from tempfile import mkdtemp

from django.core.management.base import BaseCommand

from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood

class Command(BaseCommand):
    """Script to load flood test data for demo purpose only.

    """
    help = 'Script to load flood test data for demo purpose only.'

    def handle(self, *args, **options):
        # Copy file to hazard drop directory
        REALTIME_HAZARD_DROP = os.environ.get(
            'REALTIME_HAZARD_DROP',
            '/home/realtime/hazard-drop/')
        hazard_drop_path = mkdtemp(dir=REALTIME_HAZARD_DROP)
        hazard_drop_path = os.path.join(
            hazard_drop_path, os.path.basename(flood_layer_uri))
        print 'Copy flood data to %s' % hazard_drop_path
        shutil.copy(flood_layer_uri, hazard_drop_path)

        flood_id = '2018022511-6-rw'
        print 'Send flood data to InaSAFE Django with flood id = %s' % flood_id
        process_flood.delay(
            flood_id=flood_id,
            data_source='hazard_file',
            data_source_args={
                'filename': hazard_drop_path
            }
        )

Fix wrong path to flood data to push.

Fix wrong path to flood data to push.

Response:
<REPLACE_OLD> flood_layer_uri
 <REPLACE_NEW> hazard_drop_path
 <REPLACE_END> <|endoftext|> # coding=utf-8
import os
import shutil
from tempfile import mkdtemp

from django.core.management.base import BaseCommand

from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood

class Command(BaseCommand):
    """Script to load flood test data for demo purpose only.

    """
    help = 'Script to load flood test data for demo purpose only.'

    def handle(self, *args, **options):
        # Copy file to hazard drop directory
        REALTIME_HAZARD_DROP = os.environ.get(
            'REALTIME_HAZARD_DROP',
            '/home/realtime/hazard-drop/')
        hazard_drop_path = mkdtemp(dir=REALTIME_HAZARD_DROP)
        hazard_drop_path = os.path.join(
            hazard_drop_path, os.path.basename(flood_layer_uri))
        print 'Copy flood data to %s' % hazard_drop_path
        shutil.copy(flood_layer_uri, hazard_drop_path)

        flood_id = '2018022511-6-rw'
        print 'Send flood data to InaSAFE Django with flood id = %s' % flood_id
        process_flood.delay(
            flood_id=flood_id,
            data_source='hazard_file',
            data_source_args={
                'filename': hazard_drop_path
            }
        )

Prompt:
Fix wrong path to flood data to push.

# coding=utf-8
import os
import shutil
from tempfile import mkdtemp

from django.core.management.base import BaseCommand

from realtime.tasks.test.test_realtime_tasks import flood_layer_uri
from realtime.tasks.realtime.flood import process_flood

class Command(BaseCommand):
    """Script to load flood test data for demo purpose only.

    """
    help = 'Script to load flood test data for demo purpose only.'

    def handle(self, *args, **options):
        # Copy file to hazard drop directory
        REALTIME_HAZARD_DROP = os.environ.get(
            'REALTIME_HAZARD_DROP',
            '/home/realtime/hazard-drop/')
        hazard_drop_path = mkdtemp(dir=REALTIME_HAZARD_DROP)
        hazard_drop_path = os.path.join(
            hazard_drop_path, os.path.basename(flood_layer_uri))
        print 'Copy flood data to %s' % hazard_drop_path
        shutil.copy(flood_layer_uri, hazard_drop_path)

        flood_id = '2018022511-6-rw'
        print 'Send flood data to InaSAFE Django with flood id = %s' % flood_id
        process_flood.delay(
            flood_id=flood_id,
            data_source='hazard_file',
            data_source_args={
                'filename': flood_layer_uri
            }
        )


from functools import wraps

from flask import abort
from flask_login import current_user

def role_required(*roles):
    """Ensure that logged in user has one of the required roles.

    Return 403 if the user doesn't have a required role.

    Should be applied before the `@login_required` decorator:

        @login_required
        @role_required('admin', 'admin-ccs')
        def view():
            ...

    """

    def role_decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not any(current_user.has_role(role) for role in roles):
                return abort(403, "One of {} roles required".format(", ".join(roles)))
            return func(*args, **kwargs)

        return decorated_view

    return role_decorator

Add `role_required` view decorator to check current_user role

Returns 403 if user has none of the roles listed in the decorator
arguments.

Response:
<INSERT> from functools import wraps

from flask import abort
from flask_login import current_user

def role_required(*roles):
 <INSERT_END> <INSERT>   """Ensure that logged in user has one of the required roles.

    Return 403 if the user doesn't have a required role.

    Should be applied before the `@login_required` decorator:

        @login_required
        @role_required('admin', 'admin-ccs')
        def view():
            ...

    """

    def role_decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not any(current_user.has_role(role) for role in roles):
                return abort(403, "One of {} roles required".format(", ".join(roles)))
            return func(*args, **kwargs)

        return decorated_view

    return role_decorator
 <INSERT_END> <|endoftext|> from functools import wraps

from flask import abort
from flask_login import current_user

def role_required(*roles):
    """Ensure that logged in user has one of the required roles.

    Return 403 if the user doesn't have a required role.

    Should be applied before the `@login_required` decorator:

        @login_required
        @role_required('admin', 'admin-ccs')
        def view():
            ...

    """

    def role_decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not any(current_user.has_role(role) for role in roles):
                return abort(403, "One of {} roles required".format(", ".join(roles)))
            return func(*args, **kwargs)

        return decorated_view

    return role_decorator

Prompt:
Add `role_required` view decorator to check current_user role

Returns 403 if user has none of the roles listed in the decorator
arguments.


import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import template

SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS

def check_context_processors():
    allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
    ctx_present = False

    if django.VERSION < (1, 8,):
        if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
            ctx_present = True
    else:
        for engine in template.engines.templates.values():
            if allauth_ctx in engine.get('OPTIONS', {})\
                    .get('context_processors', []):
                ctx_present = True
                break

    if not ctx_present:
        excmsg = ("socialaccount context processor "
                  "not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
                  "See settings.py instructions here: "
                  "https://github.com/pennersr/django-allauth#installation")
        raise ImproperlyConfigured(excmsg)

if SOCIALACCOUNT_ENABLED:
    check_context_processors()

LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')

USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

Response:
<REPLACE_OLD> ImproperlyConfigured

SOCIALACCOUNT_ENABLED <REPLACE_NEW> ImproperlyConfigured
from django import template

SOCIALACCOUNT_ENABLED <REPLACE_END> <REPLACE_OLD> settings.TEMPLATES:
 <REPLACE_NEW> template.engines.templates.values():
 <REPLACE_END> <|endoftext|> import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import template

SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS

def check_context_processors():
    allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
    ctx_present = False

    if django.VERSION < (1, 8,):
        if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
            ctx_present = True
    else:
        for engine in template.engines.templates.values():
            if allauth_ctx in engine.get('OPTIONS', {})\
                    .get('context_processors', []):
                ctx_present = True
                break

    if not ctx_present:
        excmsg = ("socialaccount context processor "
                  "not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
                  "See settings.py instructions here: "
                  "https://github.com/pennersr/django-allauth#installation")
        raise ImproperlyConfigured(excmsg)

if SOCIALACCOUNT_ENABLED:
    check_context_processors()

LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')

USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

Prompt:
Fix for checking the context processors on Django 1.8

If the user has not migrated their settings file to use the new TEMPLATES
method in Django 1.8, settings.TEMPLATES is an empty list.

Instead, if we check django.templates.engines it will be populated with the
automatically migrated data from settings.TEMPLATE*.

import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS

def check_context_processors():
    allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
    ctx_present = False

    if django.VERSION < (1, 8,):
        if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
            ctx_present = True
    else:
        for engine in settings.TEMPLATES:
            if allauth_ctx in engine.get('OPTIONS', {})\
                    .get('context_processors', []):
                ctx_present = True
                break

    if not ctx_present:
        excmsg = ("socialaccount context processor "
                  "not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
                  "See settings.py instructions here: "
                  "https://github.com/pennersr/django-allauth#installation")
        raise ImproperlyConfigured(excmsg)

if SOCIALACCOUNT_ENABLED:
    check_context_processors()

LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')

USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')


#!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
#    Copyright (C) 2004 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.

from networkx import *

z=[5,3,3,3,3,2,2,2,1,1,1]
print(is_valid_degree_sequence(z))

print("Configuration model")
G=configuration_model(z)  # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
    if d in hist:
        hist[d]+=1
    else:
        hist[d]=1
print("degree #nodes")
for d in hist:
    print('%d %d' % (d,hist[d]))

Response:
<REPLACE_OLD> *

z=[5,3,3,3,3,2,2,2,1,1,1]
print is_valid_degree_sequence(z)

print("Configuration <REPLACE_NEW> *

z=[5,3,3,3,3,2,2,2,1,1,1]
print(is_valid_degree_sequence(z))

print("Configuration <REPLACE_END> <REPLACE_OLD> (d,hist[d]))

 <REPLACE_NEW> (d,hist[d]))
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
#    Copyright (C) 2004 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.

from networkx import *

z=[5,3,3,3,3,2,2,2,1,1,1]
print(is_valid_degree_sequence(z))

print("Configuration model")
G=configuration_model(z)  # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
    if d in hist:
        hist[d]+=1
    else:
        hist[d]=1
print("degree #nodes")
for d in hist:
    print('%d %d' % (d,hist[d]))

Prompt:
Remove Python 3 incompatible print statement

#!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
#    Copyright (C) 2004 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.

from networkx import *

z=[5,3,3,3,3,2,2,2,1,1,1]
print is_valid_degree_sequence(z)

print("Configuration model")
G=configuration_model(z)  # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
    if d in hist:
        hist[d]+=1
    else:
        hist[d]=1
print("degree #nodes")
for d in hist:
    print('%d %d' % (d,hist[d]))


# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-02 04:26
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields

class Migration(migrations.Migration):

    dependencies = [
        ('wagtailcore', '0033_remove_golive_expiry_help_text'),
        ('pages', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='RegularPage',
            fields=[
                ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
                ('subtitle', models.CharField(blank=True, default='', max_length=255)),
                ('body', wagtail.wagtailcore.fields.RichTextField(blank=True, default='')),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
    ]

Add missing migration for tests.app.pages (fixes build)

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-02 04:26
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields

class Migration(migrations.Migration):

    dependencies = [
        ('wagtailcore', '0033_remove_golive_expiry_help_text'),
        ('pages', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='RegularPage',
            fields=[
                ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
                ('subtitle', models.CharField(blank=True, default='', max_length=255)),
                ('body', wagtail.wagtailcore.fields.RichTextField(blank=True, default='')),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
    ]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-02 04:26
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields

class Migration(migrations.Migration):

    dependencies = [
        ('wagtailcore', '0033_remove_golive_expiry_help_text'),
        ('pages', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='RegularPage',
            fields=[
                ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
                ('subtitle', models.CharField(blank=True, default='', max_length=255)),
                ('body', wagtail.wagtailcore.fields.RichTextField(blank=True, default='')),
            ],
            options={
                'abstract': False,
            },
            bases=('wagtailcore.page',),
        ),
    ]

Prompt: Add missing migration for tests.app.pages (fixes build)


from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator

def test_tee_generator():

    class QuuxGenerator(CustomGenerator):
        aa = Integer(100, 200)
        bb = Integer(300, 400)
        cc = IntegerDerived(low=aa, high=bb)
        dd = Tee(cc, num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_dd_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.dd])

    dd_is_always_between_aa_and_bb = all(df.apply(check_dd_is_between_aa_and_bb, axis=1))
    assert True == dd_is_always_between_aa_and_bb

def test_tee_generator_v2():

    class QuuxGenerator(CustomGenerator):
        aa = Integer(100, 200)
        bb = Integer(300, 400)
        cc = Tee(IntegerDerived(low=aa, high=bb), num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_cc_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.cc])

    cc_is_always_between_aa_and_bb = all(df.apply(check_cc_is_between_aa_and_bb, axis=1))
    assert True == cc_is_always_between_aa_and_bb

def test_tee_generator_with_timestamps():
    """
    Regression test to ensure that Tee properly deals with timestamp generators that output their timestamps as strings.
    """

    class QuuxGenerator(CustomGenerator):
        aa = TimestampPrimitive(date="2018-01-01").strftime("%Y-%m-%d %H:%M:%S")
        bb = TimestampPrimitive(date="2018-01-02").strftime("%Y-%m-%d %H:%M:%S")
        cc = Tee(TimestampDerived(start=aa, end=bb).strftime("%Y-%m-%d %H:%M:%S"), num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_cc_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.cc])

    cc_is_always_between_aa_and_bb = all(df.apply(check_cc_is_between_aa_and_bb, axis=1))
    assert True == cc_is_always_between_aa_and_bb

Add a few tests for Tee

Add a few tests for Tee

Response:
<REPLACE_OLD>  <REPLACE_NEW> from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator

def test_tee_generator():

    class QuuxGenerator(CustomGenerator):
        aa = Integer(100, 200)
        bb = Integer(300, 400)
        cc = IntegerDerived(low=aa, high=bb)
        dd = Tee(cc, num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_dd_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.dd])

    dd_is_always_between_aa_and_bb = all(df.apply(check_dd_is_between_aa_and_bb, axis=1))
    assert True == dd_is_always_between_aa_and_bb

def test_tee_generator_v2():

    class QuuxGenerator(CustomGenerator):
        aa = Integer(100, 200)
        bb = Integer(300, 400)
        cc = Tee(IntegerDerived(low=aa, high=bb), num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_cc_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.cc])

    cc_is_always_between_aa_and_bb = all(df.apply(check_cc_is_between_aa_and_bb, axis=1))
    assert True == cc_is_always_between_aa_and_bb

def test_tee_generator_with_timestamps():
    """
    Regression test to ensure that Tee properly deals with timestamp generators that output their timestamps as strings.
    """

    class QuuxGenerator(CustomGenerator):
        aa = TimestampPrimitive(date="2018-01-01").strftime("%Y-%m-%d %H:%M:%S")
        bb = TimestampPrimitive(date="2018-01-02").strftime("%Y-%m-%d %H:%M:%S")
        cc = Tee(TimestampDerived(start=aa, end=bb).strftime("%Y-%m-%d %H:%M:%S"), num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_cc_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.cc])

    cc_is_always_between_aa_and_bb = all(df.apply(check_cc_is_between_aa_and_bb, axis=1))
    assert True == cc_is_always_between_aa_and_bb
 <REPLACE_END> <|endoftext|> from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator

def test_tee_generator():

    class QuuxGenerator(CustomGenerator):
        aa = Integer(100, 200)
        bb = Integer(300, 400)
        cc = IntegerDerived(low=aa, high=bb)
        dd = Tee(cc, num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_dd_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.dd])

    dd_is_always_between_aa_and_bb = all(df.apply(check_dd_is_between_aa_and_bb, axis=1))
    assert True == dd_is_always_between_aa_and_bb

def test_tee_generator_v2():

    class QuuxGenerator(CustomGenerator):
        aa = Integer(100, 200)
        bb = Integer(300, 400)
        cc = Tee(IntegerDerived(low=aa, high=bb), num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_cc_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.cc])

    cc_is_always_between_aa_and_bb = all(df.apply(check_cc_is_between_aa_and_bb, axis=1))
    assert True == cc_is_always_between_aa_and_bb

def test_tee_generator_with_timestamps():
    """
    Regression test to ensure that Tee properly deals with timestamp generators that output their timestamps as strings.
    """

    class QuuxGenerator(CustomGenerator):
        aa = TimestampPrimitive(date="2018-01-01").strftime("%Y-%m-%d %H:%M:%S")
        bb = TimestampPrimitive(date="2018-01-02").strftime("%Y-%m-%d %H:%M:%S")
        cc = Tee(TimestampDerived(start=aa, end=bb).strftime("%Y-%m-%d %H:%M:%S"), num=Integer(1, 8))

    g = QuuxGenerator()
    items = g.generate(100, seed=12345)
    df = items.to_df()

    def check_cc_is_between_aa_and_bb(row):
        return all([row.aa <= x <= row.bb for x in row.cc])

    cc_is_always_between_aa_and_bb = all(df.apply(check_cc_is_between_aa_and_bb, axis=1))
    assert True == cc_is_always_between_aa_and_bb

Prompt: Add a few tests for Tee


import os
from setuptools import setup

longDesc = ""
if os.path.exists("README.rst"):
	longDesc = open("README.rst").read().strip()

setup(
    name = "pytesseract",
    version = "0.1.6",
    author = "Samuel Hoffstaetter",
    author_email="pytesseract@madmaze.net",
    maintainer = "Matthias Lee",
    maintainer_email = "pytesseract@madmaze.net",
    description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
    long_description = longDesc,
    license = "GPLv3",
    keywords = "python-tesseract OCR Python",
    url = "https://github.com/madmaze/python-tesseract",
    packages=['pytesseract'],
    package_dir={'pytesseract': 'src'},
    package_data = {'pytesseract': ['*.png','*.jpg']},
    entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
    classifiers = [
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ]
)

Response:
<REPLACE_OLD> author_email="",
 <REPLACE_NEW> author_email="pytesseract@madmaze.net",
 <REPLACE_END> <|endoftext|> import os
from setuptools import setup

longDesc = ""
if os.path.exists("README.rst"):
	longDesc = open("README.rst").read().strip()

setup(
    name = "pytesseract",
    version = "0.1.6",
    author = "Samuel Hoffstaetter",
    author_email="pytesseract@madmaze.net",
    maintainer = "Matthias Lee",
    maintainer_email = "pytesseract@madmaze.net",
    description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
    long_description = longDesc,
    license = "GPLv3",
    keywords = "python-tesseract OCR Python",
    url = "https://github.com/madmaze/python-tesseract",
    packages=['pytesseract'],
    package_dir={'pytesseract': 'src'},
    package_data = {'pytesseract': ['*.png','*.jpg']},
    entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
    classifiers = [
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ]
)

Prompt:
Include author email since it's required info

Same as maintainer email, because the author email is unknown
import os
from setuptools import setup

longDesc = ""
if os.path.exists("README.rst"):
	longDesc = open("README.rst").read().strip()

setup(
    name = "pytesseract",
    version = "0.1.6",
    author = "Samuel Hoffstaetter",
    author_email="",
    maintainer = "Matthias Lee",
    maintainer_email = "pytesseract@madmaze.net",
    description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
    long_description = longDesc,
    license = "GPLv3",
    keywords = "python-tesseract OCR Python",
    url = "https://github.com/madmaze/python-tesseract",
    packages=['pytesseract'],
    package_dir={'pytesseract': 'src'},
    package_data = {'pytesseract': ['*.png','*.jpg']},
    entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
    classifiers = [
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ]
)


import datetime

from django.core.management.base import BaseCommand, CommandError

from pontoon.administration.files import (
    update_from_repository,
    extract_to_database,
)

from pontoon.base.models import Project

class Command(BaseCommand):
    args = '<project_id project_id ...>'
    help = 'Update projects from repositories and store changes to database'

    def handle(self, *args, **options):
        projects = Project.objects.all()
        if args:
            projects = projects.filter(pk__in=args)
        else:
            self.stdout.write('%s\n' % self.help.upper())

        for project in projects:
            try:
                update_from_repository(project)
                extract_to_database(project)
                now = datetime.datetime.now()
                self.stdout.write(
                    '[%s]: Updated project %s\n' % (now, project))
            except Exception as e:
                now = datetime.datetime.now()
                raise CommandError(
                    '[%s]: Update error: %s\n' % (now, unicode(e)))

Print new line after operation title

Print new line after operation title

Response:
<REPLACE_OLD> self.stdout.write(self.help.upper())

 <REPLACE_NEW> self.stdout.write('%s\n' % self.help.upper())

 <REPLACE_END> <|endoftext|>
import datetime

from django.core.management.base import BaseCommand, CommandError

from pontoon.administration.files import (
    update_from_repository,
    extract_to_database,
)

from pontoon.base.models import Project

class Command(BaseCommand):
    args = '<project_id project_id ...>'
    help = 'Update projects from repositories and store changes to database'

    def handle(self, *args, **options):
        projects = Project.objects.all()
        if args:
            projects = projects.filter(pk__in=args)
        else:
            self.stdout.write('%s\n' % self.help.upper())

        for project in projects:
            try:
                update_from_repository(project)
                extract_to_database(project)
                now = datetime.datetime.now()
                self.stdout.write(
                    '[%s]: Updated project %s\n' % (now, project))
            except Exception as e:
                now = datetime.datetime.now()
                raise CommandError(
                    '[%s]: Update error: %s\n' % (now, unicode(e)))

Prompt:
Print new line after operation title

import datetime

from django.core.management.base import BaseCommand, CommandError

from pontoon.administration.files import (
    update_from_repository,
    extract_to_database,
)

from pontoon.base.models import Project

class Command(BaseCommand):
    args = '<project_id project_id ...>'
    help = 'Update projects from repositories and store changes to database'

    def handle(self, *args, **options):
        projects = Project.objects.all()
        if args:
            projects = projects.filter(pk__in=args)
        else:
            self.stdout.write(self.help.upper())

        for project in projects:
            try:
                update_from_repository(project)
                extract_to_database(project)
                now = datetime.datetime.now()
                self.stdout.write(
                    '[%s]: Updated project %s\n' % (now, project))
            except Exception as e:
                now = datetime.datetime.now()
                raise CommandError(
                    '[%s]: Update error: %s\n' % (now, unicode(e)))


"""Routines used by WMT hooks for TopoFlow components."""

choices_map = {
    'Yes': 1,
    'No': 0
}
units_map = {
    'meters': 'm^2',
    'kilometers': 'km^2'
}

def get_dtype(parameter_value):
    """Get the TopoFlow data type of a parameter.

    Parameters
    ----------
    parameter_value : object
      An object, a scalar.

    """
    try:
        float(parameter_value)
    except ValueError:
        return 'string'
    else:
        return 'float'

def assign_parameters(env, file_list):
    """Assign values for input parameters in a TopoFlow component.

    A subset of TopoFlow input parameters can take a scalar value, or,
    through an uploaded file, a time series, a grid, or a grid
    sequence. This function assigns such parameters a scalar value, or
    the name of a file, based on the user's selection in WMT.

    Parameters
    ----------
    env : dict
      A dict of component parameter values from WMT.
    file_list : list
      A list of file names used by the component.

    """
    terminator = '_ptype'
    for key in env.copy().iterkeys():
        if key.endswith(terminator):
            key_root, sep, end = key.partition(terminator)
            if env[key] == 'Scalar':
                env[key_root] = env[key_root + '_scalar']
            else:
                env[key_root] = env[key_root + '_file']
                file_list.append(key_root)
            env[key_root + '_dtype'] = get_dtype(env[key_root])

Response:
<REPLACE_OLD> def <REPLACE_NEW> """Routines used by WMT hooks for TopoFlow components."""

choices_map = {
    'Yes': 1,
    'No': 0
}
units_map = {
    'meters': 'm^2',
    'kilometers': 'km^2'
}

def <REPLACE_END> <|endoftext|> """Routines used by WMT hooks for TopoFlow components."""

choices_map = {
    'Yes': 1,
    'No': 0
}
units_map = {
    'meters': 'm^2',
    'kilometers': 'km^2'
}

def get_dtype(parameter_value):
    """Get the TopoFlow data type of a parameter.

    Parameters
    ----------
    parameter_value : object
      An object, a scalar.

    """
    try:
        float(parameter_value)
    except ValueError:
        return 'string'
    else:
        return 'float'

def assign_parameters(env, file_list):
    """Assign values for input parameters in a TopoFlow component.

    A subset of TopoFlow input parameters can take a scalar value, or,
    through an uploaded file, a time series, a grid, or a grid
    sequence. This function assigns such parameters a scalar value, or
    the name of a file, based on the user's selection in WMT.

    Parameters
    ----------
    env : dict
      A dict of component parameter values from WMT.
    file_list : list
      A list of file names used by the component.

    """
    terminator = '_ptype'
    for key in env.copy().iterkeys():
        if key.endswith(terminator):
            key_root, sep, end = key.partition(terminator)
            if env[key] == 'Scalar':
                env[key_root] = env[key_root + '_scalar']
            else:
                env[key_root] = env[key_root + '_file']
                file_list.append(key_root)
            env[key_root + '_dtype'] = get_dtype(env[key_root])

Prompt:
Add choices_map and units_map global variables

def get_dtype(parameter_value):
    """Get the TopoFlow data type of a parameter.

    Parameters
    ----------
    parameter_value : object
      An object, a scalar.

    """
    try:
        float(parameter_value)
    except ValueError:
        return 'string'
    else:
        return 'float'

def assign_parameters(env, file_list):
    """Assign values for input parameters in a TopoFlow component.

    A subset of TopoFlow input parameters can take a scalar value, or,
    through an uploaded file, a time series, a grid, or a grid
    sequence. This function assigns such parameters a scalar value, or
    the name of a file, based on the user's selection in WMT.

    Parameters
    ----------
    env : dict
      A dict of component parameter values from WMT.
    file_list : list
      A list of file names used by the component.

    """
    terminator = '_ptype'
    for key in env.copy().iterkeys():
        if key.endswith(terminator):
            key_root, sep, end = key.partition(terminator)
            if env[key] == 'Scalar':
                env[key_root] = env[key_root + '_scalar']
            else:
                env[key_root] = env[key_root + '_file']
                file_list.append(key_root)
            env[key_root + '_dtype'] = get_dtype(env[key_root])


from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app

HTTP_MANAGER = PinHttpManager()

class Pin(BasicResource):

    def __init__(self):
        super(Pin, self).__init__()
        self.fields = {
            "num": fields.Integer,
            "mode": fields.String,
            "value": fields.Integer,
            "resistor": fields.String,
            "initial": fields.String,
            "event": fields.String,
            "bounce": fields.Integer
        }

    def pin_not_found(self):
        return {'message': 'Pin not found'}, 404

class PinList(Pin):

    def get(self):
        result = HTTP_MANAGER.read_all()
        return self.response(result, 200)

class PinDetail(Pin):

    def get(self, pin_num):
        result = HTTP_MANAGER.read_one(pin_num)
        if not result:
            return self.pin_not_found()
        return self.response(result, 200)

    def patch(self, pin_num):
        self.parser.add_argument('value', type=int)
        args = self.parser.parse_args()
        result = HTTP_MANAGER.update_value(pin_num, args['value'])
        if not result:
            return self.pin_not_found()
        return self.response(HTTP_MANAGER.read_one(pin_num), 200)

Add new fields to response

Add new fields to response

Response:
<INSERT> fields.Integer,
            "resistor": fields.String,
            "initial": fields.String,
            "event": fields.String,
            "bounce": <INSERT_END> <|endoftext|> from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app

HTTP_MANAGER = PinHttpManager()

class Pin(BasicResource):

    def __init__(self):
        super(Pin, self).__init__()
        self.fields = {
            "num": fields.Integer,
            "mode": fields.String,
            "value": fields.Integer,
            "resistor": fields.String,
            "initial": fields.String,
            "event": fields.String,
            "bounce": fields.Integer
        }

    def pin_not_found(self):
        return {'message': 'Pin not found'}, 404

class PinList(Pin):

    def get(self):
        result = HTTP_MANAGER.read_all()
        return self.response(result, 200)

class PinDetail(Pin):

    def get(self, pin_num):
        result = HTTP_MANAGER.read_one(pin_num)
        if not result:
            return self.pin_not_found()
        return self.response(result, 200)

    def patch(self, pin_num):
        self.parser.add_argument('value', type=int)
        args = self.parser.parse_args()
        result = HTTP_MANAGER.update_value(pin_num, args['value'])
        if not result:
            return self.pin_not_found()
        return self.response(HTTP_MANAGER.read_one(pin_num), 200)

Prompt:
Add new fields to response

from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app

HTTP_MANAGER = PinHttpManager()

class Pin(BasicResource):

    def __init__(self):
        super(Pin, self).__init__()
        self.fields = {
            "num": fields.Integer,
            "mode": fields.String,
            "value": fields.Integer
        }

    def pin_not_found(self):
        return {'message': 'Pin not found'}, 404

class PinList(Pin):

    def get(self):
        result = HTTP_MANAGER.read_all()
        return self.response(result, 200)

class PinDetail(Pin):

    def get(self, pin_num):
        result = HTTP_MANAGER.read_one(pin_num)
        if not result:
            return self.pin_not_found()
        return self.response(result, 200)

    def patch(self, pin_num):
        self.parser.add_argument('value', type=int)
        args = self.parser.parse_args()
        result = HTTP_MANAGER.update_value(pin_num, args['value'])
        if not result:
            return self.pin_not_found()
        return self.response(HTTP_MANAGER.read_one(pin_num), 200)


"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from django import forms

from project.models import Project

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project

class DjangoRecipeForm(forms.Form):
    name = forms.CharField(initial="django")
    settings = forms.CharField()
    version = forms.ChoiceField(choices=[
        ("trunk", "trunk"),
        ("1.2", "1.2"),
        ("1.1.2", "1.1.2"),
        ("1.1", "1.1"),
        ("1.0.4", "1.04"),
        ("0.96", "0.96"),
        ])
    eggs = forms.CharField()
    project = forms.CharField()
    extra_paths = forms.CharField()
    fcgi = forms.BooleanField()
    wsgi = forms.BooleanField()

recipe_form_map = {
        'djangorecipe': DjangoRecipeForm
        }

Add a name for the recipe section

Add a name for the recipe section

Response:
<INSERT> name = forms.CharField(initial="django")
    <INSERT_END> <|endoftext|> """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from django import forms

from project.models import Project

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project

class DjangoRecipeForm(forms.Form):
    name = forms.CharField(initial="django")
    settings = forms.CharField()
    version = forms.ChoiceField(choices=[
        ("trunk", "trunk"),
        ("1.2", "1.2"),
        ("1.1.2", "1.1.2"),
        ("1.1", "1.1"),
        ("1.0.4", "1.04"),
        ("0.96", "0.96"),
        ])
    eggs = forms.CharField()
    project = forms.CharField()
    extra_paths = forms.CharField()
    fcgi = forms.BooleanField()
    wsgi = forms.BooleanField()

recipe_form_map = {
        'djangorecipe': DjangoRecipeForm
        }

Prompt:
Add a name for the recipe section

"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from django import forms

from project.models import Project

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project

class DjangoRecipeForm(forms.Form):
    settings = forms.CharField()
    version = forms.ChoiceField(choices=[
        ("trunk", "trunk"),
        ("1.2", "1.2"),
        ("1.1.2", "1.1.2"),
        ("1.1", "1.1"),
        ("1.0.4", "1.04"),
        ("0.96", "0.96"),
        ])
    eggs = forms.CharField()
    project = forms.CharField()
    extra_paths = forms.CharField()
    fcgi = forms.BooleanField()
    wsgi = forms.BooleanField()

recipe_form_map = {
        'djangorecipe': DjangoRecipeForm
        }


import logging

from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient

import warner
import archiver
import announcer
import flagger
from config import Config

_config = Config()

raven_client = RavenClient()

# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if _config.test_schedule:
    schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
    schedule_kwargs = {"hour": 4}

sched = BlockingScheduler()

@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
    logging.info("Destalinating")
    if not _config.sb_token or not _config.api_token:
        logging.error(
            "Missing at least one required Slack environment variable.\n"
            "Make sure to set DESTALINATOR_SB_TOKEN and DESTALINATOR_API_TOKEN."
        )
    else:
        try:
            warner.Warner().warn()
            archiver.Archiver().archive()
            announcer.Announcer().announce()
            flagger.Flagger().flag()
            logging.info("OK: destalinated")
        except Exception as e:  # pylint: disable=W0703
            raven_client.captureException()
            if not _config.sentry_dsn:
                raise e
    logging.info("END: destalinate_job")

if __name__ == "__main__":
    # Use RUN_ONCE to only run the destalinate job once immediately
    if os.getenv("RUN_ONCE"):
        destalinate_job()
    else:
        sched.start()

Response:
<INSERT> # Use RUN_ONCE to only run the destalinate job once immediately
    if os.getenv("RUN_ONCE"):
        destalinate_job()
    else:
        <INSERT_END> <|endoftext|> import logging

from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient

import warner
import archiver
import announcer
import flagger
from config import Config

_config = Config()

raven_client = RavenClient()

# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if _config.test_schedule:
    schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
    schedule_kwargs = {"hour": 4}

sched = BlockingScheduler()

@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
    logging.info("Destalinating")
    if not _config.sb_token or not _config.api_token:
        logging.error(
            "Missing at least one required Slack environment variable.\n"
            "Make sure to set DESTALINATOR_SB_TOKEN and DESTALINATOR_API_TOKEN."
        )
    else:
        try:
            warner.Warner().warn()
            archiver.Archiver().archive()
            announcer.Announcer().announce()
            flagger.Flagger().flag()
            logging.info("OK: destalinated")
        except Exception as e:  # pylint: disable=W0703
            raven_client.captureException()
            if not _config.sentry_dsn:
                raise e
    logging.info("END: destalinate_job")

if __name__ == "__main__":
    # Use RUN_ONCE to only run the destalinate job once immediately
    if os.getenv("RUN_ONCE"):
        destalinate_job()
    else:
        sched.start()

Prompt:
Use RUN_ONCE to only run the destalinate job once immediately

import logging

from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient

import warner
import archiver
import announcer
import flagger
from config import Config

_config = Config()

raven_client = RavenClient()

# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if _config.test_schedule:
    schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
    schedule_kwargs = {"hour": 4}

sched = BlockingScheduler()

@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
    logging.info("Destalinating")
    if not _config.sb_token or not _config.api_token:
        logging.error(
            "Missing at least one required Slack environment variable.\n"
            "Make sure to set DESTALINATOR_SB_TOKEN and DESTALINATOR_API_TOKEN."
        )
    else:
        try:
            warner.Warner().warn()
            archiver.Archiver().archive()
            announcer.Announcer().announce()
            flagger.Flagger().flag()
            logging.info("OK: destalinated")
        except Exception as e:  # pylint: disable=W0703
            raven_client.captureException()
            if not _config.sentry_dsn:
                raise e
    logging.info("END: destalinate_job")

if __name__ == "__main__":
    sched.start()


#!/usr/bin/env python
# Create wheel with:  python setup.py bdist_wheel
# Install with:       pip install dist/loadconfig-*-none-any.whl

from os import environ
from os.path import dirname, abspath
from setuptools import setup
import sys
if sys.version_info[0] == 3:
    from configparser import ConfigParser
else:
    from ConfigParser import ConfigParser

c = ConfigParser()
c.read('{}/setup.cfg'.format(dirname(abspath(__file__))))
environ["PBR_VERSION"] = c.get('metadata', 'version')
setup(setup_requires=['pbr'], pbr=True)

Response:
<REPLACE_OLD> setup
from six.moves.configparser <REPLACE_NEW> setup
import sys
if sys.version_info[0] == 3:
    from configparser import ConfigParser
else:
    from ConfigParser <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# Create wheel with:  python setup.py bdist_wheel
# Install with:       pip install dist/loadconfig-*-none-any.whl

from os import environ
from os.path import dirname, abspath
from setuptools import setup
import sys
if sys.version_info[0] == 3:
    from configparser import ConfigParser
else:
    from ConfigParser import ConfigParser

c = ConfigParser()
c.read('{}/setup.cfg'.format(dirname(abspath(__file__))))
environ["PBR_VERSION"] = c.get('metadata', 'version')
setup(setup_requires=['pbr'], pbr=True)

Prompt:
Remove six dependency when pip installing from sources

Signed-off-by: Daniel Mizyrycki <ef2aa52a54375f83972079d447cb6ee481ced226@glidelink.net>

#!/usr/bin/env python
# Create wheel with:  python setup.py bdist_wheel
# Install with:       pip install dist/loadconfig-*-none-any.whl

from os import environ
from os.path import dirname, abspath
from setuptools import setup
from six.moves.configparser import ConfigParser

c = ConfigParser()
c.read('{}/setup.cfg'.format(dirname(abspath(__file__))))
environ["PBR_VERSION"] = c.get('metadata', 'version')
setup(setup_requires=['pbr'], pbr=True)


from uuid import uuid4

from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase

class AuthorBuildListTest(APITestCase):
    def test_simple(self):
        fake_author_id = uuid4()

        self.create_build(self.project)

        path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex)

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 0

        author = Author(email=self.default_user.email, name='Foo Bar')
        db.session.add(author)
        build = self.create_build(self.project, author=author)

        path = '/api/0/authors/{0}/builds/'.format(author.id.hex)

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id'] == build.id.hex

        self.login(self.default_user)

        path = '/api/0/authors/me/builds/'

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id'] == build.id.hex

Response:
<REPLACE_OLD> Author(email='foo@example.com', <REPLACE_NEW> Author(email=self.default_user.email, <REPLACE_END> <INSERT> build.id.hex

        self.login(self.default_user)

        path = '/api/0/authors/me/builds/'

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id'] == <INSERT_END> <|endoftext|> from uuid import uuid4

from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase

class AuthorBuildListTest(APITestCase):
    def test_simple(self):
        fake_author_id = uuid4()

        self.create_build(self.project)

        path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex)

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 0

        author = Author(email=self.default_user.email, name='Foo Bar')
        db.session.add(author)
        build = self.create_build(self.project, author=author)

        path = '/api/0/authors/{0}/builds/'.format(author.id.hex)

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id'] == build.id.hex

        self.login(self.default_user)

        path = '/api/0/authors/me/builds/'

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id'] == build.id.hex

Prompt:
Add additional coverage to author build list

from uuid import uuid4

from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase

class AuthorBuildListTest(APITestCase):
    def test_simple(self):
        fake_author_id = uuid4()

        self.create_build(self.project)

        path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex)

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 0

        author = Author(email='foo@example.com', name='Foo Bar')
        db.session.add(author)
        build = self.create_build(self.project, author=author)

        path = '/api/0/authors/{0}/builds/'.format(author.id.hex)

        resp = self.client.get(path)
        assert resp.status_code == 200
        data = self.unserialize(resp)
        assert len(data) == 1
        assert data[0]['id'] == build.id.hex


from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements

class ConnectionLimit(ModuleData):
    implements(IPlugin, IModuleData)

    name = "ConnectionLimit"
    peerConnections = {}

    def hookIRCd(self, ircd):
        self.ircd = ircd

    def actions(self):
        return [ ("userconnect", 100, self.handleLocalConnect),
                 ("remoteregister", 100, self.handleRemoteConnect),
                 ("quit", 100, self.handleDisconnect),
                 ("remotequit", 100, self.handleDisconnect) ]

    def handleLocalConnect(self, user, *params):
        ip = user.ip
        if self.addToConnections(ip) and self.peerConnections[ip] > self.ircd.config.getWithDefault("connlimit_globmax", 3):
            user.disconnect("No more connections allowed from your IP ({})".format(ip))
            return None
        return True

    def handleRemoteConnect(self, user, *params):
        self.addToConnections(user.ip)

    def handleDisconnect(self, user, *params):
        ip = user.ip
        if ip in self.peerConnections:
            self.peerConnections[ip] -= 1
            if self.peerConnections[ip] < 1:
                del self.peerConnections[ip]

    def addToConnections(self, ip):
        if ip in self.ircd.config.getWithDefault("connlimit_whitelist", []):
            return False
        if ip in self.peerConnections:
            self.peerConnections[ip] += 1
        else:
            self.peerConnections[ip] = 1
        return True

    def load(self):
        for user in self.ircd.users:
            self.addToConnections(user.ip)

connLimit = ConnectionLimit()

Implement the connection limit module

Implement the connection limit module

Response:
<REPLACE_OLD>  <REPLACE_NEW> from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements

class ConnectionLimit(ModuleData):
    implements(IPlugin, IModuleData)

    name = "ConnectionLimit"
    peerConnections = {}

    def hookIRCd(self, ircd):
        self.ircd = ircd

    def actions(self):
        return [ ("userconnect", 100, self.handleLocalConnect),
                 ("remoteregister", 100, self.handleRemoteConnect),
                 ("quit", 100, self.handleDisconnect),
                 ("remotequit", 100, self.handleDisconnect) ]

    def handleLocalConnect(self, user, *params):
        ip = user.ip
        if self.addToConnections(ip) and self.peerConnections[ip] > self.ircd.config.getWithDefault("connlimit_globmax", 3):
            user.disconnect("No more connections allowed from your IP ({})".format(ip))
            return None
        return True

    def handleRemoteConnect(self, user, *params):
        self.addToConnections(user.ip)

    def handleDisconnect(self, user, *params):
        ip = user.ip
        if ip in self.peerConnections:
            self.peerConnections[ip] -= 1
            if self.peerConnections[ip] < 1:
                del self.peerConnections[ip]

    def addToConnections(self, ip):
        if ip in self.ircd.config.getWithDefault("connlimit_whitelist", []):
            return False
        if ip in self.peerConnections:
            self.peerConnections[ip] += 1
        else:
            self.peerConnections[ip] = 1
        return True

    def load(self):
        for user in self.ircd.users:
            self.addToConnections(user.ip)

connLimit = ConnectionLimit() <REPLACE_END> <|endoftext|> from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements

class ConnectionLimit(ModuleData):
    implements(IPlugin, IModuleData)

    name = "ConnectionLimit"
    peerConnections = {}

    def hookIRCd(self, ircd):
        self.ircd = ircd

    def actions(self):
        return [ ("userconnect", 100, self.handleLocalConnect),
                 ("remoteregister", 100, self.handleRemoteConnect),
                 ("quit", 100, self.handleDisconnect),
                 ("remotequit", 100, self.handleDisconnect) ]

    def handleLocalConnect(self, user, *params):
        ip = user.ip
        if self.addToConnections(ip) and self.peerConnections[ip] > self.ircd.config.getWithDefault("connlimit_globmax", 3):
            user.disconnect("No more connections allowed from your IP ({})".format(ip))
            return None
        return True

    def handleRemoteConnect(self, user, *params):
        self.addToConnections(user.ip)

    def handleDisconnect(self, user, *params):
        ip = user.ip
        if ip in self.peerConnections:
            self.peerConnections[ip] -= 1
            if self.peerConnections[ip] < 1:
                del self.peerConnections[ip]

    def addToConnections(self, ip):
        if ip in self.ircd.config.getWithDefault("connlimit_whitelist", []):
            return False
        if ip in self.peerConnections:
            self.peerConnections[ip] += 1
        else:
            self.peerConnections[ip] = 1
        return True

    def load(self):
        for user in self.ircd.users:
            self.addToConnections(user.ip)

connLimit = ConnectionLimit()

Prompt: Implement the connection limit module


"""

This example demonstrates how to make colorful bars.

"""

from rich.block_bar import BlockBar
from rich.console import Console
from rich.table import Table

table = Table()
table.add_column("Score")

table.add_row(BlockBar(size=100, begin=0, end=5, width=30, color="bright_red"))
table.add_row(BlockBar(size=100, begin=0, end=35, width=30, color="bright_yellow"))
table.add_row(BlockBar(size=100, begin=0, end=87, width=30, color="bright_green"))

console = Console()
console.print(table, justify="center")

Add example for block bar

Add example for block bar

Response:
<REPLACE_OLD>  <REPLACE_NEW> """

This example demonstrates how to make colorful bars.

"""

from rich.block_bar import BlockBar
from rich.console import Console
from rich.table import Table

table = Table()
table.add_column("Score")

table.add_row(BlockBar(size=100, begin=0, end=5, width=30, color="bright_red"))
table.add_row(BlockBar(size=100, begin=0, end=35, width=30, color="bright_yellow"))
table.add_row(BlockBar(size=100, begin=0, end=87, width=30, color="bright_green"))

console = Console()
console.print(table, justify="center")
 <REPLACE_END> <|endoftext|> """

This example demonstrates how to make colorful bars.

"""

from rich.block_bar import BlockBar
from rich.console import Console
from rich.table import Table

table = Table()
table.add_column("Score")

table.add_row(BlockBar(size=100, begin=0, end=5, width=30, color="bright_red"))
table.add_row(BlockBar(size=100, begin=0, end=35, width=30, color="bright_yellow"))
table.add_row(BlockBar(size=100, begin=0, end=87, width=30, color="bright_green"))

console = Console()
console.print(table, justify="center")

Prompt: Add example for block bar


# Return true if two strings are anagrams of one another

def is_anagram(str_one, str_two):
	# lower case both strings to account for case insensitivity
	a = str_one.lower()
	b = str_two.lower()

	# convert strings into lists and sort each
	a = list(a)
	b = list(b)

	# sort lists
	a.sort()
	b.sort()

	# consolidate lists into strings
	a = "".join(a)
	b = "".join(b)

	# compare sorted strings
	if a == b:
		print True
	else:
		print False

# test cases
word_one = "pea"
word_two = "Ape"
is_anagram(word_one, word_two) # returns true

word_three = "arm"
word_four = "mary"
is_anagram(word_three, word_four) # returns false

Debug and add test cases

Debug and add test cases

Response:
<REPLACE_OLD> list(a).sort()
	b <REPLACE_NEW> list(a)
	b <REPLACE_END> <REPLACE_OLD> list(b).sort()

	# convert <REPLACE_NEW> list(b)

	# sort lists
	a.sort()
	b.sort()

	# consolidate <REPLACE_END> <DELETE> back <DELETE_END> <REPLACE_OLD> b:
		return true
	else:
		return false

 <REPLACE_NEW> b:
		print True
	else:
		print False

# test cases
word_one = "pea"
word_two = "Ape"
is_anagram(word_one, word_two) # returns true

word_three = "arm"
word_four = "mary"
is_anagram(word_three, word_four) # returns false
 <REPLACE_END> <|endoftext|> # Return true if two strings are anagrams of one another

def is_anagram(str_one, str_two):
	# lower case both strings to account for case insensitivity
	a = str_one.lower()
	b = str_two.lower()

	# convert strings into lists and sort each
	a = list(a)
	b = list(b)

	# sort lists
	a.sort()
	b.sort()

	# consolidate lists into strings
	a = "".join(a)
	b = "".join(b)

	# compare sorted strings
	if a == b:
		print True
	else:
		print False

# test cases
word_one = "pea"
word_two = "Ape"
is_anagram(word_one, word_two) # returns true

word_three = "arm"
word_four = "mary"
is_anagram(word_three, word_four) # returns false

Prompt:
Debug and add test cases

# Return true if two strings are anagrams of one another

def is_anagram(str_one, str_two):
	# lower case both strings to account for case insensitivity
	a = str_one.lower()
	b = str_two.lower()

	# convert strings into lists and sort each
	a = list(a).sort()
	b = list(b).sort()

	# convert lists back into strings
	a = "".join(a)
	b = "".join(b)

	# compare sorted strings
	if a == b:
		return true
	else:
		return false


#! /usr/bin/env python

from os import environ
from subprocess import check_call
from urlparse import urlparse

if 'MONGOLAB_URI' in environ:
    print 'Using', environ['MONGOLAB_URI']
    url = urlparse(environ['MONGOLAB_URI'])
    cmd = 'mongo -u %s -p %s %s:%d/%s' % (url.username,
                                          url.password,
                                          url.hostname,
                                          url.port,
                                          url.path[1:])
else:
    cmd = 'mongo TaarifaAPI'
check_call(cmd, shell=True)

Add script to run a mongo shell in the MongoLab environment

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

from os import environ
from subprocess import check_call
from urlparse import urlparse

if 'MONGOLAB_URI' in environ:
    print 'Using', environ['MONGOLAB_URI']
    url = urlparse(environ['MONGOLAB_URI'])
    cmd = 'mongo -u %s -p %s %s:%d/%s' % (url.username,
                                          url.password,
                                          url.hostname,
                                          url.port,
                                          url.path[1:])
else:
    cmd = 'mongo TaarifaAPI'
check_call(cmd, shell=True)
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python

from os import environ
from subprocess import check_call
from urlparse import urlparse

if 'MONGOLAB_URI' in environ:
    print 'Using', environ['MONGOLAB_URI']
    url = urlparse(environ['MONGOLAB_URI'])
    cmd = 'mongo -u %s -p %s %s:%d/%s' % (url.username,
                                          url.password,
                                          url.hostname,
                                          url.port,
                                          url.path[1:])
else:
    cmd = 'mongo TaarifaAPI'
check_call(cmd, shell=True)

Prompt: Add script to run a mongo shell in the MongoLab environment


import gettext
import os

gettext.install('nova')

from nova import utils

def setup(app):
    rootdir = os.path.abspath(app.srcdir + '/..')
    print "**Autodocumenting from %s" % rootdir
    rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir)
    print rv[0]

Fix doc building endpoint for gettext.

Fix doc building endpoint for gettext.

Response:
<REPLACE_OLD> os

from <REPLACE_NEW> gettext
import os

gettext.install('nova')

from <REPLACE_END> <|endoftext|> import gettext
import os

gettext.install('nova')

from nova import utils

def setup(app):
    rootdir = os.path.abspath(app.srcdir + '/..')
    print "**Autodocumenting from %s" % rootdir
    rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir)
    print rv[0]

Prompt:
Fix doc building endpoint for gettext.
import os

from nova import utils

def setup(app):
    rootdir = os.path.abspath(app.srcdir + '/..')
    print "**Autodocumenting from %s" % rootdir
    rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir)
    print rv[0]


from django.db import models
from django.utils import timezone

class DoorStatus(models.Model):
    datetime = models.DateTimeField()
    status = models.BooleanField(default=False)
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

    @staticmethod
    def get_door_by_name(name):

        # Creates the object if it does not exist
        try:
            door = DoorStatus.objects.get(name=name)
            return door
        except DoorStatus.DoesNotExist:
            door = DoorStatus.objects.create(name=name, datetime=timezone.now())
            return door

    class Meta:
        verbose_name_plural = "Door Statuses"

class OpenData(models.Model):
    opened = models.DateTimeField()
    closed = models.DateTimeField()

    def __str__(self):
        return str(self.opened)

Change plural name of DoorStatus model

Change plural name of DoorStatus model

Response:
<REPLACE_OLD> door

class <REPLACE_NEW> door

    class Meta:
        verbose_name_plural = "Door Statuses"

class <REPLACE_END> <|endoftext|> from django.db import models
from django.utils import timezone

class DoorStatus(models.Model):
    datetime = models.DateTimeField()
    status = models.BooleanField(default=False)
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

    @staticmethod
    def get_door_by_name(name):

        # Creates the object if it does not exist
        try:
            door = DoorStatus.objects.get(name=name)
            return door
        except DoorStatus.DoesNotExist:
            door = DoorStatus.objects.create(name=name, datetime=timezone.now())
            return door

    class Meta:
        verbose_name_plural = "Door Statuses"

class OpenData(models.Model):
    opened = models.DateTimeField()
    closed = models.DateTimeField()

    def __str__(self):
        return str(self.opened)

Prompt:
Change plural name of DoorStatus model

from django.db import models
from django.utils import timezone

class DoorStatus(models.Model):
    datetime = models.DateTimeField()
    status = models.BooleanField(default=False)
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

    @staticmethod
    def get_door_by_name(name):

        # Creates the object if it does not exist
        try:
            door = DoorStatus.objects.get(name=name)
            return door
        except DoorStatus.DoesNotExist:
            door = DoorStatus.objects.create(name=name, datetime=timezone.now())
            return door

class OpenData(models.Model):
    opened = models.DateTimeField()
    closed = models.DateTimeField()

    def __str__(self):
        return str(self.opened)


from setuptools import setup, find_packages

setup(
    name = "biofloat",
    version = "0.1.17",
    packages = find_packages(),
    requires = ['Python (>=2.7)'],
    install_requires = [
        'beautifulsoup4>=4.4',
        'coverage>=4',
        'jupyter>=1.0.0',
        'matplotlib',
        'numpy>=1.10',
        'pandas>=0.17',
        'Pydap',
        'requests>=2.8',
        'seawater>=3.3',
        'simpletable>=0.2',
        'xray>=0.6'
    ],
    scripts = ['scripts/load_biofloat_cache.py'],

    # metadata for upload to PyPI
    author = "Mike McCann",
    author_email = "mccann@mbari.org",
    description = "Software for working with data from Bio-Argo floats",
    license = "MIT",
    keywords = "Oceanography Argo Bio-Argo drifting buoys floats",
    url = "https://github.com/biofloat/biofloat",
)

Response:
<REPLACE_OLD> find_packages
setup(
 <REPLACE_NEW> find_packages

setup(
 <REPLACE_END> <REPLACE_OLD> "0.1.1",
 <REPLACE_NEW> "0.1.17",
 <REPLACE_END> <INSERT>    requires = ['Python (>=2.7)'],
    install_requires = [
        'beautifulsoup4>=4.4',
        'coverage>=4',
        'jupyter>=1.0.0',
        'matplotlib',
        'numpy>=1.10',
        'pandas>=0.17',
        'Pydap',
        'requests>=2.8',
        'seawater>=3.3',
        'simpletable>=0.2',
        'xray>=0.6'
    ],
 <INSERT_END> <|endoftext|> from setuptools import setup, find_packages

setup(
    name = "biofloat",
    version = "0.1.17",
    packages = find_packages(),
    requires = ['Python (>=2.7)'],
    install_requires = [
        'beautifulsoup4>=4.4',
        'coverage>=4',
        'jupyter>=1.0.0',
        'matplotlib',
        'numpy>=1.10',
        'pandas>=0.17',
        'Pydap',
        'requests>=2.8',
        'seawater>=3.3',
        'simpletable>=0.2',
        'xray>=0.6'
    ],
    scripts = ['scripts/load_biofloat_cache.py'],

    # metadata for upload to PyPI
    author = "Mike McCann",
    author_email = "mccann@mbari.org",
    description = "Software for working with data from Bio-Argo floats",
    license = "MIT",
    keywords = "Oceanography Argo Bio-Argo drifting buoys floats",
    url = "https://github.com/biofloat/biofloat",
)

Prompt:
Add install_requires packages, at version 0.1.17

from setuptools import setup, find_packages
setup(
    name = "biofloat",
    version = "0.1.1",
    packages = find_packages(),
    scripts = ['scripts/load_biofloat_cache.py'],

    # metadata for upload to PyPI
    author = "Mike McCann",
    author_email = "mccann@mbari.org",
    description = "Software for working with data from Bio-Argo floats",
    license = "MIT",
    keywords = "Oceanography Argo Bio-Argo drifting buoys floats",
    url = "https://github.com/biofloat/biofloat",
)


def evalQuadratic( a, b, c, x ):

	a = int ( a )
	b = int ( b )
	c = int ( c )
	x = int ( x )

	s = (a * (x ** 2)) + (b * x) + c
	return s

a = input( "Enter a: " )
b = input( "Enter b: " )
c = input( "Enter c: " )
x = input( "Enter x: " )

print( "The answer of the quadratic equation is " + str( evalQuadratic( a, b, c, x ) ) )

Add the answer to the second question of Assignment 3

Response:
<REPLACE_OLD>  <REPLACE_NEW> def evalQuadratic( a, b, c, x ):

	a = int ( a )
	b = int ( b )
	c = int ( c )
	x = int ( x )

	s = (a * (x ** 2)) + (b * x) + c
	return s

a = input( "Enter a: " )
b = input( "Enter b: " )
c = input( "Enter c: " )
x = input( "Enter x: " )

print( "The answer of the quadratic equation is " + str( evalQuadratic( a, b, c, x ) ) ) <REPLACE_END> <|endoftext|> def evalQuadratic( a, b, c, x ):

	a = int ( a )
	b = int ( b )
	c = int ( c )
	x = int ( x )

	s = (a * (x ** 2)) + (b * x) + c
	return s

a = input( "Enter a: " )
b = input( "Enter b: " )
c = input( "Enter c: " )
x = input( "Enter x: " )

print( "The answer of the quadratic equation is " + str( evalQuadratic( a, b, c, x ) ) )

Prompt: Add the answer to the second question of Assignment 3


from setuptools import setup

version = '0.1.0dev'

with open('requirements.txt') as requirements:
    install_requires = requirements.read().split()

setup(
    name='frappeclient',
    version=version,
    author='Rushabh Mehta',
    author_email='rmehta@erpnext.com',
    packages=[
        'frappeclient'
    ],
    install_requires=install_requires,
    tests_requires=[
        'httmock<=1.2.2'
    ],
)

Response:
<REPLACE_OLD> distutils.core <REPLACE_NEW> setuptools <REPLACE_END> <REPLACE_OLD> setup
import os

version <REPLACE_NEW> setup

version <REPLACE_END> <REPLACE_OLD> '0.1.0dev'

setup(
 <REPLACE_NEW> '0.1.0dev'

with open('requirements.txt') as requirements:
 <REPLACE_END> <REPLACE_OLD> name='FrappeClient',
 <REPLACE_NEW> install_requires = requirements.read().split()

setup(
    name='frappeclient',
 <REPLACE_END> <REPLACE_OLD> download_url='https://github.com/jevonearth/frappe-client/archive/'+version+'.tar.gz',
 <REPLACE_NEW> packages=[
 <REPLACE_END> <DELETE> packages=['frappeclient',],
 <DELETE_END> <REPLACE_OLD> install_requires=open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read().split(),
)
 <REPLACE_NEW>  'frappeclient'
    ],
    install_requires=install_requires,
    tests_requires=[
        'httmock<=1.2.2'
    ],
)
 <REPLACE_END> <|endoftext|> from setuptools import setup

version = '0.1.0dev'

with open('requirements.txt') as requirements:
    install_requires = requirements.read().split()

setup(
    name='frappeclient',
    version=version,
    author='Rushabh Mehta',
    author_email='rmehta@erpnext.com',
    packages=[
        'frappeclient'
    ],
    install_requires=install_requires,
    tests_requires=[
        'httmock<=1.2.2'
    ],
)

Prompt:
Clean up, PEP-8 fixes, remove download_url

Switch to setuptools, so we can get tests_requires.
PEP-8 updates
Remove download link, as it was wrong, and it is not needed for pip
installs from git. Can be put back in if/when this package gets
published to pypi.

from distutils.core import setup
import os

version = '0.1.0dev'

setup(
    name='FrappeClient',
    version=version,
    author='Rushabh Mehta',
    author_email='rmehta@erpnext.com',
    download_url='https://github.com/jevonearth/frappe-client/archive/'+version+'.tar.gz',
    packages=['frappeclient',],
    install_requires=open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read().split(),
)


import os

from catchy import HttpCacher, xdg_directory_cacher, NoCachingStrategy

from .installer import Installer
from .sources import PackageSourceFetcher
from .providers import CachingPackageProvider
from .deployer import PackageDeployer

def create(caching):
    if not caching.enabled:
        cacher = NoCachingStrategy()
    elif caching.http_cache_url is not None:
        # TODO: add DirectoryCacher in front of HttpCacher
        cacher = HttpCacher(caching.http_cache_url, caching.http_cache_key)
    else:
        cacher = xdg_directory_cacher("whack/builds")

    package_source_fetcher = PackageSourceFetcher()
    package_provider = CachingPackageProvider(cacher)
    deployer = PackageDeployer()
    installer = Installer(package_source_fetcher, package_provider, deployer)

    return Operations(installer)

class Operations(object):
    def __init__(self, installer):
        self._installer = installer

    def install(self, package_name, install_dir, params):
        return self._installer.install(package_name, install_dir, params)

    def build(self, package_name, install_dir, params):
        return self._installer.build(package_name, install_dir, params)

def install(package, install_dir, caching, params):
    operations = create(caching)
    operations.install(package, install_dir, params)

def build(command, package, install_dir, caching, params):
    operations = create(caching)
    operations.build(package, install_dir, params)

Use XDG directory for caching

Use XDG directory for caching

Response:
<REPLACE_OLD> DirectoryCacher, <REPLACE_NEW> xdg_directory_cacher, <REPLACE_END> <REPLACE_OLD> DirectoryCacher(os.path.expanduser("~/.cache/whack/builds"))
 <REPLACE_NEW> xdg_directory_cacher("whack/builds")
 <REPLACE_END> <|endoftext|> import os

from catchy import HttpCacher, xdg_directory_cacher, NoCachingStrategy

from .installer import Installer
from .sources import PackageSourceFetcher
from .providers import CachingPackageProvider
from .deployer import PackageDeployer

def create(caching):
    if not caching.enabled:
        cacher = NoCachingStrategy()
    elif caching.http_cache_url is not None:
        # TODO: add DirectoryCacher in front of HttpCacher
        cacher = HttpCacher(caching.http_cache_url, caching.http_cache_key)
    else:
        cacher = xdg_directory_cacher("whack/builds")

    package_source_fetcher = PackageSourceFetcher()
    package_provider = CachingPackageProvider(cacher)
    deployer = PackageDeployer()
    installer = Installer(package_source_fetcher, package_provider, deployer)

    return Operations(installer)

class Operations(object):
    def __init__(self, installer):
        self._installer = installer

    def install(self, package_name, install_dir, params):
        return self._installer.install(package_name, install_dir, params)

    def build(self, package_name, install_dir, params):
        return self._installer.build(package_name, install_dir, params)

def install(package, install_dir, caching, params):
    operations = create(caching)
    operations.install(package, install_dir, params)

def build(command, package, install_dir, caching, params):
    operations = create(caching)
    operations.build(package, install_dir, params)

Prompt:
Use XDG directory for caching

import os

from catchy import HttpCacher, DirectoryCacher, NoCachingStrategy

from .installer import Installer
from .sources import PackageSourceFetcher
from .providers import CachingPackageProvider
from .deployer import PackageDeployer

def create(caching):
    if not caching.enabled:
        cacher = NoCachingStrategy()
    elif caching.http_cache_url is not None:
        # TODO: add DirectoryCacher in front of HttpCacher
        cacher = HttpCacher(caching.http_cache_url, caching.http_cache_key)
    else:
        cacher = DirectoryCacher(os.path.expanduser("~/.cache/whack/builds"))

    package_source_fetcher = PackageSourceFetcher()
    package_provider = CachingPackageProvider(cacher)
    deployer = PackageDeployer()
    installer = Installer(package_source_fetcher, package_provider, deployer)

    return Operations(installer)

class Operations(object):
    def __init__(self, installer):
        self._installer = installer

    def install(self, package_name, install_dir, params):
        return self._installer.install(package_name, install_dir, params)

    def build(self, package_name, install_dir, params):
        return self._installer.build(package_name, install_dir, params)

def install(package, install_dir, caching, params):
    operations = create(caching)
    operations.install(package, install_dir, params)

def build(command, package, install_dir, caching, params):
    operations = create(caching)
    operations.build(package, install_dir, params)


from __future__ import absolute_import, division, print_function, with_statement

import collections
from json import JSONEncoder

# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
    def __init__(self):
        super(BuckJSONEncoder, self).__init__()

    def default(self, obj):
        if isinstance(obj, collections.Mapping) and isinstance(
            obj, collections.Sized
        ):  # nopep8
            return dict(obj)
        elif isinstance(obj, collections.Iterable) and isinstance(
            obj, collections.Sized
        ):
            return list(obj)
        else:
            return super(BuckJSONEncoder, self).default(obj)

Response:
<REPLACE_OLD> self).__init__(self)

 <REPLACE_NEW> self).__init__()

 <REPLACE_END> <|endoftext|> from __future__ import absolute_import, division, print_function, with_statement

import collections
from json import JSONEncoder

# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
    def __init__(self):
        super(BuckJSONEncoder, self).__init__()

    def default(self, obj):
        if isinstance(obj, collections.Mapping) and isinstance(
            obj, collections.Sized
        ):  # nopep8
            return dict(obj)
        elif isinstance(obj, collections.Iterable) and isinstance(
            obj, collections.Sized
        ):
            return list(obj)
        else:
            return super(BuckJSONEncoder, self).default(obj)

Prompt:
Fix Python 3 incompatible super constructor invocation.

Summary: Python is a mess and requires all sorts of hacks to work :(

Reviewed By: philipjameson

fbshipit-source-id: 12f3f59a0d

from __future__ import absolute_import, division, print_function, with_statement

import collections
from json import JSONEncoder

# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
    def __init__(self):
        super(BuckJSONEncoder, self).__init__(self)

    def default(self, obj):
        if isinstance(obj, collections.Mapping) and isinstance(
            obj, collections.Sized
        ):  # nopep8
            return dict(obj)
        elif isinstance(obj, collections.Iterable) and isinstance(
            obj, collections.Sized
        ):
            return list(obj)
        else:
            return super(BuckJSONEncoder, self).default(obj)


def selection_sort(a_list):
    """Selection Sort algortihm.

    Concept:
      - Find out the max item's original slot first,
      - then swap it and the item at the max slot.
      - Iterate the procedure for the next max, etc.

    Selection sort is more efficient than bubble sort
    since the former does not swap for all successive pairs,
    and just do one swapping for each iteration.
    """
    for max_slot in reversed(range(len(a_list))):
        select_slot = 0
        for slot in range(1, max_slot + 1):
            if a_list[slot] > a_list[select_slot]:
                select_slot = slot

        temp = a_list[max_slot]
        a_list[max_slot] = a_list[select_slot]
        a_list[select_slot] = temp

def main():
    a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    print('a_list: {}'.format(a_list))
    print('By selection sort: ')
    selection_sort(a_list)
    print(a_list)

if __name__ == '__main__':
    main()

Response:
<REPLACE_OLD> etc.
 <REPLACE_NEW> etc.

    Selection sort is more efficient than bubble sort
    since the former does not swap for all successive pairs,
    and just do one swapping for each iteration.
 <REPLACE_END> <|endoftext|> def selection_sort(a_list):
    """Selection Sort algortihm.

    Concept:
      - Find out the max item's original slot first,
      - then swap it and the item at the max slot.
      - Iterate the procedure for the next max, etc.

    Selection sort is more efficient than bubble sort
    since the former does not swap for all successive pairs,
    and just do one swapping for each iteration.
    """
    for max_slot in reversed(range(len(a_list))):
        select_slot = 0
        for slot in range(1, max_slot + 1):
            if a_list[slot] > a_list[select_slot]:
                select_slot = slot

        temp = a_list[max_slot]
        a_list[max_slot] = a_list[select_slot]
        a_list[select_slot] = temp

def main():
    a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    print('a_list: {}'.format(a_list))
    print('By selection sort: ')
    selection_sort(a_list)
    print(a_list)

if __name__ == '__main__':
    main()

Prompt:
Add comment about more efficient than bubble sort

def selection_sort(a_list):
    """Selection Sort algortihm.

    Concept:
      - Find out the max item's original slot first,
      - then swap it and the item at the max slot.
      - Iterate the procedure for the next max, etc.
    """
    for max_slot in reversed(range(len(a_list))):
        select_slot = 0
        for slot in range(1, max_slot + 1):
            if a_list[slot] > a_list[select_slot]:
                select_slot = slot

        temp = a_list[max_slot]
        a_list[max_slot] = a_list[select_slot]
        a_list[select_slot] = temp

def main():
    a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
    print('a_list: {}'.format(a_list))
    print('By selection sort: ')
    selection_sort(a_list)
    print(a_list)

if __name__ == '__main__':
    main()


from setuptools import setup

setup(
    name='realexpayments',
    version='0.8.0',
    packages=['realexpayments'],
    url='https://github.com/viniciuschiele/realex-sdk',
    license='MIT',
    author='Vinicius Chiele',
    author_email='vinicius.chiele@gmail.com',
    description='Realex Payments SDK for Python',
    keywords=['realex', 'payments', 'api', 'client'],
    install_requires=['requests'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: Implementation :: CPython'
    ]
)

Rename project name to realexpayments

Rename project name to realexpayments

Response:
<REPLACE_OLD> name='realex-client',
 <REPLACE_NEW> name='realexpayments',
 <REPLACE_END> <REPLACE_OLD> url='https://github.com/viniciuschiele/realex-client',
 <REPLACE_NEW> url='https://github.com/viniciuschiele/realex-sdk',
 <REPLACE_END> <REPLACE_OLD> description='Python interface to Realex Payments',
 <REPLACE_NEW> description='Realex Payments SDK for Python',
 <REPLACE_END> <REPLACE_OLD> ]
) <REPLACE_NEW> ]
)
 <REPLACE_END> <|endoftext|> from setuptools import setup

setup(
    name='realexpayments',
    version='0.8.0',
    packages=['realexpayments'],
    url='https://github.com/viniciuschiele/realex-sdk',
    license='MIT',
    author='Vinicius Chiele',
    author_email='vinicius.chiele@gmail.com',
    description='Realex Payments SDK for Python',
    keywords=['realex', 'payments', 'api', 'client'],
    install_requires=['requests'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: Implementation :: CPython'
    ]
)

Prompt:
Rename project name to realexpayments

from setuptools import setup

setup(
    name='realex-client',
    version='0.8.0',
    packages=['realexpayments'],
    url='https://github.com/viniciuschiele/realex-client',
    license='MIT',
    author='Vinicius Chiele',
    author_email='vinicius.chiele@gmail.com',
    description='Python interface to Realex Payments',
    keywords=['realex', 'payments', 'api', 'client'],
    install_requires=['requests'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: Implementation :: CPython'
    ]
)


#Too many mistakes were made.
#0. should use while loop instead of for.
#1. messed up with index. maybe with the sleepy head at 3pm
class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        result = len(A)
        if result == 0:
            return result

        curr = 0
        next_index = 1
        start_index = 1
        if next_index < len(A) and A[next_index] == A[curr]:
            next_index += 1
            start_index += 1

        i = start_index
        while i < len(A):
            if A[i] > A[curr]:
                temp = A[next_index]
                A[next_index] = A[i]
                A[i] = temp
                curr = next_index
                next_index += 1
                if (i + 1) < len(A) and A[i+1] == A[curr]:
                    A[next_index] = A[i+1]
                    next_index += 1
                    i += 1
            else:
                result -= 1
            i += 1
            print A

        return result

if __name__ == "__main__":
    solution = Solution()
    A = [1, 1, 1, 1, 2, 2, 2, 2, 3]
    result = solution.removeDuplicates(A)
    print A[:result]

Remove Duplicates From Sorted Array II

Remove Duplicates From Sorted Array II

Response:
<REPLACE_OLD>  <REPLACE_NEW> #Too many mistakes were made.
#0. should use while loop instead of for.
#1. messed up with index. maybe with the sleepy head at 3pm
class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        result = len(A)
        if result == 0:
            return result

        curr = 0
        next_index = 1
        start_index = 1
        if next_index < len(A) and A[next_index] == A[curr]:
            next_index += 1
            start_index += 1

        i = start_index
        while i < len(A):
            if A[i] > A[curr]:
                temp = A[next_index]
                A[next_index] = A[i]
                A[i] = temp
                curr = next_index
                next_index += 1
                if (i + 1) < len(A) and A[i+1] == A[curr]:
                    A[next_index] = A[i+1]
                    next_index += 1
                    i += 1
            else:
                result -= 1
            i += 1
            print A

        return result

if __name__ == "__main__":
    solution = Solution()
    A = [1, 1, 1, 1, 2, 2, 2, 2, 3]
    result = solution.removeDuplicates(A)
    print A[:result]
 <REPLACE_END> <|endoftext|> #Too many mistakes were made.
#0. should use while loop instead of for.
#1. messed up with index. maybe with the sleepy head at 3pm
class Solution:
    # @param a list of integers
    # @return an integer
    def removeDuplicates(self, A):
        result = len(A)
        if result == 0:
            return result

        curr = 0
        next_index = 1
        start_index = 1
        if next_index < len(A) and A[next_index] == A[curr]:
            next_index += 1
            start_index += 1

        i = start_index
        while i < len(A):
            if A[i] > A[curr]:
                temp = A[next_index]
                A[next_index] = A[i]
                A[i] = temp
                curr = next_index
                next_index += 1
                if (i + 1) < len(A) and A[i+1] == A[curr]:
                    A[next_index] = A[i+1]
                    next_index += 1
                    i += 1
            else:
                result -= 1
            i += 1
            print A

        return result

if __name__ == "__main__":
    solution = Solution()
    A = [1, 1, 1, 1, 2, 2, 2, 2, 3]
    result = solution.removeDuplicates(A)
    print A[:result]

Prompt: Remove Duplicates From Sorted Array II


c = get_config()

# Kernel config
c.IPKernelApp.pylab = 'inline'  # if you want plotting support always

# Notebook config
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8080
c.NotebookApp.notebook_dir = '/work'

c.NotebookApp.trust_xheaders = True

c.NotebookApp.tornado_settings = {
    'headers': {
        'Content-Security-Policy': "frame-ancestors 'self' https://*.terminal.com"
    }
}

Add ipython config file with notebook dir set to /work

Response:
<INSERT> c = get_config()

# Kernel config
c.IPKernelApp.pylab = 'inline' <INSERT_END> <INSERT> # if you want plotting support always

# Notebook config
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8080
c.NotebookApp.notebook_dir = '/work'

c.NotebookApp.trust_xheaders = True

c.NotebookApp.tornado_settings = {
    'headers': {
        'Content-Security-Policy': "frame-ancestors 'self' https://*.terminal.com"
    }
}
 <INSERT_END> <|endoftext|> c = get_config()

# Kernel config
c.IPKernelApp.pylab = 'inline'  # if you want plotting support always

# Notebook config
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8080
c.NotebookApp.notebook_dir = '/work'

c.NotebookApp.trust_xheaders = True

c.NotebookApp.tornado_settings = {
    'headers': {
        'Content-Security-Policy': "frame-ancestors 'self' https://*.terminal.com"
    }
}

Prompt: Add ipython config file with notebook dir set to /work


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

# [MSB]
MSB_SERVICE_IP = '127.0.0.1'
MSB_SERVICE_PORT = '10080'

# [register]
REG_TO_MSB_WHEN_START = True
REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services"
REG_TO_MSB_REG_PARAM = {
    "serviceName": "gvnfmdriver",
    "version": "v1",
    "url": "/openoapi/gvnfmdriver/v1",
    "protocol": "REST",
    "visualRange": "1",
    "nodes": [{
        "ip": "127.0.0.1",
        "port": "8484",
        "ttl": 0
    }]
}

Add code framework of gvnfm-driver

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

# [MSB]
MSB_SERVICE_IP = '127.0.0.1'
MSB_SERVICE_PORT = '10080'

# [register]
REG_TO_MSB_WHEN_START = True
REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services"
REG_TO_MSB_REG_PARAM = {
    "serviceName": "gvnfmdriver",
    "version": "v1",
    "url": "/openoapi/gvnfmdriver/v1",
    "protocol": "REST",
    "visualRange": "1",
    "nodes": [{
        "ip": "127.0.0.1",
        "port": "8484",
        "ttl": 0
    }]
}

Prompt:
Add code framework of gvnfm-driver

Change-Id: Ibb0dd98a73860f538599328b718040df5f3f7007
Issue-Id: NFVO-132
Signed-off-by: fujinhua <302f4934d283b6f50163b4a7fd9b6c869e0ad64e@zte.com.cn>

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

# [MSB]
MSB_SERVICE_IP = '127.0.0.1'
MSB_SERVICE_PORT = '10080'

# [register]
REG_TO_MSB_WHEN_START = True
REG_TO_MSB_REG_URL = "/openoapi/microservices/v1/services"
REG_TO_MSB_REG_PARAM = {
    "serviceName": "ztevmanagerdriver",
    "version": "v1",
    "url": "/openoapi/ztevmanagerdriver/v1",
    "protocol": "REST",
    "visualRange": "1",
    "nodes": [{
        "ip": "127.0.0.1",
        "port": "8410",
        "ttl": 0
    }]
}