#!/usr/bin/env python3

import argparse
import boto3
import os
from typing import List

from mediawords.util.log import create_logger

l = create_logger(__name__)

def delete_bitly_blobs(story_ids: List[int]):
    session = boto3.Session(profile_name='mediacloud')
    s3 = session.resource('s3')
    bucket = s3.Bucket('mediacloud-bitly-processing-results')

    chunk_size = 999  # up to 1000 objects to be deleted at once
    story_ids_chunks = [story_ids[x:x + chunk_size] for x in range(0, len(story_ids), chunk_size)]

    l.info('Deleting %d Bit.ly blobs, split into %d chunks...' % (len(story_ids), len(story_ids_chunks)))

    for chunk in story_ids_chunks:
        objects_to_delete = []

        for stories_id in chunk:
            objects_to_delete.append({'Key': 'json_blobs/%d' % stories_id})

        bucket.delete_objects(
            Delete={
                'Objects': objects_to_delete,
            }
        )

    l.info('Done deleting %d Bit.ly blobs.' % len(story_ids))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Delete Bit.ly raw results from S3.',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-i', '--input_file', type=str, required=True, help='Input file with Bit.ly story IDs.')

    args = parser.parse_args()

    if not os.path.isfile(args.input_file):
        raise Exception('Input file "%s" does not exist.' % args.input_file)

    bitly_story_ids = []
    with open(args.input_file, 'r') as fh:
        for line in fh:
            line = line.rstrip("\n")
            if line:
                line = int(line)
                bitly_story_ids.append(line)

    delete_bitly_blobs(story_ids=bitly_story_ids)

Add script to delete Bit.ly raw results from S3

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

import argparse
import boto3
import os
from typing import List

from mediawords.util.log import create_logger

l = create_logger(__name__)

def delete_bitly_blobs(story_ids: List[int]):
    session = boto3.Session(profile_name='mediacloud')
    s3 = session.resource('s3')
    bucket = s3.Bucket('mediacloud-bitly-processing-results')

    chunk_size = 999  # up to 1000 objects to be deleted at once
    story_ids_chunks = [story_ids[x:x + chunk_size] for x in range(0, len(story_ids), chunk_size)]

    l.info('Deleting %d Bit.ly blobs, split into %d chunks...' % (len(story_ids), len(story_ids_chunks)))

    for chunk in story_ids_chunks:
        objects_to_delete = []

        for stories_id in chunk:
            objects_to_delete.append({'Key': 'json_blobs/%d' % stories_id})

        bucket.delete_objects(
            Delete={
                'Objects': objects_to_delete,
            }
        )

    l.info('Done deleting %d Bit.ly blobs.' % len(story_ids))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Delete Bit.ly raw results from S3.',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-i', '--input_file', type=str, required=True, help='Input file with Bit.ly story IDs.')

    args = parser.parse_args()

    if not os.path.isfile(args.input_file):
        raise Exception('Input file "%s" does not exist.' % args.input_file)

    bitly_story_ids = []
    with open(args.input_file, 'r') as fh:
        for line in fh:
            line = line.rstrip("\n")
            if line:
                line = int(line)
                bitly_story_ids.append(line)

    delete_bitly_blobs(story_ids=bitly_story_ids)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3

import argparse
import boto3
import os
from typing import List

from mediawords.util.log import create_logger

l = create_logger(__name__)

def delete_bitly_blobs(story_ids: List[int]):
    session = boto3.Session(profile_name='mediacloud')
    s3 = session.resource('s3')
    bucket = s3.Bucket('mediacloud-bitly-processing-results')

    chunk_size = 999  # up to 1000 objects to be deleted at once
    story_ids_chunks = [story_ids[x:x + chunk_size] for x in range(0, len(story_ids), chunk_size)]

    l.info('Deleting %d Bit.ly blobs, split into %d chunks...' % (len(story_ids), len(story_ids_chunks)))

    for chunk in story_ids_chunks:
        objects_to_delete = []

        for stories_id in chunk:
            objects_to_delete.append({'Key': 'json_blobs/%d' % stories_id})

        bucket.delete_objects(
            Delete={
                'Objects': objects_to_delete,
            }
        )

    l.info('Done deleting %d Bit.ly blobs.' % len(story_ids))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Delete Bit.ly raw results from S3.',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-i', '--input_file', type=str, required=True, help='Input file with Bit.ly story IDs.')

    args = parser.parse_args()

    if not os.path.isfile(args.input_file):
        raise Exception('Input file "%s" does not exist.' % args.input_file)

    bitly_story_ids = []
    with open(args.input_file, 'r') as fh:
        for line in fh:
            line = line.rstrip("\n")
            if line:
                line = int(line)
                bitly_story_ids.append(line)

    delete_bitly_blobs(story_ids=bitly_story_ids)

Prompt: Add script to delete Bit.ly raw results from S3


# -*- coding: utf-8 -*-
from flask import Flask, render_template_string
import jinja2

def test_undefined_variable__no_error():
    app = Flask(__name__)
    assert issubclass(app.jinja_env.undefined, jinja2.Undefined)

    @app.route('/')
    def endpoint():
        return render_template_string('foo = [{{bar}}]', foo='blabla')

    resp = app.test_client().get('/')

    # http://jinja.pocoo.org/docs/2.10/templates/#variables
    # If a variable or attribute does not exist, you will get back an undefined
    # value. What you can do with that kind of value depends on the application
    # configuration: the default behavior is to evaluate to an empty string if
    # printed or iterated over, and to fail for every other operation.
    assert resp.data == 'foo = []'

def test_undefined_variable__strict__raise_error(capsys):
    app = Flask(__name__)

    # http://jinja.pocoo.org/docs/2.10/api/#undefined-types
    # The closest to regular Python behavior is the StrictUndefined which
    # disallows all operations beside testing if it’s an undefined object.
    app.jinja_env.undefined = jinja2.StrictUndefined

    @app.route('/')
    def endpoint():
        return render_template_string('foo = [{{bar}}]', foo='blabla')

    resp = app.test_client().get('/')

    assert resp.status_code == 500
    assert "UndefinedError: 'bar' is undefined" in capsys.readouterr()[1]

Fix source code encoding error

[flask] Fix source code encoding error

Response:
<REPLACE_OLD> from <REPLACE_NEW> # -*- coding: utf-8 -*-
from <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from flask import Flask, render_template_string
import jinja2

def test_undefined_variable__no_error():
    app = Flask(__name__)
    assert issubclass(app.jinja_env.undefined, jinja2.Undefined)

    @app.route('/')
    def endpoint():
        return render_template_string('foo = [{{bar}}]', foo='blabla')

    resp = app.test_client().get('/')

    # http://jinja.pocoo.org/docs/2.10/templates/#variables
    # If a variable or attribute does not exist, you will get back an undefined
    # value. What you can do with that kind of value depends on the application
    # configuration: the default behavior is to evaluate to an empty string if
    # printed or iterated over, and to fail for every other operation.
    assert resp.data == 'foo = []'

def test_undefined_variable__strict__raise_error(capsys):
    app = Flask(__name__)

    # http://jinja.pocoo.org/docs/2.10/api/#undefined-types
    # The closest to regular Python behavior is the StrictUndefined which
    # disallows all operations beside testing if it’s an undefined object.
    app.jinja_env.undefined = jinja2.StrictUndefined

    @app.route('/')
    def endpoint():
        return render_template_string('foo = [{{bar}}]', foo='blabla')

    resp = app.test_client().get('/')

    assert resp.status_code == 500
    assert "UndefinedError: 'bar' is undefined" in capsys.readouterr()[1]

Prompt:
[flask] Fix source code encoding error

from flask import Flask, render_template_string
import jinja2

def test_undefined_variable__no_error():
    app = Flask(__name__)
    assert issubclass(app.jinja_env.undefined, jinja2.Undefined)

    @app.route('/')
    def endpoint():
        return render_template_string('foo = [{{bar}}]', foo='blabla')

    resp = app.test_client().get('/')

    # http://jinja.pocoo.org/docs/2.10/templates/#variables
    # If a variable or attribute does not exist, you will get back an undefined
    # value. What you can do with that kind of value depends on the application
    # configuration: the default behavior is to evaluate to an empty string if
    # printed or iterated over, and to fail for every other operation.
    assert resp.data == 'foo = []'

def test_undefined_variable__strict__raise_error(capsys):
    app = Flask(__name__)

    # http://jinja.pocoo.org/docs/2.10/api/#undefined-types
    # The closest to regular Python behavior is the StrictUndefined which
    # disallows all operations beside testing if it’s an undefined object.
    app.jinja_env.undefined = jinja2.StrictUndefined

    @app.route('/')
    def endpoint():
        return render_template_string('foo = [{{bar}}]', foo='blabla')

    resp = app.test_client().get('/')

    assert resp.status_code == 500
    assert "UndefinedError: 'bar' is undefined" in capsys.readouterr()[1]


import enumgen
from pprint import pprint
import os
import os.path

data = enumgen.fetch_csv(
	"http://www.iana.org/assignments/dns-parameters/dns-parameters-2.csv")

data_dict = []
for row in data:
	if '-' in row[0]: continue
	if ' ' in row[2]:
		row[2] = row[2].split(' ')[-1].strip('()')
	if row[2] in [i['name'] for i in data_dict]: continue
	data_dict.append({
		"name": row[2],
		"value": int(row[0]),
		"desc": row[3],
		})

print(enumgen.render_template(
	os.path.join(os.path.dirname(__file__), 'templates'),
	'enum_with_tests.rs.jinja2',
	ename='RRClass',
	rep='u16',
	default='Reserved',
	default_val=0,
	variants=data_dict,
	))

Add RRClass generation script to git

Add RRClass generation script to git

Response:
<REPLACE_OLD>  <REPLACE_NEW> import enumgen
from pprint import pprint
import os
import os.path

data = enumgen.fetch_csv(
	"http://www.iana.org/assignments/dns-parameters/dns-parameters-2.csv")

data_dict = []
for row in data:
	if '-' in row[0]: continue
	if ' ' in row[2]:
		row[2] = row[2].split(' ')[-1].strip('()')
	if row[2] in [i['name'] for i in data_dict]: continue
	data_dict.append({
		"name": row[2],
		"value": int(row[0]),
		"desc": row[3],
		})

print(enumgen.render_template(
	os.path.join(os.path.dirname(__file__), 'templates'),
	'enum_with_tests.rs.jinja2',
	ename='RRClass',
	rep='u16',
	default='Reserved',
	default_val=0,
	variants=data_dict,
	)) <REPLACE_END> <|endoftext|> import enumgen
from pprint import pprint
import os
import os.path

data = enumgen.fetch_csv(
	"http://www.iana.org/assignments/dns-parameters/dns-parameters-2.csv")

data_dict = []
for row in data:
	if '-' in row[0]: continue
	if ' ' in row[2]:
		row[2] = row[2].split(' ')[-1].strip('()')
	if row[2] in [i['name'] for i in data_dict]: continue
	data_dict.append({
		"name": row[2],
		"value": int(row[0]),
		"desc": row[3],
		})

print(enumgen.render_template(
	os.path.join(os.path.dirname(__file__), 'templates'),
	'enum_with_tests.rs.jinja2',
	ename='RRClass',
	rep='u16',
	default='Reserved',
	default_val=0,
	variants=data_dict,
	))

Prompt: Add RRClass generation script to git


Remove blank line at end of file.

Remove blank line at end of file.

Response:
<REPLACE_OLD> pass

 <REPLACE_NEW> pass
 <REPLACE_END> <|endoftext|> class Formatter(object):
    name = None
    description = None

    def __init__(self, stream, config):
        self.stream = stream
        self.config = config

    def uri(self, uri):
        pass

    def feature(self, feature):
        pass

    def background(self, background):
        pass

    def scenario(self, scenario):
        pass

    def scenario_outline(self, outline):
        pass

    def examples(self, examples):
        pass

    def step(self, step):
        pass

    def match(self, match):
        pass

    def result(self, result):
        pass

    def eof(self):
        pass

    def close(self):
        pass

Prompt:
Remove blank line at end of file.

class Formatter(object):
    name = None
    description = None

    def __init__(self, stream, config):
        self.stream = stream
        self.config = config

    def uri(self, uri):
        pass

    def feature(self, feature):
        pass

    def background(self, background):
        pass

    def scenario(self, scenario):
        pass

    def scenario_outline(self, outline):
        pass

    def examples(self, examples):
        pass

    def step(self, step):
        pass

    def match(self, match):
        pass

    def result(self, result):
        pass

    def eof(self):
        pass

    def close(self):
        pass


"""Package Keysmith."""

import codecs
import os.path

import setuptools  # type: ignore

import keysmith  # This project only depends on the standard library.

def read(*parts):
    """Read a file in this repository."""
    here = os.path.abspath(os.path.dirname(__file__))
    with codecs.open(os.path.join(here, *parts), 'r') as file_:
        return file_.read()

ENTRY_POINTS = {
    'console_scripts': [
        '{name}={module}:{function}'.format(
            name=keysmith.CONSOLE_SCRIPT,
            module=keysmith.__name__,
            function=keysmith.main.__name__,
        ),
    ],
}

if __name__ == '__main__':
    setuptools.setup(
        name=keysmith.__name__,
        version=keysmith.__version__,
        description='Passphrase Generator',
        long_description=read('README.rst'),
        author='David Tucker',
        author_email='david@tucker.name',
        license='BSD 3-Clause License',
        url='https://github.com/dmtucker/keysmith',
        python_requires='~=3.5',
        py_modules=[keysmith.__name__],
        entry_points=ENTRY_POINTS,
        keywords='diceware generator keygen passphrase password',
        classifiers=['Development Status :: 7 - Inactive'],
    )

Update the project Development Status

Update the project Development Status

Response:
<REPLACE_OLD> 5 <REPLACE_NEW> 7 <REPLACE_END> <REPLACE_OLD> Production/Stable'],
 <REPLACE_NEW> Inactive'],
 <REPLACE_END> <|endoftext|> """Package Keysmith."""

import codecs
import os.path

import setuptools  # type: ignore

import keysmith  # This project only depends on the standard library.

def read(*parts):
    """Read a file in this repository."""
    here = os.path.abspath(os.path.dirname(__file__))
    with codecs.open(os.path.join(here, *parts), 'r') as file_:
        return file_.read()

ENTRY_POINTS = {
    'console_scripts': [
        '{name}={module}:{function}'.format(
            name=keysmith.CONSOLE_SCRIPT,
            module=keysmith.__name__,
            function=keysmith.main.__name__,
        ),
    ],
}

if __name__ == '__main__':
    setuptools.setup(
        name=keysmith.__name__,
        version=keysmith.__version__,
        description='Passphrase Generator',
        long_description=read('README.rst'),
        author='David Tucker',
        author_email='david@tucker.name',
        license='BSD 3-Clause License',
        url='https://github.com/dmtucker/keysmith',
        python_requires='~=3.5',
        py_modules=[keysmith.__name__],
        entry_points=ENTRY_POINTS,
        keywords='diceware generator keygen passphrase password',
        classifiers=['Development Status :: 7 - Inactive'],
    )

Prompt:
Update the project Development Status

"""Package Keysmith."""

import codecs
import os.path

import setuptools  # type: ignore

import keysmith  # This project only depends on the standard library.

def read(*parts):
    """Read a file in this repository."""
    here = os.path.abspath(os.path.dirname(__file__))
    with codecs.open(os.path.join(here, *parts), 'r') as file_:
        return file_.read()

ENTRY_POINTS = {
    'console_scripts': [
        '{name}={module}:{function}'.format(
            name=keysmith.CONSOLE_SCRIPT,
            module=keysmith.__name__,
            function=keysmith.main.__name__,
        ),
    ],
}

if __name__ == '__main__':
    setuptools.setup(
        name=keysmith.__name__,
        version=keysmith.__version__,
        description='Passphrase Generator',
        long_description=read('README.rst'),
        author='David Tucker',
        author_email='david@tucker.name',
        license='BSD 3-Clause License',
        url='https://github.com/dmtucker/keysmith',
        python_requires='~=3.5',
        py_modules=[keysmith.__name__],
        entry_points=ENTRY_POINTS,
        keywords='diceware generator keygen passphrase password',
        classifiers=['Development Status :: 5 - Production/Stable'],
    )


from django.db import models
from tinymce import models as tinymce_models

photos_path = "simple-faq/"

class Topic(models.Model):
    text = models.CharField(max_length=200)
    number = models.IntegerField()

    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return u'(%s) %s' % (self.number, self.text, )

class Question(models.Model):
    text = models.CharField(max_length=200)
    answer_text = tinymce_models.HTMLField()
    topic = models.ForeignKey(Topic, related_name="questions")
    header_picture = models.ImageField(upload_to=photos_path, blank=True)
    number = models.IntegerField()
    related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True)

    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return u'(%s) %s' % (self.number, self.text, )

Fix path where the images are saved.

Fix path where the images are saved.

Response:
<REPLACE_OLD> "/simple-faq/"

class <REPLACE_NEW> "simple-faq/"

class <REPLACE_END> <|endoftext|> from django.db import models
from tinymce import models as tinymce_models

photos_path = "simple-faq/"

class Topic(models.Model):
    text = models.CharField(max_length=200)
    number = models.IntegerField()

    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return u'(%s) %s' % (self.number, self.text, )

class Question(models.Model):
    text = models.CharField(max_length=200)
    answer_text = tinymce_models.HTMLField()
    topic = models.ForeignKey(Topic, related_name="questions")
    header_picture = models.ImageField(upload_to=photos_path, blank=True)
    number = models.IntegerField()
    related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True)

    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return u'(%s) %s' % (self.number, self.text, )

Prompt:
Fix path where the images are saved.

from django.db import models
from tinymce import models as tinymce_models

photos_path = "/simple-faq/"

class Topic(models.Model):
    text = models.CharField(max_length=200)
    number = models.IntegerField()

    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return u'(%s) %s' % (self.number, self.text, )

class Question(models.Model):
    text = models.CharField(max_length=200)
    answer_text = tinymce_models.HTMLField()
    topic = models.ForeignKey(Topic, related_name="questions")
    header_picture = models.ImageField(upload_to=photos_path, blank=True)
    number = models.IntegerField()
    related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True)

    class Meta:
        ordering = ['number']

    def __unicode__(self):
        return u'(%s) %s' % (self.number, self.text, )


class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l, r = 1, len(nums) - 1
        while l < r:
            m = l + (r - l) / 2
            cnt = 0
            for num in nums:
                if num <= m:
                    cnt += 1
            print l, r, m
            if cnt > m:
                r = m
            else:
                l = m + 1
        return l

Add the bin search py version of FindtheDupNum

Response:
<REPLACE_OLD>  <REPLACE_NEW> class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l, r = 1, len(nums) - 1
        while l < r:
            m = l + (r - l) / 2
            cnt = 0
            for num in nums:
                if num <= m:
                    cnt += 1
            print l, r, m
            if cnt > m:
                r = m
            else:
                l = m + 1
        return l
 <REPLACE_END> <|endoftext|> class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l, r = 1, len(nums) - 1
        while l < r:
            m = l + (r - l) / 2
            cnt = 0
            for num in nums:
                if num <= m:
                    cnt += 1
            print l, r, m
            if cnt > m:
                r = m
            else:
                l = m + 1
        return l

Prompt: Add the bin search py version of FindtheDupNum


#
# Perl (Inline::Perl) helpers
#

# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
    """Convert 'bytes' string to 'unicode' if needed.
    (http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
    if string is not None:
        if isinstance(string, bytes):
            string = string.decode('utf-8')
    return string

# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_object_from_bytes_if_needed(obj):
    """Convert object (dictionary, list or string) from 'bytes' string to 'unicode' if needed."""
    if isinstance(obj, dict):
        result = dict()
        for k, v in obj.items():
            k = decode_object_from_bytes_if_needed(k)
            v = decode_object_from_bytes_if_needed(v)
            result[k] = v
    elif isinstance(obj, list):
        result = list()
        for v in obj:
            v = decode_object_from_bytes_if_needed(v)
            result.append(v)
    else:
        result = decode_string_from_bytes_if_needed(obj)
    return result

Response:
<INSERT> """Convert object (dictionary, list or string) from 'bytes' string to 'unicode' if needed."""
    <INSERT_END> <|endoftext|> #
# Perl (Inline::Perl) helpers
#

# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
    """Convert 'bytes' string to 'unicode' if needed.
    (http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
    if string is not None:
        if isinstance(string, bytes):
            string = string.decode('utf-8')
    return string

# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_object_from_bytes_if_needed(obj):
    """Convert object (dictionary, list or string) from 'bytes' string to 'unicode' if needed."""
    if isinstance(obj, dict):
        result = dict()
        for k, v in obj.items():
            k = decode_object_from_bytes_if_needed(k)
            v = decode_object_from_bytes_if_needed(v)
            result[k] = v
    elif isinstance(obj, list):
        result = list()
        for v in obj:
            v = decode_object_from_bytes_if_needed(v)
            result.append(v)
    else:
        result = decode_string_from_bytes_if_needed(obj)
    return result

Prompt:
Add comment describing what does the method do

#
# Perl (Inline::Perl) helpers
#

# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
    """Convert 'bytes' string to 'unicode' if needed.
    (http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
    if string is not None:
        if isinstance(string, bytes):
            string = string.decode('utf-8')
    return string

# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_object_from_bytes_if_needed(obj):
    if isinstance(obj, dict):
        result = dict()
        for k, v in obj.items():
            k = decode_object_from_bytes_if_needed(k)
            v = decode_object_from_bytes_if_needed(v)
            result[k] = v
    elif isinstance(obj, list):
        result = list()
        for v in obj:
            v = decode_object_from_bytes_if_needed(v)
            result.append(v)
    else:
        result = decode_string_from_bytes_if_needed(obj)
    return result


from sqlalchemy import Column, Integer, String, func
from app import db

class CnesBed(db.Model):
    __tablename__ = 'cnes_bed'
    year          = Column(Integer, primary_key=True)
    region        = Column(String(1), primary_key=True)
    mesoregion    = Column(String(4), primary_key=True)
    microregion   = Column(String(5), primary_key=True)
    state         = Column(String(2), primary_key=True)
    municipality  = Column(String(7), primary_key=True)
    cnes          = Column(String(7), primary_key=True)
    bed_type      = Column(String(7), primary_key=True)

    @classmethod
    def dimensions(cls):
        return [
            'year',
            'region',
            'mesoregion',
            'microregion',
            'state',
            'municipality',
        ]

    @classmethod
    def aggregate(cls, value):
        return {
            'beds': func.count()
        }[value]

    @classmethod
    def values(cls):
        return ['beds']

Response:
<INSERT> primary_key=True)
    bed_type      = Column(String(7), <INSERT_END> <REPLACE_OLD> func.count(cls.cnes)
 <REPLACE_NEW> func.count()
 <REPLACE_END> <|endoftext|> from sqlalchemy import Column, Integer, String, func
from app import db

class CnesBed(db.Model):
    __tablename__ = 'cnes_bed'
    year          = Column(Integer, primary_key=True)
    region        = Column(String(1), primary_key=True)
    mesoregion    = Column(String(4), primary_key=True)
    microregion   = Column(String(5), primary_key=True)
    state         = Column(String(2), primary_key=True)
    municipality  = Column(String(7), primary_key=True)
    cnes          = Column(String(7), primary_key=True)
    bed_type      = Column(String(7), primary_key=True)

    @classmethod
    def dimensions(cls):
        return [
            'year',
            'region',
            'mesoregion',
            'microregion',
            'state',
            'municipality',
        ]

    @classmethod
    def aggregate(cls, value):
        return {
            'beds': func.count()
        }[value]

    @classmethod
    def values(cls):
        return ['beds']

Prompt:
Add bed_type to cnes_establishment model

from sqlalchemy import Column, Integer, String, func
from app import db

class CnesBed(db.Model):
    __tablename__ = 'cnes_bed'
    year          = Column(Integer, primary_key=True)
    region        = Column(String(1), primary_key=True)
    mesoregion    = Column(String(4), primary_key=True)
    microregion   = Column(String(5), primary_key=True)
    state         = Column(String(2), primary_key=True)
    municipality  = Column(String(7), primary_key=True)
    cnes          = Column(String(7), primary_key=True)

    @classmethod
    def dimensions(cls):
        return [
            'year',
            'region',
            'mesoregion',
            'microregion',
            'state',
            'municipality',
        ]

    @classmethod
    def aggregate(cls, value):
        return {
            'beds': func.count(cls.cnes)
        }[value]

    @classmethod
    def values(cls):
        return ['beds']


from django.test import TestCase
from django.urls import reverse

from wagtail.test.utils import WagtailTestUtils
from wagtail.users.models import UserProfile

class TestDismissiblesView(TestCase, WagtailTestUtils):
    def setUp(self):
        self.user = self.login()
        self.profile = UserProfile.get_for_user(self.user)
        self.url = reverse("wagtailadmin_dismissibles")

    def test_get_initial(self):
        response = self.client.get(self.url)
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_patch_valid(self):
        response = self.client.patch(
            self.url, data={"foo": "bar"}, content_type="application/json"
        )
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"foo": "bar"})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})

    def test_patch_invalid(self):
        response = self.client.patch(
            self.url, data="invalid", content_type="application/json"
        )
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 400)
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_post(self):
        # The view only accepts GET and PATCH
        response = self.client.post(self.url, data={"foo": "bar"})
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 405)
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_get_without_userprofile(self):
        # GET should work even if the user doesn't have a UserProfile,
        # but it shouldn't create one
        self.profile.delete()
        response = self.client.get(self.url)
        self.user.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {})
        self.assertIsNone(getattr(self.user, "wagtail_userprofile", None))

    def test_patch_without_userprofile(self):
        # PATCH should work even if the user doesn't have a UserProfile,
        # in which case it should create one
        self.profile.delete()
        response = self.client.patch(
            self.url, data={"foo": "bar"}, content_type="application/json"
        )
        self.user.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"foo": "bar"})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})

Add tests for Dismissibles view

Add tests for Dismissibles view

Response:
<REPLACE_OLD>  <REPLACE_NEW> from django.test import TestCase
from django.urls import reverse

from wagtail.test.utils import WagtailTestUtils
from wagtail.users.models import UserProfile

class TestDismissiblesView(TestCase, WagtailTestUtils):
    def setUp(self):
        self.user = self.login()
        self.profile = UserProfile.get_for_user(self.user)
        self.url = reverse("wagtailadmin_dismissibles")

    def test_get_initial(self):
        response = self.client.get(self.url)
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_patch_valid(self):
        response = self.client.patch(
            self.url, data={"foo": "bar"}, content_type="application/json"
        )
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"foo": "bar"})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})

    def test_patch_invalid(self):
        response = self.client.patch(
            self.url, data="invalid", content_type="application/json"
        )
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 400)
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_post(self):
        # The view only accepts GET and PATCH
        response = self.client.post(self.url, data={"foo": "bar"})
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 405)
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_get_without_userprofile(self):
        # GET should work even if the user doesn't have a UserProfile,
        # but it shouldn't create one
        self.profile.delete()
        response = self.client.get(self.url)
        self.user.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {})
        self.assertIsNone(getattr(self.user, "wagtail_userprofile", None))

    def test_patch_without_userprofile(self):
        # PATCH should work even if the user doesn't have a UserProfile,
        # in which case it should create one
        self.profile.delete()
        response = self.client.patch(
            self.url, data={"foo": "bar"}, content_type="application/json"
        )
        self.user.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"foo": "bar"})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})
 <REPLACE_END> <|endoftext|> from django.test import TestCase
from django.urls import reverse

from wagtail.test.utils import WagtailTestUtils
from wagtail.users.models import UserProfile

class TestDismissiblesView(TestCase, WagtailTestUtils):
    def setUp(self):
        self.user = self.login()
        self.profile = UserProfile.get_for_user(self.user)
        self.url = reverse("wagtailadmin_dismissibles")

    def test_get_initial(self):
        response = self.client.get(self.url)
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_patch_valid(self):
        response = self.client.patch(
            self.url, data={"foo": "bar"}, content_type="application/json"
        )
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"foo": "bar"})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})

    def test_patch_invalid(self):
        response = self.client.patch(
            self.url, data="invalid", content_type="application/json"
        )
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 400)
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_post(self):
        # The view only accepts GET and PATCH
        response = self.client.post(self.url, data={"foo": "bar"})
        self.profile.refresh_from_db()
        self.assertEqual(response.status_code, 405)
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {})

    def test_get_without_userprofile(self):
        # GET should work even if the user doesn't have a UserProfile,
        # but it shouldn't create one
        self.profile.delete()
        response = self.client.get(self.url)
        self.user.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {})
        self.assertIsNone(getattr(self.user, "wagtail_userprofile", None))

    def test_patch_without_userprofile(self):
        # PATCH should work even if the user doesn't have a UserProfile,
        # in which case it should create one
        self.profile.delete()
        response = self.client.patch(
            self.url, data={"foo": "bar"}, content_type="application/json"
        )
        self.user.refresh_from_db()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {"foo": "bar"})
        self.assertEqual(self.user.wagtail_userprofile.dismissibles, {"foo": "bar"})

Prompt: Add tests for Dismissibles view


import argparse
import sys

def main(raw_args=sys.argv[1:]):
    """
    A tool to automatically request, renew and distribute Let's Encrypt
    certificates for apps running on Marathon and served by marathon-lb.
    """
    parser = argparse.ArgumentParser(
        description='Automatically manage ACME certificates for Marathon apps')
    parser.add_argument('-a', '--acme',
                        help='The address for the ACME Directory Resource '
                             '(default: %(default)s)',
                        default=(
                            'https://acme-v01.api.letsencrypt.org/directory'))
    parser.add_argument('-m', '--marathon', nargs='+',
                        help='The address for the Marathon HTTP API (default: '
                             '%(default)s)',
                        default='http://marathon.mesos:8080')
    parser.add_argument('-l', '--lb', nargs='+',
                        help='The address for the marathon-lb HTTP API '
                             '(default: %(default)s)',
                        default='http://marathon-lb.marathon.mesos:9090')
    parser.add_argument('-g', '--group',
                        help='The marathon-lb group to issue certificates for '
                             '(default: %(default)s)',
                        default='external')
    parser.add_argument('storage-dir',
                        help='Path to directory for storing certificates')

    args = parser.parse_args(raw_args)  # noqa

if __name__ == '__main__':
    main()

Add --group option to CLI

Add --group option to CLI

Response:
<INSERT> parser.add_argument('-g', '--group',
                        help='The marathon-lb group to issue certificates for '
                             '(default: %(default)s)',
                        default='external')
    <INSERT_END> <|endoftext|> import argparse
import sys

def main(raw_args=sys.argv[1:]):
    """
    A tool to automatically request, renew and distribute Let's Encrypt
    certificates for apps running on Marathon and served by marathon-lb.
    """
    parser = argparse.ArgumentParser(
        description='Automatically manage ACME certificates for Marathon apps')
    parser.add_argument('-a', '--acme',
                        help='The address for the ACME Directory Resource '
                             '(default: %(default)s)',
                        default=(
                            'https://acme-v01.api.letsencrypt.org/directory'))
    parser.add_argument('-m', '--marathon', nargs='+',
                        help='The address for the Marathon HTTP API (default: '
                             '%(default)s)',
                        default='http://marathon.mesos:8080')
    parser.add_argument('-l', '--lb', nargs='+',
                        help='The address for the marathon-lb HTTP API '
                             '(default: %(default)s)',
                        default='http://marathon-lb.marathon.mesos:9090')
    parser.add_argument('-g', '--group',
                        help='The marathon-lb group to issue certificates for '
                             '(default: %(default)s)',
                        default='external')
    parser.add_argument('storage-dir',
                        help='Path to directory for storing certificates')

    args = parser.parse_args(raw_args)  # noqa

if __name__ == '__main__':
    main()

Prompt:
Add --group option to CLI

import argparse
import sys

def main(raw_args=sys.argv[1:]):
    """
    A tool to automatically request, renew and distribute Let's Encrypt
    certificates for apps running on Marathon and served by marathon-lb.
    """
    parser = argparse.ArgumentParser(
        description='Automatically manage ACME certificates for Marathon apps')
    parser.add_argument('-a', '--acme',
                        help='The address for the ACME Directory Resource '
                             '(default: %(default)s)',
                        default=(
                            'https://acme-v01.api.letsencrypt.org/directory'))
    parser.add_argument('-m', '--marathon', nargs='+',
                        help='The address for the Marathon HTTP API (default: '
                             '%(default)s)',
                        default='http://marathon.mesos:8080')
    parser.add_argument('-l', '--lb', nargs='+',
                        help='The address for the marathon-lb HTTP API '
                             '(default: %(default)s)',
                        default='http://marathon-lb.marathon.mesos:9090')
    parser.add_argument('storage-dir',
                        help='Path to directory for storing certificates')

    args = parser.parse_args(raw_args)  # noqa

if __name__ == '__main__':
    main()


import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor

def test_parse_unit_valid():
    """Parse a valid unit
    """
    meter = parse_unit('m')
    assert str(meter) == 'meter'

@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
    """Warn if unit not recognised
    """
    unit = 'unrecognisable'
    parse_unit(unit)
    msg = "Unrecognised unit: %s"
    warning_logger.assert_called_with(msg, unit)

def test_convert_unit():

    data = np.array([[1, 2], [3, 4]], dtype=float)

    convertor = UnitConvertor()
    actual = convertor.convert(data, 'liter', 'milliliter')

    expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)

    np.allclose(actual, expected)

Add test for normal unit conversion

Add test for normal unit conversion

Response:
<REPLACE_OLD> from <REPLACE_NEW> import numpy as np
from <REPLACE_END> <REPLACE_OLD> parse_unit

def <REPLACE_NEW> parse_unit
from smif.convert import UnitConvertor

def <REPLACE_END> <REPLACE_OLD> unit)
 <REPLACE_NEW> unit)

def test_convert_unit():

    data = np.array([[1, 2], [3, 4]], dtype=float)

    convertor = UnitConvertor()
    actual = convertor.convert(data, 'liter', 'milliliter')

    expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)

    np.allclose(actual, expected)
 <REPLACE_END> <|endoftext|> import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor

def test_parse_unit_valid():
    """Parse a valid unit
    """
    meter = parse_unit('m')
    assert str(meter) == 'meter'

@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
    """Warn if unit not recognised
    """
    unit = 'unrecognisable'
    parse_unit(unit)
    msg = "Unrecognised unit: %s"
    warning_logger.assert_called_with(msg, unit)

def test_convert_unit():

    data = np.array([[1, 2], [3, 4]], dtype=float)

    convertor = UnitConvertor()
    actual = convertor.convert(data, 'liter', 'milliliter')

    expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)

    np.allclose(actual, expected)

Prompt:
Add test for normal unit conversion

from unittest.mock import patch
from smif.convert.unit import parse_unit

def test_parse_unit_valid():
    """Parse a valid unit
    """
    meter = parse_unit('m')
    assert str(meter) == 'meter'

@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
    """Warn if unit not recognised
    """
    unit = 'unrecognisable'
    parse_unit(unit)
    msg = "Unrecognised unit: %s"
    warning_logger.assert_called_with(msg, unit)


"""accounts app unittests for views

"""
from django.test import TestCase

from accounts.forms import LoginForm

class LoginFormTest(TestCase):
    """Tests the form which validates the email used for login.

    """
    def test_valid_email_accepted(self):
        form = LoginForm({'email': 'newvisitor@example.com'})
        self.assertTrue(form.is_valid())

    def test_invalid_email_declined(self):
        form = LoginForm({'email': 'invalidemail'})
        self.assertFalse(form.is_valid())

Add form tests for LoginForm

Add form tests for LoginForm

Response:
<INSERT> """accounts app unittests for views

"""
from django.test import TestCase

from accounts.forms import LoginForm

class LoginFormTest(TestCase):
 <INSERT_END> <INSERT>   """Tests the form which validates the email used for login.

    """
    def test_valid_email_accepted(self):
        form = LoginForm({'email': 'newvisitor@example.com'})
        self.assertTrue(form.is_valid())

    def test_invalid_email_declined(self):
        form = LoginForm({'email': 'invalidemail'})
        self.assertFalse(form.is_valid())
 <INSERT_END> <|endoftext|> """accounts app unittests for views

"""
from django.test import TestCase

from accounts.forms import LoginForm

class LoginFormTest(TestCase):
    """Tests the form which validates the email used for login.

    """
    def test_valid_email_accepted(self):
        form = LoginForm({'email': 'newvisitor@example.com'})
        self.assertTrue(form.is_valid())

    def test_invalid_email_declined(self):
        form = LoginForm({'email': 'invalidemail'})
        self.assertFalse(form.is_valid())

Prompt: Add form tests for LoginForm


# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import tracing_backend
from telemetry.core.timeline import model
from telemetry.page.actions import action_runner as action_runner_module
# pylint: disable=W0401,W0614
from telemetry.page.actions.all_page_actions import *
from telemetry.unittest import tab_test_case
from telemetry.web_perf import timeline_interaction_record as tir_module

class ActionRunnerTest(tab_test_case.TabTestCase):
  def testIssuingInteractionRecord(self):
    action_runner = action_runner_module.ActionRunner(self._tab)
    self.Navigate('interaction_enabled_page.html')
    action_runner.RunAction(WaitAction({'seconds': 1}))
    self._browser.StartTracing(tracing_backend.DEFAULT_TRACE_CATEGORIES)
    action_runner.BeginInteraction('TestInteraction', [tir_module.IS_SMOOTH])
    action_runner.EndInteraction('TestInteraction', [tir_module.IS_SMOOTH])
    trace_data = self._browser.StopTracing()
    timeline_model = model.TimelineModel(trace_data)

    records = []
    renderer_thread = timeline_model.GetRendererThreadFromTab(self._tab)
    for event in renderer_thread.async_slices:
      if not tir_module.IsTimelineInteractionRecord(event.name):
        continue
      records.append(tir_module.TimelineInteractionRecord.FromEvent(event))
    self.assertEqual(1, len(records),
                     'Fail to issue the interaction record on tracing timeline.'
                     ' Trace data:\n%s' % repr(trace_data.EventData()))
    self.assertEqual('TestInteraction', records[0].logical_name)
    self.assertTrue(records[0].is_smooth)

Add unittests for action_runner.BeginInteraction and action_runner.EndInteraction.

This is a reland of https://codereview.chromium.org/294943006 after it's reverted in
https://codereview.chromium.org/284183014/.

BUG=368767

Review URL: https://codereview.chromium.org/299443017

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@272782 0039d316-1c4b-4281-b951-d872f2087c98

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import tracing_backend
from telemetry.core.timeline import model
from telemetry.page.actions import action_runner as action_runner_module
# pylint: disable=W0401,W0614
from telemetry.page.actions.all_page_actions import *
from telemetry.unittest import tab_test_case
from telemetry.web_perf import timeline_interaction_record as tir_module

class ActionRunnerTest(tab_test_case.TabTestCase):
  def testIssuingInteractionRecord(self):
    action_runner = action_runner_module.ActionRunner(self._tab)
    self.Navigate('interaction_enabled_page.html')
    action_runner.RunAction(WaitAction({'seconds': 1}))
    self._browser.StartTracing(tracing_backend.DEFAULT_TRACE_CATEGORIES)
    action_runner.BeginInteraction('TestInteraction', [tir_module.IS_SMOOTH])
    action_runner.EndInteraction('TestInteraction', [tir_module.IS_SMOOTH])
    trace_data = self._browser.StopTracing()
    timeline_model = model.TimelineModel(trace_data)

    records = []
    renderer_thread = timeline_model.GetRendererThreadFromTab(self._tab)
    for event in renderer_thread.async_slices:
      if not tir_module.IsTimelineInteractionRecord(event.name):
        continue
      records.append(tir_module.TimelineInteractionRecord.FromEvent(event))
    self.assertEqual(1, len(records),
                     'Fail to issue the interaction record on tracing timeline.'
                     ' Trace data:\n%s' % repr(trace_data.EventData()))
    self.assertEqual('TestInteraction', records[0].logical_name)
    self.assertTrue(records[0].is_smooth)
 <REPLACE_END> <|endoftext|> # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import tracing_backend
from telemetry.core.timeline import model
from telemetry.page.actions import action_runner as action_runner_module
# pylint: disable=W0401,W0614
from telemetry.page.actions.all_page_actions import *
from telemetry.unittest import tab_test_case
from telemetry.web_perf import timeline_interaction_record as tir_module

class ActionRunnerTest(tab_test_case.TabTestCase):
  def testIssuingInteractionRecord(self):
    action_runner = action_runner_module.ActionRunner(self._tab)
    self.Navigate('interaction_enabled_page.html')
    action_runner.RunAction(WaitAction({'seconds': 1}))
    self._browser.StartTracing(tracing_backend.DEFAULT_TRACE_CATEGORIES)
    action_runner.BeginInteraction('TestInteraction', [tir_module.IS_SMOOTH])
    action_runner.EndInteraction('TestInteraction', [tir_module.IS_SMOOTH])
    trace_data = self._browser.StopTracing()
    timeline_model = model.TimelineModel(trace_data)

    records = []
    renderer_thread = timeline_model.GetRendererThreadFromTab(self._tab)
    for event in renderer_thread.async_slices:
      if not tir_module.IsTimelineInteractionRecord(event.name):
        continue
      records.append(tir_module.TimelineInteractionRecord.FromEvent(event))
    self.assertEqual(1, len(records),
                     'Fail to issue the interaction record on tracing timeline.'
                     ' Trace data:\n%s' % repr(trace_data.EventData()))
    self.assertEqual('TestInteraction', records[0].logical_name)
    self.assertTrue(records[0].is_smooth)

Prompt:
Add unittests for action_runner.BeginInteraction and action_runner.EndInteraction.

This is a reland of https://codereview.chromium.org/294943006 after it's reverted in
https://codereview.chromium.org/284183014/.

BUG=368767

Review URL: https://codereview.chromium.org/299443017

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@272782 0039d316-1c4b-4281-b951-d872f2087c98


from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension

# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''

KVSessionExtension(store, app)

import api.userview

Response:
<REPLACE_OLD> Flask

app <REPLACE_NEW> Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension

# Use DictStore until the code is ready for production
store = DictStore()
app <REPLACE_END> <REPLACE_OLD> ''

import <REPLACE_NEW> ''

KVSessionExtension(store, app)

import <REPLACE_END> <|endoftext|> from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension

# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''

KVSessionExtension(store, app)

import api.userview

Prompt:
Change so that kvsession (server side sessions) is used instead of flask default

from flask import Flask

app = Flask(__name__)
app.secret_key = ''

import api.userview


# -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model

WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')

class WishListForm(forms.ModelForm):

    def __init__(self, user, *args, **kwargs):
        super(WishListForm, self).__init__(*args, **kwargs)
        self.instance.owner = user

    class Meta:
        model = WishList
        fields = ('name', )

class WishListLineForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(WishListLineForm, self).__init__(*args, **kwargs)
        self.fields['quantity'].widget.attrs['size'] = 2

LineFormset = inlineformset_factory(
    WishList, Line, fields=('quantity', ), form=WishListLineForm,
    extra=0, can_delete=False)

Response:
<REPLACE_OLD> inlineformset_factory

WishList <REPLACE_NEW> inlineformset_factory, fields_for_model

WishList <REPLACE_END> <REPLACE_OLD> )

LineFormset = inlineformset_factory(WishList, Line, fields=('quantity', ),
 <REPLACE_NEW> )

class WishListLineForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
 <REPLACE_END> <INSERT> super(WishListLineForm, self).__init__(*args, **kwargs)
 <INSERT_END> <INSERT> self.fields['quantity'].widget.attrs['size'] = 2

LineFormset = inlineformset_factory(
 <INSERT_END> <REPLACE_OLD>                <REPLACE_NEW> WishList, Line, fields=('quantity', ), form=WishListLineForm,
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model

WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')

class WishListForm(forms.ModelForm):

    def __init__(self, user, *args, **kwargs):
        super(WishListForm, self).__init__(*args, **kwargs)
        self.instance.owner = user

    class Meta:
        model = WishList
        fields = ('name', )

class WishListLineForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(WishListLineForm, self).__init__(*args, **kwargs)
        self.fields['quantity'].widget.attrs['size'] = 2

LineFormset = inlineformset_factory(
    WishList, Line, fields=('quantity', ), form=WishListLineForm,
    extra=0, can_delete=False)

Prompt:
Set size on wishlist line quantity form field

This doesn't actually work since there is an overriding CSS style.  When
issue #851 is resolved, this should start working.

# -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory

WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')

class WishListForm(forms.ModelForm):

    def __init__(self, user, *args, **kwargs):
        super(WishListForm, self).__init__(*args, **kwargs)
        self.instance.owner = user

    class Meta:
        model = WishList
        fields = ('name', )

LineFormset = inlineformset_factory(WishList, Line, fields=('quantity', ),
                                    extra=0, can_delete=False)


import django_filters

class PagedFilterSet(django_filters.FilterSet):
    """Removes page parameters from the query when applying filters."""

    page_kwarg = 'page'

    def __init__(self, data, *args, **kwargs):
        if self.page_kwarg in data:
            # Create a mutable copy
            data = data.copy()
            del data[self.page_kwarg]
        return super().__init__(data=data, *args, **kwargs)

class DefaultsFilterSet(PagedFilterSet):
    """Extend to define default filter values.

    Set the defaults attribute. E.g.:
        defaults = {
            'is_archived': 'false'
        }
    """

    defaults = None

    def __init__(self, data, *args, **kwargs):
        data = data.copy()

        # Set the defaults if they are not manually set yet
        for key, value in self.defaults.items():
            if key not in data:
                data[key] = value

        super().__init__(data, *args, **kwargs)

Response:
<REPLACE_OLD> query_data, <REPLACE_NEW> data, <REPLACE_END> <REPLACE_OLD> query_data.copy()

 <REPLACE_NEW> data.copy()

 <REPLACE_END> <|endoftext|> import django_filters

class PagedFilterSet(django_filters.FilterSet):
    """Removes page parameters from the query when applying filters."""

    page_kwarg = 'page'

    def __init__(self, data, *args, **kwargs):
        if self.page_kwarg in data:
            # Create a mutable copy
            data = data.copy()
            del data[self.page_kwarg]
        return super().__init__(data=data, *args, **kwargs)

class DefaultsFilterSet(PagedFilterSet):
    """Extend to define default filter values.

    Set the defaults attribute. E.g.:
        defaults = {
            'is_archived': 'false'
        }
    """

    defaults = None

    def __init__(self, data, *args, **kwargs):
        data = data.copy()

        # Set the defaults if they are not manually set yet
        for key, value in self.defaults.items():
            if key not in data:
                data[key] = value

        super().__init__(data, *args, **kwargs)

Prompt:
Make constructor of DefaultFilterSet compatible

 - arguments had different names than FilterSet before

import django_filters

class PagedFilterSet(django_filters.FilterSet):
    """Removes page parameters from the query when applying filters."""

    page_kwarg = 'page'

    def __init__(self, data, *args, **kwargs):
        if self.page_kwarg in data:
            # Create a mutable copy
            data = data.copy()
            del data[self.page_kwarg]
        return super().__init__(data=data, *args, **kwargs)

class DefaultsFilterSet(PagedFilterSet):
    """Extend to define default filter values.

    Set the defaults attribute. E.g.:
        defaults = {
            'is_archived': 'false'
        }
    """

    defaults = None

    def __init__(self, query_data, *args, **kwargs):
        data = query_data.copy()

        # Set the defaults if they are not manually set yet
        for key, value in self.defaults.items():
            if key not in data:
                data[key] = value

        super().__init__(data, *args, **kwargs)


"""Remove the match table.

Revision ID: a8849e4e6784
Revises: 2979a1322381
Create Date: 2020-03-14 20:16:35.882396

"""
from alembic import op

# revision identifiers, used by Alembic.
revision = 'a8849e4e6784'
down_revision = '2979a1322381'

def upgrade():
    op.drop_index('ix_match_collection_id', table_name='match')
    op.drop_index('ix_match_match_collection_id', table_name='match')
    op.drop_table('match')

def downgrade():
    pass

Drop the old xref table

Drop the old xref table

Response:
<INSERT> """Remove the match table.

Revision ID: a8849e4e6784
Revises: 2979a1322381
Create Date: 2020-03-14 20:16:35.882396

"""
from alembic import op

# revision identifiers, used by Alembic.
revision = 'a8849e4e6784'
down_revision = '2979a1322381'

def upgrade():
 <INSERT_END> <INSERT>   op.drop_index('ix_match_collection_id', table_name='match')
    op.drop_index('ix_match_match_collection_id', table_name='match')
    op.drop_table('match')

def downgrade():
    pass
 <INSERT_END> <|endoftext|> """Remove the match table.

Revision ID: a8849e4e6784
Revises: 2979a1322381
Create Date: 2020-03-14 20:16:35.882396

"""
from alembic import op

# revision identifiers, used by Alembic.
revision = 'a8849e4e6784'
down_revision = '2979a1322381'

def upgrade():
    op.drop_index('ix_match_collection_id', table_name='match')
    op.drop_index('ix_match_match_collection_id', table_name='match')
    op.drop_table('match')

def downgrade():
    pass

Prompt: Drop the old xref table


# Copyright 2015 Internap.
#
# 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 warnings

from netman.core.objects.interface import BaseInterface

class Bond(BaseInterface):
    def __init__(self, number=None, link_speed=None, members=None, **interface):
        super(Bond, self).__init__(**interface)
        self.number = number
        self.link_speed = link_speed
        self.members = members or []

    @property
    def interface(self):
        warnings.warn('Deprecated: Use directly the members of Bond instead.',
                      category=DeprecationWarning)
        return self

Response:
<REPLACE_OLD> License.

from <REPLACE_NEW> License.
import warnings

from <REPLACE_END> <REPLACE_OLD> []
 <REPLACE_NEW> []

    @property
    def interface(self):
        warnings.warn('Deprecated: Use directly the members of Bond instead.',
                      category=DeprecationWarning)
        return self
 <REPLACE_END> <|endoftext|> # Copyright 2015 Internap.
#
# 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 warnings

from netman.core.objects.interface import BaseInterface

class Bond(BaseInterface):
    def __init__(self, number=None, link_speed=None, members=None, **interface):
        super(Bond, self).__init__(**interface)
        self.number = number
        self.link_speed = link_speed
        self.members = members or []

    @property
    def interface(self):
        warnings.warn('Deprecated: Use directly the members of Bond instead.',
                      category=DeprecationWarning)
        return self

Prompt:
Support deprecated use of the interface property of Bond.

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

from netman.core.objects.interface import BaseInterface

class Bond(BaseInterface):
    def __init__(self, number=None, link_speed=None, members=None, **interface):
        super(Bond, self).__init__(**interface)
        self.number = number
        self.link_speed = link_speed
        self.members = members or []


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

import os

from betamax import Betamax
from betamax_serializers import pretty_json

URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')

if URL.endswith('/'):
    URL = URL[:-1]

Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with Betamax.configure() as config:
    config.cassette_library_dir = 'test/fixtures/cassettes'
    config.define_cassette_placeholder('<APIKEY>', APIKEY)
    config.default_cassette_options['serialize_with'] = 'prettyjson'

Normalize URL for test cases.

Normalize URL for test cases.

Response:
<REPLACE_OLD> '12341234')

Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with <REPLACE_NEW> '12341234')

if URL.endswith('/'):
    URL = URL[:-1]

Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import os

from betamax import Betamax
from betamax_serializers import pretty_json

URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')

if URL.endswith('/'):
    URL = URL[:-1]

Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with Betamax.configure() as config:
    config.cassette_library_dir = 'test/fixtures/cassettes'
    config.define_cassette_placeholder('<APIKEY>', APIKEY)
    config.default_cassette_options['serialize_with'] = 'prettyjson'

Prompt:
Normalize URL for test cases.

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

import os

from betamax import Betamax
from betamax_serializers import pretty_json

URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')

Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with Betamax.configure() as config:
    config.cassette_library_dir = 'test/fixtures/cassettes'
    config.define_cassette_placeholder('<APIKEY>', APIKEY)
    config.default_cassette_options['serialize_with'] = 'prettyjson'


#!/usr/bin/env python
#coding: utf-8
from cms import VERSION

from setuptools import setup, find_packages

EXCLUDE_FROM_PACKAGES = ['cms.bin']

setup(
    name="onespacemedia-cms",
    version=".".join(str(n) for n in VERSION),
    url="https://github.com/onespacemedia/cms",
    author="Daniel Samuels",
    author_email="daniel@onespacemedia.com",
    license="BSD",
    packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
    include_package_data=True,
    scripts=['cms/bin/start_cms_project.py'],
    zip_safe=False,
    entry_points={
        "console_scripts": [
            "start_cms_project.py = cms.bin.start_cms_project:main",
        ],
    },
    description='CMS used by Onespacemedia',
    install_requires=[
        'django',
        'psycopg2',
        'django-suit',
        'django-optimizations',
        'Pillow',
        'django-reversion',
        'django-usertools',
        'django-historylinks',
        'django-watson',
        'django-extensions',
        'Werkzeug',
        'raven'
    ],
)

Add raven to the dependancy list.

Add raven to the dependancy list.

Response:
<REPLACE_OLD> 'Werkzeug'
 <REPLACE_NEW> 'Werkzeug',
        'raven'
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#coding: utf-8
from cms import VERSION

from setuptools import setup, find_packages

EXCLUDE_FROM_PACKAGES = ['cms.bin']

setup(
    name="onespacemedia-cms",
    version=".".join(str(n) for n in VERSION),
    url="https://github.com/onespacemedia/cms",
    author="Daniel Samuels",
    author_email="daniel@onespacemedia.com",
    license="BSD",
    packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
    include_package_data=True,
    scripts=['cms/bin/start_cms_project.py'],
    zip_safe=False,
    entry_points={
        "console_scripts": [
            "start_cms_project.py = cms.bin.start_cms_project:main",
        ],
    },
    description='CMS used by Onespacemedia',
    install_requires=[
        'django',
        'psycopg2',
        'django-suit',
        'django-optimizations',
        'Pillow',
        'django-reversion',
        'django-usertools',
        'django-historylinks',
        'django-watson',
        'django-extensions',
        'Werkzeug',
        'raven'
    ],
)

Prompt:
Add raven to the dependancy list.
#!/usr/bin/env python
#coding: utf-8
from cms import VERSION

from setuptools import setup, find_packages

EXCLUDE_FROM_PACKAGES = ['cms.bin']

setup(
    name="onespacemedia-cms",
    version=".".join(str(n) for n in VERSION),
    url="https://github.com/onespacemedia/cms",
    author="Daniel Samuels",
    author_email="daniel@onespacemedia.com",
    license="BSD",
    packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
    include_package_data=True,
    scripts=['cms/bin/start_cms_project.py'],
    zip_safe=False,
    entry_points={
        "console_scripts": [
            "start_cms_project.py = cms.bin.start_cms_project:main",
        ],
    },
    description='CMS used by Onespacemedia',
    install_requires=[
        'django',
        'psycopg2',
        'django-suit',
        'django-optimizations',
        'Pillow',
        'django-reversion',
        'django-usertools',
        'django-historylinks',
        'django-watson',
        'django-extensions',
        'Werkzeug'
    ],
)


import json

from django.conf import settings

from mock import Mock, patch

class MockRpc(object):
    def setUp(self):
        self.response = self.set_response()
        self.request = None

        self.rpc_patcher = patch('go.api.go_api.client.rpc')
        self.mock_rpc = self.rpc_patcher.start()
        self.mock_rpc.side_effect = self.set_request

    def set_request(self, session_id, method, params, id=None):
        self.request = {
            'session_id': session_id,
            'method': method,
            'params': params,
            'id': id,
        }

        return self.response

    def tearDown(self):
        self.rpc_patcher.stop()

    @staticmethod
    def make_response_data(result={}, id=None):
        return {
            'id': id,
            'jsonrpc': '2.0',
            'result': result,
        }

    def set_response(self, result={}, id=None):
        response = Mock()
        response.status_code = 200
        response.json = self.make_response_data(result, id)
        self.response = response

    def set_rpc_error_response(self, error, id=None):
        response = Mock()
        response.status_code = 200

        data = self.make_response_data(result=None, id=id)
        data.error = error
        response.json = data

        self.response = response

    def set_error_response(self, code, text):
        response = Mock()
        response.status_code = code
        response.text = text
        self.response = response

    def check_request(self, session_id, method, params, id=None):
        self.mock_post.assert_called_once_with(
            settings.GO_API_URL,
            auth=('session_id', session_id),
            data=json.dumps({
                'jsonrpc': '2.0',
                'id': id,
                'params': params,
                'method': method,
            }))

Add MockRpc test utility class

Add MockRpc test utility class

Response:
<REPLACE_OLD>  <REPLACE_NEW> import json

from django.conf import settings

from mock import Mock, patch

class MockRpc(object):
    def setUp(self):
        self.response = self.set_response()
        self.request = None

        self.rpc_patcher = patch('go.api.go_api.client.rpc')
        self.mock_rpc = self.rpc_patcher.start()
        self.mock_rpc.side_effect = self.set_request

    def set_request(self, session_id, method, params, id=None):
        self.request = {
            'session_id': session_id,
            'method': method,
            'params': params,
            'id': id,
        }

        return self.response

    def tearDown(self):
        self.rpc_patcher.stop()

    @staticmethod
    def make_response_data(result={}, id=None):
        return {
            'id': id,
            'jsonrpc': '2.0',
            'result': result,
        }

    def set_response(self, result={}, id=None):
        response = Mock()
        response.status_code = 200
        response.json = self.make_response_data(result, id)
        self.response = response

    def set_rpc_error_response(self, error, id=None):
        response = Mock()
        response.status_code = 200

        data = self.make_response_data(result=None, id=id)
        data.error = error
        response.json = data

        self.response = response

    def set_error_response(self, code, text):
        response = Mock()
        response.status_code = code
        response.text = text
        self.response = response

    def check_request(self, session_id, method, params, id=None):
        self.mock_post.assert_called_once_with(
            settings.GO_API_URL,
            auth=('session_id', session_id),
            data=json.dumps({
                'jsonrpc': '2.0',
                'id': id,
                'params': params,
                'method': method,
            }))
 <REPLACE_END> <|endoftext|> import json

from django.conf import settings

from mock import Mock, patch

class MockRpc(object):
    def setUp(self):
        self.response = self.set_response()
        self.request = None

        self.rpc_patcher = patch('go.api.go_api.client.rpc')
        self.mock_rpc = self.rpc_patcher.start()
        self.mock_rpc.side_effect = self.set_request

    def set_request(self, session_id, method, params, id=None):
        self.request = {
            'session_id': session_id,
            'method': method,
            'params': params,
            'id': id,
        }

        return self.response

    def tearDown(self):
        self.rpc_patcher.stop()

    @staticmethod
    def make_response_data(result={}, id=None):
        return {
            'id': id,
            'jsonrpc': '2.0',
            'result': result,
        }

    def set_response(self, result={}, id=None):
        response = Mock()
        response.status_code = 200
        response.json = self.make_response_data(result, id)
        self.response = response

    def set_rpc_error_response(self, error, id=None):
        response = Mock()
        response.status_code = 200

        data = self.make_response_data(result=None, id=id)
        data.error = error
        response.json = data

        self.response = response

    def set_error_response(self, code, text):
        response = Mock()
        response.status_code = code
        response.text = text
        self.response = response

    def check_request(self, session_id, method, params, id=None):
        self.mock_post.assert_called_once_with(
            settings.GO_API_URL,
            auth=('session_id', session_id),
            data=json.dumps({
                'jsonrpc': '2.0',
                'id': id,
                'params': params,
                'method': method,
            }))

Prompt: Add MockRpc test utility class


# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

__version__ = "0.1"

try:
    __import__('pkg_resources').declare_namespace(__name__)
except ImportError:
    from pkgutil import extend_path
    __path__ = extend_path(__path__, __name__)

Add module info for politics.

Add module info for politics.

Response:
<INSERT> # encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. <INSERT_END> <INSERT> See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

__version__ = "0.1"

try:
    __import__('pkg_resources').declare_namespace(__name__)
except ImportError:
    from pkgutil import extend_path
    __path__ = extend_path(__path__, __name__)
 <INSERT_END> <|endoftext|> # encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

__version__ = "0.1"

try:
    __import__('pkg_resources').declare_namespace(__name__)
except ImportError:
    from pkgutil import extend_path
    __path__ = extend_path(__path__, __name__)

Prompt: Add module info for politics.


import nose
import cle

import os
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                             os.path.join('..', '..', 'binaries', 'tests'))

def test_progname():
    filename = os.path.join(test_location, 'x86_64', 'cat')
    ld = cle.Loader(filename, auto_load_libs=False)
    progname_ptr_symbol = ld.find_symbol('__progname')
    progname_ptr = ld.memory.unpack_word(progname_ptr_symbol.rebased_addr)

    nose.tools.assert_not_equal(progname_ptr, 0)

    progname = ld.memory.load(progname_ptr, 8)
    nose.tools.assert_equal(progname, b'program\0')

def test_got_relocation():
    filename = os.path.join(test_location, 'x86_64', 'multiarch_main_main.o')
    ld = cle.Loader(filename)

    reloc = ld.main_object.relocs[1]
    nose.tools.assert_equal(reloc.symbol.name, 'vex_failure_exit')  # this should never fail
    nose.tools.assert_equal(reloc.symbol.resolvedby.name, 'got.vex_failure_exit')

    ptr = ld.memory.unpack_word(reloc.symbol.resolvedby.rebased_addr)
    final_symbol = ld.find_symbol(ptr)

    nose.tools.assert_is_not(final_symbol, None)
    nose.tools.assert_equal(final_symbol.name, 'vex_failure_exit')
    nose.tools.assert_true(final_symbol.is_extern)

if __name__ == '__main__':
    test_progname()
    test_got_relocation()

Add test for simdata and GOT relocations

Response:
<INSERT> import nose
import cle

import os
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
 <INSERT_END> <INSERT>                                            os.path.join('..', '..', 'binaries', 'tests'))

def test_progname():
    filename = os.path.join(test_location, 'x86_64', 'cat')
    ld = cle.Loader(filename, auto_load_libs=False)
    progname_ptr_symbol = ld.find_symbol('__progname')
    progname_ptr = ld.memory.unpack_word(progname_ptr_symbol.rebased_addr)

    nose.tools.assert_not_equal(progname_ptr, 0)

    progname = ld.memory.load(progname_ptr, 8)
    nose.tools.assert_equal(progname, b'program\0')

def test_got_relocation():
    filename = os.path.join(test_location, 'x86_64', 'multiarch_main_main.o')
    ld = cle.Loader(filename)

    reloc = ld.main_object.relocs[1]
    nose.tools.assert_equal(reloc.symbol.name, 'vex_failure_exit')  # this should never fail
    nose.tools.assert_equal(reloc.symbol.resolvedby.name, 'got.vex_failure_exit')

    ptr = ld.memory.unpack_word(reloc.symbol.resolvedby.rebased_addr)
    final_symbol = ld.find_symbol(ptr)

    nose.tools.assert_is_not(final_symbol, None)
    nose.tools.assert_equal(final_symbol.name, 'vex_failure_exit')
    nose.tools.assert_true(final_symbol.is_extern)

if __name__ == '__main__':
    test_progname()
    test_got_relocation()
 <INSERT_END> <|endoftext|> import nose
import cle

import os
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                             os.path.join('..', '..', 'binaries', 'tests'))

def test_progname():
    filename = os.path.join(test_location, 'x86_64', 'cat')
    ld = cle.Loader(filename, auto_load_libs=False)
    progname_ptr_symbol = ld.find_symbol('__progname')
    progname_ptr = ld.memory.unpack_word(progname_ptr_symbol.rebased_addr)

    nose.tools.assert_not_equal(progname_ptr, 0)

    progname = ld.memory.load(progname_ptr, 8)
    nose.tools.assert_equal(progname, b'program\0')

def test_got_relocation():
    filename = os.path.join(test_location, 'x86_64', 'multiarch_main_main.o')
    ld = cle.Loader(filename)

    reloc = ld.main_object.relocs[1]
    nose.tools.assert_equal(reloc.symbol.name, 'vex_failure_exit')  # this should never fail
    nose.tools.assert_equal(reloc.symbol.resolvedby.name, 'got.vex_failure_exit')

    ptr = ld.memory.unpack_word(reloc.symbol.resolvedby.rebased_addr)
    final_symbol = ld.find_symbol(ptr)

    nose.tools.assert_is_not(final_symbol, None)
    nose.tools.assert_equal(final_symbol.name, 'vex_failure_exit')
    nose.tools.assert_true(final_symbol.is_extern)

if __name__ == '__main__':
    test_progname()
    test_got_relocation()

Prompt: Add test for simdata and GOT relocations


from mock import patch

from django.test import TestCase
from breach.sniffer import Sniffer

class SnifferTest(TestCase):
    def setUp(self):
        self.endpoint = 'http://localhost'
        self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')

    @patch('breach.sniffer.requests')
    def test_sniffer_start(self, requests):
        self.sniffer.start()
        self.assertTrue(requests.post.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_read(self, requests):
        self.sniffer.read()
        self.assertTrue(requests.get.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_delete(self, requests):
        self.sniffer.delete()
        self.assertTrue(requests.post.called)

Migrate Sniffer unit test to new API

Migrate Sniffer unit test to new API

Response:
<REPLACE_OLD> Sniffer(self.endpoint)

        self.source_ip = '147.102.239.229'
        self.destination_host = 'dionyziz.com'

 <REPLACE_NEW> Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')

 <REPLACE_END> <REPLACE_OLD> self.sniffer.start(self.source_ip, self.destination_host)
 <REPLACE_NEW> self.sniffer.start()
 <REPLACE_END> <REPLACE_OLD> self.sniffer.read(self.source_ip, self.destination_host)
 <REPLACE_NEW> self.sniffer.read()
 <REPLACE_END> <REPLACE_OLD> self.sniffer.delete(self.source_ip, self.destination_host)
 <REPLACE_NEW> self.sniffer.delete()
 <REPLACE_END> <|endoftext|> from mock import patch

from django.test import TestCase
from breach.sniffer import Sniffer

class SnifferTest(TestCase):
    def setUp(self):
        self.endpoint = 'http://localhost'
        self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')

    @patch('breach.sniffer.requests')
    def test_sniffer_start(self, requests):
        self.sniffer.start()
        self.assertTrue(requests.post.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_read(self, requests):
        self.sniffer.read()
        self.assertTrue(requests.get.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_delete(self, requests):
        self.sniffer.delete()
        self.assertTrue(requests.post.called)

Prompt:
Migrate Sniffer unit test to new API

from mock import patch

from django.test import TestCase
from breach.sniffer import Sniffer

class SnifferTest(TestCase):
    def setUp(self):
        self.endpoint = 'http://localhost'
        self.sniffer = Sniffer(self.endpoint)

        self.source_ip = '147.102.239.229'
        self.destination_host = 'dionyziz.com'

    @patch('breach.sniffer.requests')
    def test_sniffer_start(self, requests):
        self.sniffer.start(self.source_ip, self.destination_host)
        self.assertTrue(requests.post.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_read(self, requests):
        self.sniffer.read(self.source_ip, self.destination_host)
        self.assertTrue(requests.get.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_delete(self, requests):
        self.sniffer.delete(self.source_ip, self.destination_host)
        self.assertTrue(requests.post.called)


from setuptools import setup

setup(name='striketracker',
      version='0.5.1',
      description='Command line interface to the Highwinds CDN',
      url='https://github.com/Highwinds/striketracker',
      author='Mark Cahill',
      author_email='support@highwinds.com',
      license='MIT',
      packages=['striketracker'],
      install_requires=[
          'requests>=2.0.1',
          'PyYAML>=3.10'
      ],
      scripts=['bin/striketracker'],
      test_suite='nose.collector',
      tests_require=['nose', 'responses', 'coverage'],
      zip_safe=False)

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

setup(name='striketracker',
      version='0.5.1',
      description='Command line interface to the Highwinds CDN',
      url='https://github.com/Highwinds/striketracker',
      author='Mark Cahill',
      author_email='support@highwinds.com',
      license='MIT',
      packages=['striketracker'],
      install_requires=[
          'requests>=2.0.1',
          'PyYAML>=3.10'
      ],
      scripts=['bin/striketracker'],
      test_suite='nose.collector',
      tests_require=['nose', 'responses', 'coverage'],
      zip_safe=False)

Prompt:
Bump version number for host clone functionality

from setuptools import setup

setup(name='striketracker',
      version='0.5',
      description='Command line interface to the Highwinds CDN',
      url='https://github.com/Highwinds/striketracker',
      author='Mark Cahill',
      author_email='support@highwinds.com',
      license='MIT',
      packages=['striketracker'],
      install_requires=[
          'requests>=2.0.1',
          'PyYAML>=3.10'
      ],
      scripts=['bin/striketracker'],
      test_suite='nose.collector',
      tests_require=['nose', 'responses', 'coverage'],
      zip_safe=False)


# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017

import os.path

# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
	os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js'

PYGMENTS_STYLE = 'default'

def get_pygments_stylesheet(selector, style=None):
	if style is None:
		style = PYGMENTS_STYLE
	if style == '':
		return ''
	try:
		from pygments.formatters import HtmlFormatter
	except ImportError:
		return ''
	else:
		return HtmlFormatter(style=style).get_style_defs(selector) + '\n'

def get_mathjax_url(webenv):
	if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
		return MATHJAX_LOCAL_URL
	else:
		return MATHJAX_WEB_URL

Update MathJax URL to 2.7.2

Update MathJax URL to 2.7.2

Response:
<REPLACE_OLD> 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js'

PYGMENTS_STYLE <REPLACE_NEW> 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js'

PYGMENTS_STYLE <REPLACE_END> <|endoftext|> # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017

import os.path

# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
	os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js'

PYGMENTS_STYLE = 'default'

def get_pygments_stylesheet(selector, style=None):
	if style is None:
		style = PYGMENTS_STYLE
	if style == '':
		return ''
	try:
		from pygments.formatters import HtmlFormatter
	except ImportError:
		return ''
	else:
		return HtmlFormatter(style=style).get_style_defs(selector) + '\n'

def get_mathjax_url(webenv):
	if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
		return MATHJAX_LOCAL_URL
	else:
		return MATHJAX_WEB_URL

Prompt:
Update MathJax URL to 2.7.2

# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017

import os.path

# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
	os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js'

PYGMENTS_STYLE = 'default'

def get_pygments_stylesheet(selector, style=None):
	if style is None:
		style = PYGMENTS_STYLE
	if style == '':
		return ''
	try:
		from pygments.formatters import HtmlFormatter
	except ImportError:
		return ''
	else:
		return HtmlFormatter(style=style).get_style_defs(selector) + '\n'

def get_mathjax_url(webenv):
	if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
		return MATHJAX_LOCAL_URL
	else:
		return MATHJAX_WEB_URL


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup

with open("README.md") as readme_file:
    readme = readme_file.read()

requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]

setup(
    author="Ryan Gibson",
    author_email="ryanalexandergibson@gmail.com",
    name="stego_lsb",
    version="1.3.1",
    description="stego lsb",
    keywords="stego lsb",
    license="MIT",
    long_description=readme,
    long_description_content_type="text/markdown",
    url="https://github.com/ragibson/Steganography",
    install_requires=requirements,
    entry_points="""
        [console_scripts]
        stegolsb=stego_lsb.cli:main
    """,
    include_package_data=True,
    packages=find_packages(include=["stego_lsb"]),
    zip_safe=False,
    python_requires=">=3.7",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3 :: Only",
    ],
)

Response:
<REPLACE_OLD> python_requires=">=3.6",
 <REPLACE_NEW> python_requires=">=3.7",
 <REPLACE_END> <DELETE> 3.6",
        "Programming Language :: Python :: <DELETE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup

with open("README.md") as readme_file:
    readme = readme_file.read()

requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]

setup(
    author="Ryan Gibson",
    author_email="ryanalexandergibson@gmail.com",
    name="stego_lsb",
    version="1.3.1",
    description="stego lsb",
    keywords="stego lsb",
    license="MIT",
    long_description=readme,
    long_description_content_type="text/markdown",
    url="https://github.com/ragibson/Steganography",
    install_requires=requirements,
    entry_points="""
        [console_scripts]
        stegolsb=stego_lsb.cli:main
    """,
    include_package_data=True,
    packages=find_packages(include=["stego_lsb"]),
    zip_safe=False,
    python_requires=">=3.7",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3 :: Only",
    ],
)

Prompt:
Remove support for end-of-life Python 3.6 in next release

Checked again just now and we are still waiting on Python 3.10 stability
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup

with open("README.md") as readme_file:
    readme = readme_file.read()

requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]

setup(
    author="Ryan Gibson",
    author_email="ryanalexandergibson@gmail.com",
    name="stego_lsb",
    version="1.3.1",
    description="stego lsb",
    keywords="stego lsb",
    license="MIT",
    long_description=readme,
    long_description_content_type="text/markdown",
    url="https://github.com/ragibson/Steganography",
    install_requires=requirements,
    entry_points="""
        [console_scripts]
        stegolsb=stego_lsb.cli:main
    """,
    include_package_data=True,
    packages=find_packages(include=["stego_lsb"]),
    zip_safe=False,
    python_requires=">=3.6",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3 :: Only",
    ],
)


# -*- coding: utf-8 -*-
from rest_framework import serializers

from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game

class BroadcastSerializer(serializers.ModelSerializer):
    class Meta:
        depth = 1
        model = Broadcast

class RaidSerializer(serializers.ModelSerializer):
    class Meta:
        model = Raid

class SeriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Series

class GameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Game

Add Raid to the API.

Add Raid to the API.

Response:
<INSERT> Raid, <INSERT_END> <INSERT> RaidSerializer(serializers.ModelSerializer):
    class Meta:
        model = Raid

class <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from rest_framework import serializers

from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game

class BroadcastSerializer(serializers.ModelSerializer):
    class Meta:
        depth = 1
        model = Broadcast

class RaidSerializer(serializers.ModelSerializer):
    class Meta:
        model = Raid

class SeriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Series

class GameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Game

Prompt:
Add Raid to the API.

# -*- coding: utf-8 -*-
from rest_framework import serializers

from apps.broadcasts.models import Broadcast, Series
from apps.games.models import Game

class BroadcastSerializer(serializers.ModelSerializer):
    class Meta:
        depth = 1
        model = Broadcast

class SeriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Series

class GameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Game


# coding: utf-8

from __future__ import unicode_literals

from six.moves import map   # pylint:disable=redefined-builtin

__all__ = list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))

Response:
<REPLACE_OLD> unicode_literals

import six

__all__ = [
 <REPLACE_NEW> unicode_literals

from six.moves import map <REPLACE_END> <REPLACE_OLD>  'collaboration',
    'events',
    'file',
    'folder',
    'group',
    'group_membership',
    'search',
    'user',
]

if six.PY2:
    __all__ <REPLACE_NEW> # pylint:disable=redefined-builtin

__all__ <REPLACE_END> <REPLACE_OLD> [unicode.encode(x, 'utf-8') for x in __all__]
 <REPLACE_NEW> list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))
 <REPLACE_END> <|endoftext|> # coding: utf-8

from __future__ import unicode_literals

from six.moves import map   # pylint:disable=redefined-builtin

__all__ = list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))

Prompt:
Change format of sub-module names in the object module to str

# coding: utf-8

from __future__ import unicode_literals

import six

__all__ = [
    'collaboration',
    'events',
    'file',
    'folder',
    'group',
    'group_membership',
    'search',
    'user',
]

if six.PY2:
    __all__ = [unicode.encode(x, 'utf-8') for x in __all__]


import MOS6502
import instructions

def disasm(memory):
    index = 0
    lines = []

    while index < len(memory):
        currInst = instructions.instructions[memory[index]]

        line = currInst.mnem + " "
        line += currInst.operType + " "
        if currInst.size > 1:
            for i in range(1, currInst.size):
                line += hex(memory[i]) + " "

        lines.append(line)
        index += currInst.size

    return lines

code = [0x78, 0xD8, 0xA9, 0x10, 0x8D, 0x00, 0x20, 0xA2]
print disasm(code)

Add quick dumb disassembler for upcoming debugger

Response:
<INSERT> import MOS6502
import instructions

def disasm(memory):
 <INSERT_END> <INSERT>   index = 0
    lines = []

    while index < len(memory):
        currInst = instructions.instructions[memory[index]]

        line = currInst.mnem + " "
        line += currInst.operType + " "
        if currInst.size > 1:
            for i in range(1, currInst.size):
                line += hex(memory[i]) + " "

        lines.append(line)
        index += currInst.size

    return lines

code = [0x78, 0xD8, 0xA9, 0x10, 0x8D, 0x00, 0x20, 0xA2]
print disasm(code)
 <INSERT_END> <|endoftext|> import MOS6502
import instructions

def disasm(memory):
    index = 0
    lines = []

    while index < len(memory):
        currInst = instructions.instructions[memory[index]]

        line = currInst.mnem + " "
        line += currInst.operType + " "
        if currInst.size > 1:
            for i in range(1, currInst.size):
                line += hex(memory[i]) + " "

        lines.append(line)
        index += currInst.size

    return lines

code = [0x78, 0xD8, 0xA9, 0x10, 0x8D, 0x00, 0x20, 0xA2]
print disasm(code)

Prompt: Add quick dumb disassembler for upcoming debugger