"""
Data migration to convert absolute paths in block_structure.data to be relative.

This has only been tested with MySQL, though it should also work for Postgres as
well. This is necessary to manually correct absolute paths in the "data" field
of the block_structure table. For S3 storage, having a path that starts with
"/courses/" puts things in the same place as a path starting with "courses/",
but absolute paths are not permitted for FileFields.

These values would have always been broken in devstack (because it's not in
MEDIA_ROOT), but it used to work for the S3 storages option because the security
checking happened at the storage layer, and the path is equivalent in S3 because
we just append either value to the bucket's root.

However, in Django > 2.2.20, this checking against absolute paths has been added
to the FileField itself, and an upgrade attempt started causing write failures
to Block Structures.

There are separate PRs to fix the config values so that new writes start with a
"courses/" prefix. This migration to is fix old entries by removing any leading
"/" characters.

THIS MIGRATION MUST BE RUN BEFORE UPGRADING TO DJANGO > 2.2.20 IF YOU ARE
USING A STORAGE_CLASS IN BLOCK_STRUCTURES_SETTINGS. If you do not specify this
setting and only run Block Structures out of memcached, this should not affect
you.
"""

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('block_structure', '0004_blockstructuremodel_usagekeywithrun'),
    ]

    operations = [
        migrations.RunSQL(
            """
            UPDATE block_structure
                SET data = right(data, length(data) - 1)
                WHERE data like '/%';
            """
        )
    ]

fix: Convert block_structure.data to relative paths (TNL-8335)

In order to upgrade to Django > 2.2.20, we can't continue to use
absolute paths in the block_structure's data FileField. This used to
work for S3, but it will not work going forward due to a security fix
in Django 2.2.21.

This data migration will remove the starting '/' from any paths in the
block_structure table. The resulting locations in S3 should be
unaffected.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """
Data migration to convert absolute paths in block_structure.data to be relative.

This has only been tested with MySQL, though it should also work for Postgres as
well. This is necessary to manually correct absolute paths in the "data" field
of the block_structure table. For S3 storage, having a path that starts with
"/courses/" puts things in the same place as a path starting with "courses/",
but absolute paths are not permitted for FileFields.

These values would have always been broken in devstack (because it's not in
MEDIA_ROOT), but it used to work for the S3 storages option because the security
checking happened at the storage layer, and the path is equivalent in S3 because
we just append either value to the bucket's root.

However, in Django > 2.2.20, this checking against absolute paths has been added
to the FileField itself, and an upgrade attempt started causing write failures
to Block Structures.

There are separate PRs to fix the config values so that new writes start with a
"courses/" prefix. This migration to is fix old entries by removing any leading
"/" characters.

THIS MIGRATION MUST BE RUN BEFORE UPGRADING TO DJANGO > 2.2.20 IF YOU ARE
USING A STORAGE_CLASS IN BLOCK_STRUCTURES_SETTINGS. If you do not specify this
setting and only run Block Structures out of memcached, this should not affect
you.
"""

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('block_structure', '0004_blockstructuremodel_usagekeywithrun'),
    ]

    operations = [
        migrations.RunSQL(
            """
            UPDATE block_structure
                SET data = right(data, length(data) - 1)
                WHERE data like '/%';
            """
        )
    ]
 <REPLACE_END> <|endoftext|> """
Data migration to convert absolute paths in block_structure.data to be relative.

This has only been tested with MySQL, though it should also work for Postgres as
well. This is necessary to manually correct absolute paths in the "data" field
of the block_structure table. For S3 storage, having a path that starts with
"/courses/" puts things in the same place as a path starting with "courses/",
but absolute paths are not permitted for FileFields.

These values would have always been broken in devstack (because it's not in
MEDIA_ROOT), but it used to work for the S3 storages option because the security
checking happened at the storage layer, and the path is equivalent in S3 because
we just append either value to the bucket's root.

However, in Django > 2.2.20, this checking against absolute paths has been added
to the FileField itself, and an upgrade attempt started causing write failures
to Block Structures.

There are separate PRs to fix the config values so that new writes start with a
"courses/" prefix. This migration to is fix old entries by removing any leading
"/" characters.

THIS MIGRATION MUST BE RUN BEFORE UPGRADING TO DJANGO > 2.2.20 IF YOU ARE
USING A STORAGE_CLASS IN BLOCK_STRUCTURES_SETTINGS. If you do not specify this
setting and only run Block Structures out of memcached, this should not affect
you.
"""

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('block_structure', '0004_blockstructuremodel_usagekeywithrun'),
    ]

    operations = [
        migrations.RunSQL(
            """
            UPDATE block_structure
                SET data = right(data, length(data) - 1)
                WHERE data like '/%';
            """
        )
    ]

Prompt:
fix: Convert block_structure.data to relative paths (TNL-8335)

In order to upgrade to Django > 2.2.20, we can't continue to use
absolute paths in the block_structure's data FileField. This used to
work for S3, but it will not work going forward due to a security fix
in Django 2.2.21.

This data migration will remove the starting '/' from any paths in the
block_structure table. The resulting locations in S3 should be
unaffected.


"""Parse python code into the abstract syntax tree and represent as JSON"""
from __future__ import print_function
import ast
from itertools import chain, count
import json
import sys

def dictify(obj):
    if hasattr(obj, "__dict__"):
        result = {k: dictify(v) for k, v in chain(obj.__dict__.items(), [("classname", obj.__class__.__name__)])}
        return result
    elif isinstance(obj, list):
        return [dictify(x) for x in obj]
    else:
        return obj

def parse_file(filename):
    with open(filename) as f:
        source = f.read()
        return ast.parse(source, filename=filename, mode="exec")

def main(args):
    filename = args[0]
    if len(args) != 1 or filename.lower() in ("help", "h", "-h", "--help"):
        print(__doc__)
    else:
        ast_node = parse_file(filename)
        ast_dict = dictify(ast_node)
        ast_json = json.dumps(ast_dict, sort_keys=True, indent=4, separators=(',', ': '))
        print(ast_json)

if __name__ == "__main__":
    main(sys.argv[1:])

Add basic ast to json converter

Add basic ast to json converter

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Parse python code into the abstract syntax tree and represent as JSON"""
from __future__ import print_function
import ast
from itertools import chain, count
import json
import sys

def dictify(obj):
    if hasattr(obj, "__dict__"):
        result = {k: dictify(v) for k, v in chain(obj.__dict__.items(), [("classname", obj.__class__.__name__)])}
        return result
    elif isinstance(obj, list):
        return [dictify(x) for x in obj]
    else:
        return obj

def parse_file(filename):
    with open(filename) as f:
        source = f.read()
        return ast.parse(source, filename=filename, mode="exec")

def main(args):
    filename = args[0]
    if len(args) != 1 or filename.lower() in ("help", "h", "-h", "--help"):
        print(__doc__)
    else:
        ast_node = parse_file(filename)
        ast_dict = dictify(ast_node)
        ast_json = json.dumps(ast_dict, sort_keys=True, indent=4, separators=(',', ': '))
        print(ast_json)

if __name__ == "__main__":
    main(sys.argv[1:])
 <REPLACE_END> <|endoftext|> """Parse python code into the abstract syntax tree and represent as JSON"""
from __future__ import print_function
import ast
from itertools import chain, count
import json
import sys

def dictify(obj):
    if hasattr(obj, "__dict__"):
        result = {k: dictify(v) for k, v in chain(obj.__dict__.items(), [("classname", obj.__class__.__name__)])}
        return result
    elif isinstance(obj, list):
        return [dictify(x) for x in obj]
    else:
        return obj

def parse_file(filename):
    with open(filename) as f:
        source = f.read()
        return ast.parse(source, filename=filename, mode="exec")

def main(args):
    filename = args[0]
    if len(args) != 1 or filename.lower() in ("help", "h", "-h", "--help"):
        print(__doc__)
    else:
        ast_node = parse_file(filename)
        ast_dict = dictify(ast_node)
        ast_json = json.dumps(ast_dict, sort_keys=True, indent=4, separators=(',', ': '))
        print(ast_json)

if __name__ == "__main__":
    main(sys.argv[1:])

Prompt: Add basic ast to json converter


""" Helper classes """

import facebook
import requests as r

class FacebookData:
    def __init__(self, token):
        """
        :param token: Facebook Page token
        :param _api: Instance of the GraphAPI object
        """
        self.token = token
        self._api = facebook.GraphAPI(self.token)

    def get_user_name(self, _id):
        """
        :param _id: find user object by _id
        :return: first name of user, type -> str
        """
        if not isinstance(_id, str):
            raise ValueError('id must be a str')
        user = self._api.get_object(_id)
        return user['first_name'] if user else None

class WeatherData:
    """
    Class which collect weather data
    """
    def __init__(self, api_token):
        """
        :param api_token: Open Weather TOKEN
        """
        self.token = api_token

    def get_current_weather(self, city_name):
        """
        :param city_name: Open weather API, find by city name
        :return dictionary object with information

        for example:

        {'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
        """
        api_url = f'http://api.openweathermap.org' \
                  f'/data/2.5/weather?q={city_name}&APPID={self.token}'

        info = r.get(api_url).json()
        return info

class StackOverFlowData:
    params = {}

    def get_answer_by_title(self, title):
        pass

Response:
<REPLACE_OLD> info
 <REPLACE_NEW> info

class StackOverFlowData:
    params = {}

    def get_answer_by_title(self, title):
        pass
 <REPLACE_END> <|endoftext|> """ Helper classes """

import facebook
import requests as r

class FacebookData:
    def __init__(self, token):
        """
        :param token: Facebook Page token
        :param _api: Instance of the GraphAPI object
        """
        self.token = token
        self._api = facebook.GraphAPI(self.token)

    def get_user_name(self, _id):
        """
        :param _id: find user object by _id
        :return: first name of user, type -> str
        """
        if not isinstance(_id, str):
            raise ValueError('id must be a str')
        user = self._api.get_object(_id)
        return user['first_name'] if user else None

class WeatherData:
    """
    Class which collect weather data
    """
    def __init__(self, api_token):
        """
        :param api_token: Open Weather TOKEN
        """
        self.token = api_token

    def get_current_weather(self, city_name):
        """
        :param city_name: Open weather API, find by city name
        :return dictionary object with information

        for example:

        {'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
        """
        api_url = f'http://api.openweathermap.org' \
                  f'/data/2.5/weather?q={city_name}&APPID={self.token}'

        info = r.get(api_url).json()
        return info

class StackOverFlowData:
    params = {}

    def get_answer_by_title(self, title):
        pass

Prompt:
Add StackOverFlowData, not completed yet

""" Helper classes """

import facebook
import requests as r

class FacebookData:
    def __init__(self, token):
        """
        :param token: Facebook Page token
        :param _api: Instance of the GraphAPI object
        """
        self.token = token
        self._api = facebook.GraphAPI(self.token)

    def get_user_name(self, _id):
        """
        :param _id: find user object by _id
        :return: first name of user, type -> str
        """
        if not isinstance(_id, str):
            raise ValueError('id must be a str')
        user = self._api.get_object(_id)
        return user['first_name'] if user else None

class WeatherData:
    """
    Class which collect weather data
    """
    def __init__(self, api_token):
        """
        :param api_token: Open Weather TOKEN
        """
        self.token = api_token

    def get_current_weather(self, city_name):
        """
        :param city_name: Open weather API, find by city name
        :return dictionary object with information

        for example:

        {'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
        """
        api_url = f'http://api.openweathermap.org' \
                  f'/data/2.5/weather?q={city_name}&APPID={self.token}'

        info = r.get(api_url).json()
        return info


import asyncio
import io
import re

from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError

@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
    """
    Set the server icon to the given image.

    Example::

        /drawtext Hello there! | icon set

    Requires an input image.
    """
    attachment = await read_image(message)
    if not attachment:
        raise CommandError("No image is available to process.")

    def execute():
        width, height = attachment.image.size
        if width < 128 or height < 128:
            raise CommandError("Image is too small (128x128 minimum size).")
        buffer = io.BytesIO()
        attachment.image.save(buffer, "png")
        return buffer.getvalue()

    image_data = await asyncio.get_event_loop().run_in_executor(None, execute)

    try:
        await message.server.update(icon=image_data)
        return "Server icon updated."
    except ForbiddenError as e:
        raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))

Fix typo in docs for /icon set.

Fix typo in docs for /icon set.

Response:
<REPLACE_OLD> set icon

 <REPLACE_NEW> icon set

 <REPLACE_END> <|endoftext|> import asyncio
import io
import re

from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError

@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
    """
    Set the server icon to the given image.

    Example::

        /drawtext Hello there! | icon set

    Requires an input image.
    """
    attachment = await read_image(message)
    if not attachment:
        raise CommandError("No image is available to process.")

    def execute():
        width, height = attachment.image.size
        if width < 128 or height < 128:
            raise CommandError("Image is too small (128x128 minimum size).")
        buffer = io.BytesIO()
        attachment.image.save(buffer, "png")
        return buffer.getvalue()

    image_data = await asyncio.get_event_loop().run_in_executor(None, execute)

    try:
        await message.server.update(icon=image_data)
        return "Server icon updated."
    except ForbiddenError as e:
        raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))

Prompt:
Fix typo in docs for /icon set.

import asyncio
import io
import re

from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError

@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
    """
    Set the server icon to the given image.

    Example::

        /drawtext Hello there! | set icon

    Requires an input image.
    """
    attachment = await read_image(message)
    if not attachment:
        raise CommandError("No image is available to process.")

    def execute():
        width, height = attachment.image.size
        if width < 128 or height < 128:
            raise CommandError("Image is too small (128x128 minimum size).")
        buffer = io.BytesIO()
        attachment.image.save(buffer, "png")
        return buffer.getvalue()

    image_data = await asyncio.get_event_loop().run_in_executor(None, execute)

    try:
        await message.server.update(icon=image_data)
        return "Server icon updated."
    except ForbiddenError as e:
        raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))


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

import datetime
from subprocess import call

from ca import app, db, mail
from ca.models import Request

from flask import Flask, render_template
from flask_mail import Message

def mail_certificate(id, email):
    with app.app_context():
        msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email])
        msg.body = render_template('mail.txt')
        with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp:
            msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read())
        mail.send(msg)

for request in Request.query.filter(Request.generation_date == None).all():  # noqa
    prompt = "Do you want to generate a certificate for {}, {} ?"
    print(prompt.format(request.id, request.email))
    print("Type y to continue")
    confirm = input('>')
    if confirm in ['Y', 'y']:
        print('generating certificate')
        call([app.config['COMMAND_BUILD'], request.id, request.email])
        #call([app.config['COMMAND_MAIL'], request.id, request.email])
        mail_certificate(request.id, request.email)
        request.generation_date = datetime.date.today()
        db.session.commit()
        print()
    else:
        print('skipping generation \n')

Response:
<INSERT> with app.app_context():
        <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
from subprocess import call

from ca import app, db, mail
from ca.models import Request

from flask import Flask, render_template
from flask_mail import Message

def mail_certificate(id, email):
    with app.app_context():
        msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email])
        msg.body = render_template('mail.txt')
        with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp:
            msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read())
        mail.send(msg)

for request in Request.query.filter(Request.generation_date == None).all():  # noqa
    prompt = "Do you want to generate a certificate for {}, {} ?"
    print(prompt.format(request.id, request.email))
    print("Type y to continue")
    confirm = input('>')
    if confirm in ['Y', 'y']:
        print('generating certificate')
        call([app.config['COMMAND_BUILD'], request.id, request.email])
        #call([app.config['COMMAND_MAIL'], request.id, request.email])
        mail_certificate(request.id, request.email)
        request.generation_date = datetime.date.today()
        db.session.commit()
        print()
    else:
        print('skipping generation \n')

Prompt:
Add app.context() to populate context for render_template

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

import datetime
from subprocess import call

from ca import app, db, mail
from ca.models import Request

from flask import Flask, render_template
from flask_mail import Message

def mail_certificate(id, email):
    msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email])
    msg.body = render_template('mail.txt')
    with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp:
        msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read())
    mail.send(msg)

for request in Request.query.filter(Request.generation_date == None).all():  # noqa
    prompt = "Do you want to generate a certificate for {}, {} ?"
    print(prompt.format(request.id, request.email))
    print("Type y to continue")
    confirm = input('>')
    if confirm in ['Y', 'y']:
        print('generating certificate')
        call([app.config['COMMAND_BUILD'], request.id, request.email])
        #call([app.config['COMMAND_MAIL'], request.id, request.email])
        mail_certificate(request.id, request.email)
        request.generation_date = datetime.date.today()
        db.session.commit()
        print()
    else:
        print('skipping generation \n')


from setuptools.command.egg_info import egg_info
import subprocess
import time

class EggInfoFromGit(egg_info):
    """Tag the build with git commit timestamp.

    If a build tag has already been set (e.g., "egg_info -b", building
    from source package), leave it alone.
    """
    def git_timestamp_tag(self):
        gitinfo = subprocess.check_output(
            ['git', 'log', '--first-parent', '--max-count=1',
             '--format=format:%ct']).strip()
        return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))

    def tags(self):
        if self.tag_build is None:
            self.tag_build = self.git_timestamp_tag()
        return egg_info.tags(self)

Response:
<REPLACE_OLD> '--format=format:%ct', '..']).strip()
 <REPLACE_NEW> '--format=format:%ct']).strip()
 <REPLACE_END> <|endoftext|> from setuptools.command.egg_info import egg_info
import subprocess
import time

class EggInfoFromGit(egg_info):
    """Tag the build with git commit timestamp.

    If a build tag has already been set (e.g., "egg_info -b", building
    from source package), leave it alone.
    """
    def git_timestamp_tag(self):
        gitinfo = subprocess.check_output(
            ['git', 'log', '--first-parent', '--max-count=1',
             '--format=format:%ct']).strip()
        return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))

    def tags(self):
        if self.tag_build is None:
            self.tag_build = self.git_timestamp_tag()
        return egg_info.tags(self)

Prompt:
Fix Python packaging to use correct git log for package time/version stamps (2nd try)

from setuptools.command.egg_info import egg_info
import subprocess
import time

class EggInfoFromGit(egg_info):
    """Tag the build with git commit timestamp.

    If a build tag has already been set (e.g., "egg_info -b", building
    from source package), leave it alone.
    """
    def git_timestamp_tag(self):
        gitinfo = subprocess.check_output(
            ['git', 'log', '--first-parent', '--max-count=1',
             '--format=format:%ct', '..']).strip()
        return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))

    def tags(self):
        if self.tag_build is None:
            self.tag_build = self.git_timestamp_tag()
        return egg_info.tags(self)


"""File information"""
import os
import pwd
import hashlib

from .config import CONFIG

def reader(fo):
    """Generator which feeds bytes to the md5 hasher"""
    while True:
        b = fo.read(128)
        if len(b) > 0:
            yield b
        else:
            raise StopIteration()

def get_file_hash(path):
    """Get md5 hash of a file"""
    hasher = hashlib.new('md5')
    if os.path.isdir(path):
        return
    else:
        try:
            with open(path, mode='br') as infile:
                for b in reader(infile):
                    hasher.update(b)

            digest = hasher.hexdigest()
            return digest
        except PermissionError:
            return ''

def FileInfo(fd, link=False, important=False):
    """Hold information about a file"""
    stats = os.stat(fd, follow_symlinks=link)
    return {
        'path': os.path.abspath(fd),
        'mode': stats.st_mode,
        'uid': stats.st_uid,
        'username': pwd.getpwuid(stats.st_uid).pw_name,
        'size': stats.st_size,
        'lastmod': int(stats.st_ctime),
        'lastcheck': 0,
        'isfile': os.path.isfile(fd),
        'isdir': not os.path.isfile(fd),
        'important': os.path.splitext(fd)[1] in CONFIG.get('fileinfo', 'important'),
        'md5sum': get_file_hash(fd),
        'problems': set()
    }

Response:
<DELETE> time
import <DELETE_END> <DELETE> stat
import <DELETE_END> <DELETE> get_file_hash(path):
    """Get md5 hash of a file"""
    def <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <REPLACE_OLD> StopIteration()

 <REPLACE_NEW> StopIteration()

def get_file_hash(path):
    """Get md5 hash of a file"""
 <REPLACE_END> <|endoftext|> """File information"""
import os
import pwd
import hashlib

from .config import CONFIG

def reader(fo):
    """Generator which feeds bytes to the md5 hasher"""
    while True:
        b = fo.read(128)
        if len(b) > 0:
            yield b
        else:
            raise StopIteration()

def get_file_hash(path):
    """Get md5 hash of a file"""
    hasher = hashlib.new('md5')
    if os.path.isdir(path):
        return
    else:
        try:
            with open(path, mode='br') as infile:
                for b in reader(infile):
                    hasher.update(b)

            digest = hasher.hexdigest()
            return digest
        except PermissionError:
            return ''

def FileInfo(fd, link=False, important=False):
    """Hold information about a file"""
    stats = os.stat(fd, follow_symlinks=link)
    return {
        'path': os.path.abspath(fd),
        'mode': stats.st_mode,
        'uid': stats.st_uid,
        'username': pwd.getpwuid(stats.st_uid).pw_name,
        'size': stats.st_size,
        'lastmod': int(stats.st_ctime),
        'lastcheck': 0,
        'isfile': os.path.isfile(fd),
        'isdir': not os.path.isfile(fd),
        'important': os.path.splitext(fd)[1] in CONFIG.get('fileinfo', 'important'),
        'md5sum': get_file_hash(fd),
        'problems': set()
    }

Prompt:
Move reader() generator out of file hasher

"""File information"""
import os
import time
import pwd
import stat
import hashlib

from .config import CONFIG

def get_file_hash(path):
    """Get md5 hash of a file"""
    def reader(fo):
        """Generator which feeds bytes to the md5 hasher"""
        while True:
            b = fo.read(128)
            if len(b) > 0:
                yield b
            else:
                raise StopIteration()

    hasher = hashlib.new('md5')
    if os.path.isdir(path):
        return
    else:
        try:
            with open(path, mode='br') as infile:
                for b in reader(infile):
                    hasher.update(b)

            digest = hasher.hexdigest()
            return digest
        except PermissionError:
            return ''

def FileInfo(fd, link=False, important=False):
    """Hold information about a file"""
    stats = os.stat(fd, follow_symlinks=link)
    return {
        'path': os.path.abspath(fd),
        'mode': stats.st_mode,
        'uid': stats.st_uid,
        'username': pwd.getpwuid(stats.st_uid).pw_name,
        'size': stats.st_size,
        'lastmod': int(stats.st_ctime),
        'lastcheck': 0,
        'isfile': os.path.isfile(fd),
        'isdir': not os.path.isfile(fd),
        'important': os.path.splitext(fd)[1] in CONFIG.get('fileinfo', 'important'),
        'md5sum': get_file_hash(fd),
        'problems': set()
    }


from know_me import serializers

def test_create(user_factory):
    """
    Saving a serializer containing valid data should create a new
    profile.
    """
    user = user_factory()
    data = {
        'name': 'John',
        'quote': "Hi, I'm John",
        'welcome_message': 'This is my profile.',
    }

    serializer = serializers.ProfileListSerializer(data=data)
    assert serializer.is_valid()

    serializer.save(user=user)
    profile = user.profile

    assert profile.name == data['name']
    assert profile.quote == data['quote']
    assert profile.welcome_message == data['welcome_message']
    assert profile.user == user

def test_serialize(profile_factory):
    """
    Test serializing a profile.
    """
    profile = profile_factory()
    serializer = serializers.ProfileListSerializer(profile)

    expected = {
        'id': profile.id,
        'name': profile.name,
        'quote': profile.quote,
        'welcome_message': profile.welcome_message,
    }

    assert serializer.data == expected

Response:
<INSERT> test_create(user_factory):
    """
    Saving a serializer containing valid data should create a new
    profile.
    """
    user = user_factory()
    data = {
        'name': 'John',
        'quote': "Hi, I'm John",
        'welcome_message': 'This is my profile.',
    }

    serializer = serializers.ProfileListSerializer(data=data)
    assert serializer.is_valid()

    serializer.save(user=user)
    profile = user.profile

    assert profile.name == data['name']
    assert profile.quote == data['quote']
    assert profile.welcome_message == data['welcome_message']
    assert profile.user == user

def <INSERT_END> <|endoftext|> from know_me import serializers

def test_create(user_factory):
    """
    Saving a serializer containing valid data should create a new
    profile.
    """
    user = user_factory()
    data = {
        'name': 'John',
        'quote': "Hi, I'm John",
        'welcome_message': 'This is my profile.',
    }

    serializer = serializers.ProfileListSerializer(data=data)
    assert serializer.is_valid()

    serializer.save(user=user)
    profile = user.profile

    assert profile.name == data['name']
    assert profile.quote == data['quote']
    assert profile.welcome_message == data['welcome_message']
    assert profile.user == user

def test_serialize(profile_factory):
    """
    Test serializing a profile.
    """
    profile = profile_factory()
    serializer = serializers.ProfileListSerializer(profile)

    expected = {
        'id': profile.id,
        'name': profile.name,
        'quote': profile.quote,
        'welcome_message': profile.welcome_message,
    }

    assert serializer.data == expected

Prompt:
Add test for creating profile from serializer.

from know_me import serializers

def test_serialize(profile_factory):
    """
    Test serializing a profile.
    """
    profile = profile_factory()
    serializer = serializers.ProfileListSerializer(profile)

    expected = {
        'id': profile.id,
        'name': profile.name,
        'quote': profile.quote,
        'welcome_message': profile.welcome_message,
    }

    assert serializer.data == expected


"""
Extended JSONPointer from python-json-pointer_
==============================================

.. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer
"""

import typing

from jsonpointer import JsonPointer as BaseJsonPointer

class JSONPointer(BaseJsonPointer):
    def __init__(self, pointer):
        super(JSONPointer, self).__init__(pointer)

    def __truediv__(self,
                    path: typing.Union['JSONPointer', str]) -> 'JSONPointer':
        parts = self.parts.copy()

        if isinstance(path, int):
            path = str(path)

        if isinstance(path, str):
            if not path.startswith('/'):
                path = f'/{path}'
            new_parts = JSONPointer(path).parts.pop(0)
            parts.append(new_parts)
        else:
            new_parts = path.parts
            parts.extend(new_parts)
        return JSONPointer.from_parts(parts)

Response:
<REPLACE_OLD> self.parts.copy()
 <REPLACE_NEW> self.parts.copy()

        if isinstance(path, int):
            path = str(path)

 <REPLACE_END> <|endoftext|> """
Extended JSONPointer from python-json-pointer_
==============================================

.. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer
"""

import typing

from jsonpointer import JsonPointer as BaseJsonPointer

class JSONPointer(BaseJsonPointer):
    def __init__(self, pointer):
        super(JSONPointer, self).__init__(pointer)

    def __truediv__(self,
                    path: typing.Union['JSONPointer', str]) -> 'JSONPointer':
        parts = self.parts.copy()

        if isinstance(path, int):
            path = str(path)

        if isinstance(path, str):
            if not path.startswith('/'):
                path = f'/{path}'
            new_parts = JSONPointer(path).parts.pop(0)
            parts.append(new_parts)
        else:
            new_parts = path.parts
            parts.extend(new_parts)
        return JSONPointer.from_parts(parts)

Prompt:
Fix bug with JSONPointer if part passed via __truediv__ is integer

"""
Extended JSONPointer from python-json-pointer_
==============================================

.. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer
"""

import typing

from jsonpointer import JsonPointer as BaseJsonPointer

class JSONPointer(BaseJsonPointer):
    def __init__(self, pointer):
        super(JSONPointer, self).__init__(pointer)

    def __truediv__(self,
                    path: typing.Union['JSONPointer', str]) -> 'JSONPointer':
        parts = self.parts.copy()
        if isinstance(path, str):
            if not path.startswith('/'):
                path = f'/{path}'
            new_parts = JSONPointer(path).parts.pop(0)
            parts.append(new_parts)
        else:
            new_parts = path.parts
            parts.extend(new_parts)
        return JSONPointer.from_parts(parts)


# LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html

from __future__ import division
import libtbx.load_env
from dials.util.procrunner import run_process
import shutil
import os

if (__name__ == "__main__") :
  xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
  assert (xia2_dir is not None)
  dest_dir = os.path.join(xia2_dir, "html")
  if os.path.exists(dest_dir):
    shutil.rmtree(dest_dir)
  os.chdir(os.path.join(xia2_dir, "doc", "sphinx"))
  result = run_process(["make", "clean"])
  assert result['exitcode'] == 0, \
      'make clean failed with exit code %d' % result['exitcode']
  result = run_process(["make", "html"])
  assert result['exitcode'] == 0, \
      'make html failed with exit code %d' % result['exitcode']
  print "Moving HTML pages to", dest_dir
  shutil.move("build/html", dest_dir)

Check make exit codes and stop on error

Check make exit codes and stop on error

Response:
<REPLACE_OLD> division
from libtbx <REPLACE_NEW> division
import libtbx.load_env
from dials.util.procrunner <REPLACE_END> <REPLACE_OLD> easy_run
import libtbx.load_env
import os.path as op
import <REPLACE_NEW> run_process
import <REPLACE_END> <REPLACE_OLD> os
import sys

if <REPLACE_NEW> os

if <REPLACE_END> <REPLACE_OLD> op.join(xia2_dir, <REPLACE_NEW> os.path.join(xia2_dir, <REPLACE_END> <REPLACE_OLD> op.exists(dest_dir):
 <REPLACE_NEW> os.path.exists(dest_dir):
 <REPLACE_END> <REPLACE_OLD> os.chdir(op.join(xia2_dir, <REPLACE_NEW> os.chdir(os.path.join(xia2_dir, <REPLACE_END> <REPLACE_OLD> easy_run.call("make clean")
 <REPLACE_NEW> result = run_process(["make", "clean"])
 <REPLACE_END> <REPLACE_OLD> easy_run.call("make html")
 <REPLACE_NEW> assert result['exitcode'] == 0, \
      'make clean failed with exit code %d' % result['exitcode']
  result = run_process(["make", "html"])
  assert result['exitcode'] == 0, \
      'make html failed with exit code %d' % result['exitcode']
 <REPLACE_END> <|endoftext|> # LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html

from __future__ import division
import libtbx.load_env
from dials.util.procrunner import run_process
import shutil
import os

if (__name__ == "__main__") :
  xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
  assert (xia2_dir is not None)
  dest_dir = os.path.join(xia2_dir, "html")
  if os.path.exists(dest_dir):
    shutil.rmtree(dest_dir)
  os.chdir(os.path.join(xia2_dir, "doc", "sphinx"))
  result = run_process(["make", "clean"])
  assert result['exitcode'] == 0, \
      'make clean failed with exit code %d' % result['exitcode']
  result = run_process(["make", "html"])
  assert result['exitcode'] == 0, \
      'make html failed with exit code %d' % result['exitcode']
  print "Moving HTML pages to", dest_dir
  shutil.move("build/html", dest_dir)

Prompt:
Check make exit codes and stop on error

# LIBTBX_SET_DISPATCHER_NAME dev.xia2.make_sphinx_html

from __future__ import division
from libtbx import easy_run
import libtbx.load_env
import os.path as op
import shutil
import os
import sys

if (__name__ == "__main__") :
  xia2_dir = libtbx.env.find_in_repositories("xia2", optional=False)
  assert (xia2_dir is not None)
  dest_dir = op.join(xia2_dir, "html")
  if op.exists(dest_dir):
    shutil.rmtree(dest_dir)
  os.chdir(op.join(xia2_dir, "doc", "sphinx"))
  easy_run.call("make clean")
  easy_run.call("make html")
  print "Moving HTML pages to", dest_dir
  shutil.move("build/html", dest_dir)


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

"""Celery configuration values."""

BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
    "visibility_timeout": 60*60*4,
    "fanout_prefix": True,
    "fanout_patterns": True
}
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_SERIALIZER = "json"
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"

Increase ack on broker to 4 hours.

Response:
<REPLACE_OLD> 10800,
 <REPLACE_NEW> 60*60*4,
 <REPLACE_END> <|endoftext|> # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Celery configuration values."""

BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
    "visibility_timeout": 60*60*4,
    "fanout_prefix": True,
    "fanout_patterns": True
}
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_SERIALIZER = "json"
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"

Prompt:
Increase ack on broker to 4 hours.

Change-Id: I4a1f0fc6d1c07014896ef6b34336396d4b30bfdd

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

"""Celery configuration values."""

BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
    "visibility_timeout": 10800,
    "fanout_prefix": True,
    "fanout_patterns": True
}
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_SERIALIZER = "json"
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"


from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from rest_framework.utils.serializer_helpers import ReturnDict

class CustomLimitOffsetPagination(LimitOffsetPagination):
    max_limit = 50

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('meta', OrderedDict([
                ('limit', self.limit),
                ('next', self.get_next_link()),
                ('offset', self.offset),
                ('previous', self.get_previous_link()),
                ('total_count', self.count),
            ])),
            ('objects', data),
        ]))

class SearchFacetListSerializer(ListSerializer):
    @property
    def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        ret = super(SearchFacetListSerializer, self).to_representation(instance)

        ret = OrderedDict([
            ('results', ret),
            ('facets', self._context.get('facets', {'fields': {}})),
        ])
        return ret

Add max limit to api pagination

Add max limit to api pagination

Response:
<INSERT>    max_limit = 50

 <INSERT_END> <|endoftext|> from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from rest_framework.utils.serializer_helpers import ReturnDict

class CustomLimitOffsetPagination(LimitOffsetPagination):
    max_limit = 50

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('meta', OrderedDict([
                ('limit', self.limit),
                ('next', self.get_next_link()),
                ('offset', self.offset),
                ('previous', self.get_previous_link()),
                ('total_count', self.count),
            ])),
            ('objects', data),
        ]))

class SearchFacetListSerializer(ListSerializer):
    @property
    def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        ret = super(SearchFacetListSerializer, self).to_representation(instance)

        ret = OrderedDict([
            ('results', ret),
            ('facets', self._context.get('facets', {'fields': {}})),
        ])
        return ret

Prompt:
Add max limit to api pagination
from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.serializers import ListSerializer
from rest_framework.utils.serializer_helpers import ReturnDict

class CustomLimitOffsetPagination(LimitOffsetPagination):
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('meta', OrderedDict([
                ('limit', self.limit),
                ('next', self.get_next_link()),
                ('offset', self.offset),
                ('previous', self.get_previous_link()),
                ('total_count', self.count),
            ])),
            ('objects', data),
        ]))

class SearchFacetListSerializer(ListSerializer):
    @property
    def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self)

    def to_representation(self, instance):
        ret = super(SearchFacetListSerializer, self).to_representation(instance)

        ret = OrderedDict([
            ('results', ret),
            ('facets', self._context.get('facets', {'fields': {}})),
        ])
        return ret


import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "{{cookiecutter.repo_name}}",
    version = "{{cookiecutter.version}}",
    author = "{{cookiecutter.full_name}}",
    author_email = "{{cookiecutter.email}}",
    description = "{{cookiecutter.short_description}}",
    license = "MIT",
    keywords=(
        "Python, cookiecutter, kivy, buildozer, pytest, projects, project "
        "templates, example, documentation, tutorial, setup.py, package, "
        "android, touch, mobile, NUI"
    ),
    url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires = ['kivy>=1.8.0'],
    package_data={
        '{{cookiecutter.repo_name}}': ['*.kv*']
    },
    entry_points={
        'console_scripts': [
            '{{cookiecutter.repo_name}}={{cookiecutter.repo_name}}.main:main'
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: X11 Applications',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Artistic Software',
        'Topic :: Multimedia :: Graphics :: Presentation',
        'Topic :: Software Development :: User Interfaces',
    ],
)

Set up console script for main

Set up console script for main

Response:
<INSERT> entry_points={
        'console_scripts': [
            '{{cookiecutter.repo_name}}={{cookiecutter.repo_name}}.main:main'
        ]
    },
    <INSERT_END> <|endoftext|> import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "{{cookiecutter.repo_name}}",
    version = "{{cookiecutter.version}}",
    author = "{{cookiecutter.full_name}}",
    author_email = "{{cookiecutter.email}}",
    description = "{{cookiecutter.short_description}}",
    license = "MIT",
    keywords=(
        "Python, cookiecutter, kivy, buildozer, pytest, projects, project "
        "templates, example, documentation, tutorial, setup.py, package, "
        "android, touch, mobile, NUI"
    ),
    url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires = ['kivy>=1.8.0'],
    package_data={
        '{{cookiecutter.repo_name}}': ['*.kv*']
    },
    entry_points={
        'console_scripts': [
            '{{cookiecutter.repo_name}}={{cookiecutter.repo_name}}.main:main'
        ]
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: X11 Applications',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Artistic Software',
        'Topic :: Multimedia :: Graphics :: Presentation',
        'Topic :: Software Development :: User Interfaces',
    ],
)

Prompt:
Set up console script for main

import os
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "{{cookiecutter.repo_name}}",
    version = "{{cookiecutter.version}}",
    author = "{{cookiecutter.full_name}}",
    author_email = "{{cookiecutter.email}}",
    description = "{{cookiecutter.short_description}}",
    license = "MIT",
    keywords=(
        "Python, cookiecutter, kivy, buildozer, pytest, projects, project "
        "templates, example, documentation, tutorial, setup.py, package, "
        "android, touch, mobile, NUI"
    ),
    url = "https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}",
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires = ['kivy>=1.8.0'],
    package_data={
        '{{cookiecutter.repo_name}}': ['*.kv*']
    },
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: X11 Applications',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Topic :: Artistic Software',
        'Topic :: Multimedia :: Graphics :: Presentation',
        'Topic :: Software Development :: User Interfaces',
    ],
)


# Generated by Django 2.0.13 on 2020-04-23 12:55

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('signage', '0012_auto_20200406_1411'),
    ]

    operations = [
        migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]),
        migrations.RemoveField(
            model_name='blade',
            name='deleted',
        ),
        migrations.RemoveField(
            model_name='blade',
            name='structure',
        ),
        migrations.RemoveField(
            model_name='line',
            name='structure',
        ),
        migrations.AlterField(
            model_name='line',
            name='blade',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines',
                                    to='signage.Blade', verbose_name='Blade'),
        ),
    ]

Response:
<INSERT> migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]),
        <INSERT_END> <|endoftext|> # Generated by Django 2.0.13 on 2020-04-23 12:55

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('signage', '0012_auto_20200406_1411'),
    ]

    operations = [
        migrations.RunSQL(sql=[("DELETE FROM geotrek.signage_blade WHERE deleted=TRUE;", )]),
        migrations.RemoveField(
            model_name='blade',
            name='deleted',
        ),
        migrations.RemoveField(
            model_name='blade',
            name='structure',
        ),
        migrations.RemoveField(
            model_name='line',
            name='structure',
        ),
        migrations.AlterField(
            model_name='line',
            name='blade',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines',
                                    to='signage.Blade', verbose_name='Blade'),
        ),
    ]

Prompt:
Remove element with deleted=true before removefield

# Generated by Django 2.0.13 on 2020-04-23 12:55

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('signage', '0012_auto_20200406_1411'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='blade',
            name='deleted',
        ),
        migrations.RemoveField(
            model_name='blade',
            name='structure',
        ),
        migrations.RemoveField(
            model_name='line',
            name='structure',
        ),
        migrations.AlterField(
            model_name='line',
            name='blade',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines',
                                    to='signage.Blade', verbose_name='Blade'),
        ),
    ]


from share.provider import ProviderAppConfig
from .harvester import OSFRegistrationsHarvester

class AppConfig(ProviderAppConfig):
    name = 'providers.io.osf.registrations'
    version = '0.0.1'
    title = 'osf_registrations'
    long_title = 'Open Science Framework Registrations'
    home_page = 'http://api.osf.io/registrations/'
    harvester = OSFRegistrationsHarvester

Add the app config for osf registrations

Response:
<INSERT> from share.provider import ProviderAppConfig
from .harvester import OSFRegistrationsHarvester

class AppConfig(ProviderAppConfig):
 <INSERT_END> <INSERT>   name = 'providers.io.osf.registrations'
    version = '0.0.1'
    title = 'osf_registrations'
    long_title = 'Open Science Framework Registrations'
    home_page = 'http://api.osf.io/registrations/'
    harvester = OSFRegistrationsHarvester
 <INSERT_END> <|endoftext|> from share.provider import ProviderAppConfig
from .harvester import OSFRegistrationsHarvester

class AppConfig(ProviderAppConfig):
    name = 'providers.io.osf.registrations'
    version = '0.0.1'
    title = 'osf_registrations'
    long_title = 'Open Science Framework Registrations'
    home_page = 'http://api.osf.io/registrations/'
    harvester = OSFRegistrationsHarvester

Prompt: Add the app config for osf registrations


from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

for template_engine in TEMPLATES:
    template_engine['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'

try:
    import debug_toolbar
except ImportError:
     pass
else:
    INSTALLED_APPS += ('debug_toolbar',)
    MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INTERNAL_IPS = ('127.0.0.1', 'localhost')
    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

try:
    from .local import *
except ImportError:
    pass

try:
    from .polygons import *
except ImportError:
    pass

LOGGING = {
        'version': 1,
        'handlers': {
                'console': {
                        'class': 'logging.StreamHandler'},
        },
        'loggers': {'background_task': {'handlers': ['console'], 'level': 'INFO'}}}

try:
    INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
    pass

Print tracebacks that happened in tasks

Print tracebacks that happened in tasks

Response:
<REPLACE_OLD> pass

try:
 <REPLACE_NEW> pass

LOGGING = {
        'version': 1,
        'handlers': {
                'console': {
                        'class': 'logging.StreamHandler'},
        },
        'loggers': {'background_task': {'handlers': ['console'], 'level': 'INFO'}}}

try:
 <REPLACE_END> <|endoftext|> from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

for template_engine in TEMPLATES:
    template_engine['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'

try:
    import debug_toolbar
except ImportError:
     pass
else:
    INSTALLED_APPS += ('debug_toolbar',)
    MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INTERNAL_IPS = ('127.0.0.1', 'localhost')
    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

try:
    from .local import *
except ImportError:
    pass

try:
    from .polygons import *
except ImportError:
    pass

LOGGING = {
        'version': 1,
        'handlers': {
                'console': {
                        'class': 'logging.StreamHandler'},
        },
        'loggers': {'background_task': {'handlers': ['console'], 'level': 'INFO'}}}

try:
    INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
    pass

Prompt:
Print tracebacks that happened in tasks

from .base import *

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

for template_engine in TEMPLATES:
    template_engine['OPTIONS']['debug'] = True

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'

try:
    import debug_toolbar
except ImportError:
     pass
else:
    INSTALLED_APPS += ('debug_toolbar',)
    MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INTERNAL_IPS = ('127.0.0.1', 'localhost')
    DEBUG_TOOLBAR_CONFIG = {
        'JQUERY_URL': '',
    }

try:
    from .local import *
except ImportError:
    pass

try:
    from .polygons import *
except ImportError:
    pass

try:
    INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
    pass


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

VERSION = (0, 12,)

__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)

Change the version to v0.12

Change the version to v0.12

Response:
<REPLACE_OLD> 11,)

__author__ <REPLACE_NEW> 12,)

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

VERSION = (0, 12,)

__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)

Prompt:
Change the version to v0.12

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

VERSION = (0, 11,)

__author__ = 'Mosky <http://mosky.tw>'
__version__ = '.'.join(str(v) for v in VERSION)


"""
Warnings Module
===============

Contains a collection of warning messages for consistent package wide notifications

"""

#-Numba-#
numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n"
                            "This will reduce the overall performance of this package.\n"
                            "To install please use the anaconda distribution.\n"
                            "http://continuum.io/downloads")

Response:
<REPLACE_OLD> "Numba <REPLACE_NEW> ("Numba <REPLACE_END> <DELETE>  <DELETE_END> <REPLACE_OLD> routine." <REPLACE_NEW> routines.\n"
                            "This will reduce the overall performance of this package.\n"
                            "To install please use the anaconda distribution.\n"
                            "http://continuum.io/downloads") <REPLACE_END> <|endoftext|> """
Warnings Module
===============

Contains a collection of warning messages for consistent package wide notifications

"""

#-Numba-#
numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n"
                            "This will reduce the overall performance of this package.\n"
                            "To install please use the anaconda distribution.\n"
                            "http://continuum.io/downloads")

Prompt:
Update warning message if numba import fails

"""
Warnings Module
===============

Contains a collection of warning messages for consistent package wide notifications

"""

#-Numba-#
numba_import_fail_message = "Numba import failed.  Falling back to non-optimized routine."


from os import environ

import dj_database_url

from .base import *

INSTALLED_APPS += (
    'djangosecure',
)

PRODUCTION_MIDDLEWARE_CLASSES = (
    'djangosecure.middleware.SecurityMiddleware',
)

MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES

DATABASES = {'default': dj_database_url.config()}

SECRET_KEY = environ.get('SECRET_KEY')

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [DOMAIN]

# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

SECURE_REDIRECT_EXEMPT = [
    '^(?!hub/).*'
]

Response:
<REPLACE_OLD> 'https')
 <REPLACE_NEW> 'https')

SECURE_REDIRECT_EXEMPT = [
    '^(?!hub/).*'
]
 <REPLACE_END> <|endoftext|> from os import environ

import dj_database_url

from .base import *

INSTALLED_APPS += (
    'djangosecure',
)

PRODUCTION_MIDDLEWARE_CLASSES = (
    'djangosecure.middleware.SecurityMiddleware',
)

MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES

DATABASES = {'default': dj_database_url.config()}

SECRET_KEY = environ.get('SECRET_KEY')

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [DOMAIN]

# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

SECURE_REDIRECT_EXEMPT = [
    '^(?!hub/).*'
]

Prompt:
Add SECURE_REDIRECT_EXEMPT to old HTTP callbacks
from os import environ

import dj_database_url

from .base import *

INSTALLED_APPS += (
    'djangosecure',
)

PRODUCTION_MIDDLEWARE_CLASSES = (
    'djangosecure.middleware.SecurityMiddleware',
)

MIDDLEWARE_CLASSES = PRODUCTION_MIDDLEWARE_CLASSES + MIDDLEWARE_CLASSES

DATABASES = {'default': dj_database_url.config()}

SECRET_KEY = environ.get('SECRET_KEY')

DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = [DOMAIN]

# django-secure
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 15
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_FRAME_DENY = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')


"""Utility for clearing all keys out of redis -- do not use in production!"""

import sys
from optparse import OptionParser

import redis

def option_parser():
    parser = OptionParser()
    parser.add_option("-f", "--force",
                      action="store_true", dest="force", default=False,
                      help="Don't ask for confirmation.")
    return parser

def main():
    parser = option_parser()
    options, args = parser.parse_args()
    if args:
        parser.print_help()
        return 1
    if not options.force:
        confirm = raw_input("About to delete ALL redis keys. "
                            "Press Y to confirm, N to exit: ")
        if confirm.lower() != 'y':
            return 1
    r_server = redis.Redis()
    keys = r_server.keys()
    for key in keys:
        r_server.delete(key)
    print "Deleted %i keys." % len(keys)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Add utility for clearing out redis keys from tests.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Utility for clearing all keys out of redis -- do not use in production!"""

import sys
from optparse import OptionParser

import redis

def option_parser():
    parser = OptionParser()
    parser.add_option("-f", "--force",
                      action="store_true", dest="force", default=False,
                      help="Don't ask for confirmation.")
    return parser

def main():
    parser = option_parser()
    options, args = parser.parse_args()
    if args:
        parser.print_help()
        return 1
    if not options.force:
        confirm = raw_input("About to delete ALL redis keys. "
                            "Press Y to confirm, N to exit: ")
        if confirm.lower() != 'y':
            return 1
    r_server = redis.Redis()
    keys = r_server.keys()
    for key in keys:
        r_server.delete(key)
    print "Deleted %i keys." % len(keys)
    return 0

if __name__ == "__main__":
    sys.exit(main())
 <REPLACE_END> <|endoftext|> """Utility for clearing all keys out of redis -- do not use in production!"""

import sys
from optparse import OptionParser

import redis

def option_parser():
    parser = OptionParser()
    parser.add_option("-f", "--force",
                      action="store_true", dest="force", default=False,
                      help="Don't ask for confirmation.")
    return parser

def main():
    parser = option_parser()
    options, args = parser.parse_args()
    if args:
        parser.print_help()
        return 1
    if not options.force:
        confirm = raw_input("About to delete ALL redis keys. "
                            "Press Y to confirm, N to exit: ")
        if confirm.lower() != 'y':
            return 1
    r_server = redis.Redis()
    keys = r_server.keys()
    for key in keys:
        r_server.delete(key)
    print "Deleted %i keys." % len(keys)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Prompt: Add utility for clearing out redis keys from tests.


import sys

s = 0.0

for line in sys.stdin:
    _, b, c = line.split()
    b, c = int(b), float(c)
    s += c * b

print(f'VALOR A PAGAR: R$ {s:.2f}')

Response:
<REPLACE_OLD> a, <REPLACE_NEW> _, <REPLACE_END> <DELETE> a, <DELETE_END> <DELETE> int(a), <DELETE_END> <|endoftext|> import sys

s = 0.0

for line in sys.stdin:
    _, b, c = line.split()
    b, c = int(b), float(c)
    s += c * b

print(f'VALOR A PAGAR: R$ {s:.2f}')

Prompt:
Refactor python version of Simple Calculate

import sys

s = 0.0

for line in sys.stdin:
    a, b, c = line.split()
    a, b, c = int(a), int(b), float(c)
    s += c * b

print(f'VALOR A PAGAR: R$ {s:.2f}')


"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015  Dirk Beyer
All rights reserved.
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.
"""

import benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])

class Tool(yogar_cbmc.Tool):

    REQUIRED_PATHS = [
                  "yogar-cbmc"
                  ]

    def executable(self):
        return util.find_executable('yogar-cbmc-parallel')

    def name(self):
        return 'Yogar-CBMC-Parallel'

    def cmdline(self, executable, options, tasks, propertyfile, rlimits):
        return [executable] + options + tasks

Response:
<INSERT> REQUIRED_PATHS = [
                  "yogar-cbmc"
                  ]

    <INSERT_END> <|endoftext|> """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015  Dirk Beyer
All rights reserved.
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.
"""

import benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])

class Tool(yogar_cbmc.Tool):

    REQUIRED_PATHS = [
                  "yogar-cbmc"
                  ]

    def executable(self):
        return util.find_executable('yogar-cbmc-parallel')

    def name(self):
        return 'Yogar-CBMC-Parallel'

    def cmdline(self, executable, options, tasks, propertyfile, rlimits):
        return [executable] + options + tasks

Prompt:
Add forgotten program file for deployment

"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015  Dirk Beyer
All rights reserved.
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.
"""

import benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])

class Tool(yogar_cbmc.Tool):

    def executable(self):
        return util.find_executable('yogar-cbmc-parallel')

    def name(self):
        return 'Yogar-CBMC-Parallel'

    def cmdline(self, executable, options, tasks, propertyfile, rlimits):
        return [executable] + options + tasks


import warnings

from signac import *
__all__ = ['core', 'contrib', 'db']

msg = "compdb was renamed to signac. Please import signac in the future."
print('Warning!',msg)
warnings.warn(msg, DeprecationWarning)

Response:
<REPLACE_OLD> *

msg <REPLACE_NEW> *
__all__ = ['core', 'contrib', 'db']

msg <REPLACE_END> <REPLACE_OLD> future."
warnings.warn(DeprecationWarning, msg)
 <REPLACE_NEW> future."
print('Warning!',msg)
warnings.warn(msg, DeprecationWarning)
 <REPLACE_END> <|endoftext|> import warnings

from signac import *
__all__ = ['core', 'contrib', 'db']

msg = "compdb was renamed to signac. Please import signac in the future."
print('Warning!',msg)
warnings.warn(msg, DeprecationWarning)

Prompt:
Add surrogate compdb package, linking to signac.

Provided to guarantee compatibility.
Prints warning on import.

import warnings

from signac import *

msg = "compdb was renamed to signac. Please import signac in the future."
warnings.warn(DeprecationWarning, msg)


import time
from datetime import timedelta

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils import timezone

from players.models import Player

class Command(BaseCommand):
    def handle(self, *args, **options):
        start_date = timezone.now() - timedelta(days=7)
        players = Player.objects.filter(Q(mmr_last_updated__isnull=True) | Q(mmr_last_updated__lt=start_date))
        self.stdout.write('Updating MMR for {} players.'.format(players.count()))
        for player in players:
            player.update_mmr()
            time.sleep(1)
        self.stdout.write(self.style.SUCCESS('Finished updating all player MMRs.'))

Add management command to update all player MMRs

Response:
<INSERT> import time
from datetime import timedelta

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils import timezone

from players.models import Player

class Command(BaseCommand):
 <INSERT_END> <INSERT>   def handle(self, *args, **options):
        start_date = timezone.now() - timedelta(days=7)
        players = Player.objects.filter(Q(mmr_last_updated__isnull=True) | Q(mmr_last_updated__lt=start_date))
        self.stdout.write('Updating MMR for {} players.'.format(players.count()))
        for player in players:
            player.update_mmr()
            time.sleep(1)
        self.stdout.write(self.style.SUCCESS('Finished updating all player MMRs.'))
 <INSERT_END> <|endoftext|> import time
from datetime import timedelta

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils import timezone

from players.models import Player

class Command(BaseCommand):
    def handle(self, *args, **options):
        start_date = timezone.now() - timedelta(days=7)
        players = Player.objects.filter(Q(mmr_last_updated__isnull=True) | Q(mmr_last_updated__lt=start_date))
        self.stdout.write('Updating MMR for {} players.'.format(players.count()))
        for player in players:
            player.update_mmr()
            time.sleep(1)
        self.stdout.write(self.style.SUCCESS('Finished updating all player MMRs.'))

Prompt: Add management command to update all player MMRs


import numpy as np
from menpofit.math.correlationfilter import mccf, imccf

# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
    r"""
    """
    def __init__(self, cf_callable=mccf, icf_callable=imccf):
        self.cf_callable = cf_callable
        self.icf_callable = icf_callable

    def increment(self, A, B, n_x, Z, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(Z, list):
            Z = np.asarray(Z)
        return self.icf_callable(A, B, n_x, Z, t)

    def train(self, X, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(X, list):
            X = np.asarray(X)
        # Return linear svm filter and bias
        return self.cf_callable(X, t)

Add dummy wrapper for correlation filters

Response:
<REPLACE_OLD>  <REPLACE_NEW> import numpy as np
from menpofit.math.correlationfilter import mccf, imccf

# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
    r"""
    """
    def __init__(self, cf_callable=mccf, icf_callable=imccf):
        self.cf_callable = cf_callable
        self.icf_callable = icf_callable

    def increment(self, A, B, n_x, Z, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(Z, list):
            Z = np.asarray(Z)
        return self.icf_callable(A, B, n_x, Z, t)

    def train(self, X, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(X, list):
            X = np.asarray(X)
        # Return linear svm filter and bias
        return self.cf_callable(X, t)
 <REPLACE_END> <|endoftext|> import numpy as np
from menpofit.math.correlationfilter import mccf, imccf

# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
    r"""
    """
    def __init__(self, cf_callable=mccf, icf_callable=imccf):
        self.cf_callable = cf_callable
        self.icf_callable = icf_callable

    def increment(self, A, B, n_x, Z, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(Z, list):
            Z = np.asarray(Z)
        return self.icf_callable(A, B, n_x, Z, t)

    def train(self, X, t):
        r"""
        """
        # Turn list of X into ndarray
        if isinstance(X, list):
            X = np.asarray(X)
        # Return linear svm filter and bias
        return self.cf_callable(X, t)

Prompt: Add dummy wrapper for correlation filters


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

import unittest

from ParseArticleReferenceTest import ParseArticleReferenceTest
from SortReferencesVisitorTest import SortReferencesVisitorTest
from ParseEditTest import ParseEditTest
from ParseAlineaReferenceTest import ParseAlineaReferenceTest
from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest
from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest
from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest

if __name__ == '__main__':
    unittest.main()

Response:
<DELETE> ParseSentenceDefinitionTest import ParseSentenceDefinitionTest
from <DELETE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

from ParseArticleReferenceTest import ParseArticleReferenceTest
from SortReferencesVisitorTest import SortReferencesVisitorTest
from ParseEditTest import ParseEditTest
from ParseAlineaReferenceTest import ParseAlineaReferenceTest
from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest
from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest
from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest

if __name__ == '__main__':
    unittest.main()

Prompt:
Fix broken reference to ParseSentenceDefinitionTest.

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

import unittest

from ParseArticleReferenceTest import ParseArticleReferenceTest
from SortReferencesVisitorTest import SortReferencesVisitorTest
from ParseEditTest import ParseEditTest
from ParseAlineaReferenceTest import ParseAlineaReferenceTest
from ParseAlineaDefinitionTest import ParseAlineaDefinitionTest
from ParseSentenceDefinitionTest import ParseSentenceDefinitionTest
from ParseHeader2ReferenceTest import ParseHeader2ReferenceTest
from ParseHeader2DefinitionTest import ParseHeader2DefinitionTest

if __name__ == '__main__':
    unittest.main()


# define flask extensions in separate file, to resolve import dependencies

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_caching import Cache
cache = Cache()

from flask_assets import Environment
assets = Environment()

from flask_babel import Babel
babel = Babel()

from flask_mail import Mail
mail = Mail()

from flask_login import LoginManager
login_manager = LoginManager()

from flask_restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

from flask_store import Store
store = Store()

from flask_rq2 import RQ
rq = RQ()

from flask_talisman import Talisman
CALLPOWER_CSP = {
    'default-src':'\'self\'',
    'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
    'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
    'font-src': ['\'self\'', 'fonts.gstatic.com'],
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman()

Response:
<INSERT> '\'unsafe-eval\'', <INSERT_END> <REPLACE_OLD> 'fonts.gstatic.com'],
}
talisman <REPLACE_NEW> 'fonts.gstatic.com'],
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman <REPLACE_END> <|endoftext|> # define flask extensions in separate file, to resolve import dependencies

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_caching import Cache
cache = Cache()

from flask_assets import Environment
assets = Environment()

from flask_babel import Babel
babel = Babel()

from flask_mail import Mail
mail = Mail()

from flask_login import LoginManager
login_manager = LoginManager()

from flask_restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

from flask_store import Store
store = Store()

from flask_rq2 import RQ
rq = RQ()

from flask_talisman import Talisman
CALLPOWER_CSP = {
    'default-src':'\'self\'',
    'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
    'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
    'font-src': ['\'self\'', 'fonts.gstatic.com'],
}
# unsafe-inline needed to render <script> tags without nonce
# unsafe-eval needed to run bootstrap templates
talisman = Talisman()

Prompt:
Include script-src unsafe-eval to allow underscore templating
Long term, we should pre-compile with webpack to avoid needing this

# define flask extensions in separate file, to resolve import dependencies

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask_caching import Cache
cache = Cache()

from flask_assets import Environment
assets = Environment()

from flask_babel import Babel
babel = Babel()

from flask_mail import Mail
mail = Mail()

from flask_login import LoginManager
login_manager = LoginManager()

from flask_restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

from flask_store import Store
store = Store()

from flask_rq2 import RQ
rq = RQ()

from flask_talisman import Talisman
CALLPOWER_CSP = {
    'default-src':'\'self\'',
    'script-src':['\'self\'', '\'unsafe-inline\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'],
    'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'],
    'font-src': ['\'self\'', 'fonts.gstatic.com'],
}
talisman = Talisman()


# -*- coding: utf-8 -*-
"""\
- Add a ``media_type`` column to the ``files`` table.
- Move the mimetype value from ``module_files`` to ``files``.

"""
from __future__ import print_function
import sys

def up(cursor):
    # Add a ``media_type`` column to the ``files`` table.
    cursor.execute("ALTER TABLE files ADD COLUMN media_type TEXT")

    # Move the mimetype value from ``module_files`` to ``files``.
    cursor.execute("UPDATE files AS f SET media_type = mf.mimetype "
                   "FROM module_files AS mf "
                   "WHERE mf.fileid = f.fileid")

    # Warn about missing mimetype.
    cursor.execute("SELECT fileid, sha1 "
                   "FROM files AS f "
                   "WHERE f.fileid NOT IN (SELECT fileid FROM module_files)")
    rows = '\n'.join(['{}, {}'.format(fid, sha1)
                      for fid, sha1 in cursor.fetchall()])
    print("These files (fileid, sha1) do not have a corresponding "
          "module_files entry:\n{}\n".format(rows),
          file=sys.stderr)

def down(cursor):
    # Remove the ``mimetype`` column from the ``files`` table.
    cursor.execute("ALTER TABLE files DROP COLUMN media_type")

Move mimetype column from module_files to files

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
"""\
- Add a ``media_type`` column to the ``files`` table.
- Move the mimetype value from ``module_files`` to ``files``.

"""
from __future__ import print_function
import sys

def up(cursor):
    # Add a ``media_type`` column to the ``files`` table.
    cursor.execute("ALTER TABLE files ADD COLUMN media_type TEXT")

    # Move the mimetype value from ``module_files`` to ``files``.
    cursor.execute("UPDATE files AS f SET media_type = mf.mimetype "
                   "FROM module_files AS mf "
                   "WHERE mf.fileid = f.fileid")

    # Warn about missing mimetype.
    cursor.execute("SELECT fileid, sha1 "
                   "FROM files AS f "
                   "WHERE f.fileid NOT IN (SELECT fileid FROM module_files)")
    rows = '\n'.join(['{}, {}'.format(fid, sha1)
                      for fid, sha1 in cursor.fetchall()])
    print("These files (fileid, sha1) do not have a corresponding "
          "module_files entry:\n{}\n".format(rows),
          file=sys.stderr)

def down(cursor):
    # Remove the ``mimetype`` column from the ``files`` table.
    cursor.execute("ALTER TABLE files DROP COLUMN media_type")
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""\
- Add a ``media_type`` column to the ``files`` table.
- Move the mimetype value from ``module_files`` to ``files``.

"""
from __future__ import print_function
import sys

def up(cursor):
    # Add a ``media_type`` column to the ``files`` table.
    cursor.execute("ALTER TABLE files ADD COLUMN media_type TEXT")

    # Move the mimetype value from ``module_files`` to ``files``.
    cursor.execute("UPDATE files AS f SET media_type = mf.mimetype "
                   "FROM module_files AS mf "
                   "WHERE mf.fileid = f.fileid")

    # Warn about missing mimetype.
    cursor.execute("SELECT fileid, sha1 "
                   "FROM files AS f "
                   "WHERE f.fileid NOT IN (SELECT fileid FROM module_files)")
    rows = '\n'.join(['{}, {}'.format(fid, sha1)
                      for fid, sha1 in cursor.fetchall()])
    print("These files (fileid, sha1) do not have a corresponding "
          "module_files entry:\n{}\n".format(rows),
          file=sys.stderr)

def down(cursor):
    # Remove the ``mimetype`` column from the ``files`` table.
    cursor.execute("ALTER TABLE files DROP COLUMN media_type")

Prompt: Move mimetype column from module_files to files


from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

from models import *

bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")

class ButtonPlugin(CMSPluginBase):
    model = ButtonPluginModel
    name = _("Button")
    #module = bootstrap_module_name
    render_template = "button_plugin.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        if instance.page_link:
            context['link'] = instance.page_link.get_absolute_url()
        else:
            context['link'] = instance.button_link
        return context

plugin_pool.register_plugin(ButtonPlugin)

Response:
<INSERT>    text_enabled = True
 <INSERT_END> <|endoftext|> from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

from models import *

bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")

class ButtonPlugin(CMSPluginBase):
    model = ButtonPluginModel
    name = _("Button")
    #module = bootstrap_module_name
    render_template = "button_plugin.html"
    text_enabled = True

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        if instance.page_link:
            context['link'] = instance.page_link.get_absolute_url()
        else:
            context['link'] = instance.button_link
        return context

plugin_pool.register_plugin(ButtonPlugin)

Prompt:
Make Button plugin usable inside Text plugin

from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

from models import *

bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")

class ButtonPlugin(CMSPluginBase):
    model = ButtonPluginModel
    name = _("Button")
    #module = bootstrap_module_name
    render_template = "button_plugin.html"

    def render(self, context, instance, placeholder):
        context['instance'] = instance
        if instance.page_link:
            context['link'] = instance.page_link.get_absolute_url()
        else:
            context['link'] = instance.button_link
        return context

plugin_pool.register_plugin(ButtonPlugin)


import __builtin__

def any(it):
    for obj in it:
        if obj:
            return True
    return False

def all(it):
    for obj in it:
        if not obj:
            return False
    return True

def max(it, key=None):
    if key is not None:
        k, value = max((key(value), value) for value in it)
        return value
    return max(it)

def min(it, key=None):
    if key is not None:
        k, value = min((key(value), value) for value in it)
        return value
    return min(it)

class Condition(object):
    """
    This wraps a condition so that it can be shared by everyone and modified
    by whomever wants to.
    """
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return self.value

class ComparableObjectMixin(object):

    def __hash__(self):
        "Implement in subclasses"
        raise NotImplementedError

    def __eq__(self, other):
        "Implement in subclasses"
        return NotImplemented

Return an actual bool from any()

Return an actual bool from any()

Response:
<REPLACE_OLD> True

def <REPLACE_NEW> True
    return False

def <REPLACE_END> <|endoftext|> import __builtin__

def any(it):
    for obj in it:
        if obj:
            return True
    return False

def all(it):
    for obj in it:
        if not obj:
            return False
    return True

def max(it, key=None):
    if key is not None:
        k, value = max((key(value), value) for value in it)
        return value
    return max(it)

def min(it, key=None):
    if key is not None:
        k, value = min((key(value), value) for value in it)
        return value
    return min(it)

class Condition(object):
    """
    This wraps a condition so that it can be shared by everyone and modified
    by whomever wants to.
    """
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return self.value

class ComparableObjectMixin(object):

    def __hash__(self):
        "Implement in subclasses"
        raise NotImplementedError

    def __eq__(self, other):
        "Implement in subclasses"
        return NotImplemented

Prompt:
Return an actual bool from any()

import __builtin__

def any(it):
    for obj in it:
        if obj:
            return True

def all(it):
    for obj in it:
        if not obj:
            return False
    return True

def max(it, key=None):
    if key is not None:
        k, value = max((key(value), value) for value in it)
        return value
    return max(it)

def min(it, key=None):
    if key is not None:
        k, value = min((key(value), value) for value in it)
        return value
    return min(it)

class Condition(object):
    """
    This wraps a condition so that it can be shared by everyone and modified
    by whomever wants to.
    """
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return self.value

class ComparableObjectMixin(object):

    def __hash__(self):
        "Implement in subclasses"
        raise NotImplementedError

    def __eq__(self, other):
        "Implement in subclasses"
        return NotImplemented


import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        "access the database"
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        "connect to SQS"
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()

Response:
<INSERT>        "access the database"
 <INSERT_END> <INSERT> "connect to SQS"
        <INSERT_END> <|endoftext|> import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        "access the database"
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        "connect to SQS"
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()

Prompt:
Add docstrings so that hubot can say what went wrong

import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()


# https://leetcode.com/problems/delete-node-in-a-linked-list/

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """

        while node.next != None:
            node.val = node.next.val
            if node.next.next is None:
                node.next = None
            else:
                node = node.next

Add problem delete note in a linked list

Response:
<INSERT> # https://leetcode.com/problems/delete-node-in-a-linked-list/

# Definition for singly-linked list.
# class ListNode(object):
# <INSERT_END> <INSERT>    def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """

        while node.next != None:
            node.val = node.next.val
            if node.next.next is None:
                node.next = None
            else:
                node = node.next <INSERT_END> <|endoftext|> # https://leetcode.com/problems/delete-node-in-a-linked-list/

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """

        while node.next != None:
            node.val = node.next.val
            if node.next.next is None:
                node.next = None
            else:
                node = node.next

Prompt: Add problem delete note in a linked list