from django.core.management.templates import BaseCommand
from django.utils.crypto import get_random_string

import fileinput

from django.conf import settings

class Command(BaseCommand):
    help = ("Replaces the SECRET_KEY VALUE in settings.py with a new one.")

    def handle(self, *args, **options):
        # Create a random SECRET_KEY hash to put it in the main settings.
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        secret_key = get_random_string(50, chars)

        file_path = "{}/settings.py".format(settings.PROJECT_DIR)

        for line in fileinput.input(file_path, inplace=True):
            if line.startswith("SECRET_KEY = "):
                print("SECRET_KEY = '{}'".format(secret_key))
            else:
                print(line, end='')

Add management command to generate a random secret key

Response:
<INSERT> from django.core.management.templates import BaseCommand
from django.utils.crypto import get_random_string

import fileinput

from django.conf import settings

class Command(BaseCommand):
 <INSERT_END> <INSERT>   help = ("Replaces the SECRET_KEY VALUE in settings.py with a new one.")

    def handle(self, *args, **options):
        # Create a random SECRET_KEY hash to put it in the main settings.
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        secret_key = get_random_string(50, chars)

        file_path = "{}/settings.py".format(settings.PROJECT_DIR)

        for line in fileinput.input(file_path, inplace=True):
            if line.startswith("SECRET_KEY = "):
                print("SECRET_KEY = '{}'".format(secret_key))
            else:
                print(line, end='')
 <INSERT_END> <|endoftext|> from django.core.management.templates import BaseCommand
from django.utils.crypto import get_random_string

import fileinput

from django.conf import settings

class Command(BaseCommand):
    help = ("Replaces the SECRET_KEY VALUE in settings.py with a new one.")

    def handle(self, *args, **options):
        # Create a random SECRET_KEY hash to put it in the main settings.
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        secret_key = get_random_string(50, chars)

        file_path = "{}/settings.py".format(settings.PROJECT_DIR)

        for line in fileinput.input(file_path, inplace=True):
            if line.startswith("SECRET_KEY = "):
                print("SECRET_KEY = '{}'".format(secret_key))
            else:
                print(line, end='')

Prompt: Add management command to generate a random secret key


from setuptools import setup, find_packages
from io import open

setup(
    name='django-debug-toolbar',
    version='1.3.2',
    description='A configurable set of panels that display various debug '
                'information about the current request/response.',
    long_description=open('README.rst', encoding='utf-8').read(),
    author='Rob Hudson',
    author_email='rob@cogit8.org',
    url='https://github.com/django-debug-toolbar/django-debug-toolbar',
    download_url='https://pypi.python.org/pypi/django-debug-toolbar',
    license='BSD',
    packages=find_packages(exclude=('tests.*', 'tests', 'example')),
    install_requires=[
        'Django>=1.4.2',
        'sqlparse',
    ],
    include_package_data=True,
    zip_safe=False,                 # because we're including static files
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)

Response:
<REPLACE_OLD> 'django>=1.4.2',
 <REPLACE_NEW> 'Django>=1.4.2',
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
from io import open

setup(
    name='django-debug-toolbar',
    version='1.3.2',
    description='A configurable set of panels that display various debug '
                'information about the current request/response.',
    long_description=open('README.rst', encoding='utf-8').read(),
    author='Rob Hudson',
    author_email='rob@cogit8.org',
    url='https://github.com/django-debug-toolbar/django-debug-toolbar',
    download_url='https://pypi.python.org/pypi/django-debug-toolbar',
    license='BSD',
    packages=find_packages(exclude=('tests.*', 'tests', 'example')),
    install_requires=[
        'Django>=1.4.2',
        'sqlparse',
    ],
    include_package_data=True,
    zip_safe=False,                 # because we're including static files
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)

Prompt:
Correct spelling of Django in requirements

It seems that using 'django' instead of 'Django' has the consequence that "pip install django_debug_toolbar" has the consequence of installing the latest version of Django, even if you already have Django installed.
from setuptools import setup, find_packages
from io import open

setup(
    name='django-debug-toolbar',
    version='1.3.2',
    description='A configurable set of panels that display various debug '
                'information about the current request/response.',
    long_description=open('README.rst', encoding='utf-8').read(),
    author='Rob Hudson',
    author_email='rob@cogit8.org',
    url='https://github.com/django-debug-toolbar/django-debug-toolbar',
    download_url='https://pypi.python.org/pypi/django-debug-toolbar',
    license='BSD',
    packages=find_packages(exclude=('tests.*', 'tests', 'example')),
    install_requires=[
        'django>=1.4.2',
        'sqlparse',
    ],
    include_package_data=True,
    zip_safe=False,                 # because we're including static files
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)


import sys
import os
import ctypes

import pyglet.window
from pyglet.gl import *
from pyglet import clock
from pyglet import image

if len(sys.argv) != 2:
    print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0]
    sys.exit()

window = pyglet.window.Window(width=400, height=400)
image = image.load(sys.argv[1])
imx = imy = 0
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    global imx, imy
    imx += dx
    imy += dy

clock.set_fps_limit(30)
while not window.has_exit:
    clock.tick()
    window.dispatch_events()
    glClear(GL_COLOR_BUFFER_BIT)
    image.blit(imx, imy, 0)
    window.flip()

Use the core, make example more useful.

Response:
<REPLACE_OLD> os

import <REPLACE_NEW> os
import ctypes

import <REPLACE_END> <REPLACE_OLD> pyglet.ext.scene2d <REPLACE_NEW> pyglet <REPLACE_END> <REPLACE_OLD> Image2d

from ctypes import *

if <REPLACE_NEW> image

if <REPLACE_END> <REPLACE_OLD> height=400)

image <REPLACE_NEW> height=400)
image <REPLACE_END> <REPLACE_OLD> Image2d.load(sys.argv[1])
s <REPLACE_NEW> image.load(sys.argv[1])
imx <REPLACE_END> <REPLACE_OLD> max(image.width, image.height)

c <REPLACE_NEW> imy <REPLACE_END> <REPLACE_OLD> clock.Clock(60)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., 1., 1., 100.)
glEnable(GL_COLOR_MATERIAL)

glMatrixMode(GL_MODELVIEW)
glClearColor(0, 0, 0, 0)
glColor4f(1, 1, 1, 1)

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)

while <REPLACE_NEW> 0
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    global imx, imy
    imx += dx
    imy += dy

clock.set_fps_limit(30)
while <REPLACE_END> <REPLACE_OLD> c.tick()
 <REPLACE_NEW> clock.tick()
 <REPLACE_END> <REPLACE_OLD> window.dispatch_events()

 <REPLACE_NEW> window.dispatch_events()
 <REPLACE_END> <REPLACE_OLD> glLoadIdentity()

    glScalef(1./s, 1./s, 1.)
    glTranslatef(-image.width/2, -image.height/2, -1.)
    image.draw()

 <REPLACE_NEW> image.blit(imx, imy, 0)
 <REPLACE_END> <|endoftext|> import sys
import os
import ctypes

import pyglet.window
from pyglet.gl import *
from pyglet import clock
from pyglet import image

if len(sys.argv) != 2:
    print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0]
    sys.exit()

window = pyglet.window.Window(width=400, height=400)
image = image.load(sys.argv[1])
imx = imy = 0
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    global imx, imy
    imx += dx
    imy += dy

clock.set_fps_limit(30)
while not window.has_exit:
    clock.tick()
    window.dispatch_events()
    glClear(GL_COLOR_BUFFER_BIT)
    image.blit(imx, imy, 0)
    window.flip()

Prompt:
Use the core, make example more useful.

git-svn-id: d4fdfcd4de20a449196f78acc655f735742cd30d@874 14d46d22-621c-0410-bb3d-6f67920f7d95

import sys
import os

import pyglet.window
from pyglet.gl import *
from pyglet import clock
from pyglet.ext.scene2d import Image2d

from ctypes import *

if len(sys.argv) != 2:
    print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0]
    sys.exit()

window = pyglet.window.Window(width=400, height=400)

image = Image2d.load(sys.argv[1])
s = max(image.width, image.height)

c = clock.Clock(60)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., 1., 1., 100.)
glEnable(GL_COLOR_MATERIAL)

glMatrixMode(GL_MODELVIEW)
glClearColor(0, 0, 0, 0)
glColor4f(1, 1, 1, 1)

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)

while not window.has_exit:
    c.tick()
    window.dispatch_events()

    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()

    glScalef(1./s, 1./s, 1.)
    glTranslatef(-image.width/2, -image.height/2, -1.)
    image.draw()

    window.flip()


# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.

import re

class Collection(object):
    '''Represent group of items that differ only by numerical component.'''

    def __init__(self, head, tail, padding, indexes=None):
        '''Initialise collection.

        *head* is the leading common part whilst *tail* is the trailing
        common part.

        *padding* specifies the "width" of the numerical component. An index
        will be padded with zeros to fill this width. A *padding* of zero
        implies no padding and width may be any size so long as no leading
        zeros are present.

        *indexes* can specify a set of numerical indexes to initially populate
        the collection with.

        '''
        super(Collection, self).__init__()
        self.head = head
        self.tail = tail
        self.padding = padding
        self.indexes = set()
        if indexes is not None:
            self.indexes.update(indexes)

        self._pattern = re.compile('^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
                                   .format(self.head, self.tail))

    def __iter__(self):
        '''Return iterator over items in collection.'''

    def __contains__(self, item):
        '''Return whether *item* is present in collection.'''

    def match(self, item):
        '''Return whether *item* matches this collection pattern.

        If a match is successful return data about the match otherwise return
        None.

        '''

    def add(self, item):
        '''Add *item* to collection.

        raise :py:class:`~clique.error.CollectionError` if *item* cannot be
        added to the collection.

        '''

    def remove(self, item):
        '''Remove *item* from collection.

        raise :py:class:`~clique.error.CollectionError` if *item* cannot be
        removed from the collection.

        '''

    def format(self, pattern):
        '''Return string representation as specified by *pattern*.'''

    def is_contiguous(self):
        '''Return whether entire collection is contiguous.'''

    def holes(self):
        '''Return holes in collection.

        Return as list of :py:class:`~clique.collection.Collection` instances.

        '''

    def merge(self, collection):
        '''Merge *collection* into this collection.

        If the *collection* is compatible with this collection then update
        indexes with all indexes in *collection*.

        '''

    def separate(self):
        '''Return contiguous parts of collection as separate collections.

        Return as list of :py:class:`~clique.collection.Collection` instances.

        '''

Add initial interface for Collection class with stubs for methods.

A Collection will represent a group of items with a common numerical
component.

Response:
<REPLACE_OLD>  <REPLACE_NEW> # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.

import re

class Collection(object):
    '''Represent group of items that differ only by numerical component.'''

    def __init__(self, head, tail, padding, indexes=None):
        '''Initialise collection.

        *head* is the leading common part whilst *tail* is the trailing
        common part.

        *padding* specifies the "width" of the numerical component. An index
        will be padded with zeros to fill this width. A *padding* of zero
        implies no padding and width may be any size so long as no leading
        zeros are present.

        *indexes* can specify a set of numerical indexes to initially populate
        the collection with.

        '''
        super(Collection, self).__init__()
        self.head = head
        self.tail = tail
        self.padding = padding
        self.indexes = set()
        if indexes is not None:
            self.indexes.update(indexes)

        self._pattern = re.compile('^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
                                   .format(self.head, self.tail))

    def __iter__(self):
        '''Return iterator over items in collection.'''

    def __contains__(self, item):
        '''Return whether *item* is present in collection.'''

    def match(self, item):
        '''Return whether *item* matches this collection pattern.

        If a match is successful return data about the match otherwise return
        None.

        '''

    def add(self, item):
        '''Add *item* to collection.

        raise :py:class:`~clique.error.CollectionError` if *item* cannot be
        added to the collection.

        '''

    def remove(self, item):
        '''Remove *item* from collection.

        raise :py:class:`~clique.error.CollectionError` if *item* cannot be
        removed from the collection.

        '''

    def format(self, pattern):
        '''Return string representation as specified by *pattern*.'''

    def is_contiguous(self):
        '''Return whether entire collection is contiguous.'''

    def holes(self):
        '''Return holes in collection.

        Return as list of :py:class:`~clique.collection.Collection` instances.

        '''

    def merge(self, collection):
        '''Merge *collection* into this collection.

        If the *collection* is compatible with this collection then update
        indexes with all indexes in *collection*.

        '''

    def separate(self):
        '''Return contiguous parts of collection as separate collections.

        Return as list of :py:class:`~clique.collection.Collection` instances.

        '''
 <REPLACE_END> <|endoftext|> # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.

import re

class Collection(object):
    '''Represent group of items that differ only by numerical component.'''

    def __init__(self, head, tail, padding, indexes=None):
        '''Initialise collection.

        *head* is the leading common part whilst *tail* is the trailing
        common part.

        *padding* specifies the "width" of the numerical component. An index
        will be padded with zeros to fill this width. A *padding* of zero
        implies no padding and width may be any size so long as no leading
        zeros are present.

        *indexes* can specify a set of numerical indexes to initially populate
        the collection with.

        '''
        super(Collection, self).__init__()
        self.head = head
        self.tail = tail
        self.padding = padding
        self.indexes = set()
        if indexes is not None:
            self.indexes.update(indexes)

        self._pattern = re.compile('^{0}(?P<index>(?P<padding>0*)\d+?){1}$'
                                   .format(self.head, self.tail))

    def __iter__(self):
        '''Return iterator over items in collection.'''

    def __contains__(self, item):
        '''Return whether *item* is present in collection.'''

    def match(self, item):
        '''Return whether *item* matches this collection pattern.

        If a match is successful return data about the match otherwise return
        None.

        '''

    def add(self, item):
        '''Add *item* to collection.

        raise :py:class:`~clique.error.CollectionError` if *item* cannot be
        added to the collection.

        '''

    def remove(self, item):
        '''Remove *item* from collection.

        raise :py:class:`~clique.error.CollectionError` if *item* cannot be
        removed from the collection.

        '''

    def format(self, pattern):
        '''Return string representation as specified by *pattern*.'''

    def is_contiguous(self):
        '''Return whether entire collection is contiguous.'''

    def holes(self):
        '''Return holes in collection.

        Return as list of :py:class:`~clique.collection.Collection` instances.

        '''

    def merge(self, collection):
        '''Merge *collection* into this collection.

        If the *collection* is compatible with this collection then update
        indexes with all indexes in *collection*.

        '''

    def separate(self):
        '''Return contiguous parts of collection as separate collections.

        Return as list of :py:class:`~clique.collection.Collection` instances.

        '''

Prompt:
Add initial interface for Collection class with stubs for methods.

A Collection will represent a group of items with a common numerical
component.


# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-05-15 14:16
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('accelerator', '0076_change_description_to_textfield'),
    ]

    operations = [
        migrations.AddField(
            model_name='program',
            name='program_overview_link',
            field=models.URLField(
                blank=True,
                null=True,
                help_text=('URL of the program overview page, '
                            'ex: https://masschallenge.org/programs-boston'),
                max_length=255,
            )
        )
    ]

[AC-6989] Add migration file form program overview link

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-05-15 14:16
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('accelerator', '0076_change_description_to_textfield'),
    ]

    operations = [
        migrations.AddField(
            model_name='program',
            name='program_overview_link',
            field=models.URLField(
                blank=True,
                null=True,
                help_text=('URL of the program overview page, '
                            'ex: https://masschallenge.org/programs-boston'),
                max_length=255,
            )
        )
    ]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-05-15 14:16
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('accelerator', '0076_change_description_to_textfield'),
    ]

    operations = [
        migrations.AddField(
            model_name='program',
            name='program_overview_link',
            field=models.URLField(
                blank=True,
                null=True,
                help_text=('URL of the program overview page, '
                            'ex: https://masschallenge.org/programs-boston'),
                max_length=255,
            )
        )
    ]

Prompt: [AC-6989] Add migration file form program overview link


#
# -*- encoding: utf-8 -*-
#

import re
import config
import surllib
import semail
import datetime
import urllib

URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'

def docFindWeekplans(bs):

    trs = bs.findAll('tr')

    for line in trs:
        if not line.has_key('class'):
            continue
        if not [c for c in line['class'].split() if c.startswith('linje')]:
            continue

        links = line.findAll('a')
        assert(len(links) >= 1)

        # find week date
        title = links[0].text

        # find url
        url = links[0]['href']
        url = url.encode('iso-8859-1')
        url = URL_PREFIX + urllib.quote(url, safe=':/?=&%')

        bs = surllib.skoleGetURL(url, True)

        msg = semail.Message('weekplans', bs)
        msg.setTitle(u'%s' % title)
        msg.updatePersonDate()
        msg.maybeSend()

def skoleWeekplans():
    global bs

    # surllib.skoleLogin()
    config.log(u'Kigger efter nye ugeplaner')

    # read the initial page
    bs = surllib.skoleGetURL(URL_MAIN, True, True)
    docFindWeekplans(bs)

if __name__ == '__main__':
    # test
    skoleWeekplans()

Make code comply to PEP8

Make code comply to PEP8

Response:
<REPLACE_OLD> 'Ugeplaner.asp'

def <REPLACE_NEW> 'Ugeplaner.asp'

def <REPLACE_END> <INSERT> url.encode('iso-8859-1')
        url = <INSERT_END> <REPLACE_OLD> urllib.quote(url.encode('iso-8859-1'), <REPLACE_NEW> urllib.quote(url, <REPLACE_END> <|endoftext|> #
# -*- encoding: utf-8 -*-
#

import re
import config
import surllib
import semail
import datetime
import urllib

URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'

def docFindWeekplans(bs):

    trs = bs.findAll('tr')

    for line in trs:
        if not line.has_key('class'):
            continue
        if not [c for c in line['class'].split() if c.startswith('linje')]:
            continue

        links = line.findAll('a')
        assert(len(links) >= 1)

        # find week date
        title = links[0].text

        # find url
        url = links[0]['href']
        url = url.encode('iso-8859-1')
        url = URL_PREFIX + urllib.quote(url, safe=':/?=&%')

        bs = surllib.skoleGetURL(url, True)

        msg = semail.Message('weekplans', bs)
        msg.setTitle(u'%s' % title)
        msg.updatePersonDate()
        msg.maybeSend()

def skoleWeekplans():
    global bs

    # surllib.skoleLogin()
    config.log(u'Kigger efter nye ugeplaner')

    # read the initial page
    bs = surllib.skoleGetURL(URL_MAIN, True, True)
    docFindWeekplans(bs)

if __name__ == '__main__':
    # test
    skoleWeekplans()

Prompt:
Make code comply to PEP8

#
# -*- encoding: utf-8 -*-
#

import re
import config
import surllib
import semail
import datetime
import urllib

URL_PREFIX = 'http://%s/Infoweb/Fi/' % config.HOSTNAME
URL_MAIN = URL_PREFIX + 'Ugeplaner.asp'

def docFindWeekplans(bs):

    trs = bs.findAll('tr')

    for line in trs:
        if not line.has_key('class'):
            continue
        if not [c for c in line['class'].split() if c.startswith('linje')]:
            continue

        links = line.findAll('a')
        assert(len(links) >= 1)

        # find week date
        title = links[0].text

        # find url
        url = links[0]['href']
        url = URL_PREFIX + urllib.quote(url.encode('iso-8859-1'), safe=':/?=&%')

        bs = surllib.skoleGetURL(url, True)

        msg = semail.Message('weekplans', bs)
        msg.setTitle(u'%s' % title)
        msg.updatePersonDate()
        msg.maybeSend()

def skoleWeekplans():
    global bs

    # surllib.skoleLogin()
    config.log(u'Kigger efter nye ugeplaner')

    # read the initial page
    bs = surllib.skoleGetURL(URL_MAIN, True, True)
    docFindWeekplans(bs)

if __name__ == '__main__':
    # test
    skoleWeekplans()


# Generated by Django 3.0.6 on 2020-06-05 14:35

from django.db import migrations
from django_countries import countries

def get_countries_without_shipping_zone(ShippingZone):
    """Return countries that are not assigned to any shipping zone."""
    covered_countries = set()
    for zone in ShippingZone.objects.all():
        covered_countries.update({c.code for c in zone.countries})
    return (country[0] for country in countries if country[0] not in covered_countries)

def assign_countries_in_default_shipping_zone(apps, schema_editor):
    ShippingZone = apps.get_model("shipping", "ShippingZone")
    qs = ShippingZone.objects.filter(default=True)
    if qs.exists():
        default_zone = qs[0]
        if not default_zone.countries:
            default_zone.countries = get_countries_without_shipping_zone(ShippingZone)
            default_zone.save(update_fields=["countries"])

class Migration(migrations.Migration):

    dependencies = [
        ("shipping", "0017_django_price_2"),
    ]

    operations = [
        migrations.RunPython(
            assign_countries_in_default_shipping_zone, migrations.RunPython.noop
        )
    ]

Move utility function to migration

Move utility function to migration

Response:
<REPLACE_OLD> migrations

from ..utils <REPLACE_NEW> migrations
from django_countries <REPLACE_END> <REPLACE_OLD> get_countries_without_shipping_zone

def <REPLACE_NEW> countries

def get_countries_without_shipping_zone(ShippingZone):
    """Return countries that are not assigned to any shipping zone."""
    covered_countries = set()
    for zone in ShippingZone.objects.all():
        covered_countries.update({c.code for c in zone.countries})
    return (country[0] for country in countries if country[0] not in covered_countries)

def <REPLACE_END> <REPLACE_OLD> get_countries_without_shipping_zone()
 <REPLACE_NEW> get_countries_without_shipping_zone(ShippingZone)
 <REPLACE_END> <|endoftext|> # Generated by Django 3.0.6 on 2020-06-05 14:35

from django.db import migrations
from django_countries import countries

def get_countries_without_shipping_zone(ShippingZone):
    """Return countries that are not assigned to any shipping zone."""
    covered_countries = set()
    for zone in ShippingZone.objects.all():
        covered_countries.update({c.code for c in zone.countries})
    return (country[0] for country in countries if country[0] not in covered_countries)

def assign_countries_in_default_shipping_zone(apps, schema_editor):
    ShippingZone = apps.get_model("shipping", "ShippingZone")
    qs = ShippingZone.objects.filter(default=True)
    if qs.exists():
        default_zone = qs[0]
        if not default_zone.countries:
            default_zone.countries = get_countries_without_shipping_zone(ShippingZone)
            default_zone.save(update_fields=["countries"])

class Migration(migrations.Migration):

    dependencies = [
        ("shipping", "0017_django_price_2"),
    ]

    operations = [
        migrations.RunPython(
            assign_countries_in_default_shipping_zone, migrations.RunPython.noop
        )
    ]

Prompt:
Move utility function to migration

# Generated by Django 3.0.6 on 2020-06-05 14:35

from django.db import migrations

from ..utils import get_countries_without_shipping_zone

def assign_countries_in_default_shipping_zone(apps, schema_editor):
    ShippingZone = apps.get_model("shipping", "ShippingZone")
    qs = ShippingZone.objects.filter(default=True)
    if qs.exists():
        default_zone = qs[0]
        if not default_zone.countries:
            default_zone.countries = get_countries_without_shipping_zone()
            default_zone.save(update_fields=["countries"])

class Migration(migrations.Migration):

    dependencies = [
        ("shipping", "0017_django_price_2"),
    ]

    operations = [
        migrations.RunPython(
            assign_countries_in_default_shipping_zone, migrations.RunPython.noop
        )
    ]


"""Coordination chatroom game."""

import dallinger as dlgr
from dallinger.compat import unicode
from dallinger.config import get_config

config = get_config()

def extra_settings():
    config.register('network', unicode)
    config.register('n', int)

class CoordinationChatroom(dlgr.experiments.Experiment):
    """Define the structure of the experiment."""

    def __init__(self, session):
        """Initialize the experiment."""
        super(CoordinationChatroom, self).__init__(session)
        self.experiment_repeats = 1
        self.num_participants = config.get('n')
        self.initial_recruitment_size = self.num_participants
        self.quorum = self.num_participants
        self.config = config
        if not self.config.ready:
            self.config.load_config()
        self.setup()

    def create_network(self):
        """Create a new network by reading the configuration file."""
        class_ = getattr(
            dlgr.networks,
            self.config.get('network')
        )
        return class_(max_size=self.num_participants)

    def info_post_request(self, node, info):
        """Run when a request to create an info is complete."""
        for agent in node.neighbors():
            node.transmit(what=info, to_whom=agent)

    def create_node(self, participant, network):
        """Create a node for a participant."""
        return dlgr.nodes.Agent(network=network, participant=participant)

Use compat for unicode import

Use compat for unicode import

Response:
<INSERT> dallinger.compat import unicode
from <INSERT_END> <REPLACE_OLD> get_config
try:
    unicode = unicode
except NameError:  # Python 3
    unicode = str

config <REPLACE_NEW> get_config

config <REPLACE_END> <|endoftext|> """Coordination chatroom game."""

import dallinger as dlgr
from dallinger.compat import unicode
from dallinger.config import get_config

config = get_config()

def extra_settings():
    config.register('network', unicode)
    config.register('n', int)

class CoordinationChatroom(dlgr.experiments.Experiment):
    """Define the structure of the experiment."""

    def __init__(self, session):
        """Initialize the experiment."""
        super(CoordinationChatroom, self).__init__(session)
        self.experiment_repeats = 1
        self.num_participants = config.get('n')
        self.initial_recruitment_size = self.num_participants
        self.quorum = self.num_participants
        self.config = config
        if not self.config.ready:
            self.config.load_config()
        self.setup()

    def create_network(self):
        """Create a new network by reading the configuration file."""
        class_ = getattr(
            dlgr.networks,
            self.config.get('network')
        )
        return class_(max_size=self.num_participants)

    def info_post_request(self, node, info):
        """Run when a request to create an info is complete."""
        for agent in node.neighbors():
            node.transmit(what=info, to_whom=agent)

    def create_node(self, participant, network):
        """Create a node for a participant."""
        return dlgr.nodes.Agent(network=network, participant=participant)

Prompt:
Use compat for unicode import

"""Coordination chatroom game."""

import dallinger as dlgr
from dallinger.config import get_config
try:
    unicode = unicode
except NameError:  # Python 3
    unicode = str

config = get_config()

def extra_settings():
    config.register('network', unicode)
    config.register('n', int)

class CoordinationChatroom(dlgr.experiments.Experiment):
    """Define the structure of the experiment."""

    def __init__(self, session):
        """Initialize the experiment."""
        super(CoordinationChatroom, self).__init__(session)
        self.experiment_repeats = 1
        self.num_participants = config.get('n')
        self.initial_recruitment_size = self.num_participants
        self.quorum = self.num_participants
        self.config = config
        if not self.config.ready:
            self.config.load_config()
        self.setup()

    def create_network(self):
        """Create a new network by reading the configuration file."""
        class_ = getattr(
            dlgr.networks,
            self.config.get('network')
        )
        return class_(max_size=self.num_participants)

    def info_post_request(self, node, info):
        """Run when a request to create an info is complete."""
        for agent in node.neighbors():
            node.transmit(what=info, to_whom=agent)

    def create_node(self, participant, network):
        """Create a node for a participant."""
        return dlgr.nodes.Agent(network=network, participant=participant)


import asyncio
import logging

logger = logging.getLogger(__name__)

class TaskRunner:
    def __init__(self, sandbox_pool, languages, checkers):
        self.sandbox_pool = sandbox_pool
        self.languages = languages
        self.checkers = checkers

    async def run(self, task):
        async with self.sandbox_pool.acquire() as box:
            language_name = task.submission.language_name
            checker_name = task.testcase.checker_name
            logger.info("Running %s, language %s, checker %s",
                    task, language_name, checker_name)
            lang = self.languages[language_name]
            check = self.checkers[checker_name]
            await lang.run_task(box, task)
            if task.verdict is not None:
                task.accepted = False
            else:
                await check.check(box, task)

Response:
<REPLACE_OLD> logger.debug("Running %s", task)
 <REPLACE_NEW> language_name = task.submission.language_name
            checker_name = task.testcase.checker_name
            logger.info("Running %s, language %s, checker %s",
                    task, language_name, checker_name)
 <REPLACE_END> <REPLACE_OLD> self.languages[task.submission.language_name]
 <REPLACE_NEW> self.languages[language_name]
 <REPLACE_END> <REPLACE_OLD> self.checkers[task.testcase.checker_name]
 <REPLACE_NEW> self.checkers[checker_name]
 <REPLACE_END> <|endoftext|> import asyncio
import logging

logger = logging.getLogger(__name__)

class TaskRunner:
    def __init__(self, sandbox_pool, languages, checkers):
        self.sandbox_pool = sandbox_pool
        self.languages = languages
        self.checkers = checkers

    async def run(self, task):
        async with self.sandbox_pool.acquire() as box:
            language_name = task.submission.language_name
            checker_name = task.testcase.checker_name
            logger.info("Running %s, language %s, checker %s",
                    task, language_name, checker_name)
            lang = self.languages[language_name]
            check = self.checkers[checker_name]
            await lang.run_task(box, task)
            if task.verdict is not None:
                task.accepted = False
            else:
                await check.check(box, task)

Prompt:
judge: Print running task, language and checker as INFO

import asyncio
import logging

logger = logging.getLogger(__name__)

class TaskRunner:
    def __init__(self, sandbox_pool, languages, checkers):
        self.sandbox_pool = sandbox_pool
        self.languages = languages
        self.checkers = checkers

    async def run(self, task):
        async with self.sandbox_pool.acquire() as box:
            logger.debug("Running %s", task)
            lang = self.languages[task.submission.language_name]
            check = self.checkers[task.testcase.checker_name]
            await lang.run_task(box, task)
            if task.verdict is not None:
                task.accepted = False
            else:
                await check.check(box, task)


import ConfigParser
import os
import unittest
from pyramid.config import Configurator
from pyramid import testing

global_config = {}

ini = ConfigParser.ConfigParser()

# we need to pull the right ini for the test we want to run
# by default pullup test.ini, but we might want to test mysql, pgsql, etc
test_ini = os.environ.get('BOOKIE_TEST_INI', None)
if test_ini:
    ini.read(test_ini)
else:
    ini.read('test.ini')

settings = dict(ini.items('app:bookie'))

def setup_db(settings):
    """ We need to create the test sqlite database to run our tests against

    If the db exists, remove it
    We're using the SA-Migrations API to create the db and catch it up to the
    latest migration level for testing

    In theory, we could use this API to do version specific testing as well if
    we needed to.

    If we want to run any tests with a fresh db we can call this function

    """
    from migrate.versioning import api as mig
    sa_url = settings['sqlalchemy.url']
    migrate_repository = 'migrations'

    # we're hackish here since we're going to assume the test db is whatever is
    # after the last slash of the SA url sqlite:///somedb.db
    db_name = sa_url[sa_url.rindex('/') + 1:]
    try:
        os.remove(db_name)
    except:
        pass

    open(db_name, 'w').close()

    mig.version_control(sa_url, migrate_repository)
    mig.upgrade(sa_url, migrate_repository)

setup_db(settings)

Response:
<REPLACE_OLD> ConfigParser.ConfigParser()
ini.read('test.ini')
settings <REPLACE_NEW> ConfigParser.ConfigParser()

# we need to pull the right ini for the test we want to run
# by default pullup test.ini, but we might want to test mysql, pgsql, etc
test_ini = os.environ.get('BOOKIE_TEST_INI', None)
if test_ini:
    ini.read(test_ini)
else:
    ini.read('test.ini')

settings <REPLACE_END> <|endoftext|> import ConfigParser
import os
import unittest
from pyramid.config import Configurator
from pyramid import testing

global_config = {}

ini = ConfigParser.ConfigParser()

# we need to pull the right ini for the test we want to run
# by default pullup test.ini, but we might want to test mysql, pgsql, etc
test_ini = os.environ.get('BOOKIE_TEST_INI', None)
if test_ini:
    ini.read(test_ini)
else:
    ini.read('test.ini')

settings = dict(ini.items('app:bookie'))

def setup_db(settings):
    """ We need to create the test sqlite database to run our tests against

    If the db exists, remove it
    We're using the SA-Migrations API to create the db and catch it up to the
    latest migration level for testing

    In theory, we could use this API to do version specific testing as well if
    we needed to.

    If we want to run any tests with a fresh db we can call this function

    """
    from migrate.versioning import api as mig
    sa_url = settings['sqlalchemy.url']
    migrate_repository = 'migrations'

    # we're hackish here since we're going to assume the test db is whatever is
    # after the last slash of the SA url sqlite:///somedb.db
    db_name = sa_url[sa_url.rindex('/') + 1:]
    try:
        os.remove(db_name)
    except:
        pass

    open(db_name, 'w').close()

    mig.version_control(sa_url, migrate_repository)
    mig.upgrade(sa_url, migrate_repository)

setup_db(settings)

Prompt:
Add ability to set test ini via env variable

import ConfigParser
import os
import unittest
from pyramid.config import Configurator
from pyramid import testing

global_config = {}

ini = ConfigParser.ConfigParser()
ini.read('test.ini')
settings = dict(ini.items('app:bookie'))

def setup_db(settings):
    """ We need to create the test sqlite database to run our tests against

    If the db exists, remove it
    We're using the SA-Migrations API to create the db and catch it up to the
    latest migration level for testing

    In theory, we could use this API to do version specific testing as well if
    we needed to.

    If we want to run any tests with a fresh db we can call this function

    """
    from migrate.versioning import api as mig
    sa_url = settings['sqlalchemy.url']
    migrate_repository = 'migrations'

    # we're hackish here since we're going to assume the test db is whatever is
    # after the last slash of the SA url sqlite:///somedb.db
    db_name = sa_url[sa_url.rindex('/') + 1:]
    try:
        os.remove(db_name)
    except:
        pass

    open(db_name, 'w').close()

    mig.version_control(sa_url, migrate_repository)
    mig.upgrade(sa_url, migrate_repository)

setup_db(settings)


# This file contains the project wide settings. It is not
# part of version control and it should be adapted to
# suit each deployment.

from os import environ

# Use the absolute path to the directory that stores the data.
# This can differ per deployment
DATA_DIRECTORY = "/home/vagrant/code/clic-project/clic/dbs/dickens/data/"

#TODO: make the cache settings imported in api.py
CACHE_DIR = ""
CACHE_LOCK = ""

# Check whether there are local settings.
# If there are, then overwrite the above settings
# with the specific settings defined in the local settings

try:
    environ['CLIC_SETTINGS'] == 'local'
    from local_settings import *
    print 'Using the local settings (local_settings.py)'

except KeyError:
    print 'Using the standard settings file (settings.py)'

Response:
<REPLACE_OLD> "/cheshire3/clic/dbs/dickens/data/"

#TODO: <REPLACE_NEW> "/home/vagrant/code/clic-project/clic/dbs/dickens/data/"

#TODO: <REPLACE_END> <|endoftext|> # This file contains the project wide settings. It is not
# part of version control and it should be adapted to
# suit each deployment.

from os import environ

# Use the absolute path to the directory that stores the data.
# This can differ per deployment
DATA_DIRECTORY = "/home/vagrant/code/clic-project/clic/dbs/dickens/data/"

#TODO: make the cache settings imported in api.py
CACHE_DIR = ""
CACHE_LOCK = ""

# Check whether there are local settings.
# If there are, then overwrite the above settings
# with the specific settings defined in the local settings

try:
    environ['CLIC_SETTINGS'] == 'local'
    from local_settings import *
    print 'Using the local settings (local_settings.py)'

except KeyError:
    print 'Using the standard settings file (settings.py)'

Prompt:
Update the setting DATA_DIRECTORY to match the vagrant setup

# This file contains the project wide settings. It is not
# part of version control and it should be adapted to
# suit each deployment.

from os import environ

# Use the absolute path to the directory that stores the data.
# This can differ per deployment
DATA_DIRECTORY = "/cheshire3/clic/dbs/dickens/data/"

#TODO: make the cache settings imported in api.py
CACHE_DIR = ""
CACHE_LOCK = ""

# Check whether there are local settings.
# If there are, then overwrite the above settings
# with the specific settings defined in the local settings

try:
    environ['CLIC_SETTINGS'] == 'local'
    from local_settings import *
    print 'Using the local settings (local_settings.py)'

except KeyError:
    print 'Using the standard settings file (settings.py)'


Add whole image as an input

Add whole image as an input

Response:
<REPLACE_OLD> [70]
]
 <REPLACE_NEW> [70],
    [0,10,20,30,40,50,60,70]
]
 <REPLACE_END> <|endoftext|> #!/usr/bin/python2
# -*- coding: utf-8 -*-

pixval = {
    'hair': 10,
    'head': 20,
    'upper': 30,
    'arms': 40,
    'lower': 50,
    'legs': 60,
    'feet': 70
}

groups = [
    [10, 20],
    [30, 40],
    [50, 60],
    [70],
    [0,10,20,30,40,50,60,70]
]

Prompt:
Add whole image as an input

#!/usr/bin/python2
# -*- coding: utf-8 -*-

pixval = {
    'hair': 10,
    'head': 20,
    'upper': 30,
    'arms': 40,
    'lower': 50,
    'legs': 60,
    'feet': 70
}

groups = [
    [10, 20],
    [30, 40],
    [50, 60],
    [70]
]


"""Manage websocket connections."""
# -*- coding: utf-8 -*-
import json

from channels import Group
from channels.auth import channel_session_user_from_http, channel_session_user

from .models import Job

import json

@channel_session_user_from_http
def ws_connect(message):
    last_jobs = message.user.jobs.order_by('-modified')[:10]

    for job in last_jobs:
        message.reply_channel.send({
            'text': json.dumps({
                'job_id': job.id,
                'title': job.title,
                'status': job.status,
            }),
        })

    Group('job-user-{}'.format(message.user.username)).add(
        message.reply_channel,
    )

@channel_session_user
def ws_disconnect(message):
    Group('job-user-{}'.format(message.user.username)).discard(
        message.reply_channel,
    )

Send last jobs on initial connection

Send last jobs on initial connection

Response:
<REPLACE_OLD> Job

@channel_session_user_from_http
def <REPLACE_NEW> Job

import json

@channel_session_user_from_http
def <REPLACE_END> <INSERT>    last_jobs = message.user.jobs.order_by('-modified')[:10]

    for job in last_jobs:
     <INSERT_END> <REPLACE_OLD> 'accept': True,
 <REPLACE_NEW>     'text': json.dumps({
                'job_id': job.id,
                'title': job.title,
                'status': job.status,
            }),
     <REPLACE_END> <|endoftext|> """Manage websocket connections."""
# -*- coding: utf-8 -*-
import json

from channels import Group
from channels.auth import channel_session_user_from_http, channel_session_user

from .models import Job

import json

@channel_session_user_from_http
def ws_connect(message):
    last_jobs = message.user.jobs.order_by('-modified')[:10]

    for job in last_jobs:
        message.reply_channel.send({
            'text': json.dumps({
                'job_id': job.id,
                'title': job.title,
                'status': job.status,
            }),
        })

    Group('job-user-{}'.format(message.user.username)).add(
        message.reply_channel,
    )

@channel_session_user
def ws_disconnect(message):
    Group('job-user-{}'.format(message.user.username)).discard(
        message.reply_channel,
    )

Prompt:
Send last jobs on initial connection

"""Manage websocket connections."""
# -*- coding: utf-8 -*-
import json

from channels import Group
from channels.auth import channel_session_user_from_http, channel_session_user

from .models import Job

@channel_session_user_from_http
def ws_connect(message):
    message.reply_channel.send({
        'accept': True,
    })

    Group('job-user-{}'.format(message.user.username)).add(
        message.reply_channel,
    )

@channel_session_user
def ws_disconnect(message):
    Group('job-user-{}'.format(message.user.username)).discard(
        message.reply_channel,
    )


#!/usr/bin/env python

import setuptools

setuptools.setup(
    name='systemd-minecraft',
    description='A systemd service file for one or more vanilla Minecraft servers',
    author='Wurstmineberg',
    author_email='mail@wurstmineberg.de',
    py_modules=['minecraft'],
    install_requires=[
        'docopt',
        'loops',
        'mcrcon',
        'more-itertools',
        'requests'
    ],
    dependency_links=[
        'git+https://github.com/fenhl/python-loops.git#egg=loops',
        'git+https://github.com/wurstmineberg/MCRcon.git#egg=mcrcon'
    ]
)

Add dependency link for mcrcon

Add dependency link for mcrcon

Response:
<REPLACE_OLD> 'git+https://github.com/fenhl/python-loops.git#egg=loops'
 <REPLACE_NEW> 'git+https://github.com/fenhl/python-loops.git#egg=loops',
        'git+https://github.com/wurstmineberg/MCRcon.git#egg=mcrcon'
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import setuptools

setuptools.setup(
    name='systemd-minecraft',
    description='A systemd service file for one or more vanilla Minecraft servers',
    author='Wurstmineberg',
    author_email='mail@wurstmineberg.de',
    py_modules=['minecraft'],
    install_requires=[
        'docopt',
        'loops',
        'mcrcon',
        'more-itertools',
        'requests'
    ],
    dependency_links=[
        'git+https://github.com/fenhl/python-loops.git#egg=loops',
        'git+https://github.com/wurstmineberg/MCRcon.git#egg=mcrcon'
    ]
)

Prompt:
Add dependency link for mcrcon

#!/usr/bin/env python

import setuptools

setuptools.setup(
    name='systemd-minecraft',
    description='A systemd service file for one or more vanilla Minecraft servers',
    author='Wurstmineberg',
    author_email='mail@wurstmineberg.de',
    py_modules=['minecraft'],
    install_requires=[
        'docopt',
        'loops',
        'mcrcon',
        'more-itertools',
        'requests'
    ],
    dependency_links=[
        'git+https://github.com/fenhl/python-loops.git#egg=loops'
    ]
)


from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import csv
import datetime

from django.core.management.base import BaseCommand

from corehq.util.couch import IterDB
from corehq.util.log import with_progress_bar
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    help = ("Save a bunch of couch documents so they are re-sent to kafka. "
            "Pass in a file with one doc id per line")

    def add_arguments(self, parser):
        parser.add_argument('ids_file')

    def handle(self, ids_file, **options):
        with open(ids_file) as f:
            doc_ids = [line.strip() for line in f]

        db = XFormInstance.get_db()  # Both forms and cases are in here
        with IterDB(db) as iter_db:
            for doc in iter_docs(db, with_progress_bar(doc_ids)):
                iter_db.save(doc)

        print("{} docs saved".format(len(iter_db.saved_ids)))
        print("{} docs errored".format(len(iter_db.error_ids)))
        not_found = len(doc_ids) - len(iter_db.saved_ids) - len(iter_db.error_ids)
        print("{} docs not found".format(not_found))

        filename = '_{}.csv'.format(ids_file, datetime.datetime.now())
        with open(filename, 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['doc_id', 'status'])
            for doc_id in doc_ids:
                if doc_id in iter_db.saved_ids:
                    status = "saved"
                elif iter_db.error_ids:
                    status = "errored"
                else:
                    status = "not_found"
                writer.writerow([doc_id, status])

        print("Saved results to {}".format(filename))

Add mgmt cmd to re-save a list of form/case IDs

https://manage.dimagi.com/default.asp?263644

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import csv
import datetime

from django.core.management.base import BaseCommand

from corehq.util.couch import IterDB
from corehq.util.log import with_progress_bar
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    help = ("Save a bunch of couch documents so they are re-sent to kafka. "
            "Pass in a file with one doc id per line")

    def add_arguments(self, parser):
        parser.add_argument('ids_file')

    def handle(self, ids_file, **options):
        with open(ids_file) as f:
            doc_ids = [line.strip() for line in f]

        db = XFormInstance.get_db()  # Both forms and cases are in here
        with IterDB(db) as iter_db:
            for doc in iter_docs(db, with_progress_bar(doc_ids)):
                iter_db.save(doc)

        print("{} docs saved".format(len(iter_db.saved_ids)))
        print("{} docs errored".format(len(iter_db.error_ids)))
        not_found = len(doc_ids) - len(iter_db.saved_ids) - len(iter_db.error_ids)
        print("{} docs not found".format(not_found))

        filename = '_{}.csv'.format(ids_file, datetime.datetime.now())
        with open(filename, 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['doc_id', 'status'])
            for doc_id in doc_ids:
                if doc_id in iter_db.saved_ids:
                    status = "saved"
                elif iter_db.error_ids:
                    status = "errored"
                else:
                    status = "not_found"
                writer.writerow([doc_id, status])

        print("Saved results to {}".format(filename))
 <REPLACE_END> <|endoftext|> from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import csv
import datetime

from django.core.management.base import BaseCommand

from corehq.util.couch import IterDB
from corehq.util.log import with_progress_bar
from couchforms.models import XFormInstance
from dimagi.utils.couch.database import iter_docs

class Command(BaseCommand):
    help = ("Save a bunch of couch documents so they are re-sent to kafka. "
            "Pass in a file with one doc id per line")

    def add_arguments(self, parser):
        parser.add_argument('ids_file')

    def handle(self, ids_file, **options):
        with open(ids_file) as f:
            doc_ids = [line.strip() for line in f]

        db = XFormInstance.get_db()  # Both forms and cases are in here
        with IterDB(db) as iter_db:
            for doc in iter_docs(db, with_progress_bar(doc_ids)):
                iter_db.save(doc)

        print("{} docs saved".format(len(iter_db.saved_ids)))
        print("{} docs errored".format(len(iter_db.error_ids)))
        not_found = len(doc_ids) - len(iter_db.saved_ids) - len(iter_db.error_ids)
        print("{} docs not found".format(not_found))

        filename = '_{}.csv'.format(ids_file, datetime.datetime.now())
        with open(filename, 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['doc_id', 'status'])
            for doc_id in doc_ids:
                if doc_id in iter_db.saved_ids:
                    status = "saved"
                elif iter_db.error_ids:
                    status = "errored"
                else:
                    status = "not_found"
                writer.writerow([doc_id, status])

        print("Saved results to {}".format(filename))

Prompt:
Add mgmt cmd to re-save a list of form/case IDs

https://manage.dimagi.com/default.asp?263644


"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.core.management.base import BaseCommand
from django.db import connection

class Command(BaseCommand):
    """
    Usage:
    python manage.py update_coordinate_names
    """
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        sql = """
        UPDATE rnc_coordinates a
        SET
        	name = b.ensembl_name,
        	primary_start = local_start,
        	primary_end = local_end
        FROM ensembl_insdc_mapping b
        WHERE
          a.primary_accession = b.insdc
          AND a.name IS NULL
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)

Add management command for updating genome coordinate names using Ensembl-INSDC mapping

Response:
<REPLACE_OLD>  <REPLACE_NEW> """
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.core.management.base import BaseCommand
from django.db import connection

class Command(BaseCommand):
    """
    Usage:
    python manage.py update_coordinate_names
    """
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        sql = """
        UPDATE rnc_coordinates a
        SET
        	name = b.ensembl_name,
        	primary_start = local_start,
        	primary_end = local_end
        FROM ensembl_insdc_mapping b
        WHERE
          a.primary_accession = b.insdc
          AND a.name IS NULL
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)
 <REPLACE_END> <|endoftext|> """
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.core.management.base import BaseCommand
from django.db import connection

class Command(BaseCommand):
    """
    Usage:
    python manage.py update_coordinate_names
    """
    def handle(self, *args, **options):
        """
        Main function, called by django.
        """
        sql = """
        UPDATE rnc_coordinates a
        SET
        	name = b.ensembl_name,
        	primary_start = local_start,
        	primary_end = local_end
        FROM ensembl_insdc_mapping b
        WHERE
          a.primary_accession = b.insdc
          AND a.name IS NULL
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)

Prompt: Add management command for updating genome coordinate names using Ensembl-INSDC mapping


from oauthlib.common import generate_client_id as oauthlib_generate_client_id

from .settings import oauth2_settings

CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

class BaseHashGenerator(object):
    """
    All generators should extend this class overriding `.hash()` method.
    """
    def hash(self):
        raise NotImplementedError()

class ClientIdGenerator(BaseHashGenerator):
    def hash(self):
        """
        Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2
        for Basic Authentication scheme
        """
        client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "")
        return oauthlib_generate_client_id(length=40, chars=client_id_charset)

class ClientSecretGenerator(BaseHashGenerator):
    def hash(self):
        return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET)

def generate_client_id():
    """
    Generate a suitable client id
    """
    client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS()
    return client_id_generator.hash()

def generate_client_secret():
    """
    Generate a suitable client secret
    """
    client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS()
    return client_secret_generator.hash()

Response:
<DELETE> CLIENT_ID_CHARACTER_SET, <DELETE_END> <REPLACE_OLD> oauth2_settings

class <REPLACE_NEW> oauth2_settings

CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

class <REPLACE_END> <REPLACE_OLD> oauthlib_generate_client_id(length=128)

def <REPLACE_NEW> oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET)

def <REPLACE_END> <|endoftext|> from oauthlib.common import generate_client_id as oauthlib_generate_client_id

from .settings import oauth2_settings

CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

class BaseHashGenerator(object):
    """
    All generators should extend this class overriding `.hash()` method.
    """
    def hash(self):
        raise NotImplementedError()

class ClientIdGenerator(BaseHashGenerator):
    def hash(self):
        """
        Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2
        for Basic Authentication scheme
        """
        client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "")
        return oauthlib_generate_client_id(length=40, chars=client_id_charset)

class ClientSecretGenerator(BaseHashGenerator):
    def hash(self):
        return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET)

def generate_client_id():
    """
    Generate a suitable client id
    """
    client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS()
    return client_id_generator.hash()

def generate_client_secret():
    """
    Generate a suitable client secret
    """
    client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS()
    return client_secret_generator.hash()

Prompt:
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations

from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id

from .settings import oauth2_settings

class BaseHashGenerator(object):
    """
    All generators should extend this class overriding `.hash()` method.
    """
    def hash(self):
        raise NotImplementedError()

class ClientIdGenerator(BaseHashGenerator):
    def hash(self):
        """
        Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2
        for Basic Authentication scheme
        """
        client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "")
        return oauthlib_generate_client_id(length=40, chars=client_id_charset)

class ClientSecretGenerator(BaseHashGenerator):
    def hash(self):
        return oauthlib_generate_client_id(length=128)

def generate_client_id():
    """
    Generate a suitable client id
    """
    client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS()
    return client_id_generator.hash()

def generate_client_secret():
    """
    Generate a suitable client secret
    """
    client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS()
    return client_secret_generator.hash()


from nazs import module
from nazs.commands import run
from nazs.sudo import root

import os
import logging

from .models import DomainSettings

logger = logging.getLogger(__name__)

class Samba(module.Module):
    """
    Samba 4 module, it deploys samba AD and file server
    """
    ETC_FILE = '/etc/samba/smb.conf'

    install_wizard = 'samba:install'

    def install(self):
        """
        Installation procedure, it writes basic smb.conf and uses samba-tool to
        provision the domain
        """
        domain_settings = DomainSettings.get()

        with root():
            if os.path.exists(self.ETC_FILE):
                os.remove(self.ETC_FILE)

            if domain_settings.mode == 'ad':
                run("samba-tool domain provision "
                    " --domain='zentyal' "
                    " --workgroup='zentyal' "
                    "--realm='zentyal.lan' "
                    "--use-xattrs=yes "
                    "--use-rfc2307 "
                    "--server-role='domain controller' "
                    "--use-ntvfs "
                    "--adminpass='foobar1!'")

            elif domain_settings.mode == 'member':
                # TODO
                pass

Response:
<REPLACE_OLD> logging

logger <REPLACE_NEW> logging

from .models import DomainSettings

logger <REPLACE_END> <INSERT> domain_settings = DomainSettings.get()

        <INSERT_END> <INSERT>            if domain_settings.mode == 'ad':
     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> "--adminpass='foobar1!'")
 <REPLACE_NEW>     "--adminpass='foobar1!'")

            elif domain_settings.mode == 'member':
                # TODO
                pass
 <REPLACE_END> <|endoftext|> from nazs import module
from nazs.commands import run
from nazs.sudo import root

import os
import logging

from .models import DomainSettings

logger = logging.getLogger(__name__)

class Samba(module.Module):
    """
    Samba 4 module, it deploys samba AD and file server
    """
    ETC_FILE = '/etc/samba/smb.conf'

    install_wizard = 'samba:install'

    def install(self):
        """
        Installation procedure, it writes basic smb.conf and uses samba-tool to
        provision the domain
        """
        domain_settings = DomainSettings.get()

        with root():
            if os.path.exists(self.ETC_FILE):
                os.remove(self.ETC_FILE)

            if domain_settings.mode == 'ad':
                run("samba-tool domain provision "
                    " --domain='zentyal' "
                    " --workgroup='zentyal' "
                    "--realm='zentyal.lan' "
                    "--use-xattrs=yes "
                    "--use-rfc2307 "
                    "--server-role='domain controller' "
                    "--use-ntvfs "
                    "--adminpass='foobar1!'")

            elif domain_settings.mode == 'member':
                # TODO
                pass

Prompt:
Use wizard settings during samba provision

from nazs import module
from nazs.commands import run
from nazs.sudo import root

import os
import logging

logger = logging.getLogger(__name__)

class Samba(module.Module):
    """
    Samba 4 module, it deploys samba AD and file server
    """
    ETC_FILE = '/etc/samba/smb.conf'

    install_wizard = 'samba:install'

    def install(self):
        """
        Installation procedure, it writes basic smb.conf and uses samba-tool to
        provision the domain
        """
        with root():
            if os.path.exists(self.ETC_FILE):
                os.remove(self.ETC_FILE)

            run("samba-tool domain provision "
                " --domain='zentyal' "
                " --workgroup='zentyal' "
                "--realm='zentyal.lan' "
                "--use-xattrs=yes "
                "--use-rfc2307 "
                "--server-role='domain controller' "
                "--use-ntvfs "
                "--adminpass='foobar1!'")


import logging
import pandas as pd
import pymongo

import emission.core.get_database as edb
import emission.storage.timeseries.builtin_timeseries as bits

class AggregateTimeSeries(bits.BuiltinTimeSeries):
    def __init__(self):
        super(AggregateTimeSeries, self).__init__(None)
        self.user_query = {}

    def _get_sort_key(self, time_query = None):
        return None

Response:
<INSERT>    def _get_sort_key(self, time_query = None):
        return None
 <INSERT_END> <|endoftext|> import logging
import pandas as pd
import pymongo

import emission.core.get_database as edb
import emission.storage.timeseries.builtin_timeseries as bits

class AggregateTimeSeries(bits.BuiltinTimeSeries):
    def __init__(self):
        super(AggregateTimeSeries, self).__init__(None)
        self.user_query = {}

    def _get_sort_key(self, time_query = None):
        return None

Prompt:
Implement a sort key method for the aggregate timeseries

This should return null because we want to mix up the identifying information
from the timeseries and sorting will re-impose some order. Also sorting takes
too much time!

import logging
import pandas as pd
import pymongo

import emission.core.get_database as edb
import emission.storage.timeseries.builtin_timeseries as bits

class AggregateTimeSeries(bits.BuiltinTimeSeries):
    def __init__(self):
        super(AggregateTimeSeries, self).__init__(None)
        self.user_query = {}


from unittest.main import main

if __name__ == '__main__':
	main(module=None, verbosity=2)

Drop Python 2 support in tests

Drop Python 2 support in tests

Response:
<REPLACE_OLD> import sys
import unittest

def main():
	if sys.version_info[0] >= 3:
		from <REPLACE_NEW> from <REPLACE_END> <REPLACE_OLD> main
		main(module=None)
	else:
		unittest.main()

if <REPLACE_NEW> main

if <REPLACE_END> <REPLACE_OLD> '__main__':
	main()
 <REPLACE_NEW> '__main__':
	main(module=None, verbosity=2)
 <REPLACE_END> <|endoftext|> from unittest.main import main

if __name__ == '__main__':
	main(module=None, verbosity=2)

Prompt:
Drop Python 2 support in tests

import sys
import unittest

def main():
	if sys.version_info[0] >= 3:
		from unittest.main import main
		main(module=None)
	else:
		unittest.main()

if __name__ == '__main__':
	main()


from . import data_structures

# 1. Stack application
def balanced_parentheses_checker(symbol_string):
    """Verify that a set of parentheses is balanced."""

    opening_symbols = '{[('
    closing_symbols = '}])'

    opening_symbols_stack = data_structures.Stack()
    symbol_count = len(symbol_string)
    counter = 0

    while counter < symbol_count:
        current_symbol = symbol_string[counter]
        if current_symbol in '{[(':
            opening_symbols_stack.push(current_symbol)
        else:
            if not opening_symbols_stack.is_empty() and \
            opening_symbols.index(opening_symbols_stack.peek()) == \
            closing_symbols.index(current_symbol):
                opening_symbols_stack.pop()
            else:
                counter = symbol_count

        counter += 1

    return opening_symbols_stack.is_empty() and counter == symbol_count

if __name__ == '__main__':
    print(balanced_parentheses_checker('[]{[]{([][])}()}'))

Apply stack in providing an efficient balanced parentheses-checker

Response:
<REPLACE_OLD>  <REPLACE_NEW> from . import data_structures

# 1. Stack application
def balanced_parentheses_checker(symbol_string):
    """Verify that a set of parentheses is balanced."""

    opening_symbols = '{[('
    closing_symbols = '}])'

    opening_symbols_stack = data_structures.Stack()
    symbol_count = len(symbol_string)
    counter = 0

    while counter < symbol_count:
        current_symbol = symbol_string[counter]
        if current_symbol in '{[(':
            opening_symbols_stack.push(current_symbol)
        else:
            if not opening_symbols_stack.is_empty() and \
            opening_symbols.index(opening_symbols_stack.peek()) == \
            closing_symbols.index(current_symbol):
                opening_symbols_stack.pop()
            else:
                counter = symbol_count

        counter += 1

    return opening_symbols_stack.is_empty() and counter == symbol_count

if __name__ == '__main__':
    print(balanced_parentheses_checker('[]{[]{([][])}()}'))
 <REPLACE_END> <|endoftext|> from . import data_structures

# 1. Stack application
def balanced_parentheses_checker(symbol_string):
    """Verify that a set of parentheses is balanced."""

    opening_symbols = '{[('
    closing_symbols = '}])'

    opening_symbols_stack = data_structures.Stack()
    symbol_count = len(symbol_string)
    counter = 0

    while counter < symbol_count:
        current_symbol = symbol_string[counter]
        if current_symbol in '{[(':
            opening_symbols_stack.push(current_symbol)
        else:
            if not opening_symbols_stack.is_empty() and \
            opening_symbols.index(opening_symbols_stack.peek()) == \
            closing_symbols.index(current_symbol):
                opening_symbols_stack.pop()
            else:
                counter = symbol_count

        counter += 1

    return opening_symbols_stack.is_empty() and counter == symbol_count

if __name__ == '__main__':
    print(balanced_parentheses_checker('[]{[]{([][])}()}'))

Prompt: Apply stack in providing an efficient balanced parentheses-checker


from django.db.models import Model, CharField, Field

class MaxLengthCharField(CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        super().__init__(*args, **kwargs)

class BaseModel(Model):
    class Meta:
        abstract = True

    def _get_explicit_field_names(self):
        return [field.name for field in self._meta.get_fields()
                if isinstance(field, Field) and field.name != 'id']

    def to_dict(self):
        fields = self._get_explicit_field_names()
        return {field: getattr(self, field) for field in fields}

    def __repr__(self):
        model = str(self.__class__.__name__)
        columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
        return '{}({})'.format(model, columns)

Add columns and values to repr

Add columns and values to repr

Response:
<INSERT> model = str(self.__class__.__name__)
        columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
        <INSERT_END> <REPLACE_OLD> 'Model({})'.format(repr(self.to_dict()))
 <REPLACE_NEW> '{}({})'.format(model, columns)
 <REPLACE_END> <|endoftext|> from django.db.models import Model, CharField, Field

class MaxLengthCharField(CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        super().__init__(*args, **kwargs)

class BaseModel(Model):
    class Meta:
        abstract = True

    def _get_explicit_field_names(self):
        return [field.name for field in self._meta.get_fields()
                if isinstance(field, Field) and field.name != 'id']

    def to_dict(self):
        fields = self._get_explicit_field_names()
        return {field: getattr(self, field) for field in fields}

    def __repr__(self):
        model = str(self.__class__.__name__)
        columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
        return '{}({})'.format(model, columns)

Prompt:
Add columns and values to repr

from django.db.models import Model, CharField, Field

class MaxLengthCharField(CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        super().__init__(*args, **kwargs)

class BaseModel(Model):
    class Meta:
        abstract = True

    def _get_explicit_field_names(self):
        return [field.name for field in self._meta.get_fields()
                if isinstance(field, Field) and field.name != 'id']

    def to_dict(self):
        fields = self._get_explicit_field_names()
        return {field: getattr(self, field) for field in fields}

    def __repr__(self):
        return 'Model({})'.format(repr(self.to_dict()))


# This module contains built-in introspector plugins for various common
# Django apps.

# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions
import south.introspection_plugins.annoying_autoonetoone

Add import of django-annoying patch

Add import of django-annoying patch

Response:
<REPLACE_OLD> south.introspection_plugins.django_objectpermissions

 <REPLACE_NEW> south.introspection_plugins.django_objectpermissions
import south.introspection_plugins.annoying_autoonetoone

 <REPLACE_END> <|endoftext|> # This module contains built-in introspector plugins for various common
# Django apps.

# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions
import south.introspection_plugins.annoying_autoonetoone

Prompt:
Add import of django-annoying patch

# This module contains built-in introspector plugins for various common
# Django apps.

# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_objectpermissions


def bot_says(channel, text, slack_client):
    return slack_client.api_call("chat.postMessage",
                                 channel=channel,
                                 text=text,
                                 as_user=True)

def compose_explanation(url):
    return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)

def ask_confirmation(message, slack_client):
    bot_says(message['channel'],
             compose_explanation(message['url']),
             slack_client)

def compose_url_list(url_cache_list):
    if len(url_cache_list) == 0:
        return "The list is empty"

    intro = "The list of urls to be confirmed is: \n"
    options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)]

    return intro + "\n".join(options)

def list_cached_urls(url_cache_list, channel, slack_client):
    bot_says(channel,
             compose_url_list(url_cache_list),
             slack_client)

Response:
<REPLACE_OLD> list_message <REPLACE_NEW> intro <REPLACE_END> <REPLACE_OLD> \n"

    <REPLACE_NEW> \n"
    options = ["{} - {}".format(i, v['url']) <REPLACE_END> <REPLACE_OLD> index <REPLACE_NEW> i, v <REPLACE_END> <REPLACE_OLD> range(0, len(url_cache_list)):
        extra = "{} - {} \n".format(index, url_cache_list[index]['url'])
        list_message = list_message <REPLACE_NEW> enumerate(url_cache_list)]

    return intro <REPLACE_END> <REPLACE_OLD> extra

    return list_message

def <REPLACE_NEW> "\n".join(options)

def <REPLACE_END> <|endoftext|> def bot_says(channel, text, slack_client):
    return slack_client.api_call("chat.postMessage",
                                 channel=channel,
                                 text=text,
                                 as_user=True)

def compose_explanation(url):
    return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)

def ask_confirmation(message, slack_client):
    bot_says(message['channel'],
             compose_explanation(message['url']),
             slack_client)

def compose_url_list(url_cache_list):
    if len(url_cache_list) == 0:
        return "The list is empty"

    intro = "The list of urls to be confirmed is: \n"
    options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)]

    return intro + "\n".join(options)

def list_cached_urls(url_cache_list, channel, slack_client):
    bot_says(channel,
             compose_url_list(url_cache_list),
             slack_client)

Prompt:
refactor: Change iteration over a collection based on ags suggestion

def bot_says(channel, text, slack_client):
    return slack_client.api_call("chat.postMessage",
                                 channel=channel,
                                 text=text,
                                 as_user=True)

def compose_explanation(url):
    return "If you would like {} to be stored please react to it with a :+1:, \
if you would like it to be ignored use :-1:".format(url)

def ask_confirmation(message, slack_client):
    bot_says(message['channel'],
             compose_explanation(message['url']),
             slack_client)

def compose_url_list(url_cache_list):
    if len(url_cache_list) == 0:
        return "The list is empty"

    list_message = "The list of urls to be confirmed is: \n"

    for index in range(0, len(url_cache_list)):
        extra = "{} - {} \n".format(index, url_cache_list[index]['url'])
        list_message = list_message + extra

    return list_message

def list_cached_urls(url_cache_list, channel, slack_client):
    bot_says(channel,
             compose_url_list(url_cache_list),
             slack_client)


# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository

class CodeSearchResult(GitHubCore):
    def __init__(self, data, session=None):
        super(CodeSearchResult, self).__init__(data, session)
        self._api = data.get('url')
        #: Filename the match occurs in
        self.name = data.get('name')
        #: Path in the repository to the file
        self.path = data.get('path')
        #: SHA in which the code can be found
        self.sha = data.get('sha')
        #: URL to the Git blob endpoint
        self.git_url = data.get('git_url')
        #: URL to the HTML view of the blob
        self.html_url = data.get('html_url')
        #: Repository the code snippet belongs to
        self.repository = Repository(data.get('repository', {}), self)
        #: Score of the result
        self.score = data.get('score')
        #: Text matches
        self.text_matches = data.get('text_matches', [])

    def __repr__(self):
        return '<CodeSearchResult [{0}]>'.format(self.path)

Add a __repr__ for CodeSearchResult

Add a __repr__ for CodeSearchResult

Response:
<REPLACE_OLD> [])
 <REPLACE_NEW> [])

    def __repr__(self):
        return '<CodeSearchResult [{0}]>'.format(self.path)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository

class CodeSearchResult(GitHubCore):
    def __init__(self, data, session=None):
        super(CodeSearchResult, self).__init__(data, session)
        self._api = data.get('url')
        #: Filename the match occurs in
        self.name = data.get('name')
        #: Path in the repository to the file
        self.path = data.get('path')
        #: SHA in which the code can be found
        self.sha = data.get('sha')
        #: URL to the Git blob endpoint
        self.git_url = data.get('git_url')
        #: URL to the HTML view of the blob
        self.html_url = data.get('html_url')
        #: Repository the code snippet belongs to
        self.repository = Repository(data.get('repository', {}), self)
        #: Score of the result
        self.score = data.get('score')
        #: Text matches
        self.text_matches = data.get('text_matches', [])

    def __repr__(self):
        return '<CodeSearchResult [{0}]>'.format(self.path)

Prompt:
Add a __repr__ for CodeSearchResult

# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository

class CodeSearchResult(GitHubCore):
    def __init__(self, data, session=None):
        super(CodeSearchResult, self).__init__(data, session)
        self._api = data.get('url')
        #: Filename the match occurs in
        self.name = data.get('name')
        #: Path in the repository to the file
        self.path = data.get('path')
        #: SHA in which the code can be found
        self.sha = data.get('sha')
        #: URL to the Git blob endpoint
        self.git_url = data.get('git_url')
        #: URL to the HTML view of the blob
        self.html_url = data.get('html_url')
        #: Repository the code snippet belongs to
        self.repository = Repository(data.get('repository', {}), self)
        #: Score of the result
        self.score = data.get('score')
        #: Text matches
        self.text_matches = data.get('text_matches', [])


"""A set of utility functions to evaluate expressions.

Sample Usage:
    print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
    print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
    t = tb.SgTable()
    t.SetFields(["a", "bb", "ccc"])
    t.Append([1, 2, 3])
    t.Append([2, 4, 6])
    print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
"""

import table as tb

class SgExpressionEvaluator:
    """A set of utility functions to evaluate expressions."""

    @staticmethod
    def EvaluateExpressionInRow(fields, row, expr):
        """
        Evaluates the results of an expression (presumably a non-terminal field)
        given a list of fields and the values of a row.
        """

        # TODO(lnishan): This works for now, but in the future we might want to implement
        # a proper evaluator (correct tokenization, 2-stack evaluation)
        pairs = zip(fields, row)
        pairs.sort(key=lambda p: len(p[0]), reverse=True)
        for pair in pairs:
            expr = expr.replace(pair[0], str(pair[1]))
        return eval(expr)

    @staticmethod
    def EvaluateExpressionsInRow(fields, row, exprs):
        return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs]

    @staticmethod
    def EvaluateExpressionsInTable(table, exprs):
        ret = tb.SgTable()
        ret.SetFields(exprs)
        for row in table:
            ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs))
        return ret

Add SgExpressionEvaluator - Evaluates expressions given fields and values

Response:
<REPLACE_OLD>  <REPLACE_NEW> """A set of utility functions to evaluate expressions.

Sample Usage:
    print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
    print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
    t = tb.SgTable()
    t.SetFields(["a", "bb", "ccc"])
    t.Append([1, 2, 3])
    t.Append([2, 4, 6])
    print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
"""

import table as tb

class SgExpressionEvaluator:
    """A set of utility functions to evaluate expressions."""

    @staticmethod
    def EvaluateExpressionInRow(fields, row, expr):
        """
        Evaluates the results of an expression (presumably a non-terminal field)
        given a list of fields and the values of a row.
        """

        # TODO(lnishan): This works for now, but in the future we might want to implement
        # a proper evaluator (correct tokenization, 2-stack evaluation)
        pairs = zip(fields, row)
        pairs.sort(key=lambda p: len(p[0]), reverse=True)
        for pair in pairs:
            expr = expr.replace(pair[0], str(pair[1]))
        return eval(expr)

    @staticmethod
    def EvaluateExpressionsInRow(fields, row, exprs):
        return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs]

    @staticmethod
    def EvaluateExpressionsInTable(table, exprs):
        ret = tb.SgTable()
        ret.SetFields(exprs)
        for row in table:
            ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs))
        return ret
 <REPLACE_END> <|endoftext|> """A set of utility functions to evaluate expressions.

Sample Usage:
    print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
    print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
    t = tb.SgTable()
    t.SetFields(["a", "bb", "ccc"])
    t.Append([1, 2, 3])
    t.Append([2, 4, 6])
    print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
"""

import table as tb

class SgExpressionEvaluator:
    """A set of utility functions to evaluate expressions."""

    @staticmethod
    def EvaluateExpressionInRow(fields, row, expr):
        """
        Evaluates the results of an expression (presumably a non-terminal field)
        given a list of fields and the values of a row.
        """

        # TODO(lnishan): This works for now, but in the future we might want to implement
        # a proper evaluator (correct tokenization, 2-stack evaluation)
        pairs = zip(fields, row)
        pairs.sort(key=lambda p: len(p[0]), reverse=True)
        for pair in pairs:
            expr = expr.replace(pair[0], str(pair[1]))
        return eval(expr)

    @staticmethod
    def EvaluateExpressionsInRow(fields, row, exprs):
        return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs]

    @staticmethod
    def EvaluateExpressionsInTable(table, exprs):
        ret = tb.SgTable()
        ret.SetFields(exprs)
        for row in table:
            ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs))
        return ret

Prompt: Add SgExpressionEvaluator - Evaluates expressions given fields and values


""" Angr module """
# pylint: disable=wildcard-import

import logging
logging.getLogger("angr").addHandler(logging.NullHandler())

from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service import *
from .analyses import *
from .analysis import *
from .tablespecs import *
from . import surveyors
from .blade import Blade
from .simos import SimOS
from .path_group import PathGroup
from .surveyors.caller import Callable
from .log import Loggers
loggers = Loggers(logging.ERROR)

Make default logging level ERROR

Make default logging level ERROR

Response:
<REPLACE_OLD> Loggers()

 <REPLACE_NEW> Loggers(logging.ERROR)
 <REPLACE_END> <|endoftext|> """ Angr module """
# pylint: disable=wildcard-import

import logging
logging.getLogger("angr").addHandler(logging.NullHandler())

from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service import *
from .analyses import *
from .analysis import *
from .tablespecs import *
from . import surveyors
from .blade import Blade
from .simos import SimOS
from .path_group import PathGroup
from .surveyors.caller import Callable
from .log import Loggers
loggers = Loggers(logging.ERROR)

Prompt:
Make default logging level ERROR

""" Angr module """
# pylint: disable=wildcard-import

import logging
logging.getLogger("angr").addHandler(logging.NullHandler())

from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service import *
from .analyses import *
from .analysis import *
from .tablespecs import *
from . import surveyors
from .blade import Blade
from .simos import SimOS
from .path_group import PathGroup
from .surveyors.caller import Callable
from .log import Loggers
loggers = Loggers()


"""
The setup package to install MasterQA requirements
"""

from setuptools import setup, find_packages  # noqa
from os import path

this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
    with open(path.join(this_directory, 'README.md'), 'rb') as f:
        long_description = f.read().decode('utf-8')
except IOError:
    long_description = (
        'Automation-Assisted Manual Testing - http://masterqa.com')

setup(
    name='masterqa',
    version='1.1.5',
    description='Automation-Assisted Manual Testing - http://masterqa.com',
    long_description=long_description,
    long_description_content_type='text/markdown',
    platforms='Mac * Windows * Linux',
    url='http://masterqa.com',
    author='Michael Mintz',
    author_email='mdmintz@gmail.com',
    maintainer='Michael Mintz',
    license='The MIT License',
    install_requires=[
        'seleniumbase',
        ],
    packages=['masterqa'],
    entry_points={
        'nose.plugins': []
        }
    )

Fix description content type for PyPi

Fix description content type for PyPi

Response:
<INSERT> long_description_content_type='text/markdown',
    <INSERT_END> <|endoftext|> """
The setup package to install MasterQA requirements
"""

from setuptools import setup, find_packages  # noqa
from os import path

this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
    with open(path.join(this_directory, 'README.md'), 'rb') as f:
        long_description = f.read().decode('utf-8')
except IOError:
    long_description = (
        'Automation-Assisted Manual Testing - http://masterqa.com')

setup(
    name='masterqa',
    version='1.1.5',
    description='Automation-Assisted Manual Testing - http://masterqa.com',
    long_description=long_description,
    long_description_content_type='text/markdown',
    platforms='Mac * Windows * Linux',
    url='http://masterqa.com',
    author='Michael Mintz',
    author_email='mdmintz@gmail.com',
    maintainer='Michael Mintz',
    license='The MIT License',
    install_requires=[
        'seleniumbase',
        ],
    packages=['masterqa'],
    entry_points={
        'nose.plugins': []
        }
    )

Prompt:
Fix description content type for PyPi

"""
The setup package to install MasterQA requirements
"""

from setuptools import setup, find_packages  # noqa
from os import path

this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
    with open(path.join(this_directory, 'README.md'), 'rb') as f:
        long_description = f.read().decode('utf-8')
except IOError:
    long_description = (
        'Automation-Assisted Manual Testing - http://masterqa.com')

setup(
    name='masterqa',
    version='1.1.5',
    description='Automation-Assisted Manual Testing - http://masterqa.com',
    long_description=long_description,
    platforms='Mac * Windows * Linux',
    url='http://masterqa.com',
    author='Michael Mintz',
    author_email='mdmintz@gmail.com',
    maintainer='Michael Mintz',
    license='The MIT License',
    install_requires=[
        'seleniumbase',
        ],
    packages=['masterqa'],
    entry_points={
        'nose.plugins': []
        }
    )


from string import Template
from collections import defaultdict
import os
import yaml

def load_defaults():
    skipper_conf = 'skipper.yaml'
    defaults = {}
    if os.path.exists(skipper_conf):
        with open(skipper_conf) as confile:
            config = yaml.load(confile)
            containers = config.pop('containers', None)
        _normalize_config(config, defaults)
        if containers is not None:
            defaults['containers'] = containers
    return defaults

def _normalize_config(config, normalized_config):
    for key, value in config.iteritems():
        if isinstance(value, dict):
            normalized_config[key] = {}
            _normalize_config(value, normalized_config[key])
        elif isinstance(value, list):
            normalized_config[key] = [_interpolate_env_vars(x) for x in value]
        else:
            normalized_key = key.replace('-', '_')
            normalized_config[normalized_key] = _interpolate_env_vars(value)

def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))

Handle env vars in volumes

Handle env vars in volumes

Response:
<REPLACE_OLD> value
 <REPLACE_NEW> [_interpolate_env_vars(x) for x in value]
 <REPLACE_END> <|endoftext|> from string import Template
from collections import defaultdict
import os
import yaml

def load_defaults():
    skipper_conf = 'skipper.yaml'
    defaults = {}
    if os.path.exists(skipper_conf):
        with open(skipper_conf) as confile:
            config = yaml.load(confile)
            containers = config.pop('containers', None)
        _normalize_config(config, defaults)
        if containers is not None:
            defaults['containers'] = containers
    return defaults

def _normalize_config(config, normalized_config):
    for key, value in config.iteritems():
        if isinstance(value, dict):
            normalized_config[key] = {}
            _normalize_config(value, normalized_config[key])
        elif isinstance(value, list):
            normalized_config[key] = [_interpolate_env_vars(x) for x in value]
        else:
            normalized_key = key.replace('-', '_')
            normalized_config[normalized_key] = _interpolate_env_vars(value)

def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))

Prompt:
Handle env vars in volumes

from string import Template
from collections import defaultdict
import os
import yaml

def load_defaults():
    skipper_conf = 'skipper.yaml'
    defaults = {}
    if os.path.exists(skipper_conf):
        with open(skipper_conf) as confile:
            config = yaml.load(confile)
            containers = config.pop('containers', None)
        _normalize_config(config, defaults)
        if containers is not None:
            defaults['containers'] = containers
    return defaults

def _normalize_config(config, normalized_config):
    for key, value in config.iteritems():
        if isinstance(value, dict):
            normalized_config[key] = {}
            _normalize_config(value, normalized_config[key])
        elif isinstance(value, list):
            normalized_config[key] = value
        else:
            normalized_key = key.replace('-', '_')
            normalized_config[normalized_key] = _interpolate_env_vars(value)

def _interpolate_env_vars(key):
    return Template(key).substitute(defaultdict(lambda: "", os.environ))