#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.

"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
    import bson
except ImportError:
    raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")

# also update in setup.py
version = "1.3"
version_info = (1, 3)

ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = '{ $meta: "textScore" }'
"""TEXT Index sort order."""

from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
                    DataError, IntegrityError, ProgrammingError, NotSupportedError)

from client import Client

Support Sort Order For TEXT Index

Support Sort Order For TEXT Index

Response:
#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.

"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
    import bson
except ImportError:
    raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")

# also update in setup.py
version = "1.3"
version_info = (1, 3)

ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""
TEXT = '{ $meta: "textScore" }'
"""TEXT Index sort order."""

from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
                    DataError, IntegrityError, ProgrammingError, NotSupportedError)

from client import Client

Prompt:
Support Sort Order For TEXT Index

#!/bin/env python
#
# Copyright 2010 bit.ly
#
# 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.

"""
AsyncMongo is an asynchronous library for accessing mongo
http://github.com/bitly/asyncmongo
"""
try:
    import bson
except ImportError:
    raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")

# also update in setup.py
version = "1.3"
version_info = (1, 3)

ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO2D = "2d"
"""Index specifier for a 2-dimensional `geospatial index`"""

from errors import (Error, InterfaceError, AuthenticationError, DatabaseError, RSConnectionError,
                    DataError, IntegrityError, ProgrammingError, NotSupportedError)

from client import Client


Response:
#!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2

class UnicodeApp(cmd2.Cmd):
    """Example cmd2 application with unicode command names."""

    def __init__(self):
        super().__init__()
        self.intro = 'Welcome the Unicode example app. Note the full Unicode support:  😇 💩'

    def do_𝛑print(self, _):
        """This command prints 𝛑 to 5 decimal places."""
        self.poutput("𝛑 = {0:.6}".format(math.pi))

    def do_你好(self, arg):
        """This command says hello in Chinese (Mandarin)."""
        self.poutput("你好 " + arg)

if __name__ == '__main__':
    app = UnicodeApp()
    app.cmdloop()

Prompt:
Fix flake8 error due to extra blank line in example

#!/usr/bin/env python
# coding=utf-8
"""A simple example demonstrating support for unicode command names.
"""
import math
import cmd2

class UnicodeApp(cmd2.Cmd):
    """Example cmd2 application with unicode command names."""

    def __init__(self):
        super().__init__()
        self.intro = 'Welcome the Unicode example app. Note the full Unicode support:  😇 💩'

    def do_𝛑print(self, _):
        """This command prints 𝛑 to 5 decimal places."""
        self.poutput("𝛑 = {0:.6}".format(math.pi))

    def do_你好(self, arg):
        """This command says hello in Chinese (Mandarin)."""
        self.poutput("你好 " + arg)

if __name__ == '__main__':
    app = UnicodeApp()
    app.cmdloop()


"""
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""

from setuptools import setup, find_packages  # noqa

setup(
    name='tensorpy',
    version='1.0.1',
    url='http://tensorpy.com',
    author='Michael Mintz',
    author_email='@mintzworld',
    maintainer='Michael Mintz',
    description='The fast & easy way to get started with Tensorflow',
    license='The MIT License',
    install_requires=[
        'requests==2.11.1',
        'six==1.10.0',
        'Pillow==3.4.1',
        'BeautifulSoup==3.2.1',
        ],
    packages=['tensorpy'],
    )

Response:
"""
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""

from setuptools import setup, find_packages  # noqa

setup(
    name='tensorpy',
    version='1.0.1',
    url='http://tensorpy.com',
    author='Michael Mintz',
    author_email='@mintzworld',
    maintainer='Michael Mintz',
    description='The fast & easy way to get started with Tensorflow',
    license='The MIT License',
    install_requires=[
        'requests==2.11.1',
        'six==1.10.0',
        'Pillow==3.4.1',
        'BeautifulSoup==3.2.1',
        ],
    packages=['tensorpy'],
    )

Prompt:
Update the "six" to force version 1.10.0

"""
The setup package to install TensorPy dependencies
*> This does NOT include TensorFlow installation
*> To install TensorFlow, use "./install_tensorflow.sh"
"""

from setuptools import setup, find_packages  # noqa

setup(
    name='tensorpy',
    version='1.0.1',
    url='http://tensorpy.com',
    author='Michael Mintz',
    author_email='@mintzworld',
    maintainer='Michael Mintz',
    description='The fast & easy way to get started with Tensorflow',
    license='The MIT License',
    install_requires=[
        'requests==2.11.1',
        'six>=1.10.0',
        'Pillow==3.4.1',
        'BeautifulSoup==3.2.1',
        ],
    packages=['tensorpy'],
    )


from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin

class CustomAction(db.Model, BaseMixin, SerializerMixin):
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(400))
    entity_type = db.Column(db.String(40), default="all")

Add entity type column to actions

Add entity type column to actions

Response:
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin

class CustomAction(db.Model, BaseMixin, SerializerMixin):
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(400))
    entity_type = db.Column(db.String(40), default="all")

Prompt:
Add entity type column to actions

from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin

class CustomAction(db.Model, BaseMixin, SerializerMixin):
    name = db.Column(db.String(80), nullable=False)
    url = db.Column(db.String(400))


def verifyUnique(string):
    if len(string) > 128:
        return False
    characterHash = [0] * 128
    for character in string:
        hashKey = ord(character)%128
        if(characterHash[hashKey] > 0):
            return False
        else:
            characterHash[hashKey] = characterHash[hashKey]+1
    return True

print verifyUnique('test') # False ,O(n)
print verifyUnique('aquickboASDFwnfxjmps><verthlzydg')  # True ,O(n)

Verify the given string has unique characters

Response:
def verifyUnique(string):
    if len(string) > 128:
        return False
    characterHash = [0] * 128
    for character in string:
        hashKey = ord(character)%128
        if(characterHash[hashKey] > 0):
            return False
        else:
            characterHash[hashKey] = characterHash[hashKey]+1
    return True

print verifyUnique('test') # False ,O(n)
print verifyUnique('aquickboASDFwnfxjmps><verthlzydg')  # True ,O(n)

Prompt: Verify the given string has unique characters


#!/usr/bin/env python
from setuptools import setup

setup(name = 'i2py',
    version = '0.3',
    description = 'Tools to work with i2p.',
    author = 'See contributors.txt',
    author_email = 'Anonymous',
    classifiers = [
    'Development Status :: 3 - Alpha',
    #'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: MIT License',
    'Intended Audience :: Developers',
    'Topic :: Utilities',
    ],
    install_requires = [      # If you plan on adding something, make it known why.
                              # Let's try to keep the dependencies minimal, okay?
    'bunch',                  # Needed by i2py.control.pyjsonrpc.
    'python-geoip',           # Needed by i2py.netdb.
    'python-geoip-geolite2',  # Needed by i2py.netdb.
    ],
    tests_require=['pytest'],
    url = 'https://github.com/chris-barry/i2py',
    packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'],
)

Response:
#!/usr/bin/env python
from setuptools import setup

setup(name = 'i2py',
    version = '0.3',
    description = 'Tools to work with i2p.',
    author = 'See contributors.txt',
    author_email = 'Anonymous',
    classifiers = [
    'Development Status :: 3 - Alpha',
    #'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: MIT License',
    'Intended Audience :: Developers',
    'Topic :: Utilities',
    ],
    install_requires = [      # If you plan on adding something, make it known why.
                              # Let's try to keep the dependencies minimal, okay?
    'bunch',                  # Needed by i2py.control.pyjsonrpc.
    'python-geoip',           # Needed by i2py.netdb.
    'python-geoip-geolite2',  # Needed by i2py.netdb.
    ],
    tests_require=['pytest'],
    url = 'https://github.com/chris-barry/i2py',
    packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'],
)

Prompt:
Change version to 0.3 due to functions changing name.

#!/usr/bin/env python
from setuptools import setup

setup(name = 'i2py',
    version = '0.2',
    description = 'Tools to work with i2p.',
    author = 'contributors.txt',
    author_email = 'Anonymous',
    classifiers = [
    'Development Status :: 3 - Alpha',
    #'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: MIT License',
    'Intended Audience :: Developers',
    'Topic :: Utilities',
    ],
    install_requires = [      # If you plan on adding something, make it known why.
                              # Let's try to keep the dependencies minimal, okay?
    'bunch',                  # Needed by i2py.control.pyjsonrpc.
    'python-geoip',           # Needed by i2py.netdb.
    'python-geoip-geolite2',  # Needed by i2py.netdb.
    ],
    tests_require=['pytest'],
    url = 'https://github.com/chris-barry/i2py',
    packages = ['i2py', 'i2py.netdb', 'i2py.control', 'i2py.control.pyjsonrpc'],
)


#!/usr/bin/env py.test
# -*- coding: utf-8 -*-
# Created on Fri Apr 25 02:33:04 2014
# License is MIT, see COPYING.txt for more details.
# @author: Danilo de Jesus da Silva Bellini

import os, re, pytest
from fractal import generate_fractal, call_kw, cli_parse_args
from io import BytesIO
from pylab import imread, imsave

def show_parameters(fname):
  """ String with CLI args to show the fractal with the given ``fname`` """
  re_complex = re.compile("(?:([+-]?\s*[0-9.]+))?\s*"
                          "(?:([+-]\s*[0-9.]+)\s*)?(.*)")
  def part_generator():
    for part in fname.rsplit(".", 1)[0].split("_"):
      if "=" in part:
        yield "--" + part
      else:
        yield " ".join(filter(lambda x: x, re_complex.match(part).groups()))
    yield "--show"
  return " ".join(part_generator())

def to_dict_params(fname):
  """ Get full kwargs from file name """
  return cli_parse_args(show_parameters(fname).split())

@pytest.mark.parametrize("fname", os.listdir("images"))
def test_file_image(fname):
  ext = os.path.splitext(fname)[-1][len(os.path.extsep):]
  kwargs = to_dict_params(fname)

  # Creates the image in memory
  mem = BytesIO()
  fractal_data = call_kw(generate_fractal, kwargs)
  imsave(mem, fractal_data, cmap=kwargs["cmap"], format=ext)
  mem.seek(0) # Return stream psition back for reading

  # Comparison pixel-by-pixel
  img_file = imread("images/" + fname)
  img_mem = imread(mem, format=ext)
  assert img_file.tolist() == img_mem.tolist()

Test with each example image in the repository

Response:
#!/usr/bin/env py.test
# -*- coding: utf-8 -*-
# Created on Fri Apr 25 02:33:04 2014
# License is MIT, see COPYING.txt for more details.
# @author: Danilo de Jesus da Silva Bellini

import os, re, pytest
from fractal import generate_fractal, call_kw, cli_parse_args
from io import BytesIO
from pylab import imread, imsave

def show_parameters(fname):
  """ String with CLI args to show the fractal with the given ``fname`` """
  re_complex = re.compile("(?:([+-]?\s*[0-9.]+))?\s*"
                          "(?:([+-]\s*[0-9.]+)\s*)?(.*)")
  def part_generator():
    for part in fname.rsplit(".", 1)[0].split("_"):
      if "=" in part:
        yield "--" + part
      else:
        yield " ".join(filter(lambda x: x, re_complex.match(part).groups()))
    yield "--show"
  return " ".join(part_generator())

def to_dict_params(fname):
  """ Get full kwargs from file name """
  return cli_parse_args(show_parameters(fname).split())

@pytest.mark.parametrize("fname", os.listdir("images"))
def test_file_image(fname):
  ext = os.path.splitext(fname)[-1][len(os.path.extsep):]
  kwargs = to_dict_params(fname)

  # Creates the image in memory
  mem = BytesIO()
  fractal_data = call_kw(generate_fractal, kwargs)
  imsave(mem, fractal_data, cmap=kwargs["cmap"], format=ext)
  mem.seek(0) # Return stream psition back for reading

  # Comparison pixel-by-pixel
  img_file = imread("images/" + fname)
  img_mem = imread(mem, format=ext)
  assert img_file.tolist() == img_mem.tolist()

Prompt: Test with each example image in the repository


import unittest
import os
import sys
from gitdata import GitData
import simplejson as json

class TestGitData(unittest.TestCase):
    def test_fetch(self):
        gd = GitData(repo="./treenexus")

        study_id = 438
        study_nexson = gd.fetch_study(study_id)
        valid = 1
        try:
            json.loads(study_nexson)
        except:
            valid = 0
        self.assertTrue( valid, "fetch_study(%s) returned valid JSON" % study_id)

    def test_write(self):
        gd = GitData(repo="./treenexus")
        author   = "John Doe <john@doe.com>"
        content  = '{"foo":"bar"}'
        study_id = 9999
        branch   = "johndoe_study_%s" % study_id
        new_sha  = gd.write_study(study_id,content,branch,author)
        self.assertTrue( new_sha != "", "new_sha is non-empty")

    def test_branch_exists(self):
        gd = GitData(repo="./treenexus")
        exists = gd.branch_exists("nothisdoesnotexist")
        self.assertTrue( exists == 0, "branch does not exist")

        exists = gd.branch_exists("master")
        self.assertTrue( exists, "master branch exists")

def suite():
    loader = unittest.TestLoader()
    testsuite = loader.loadTestsFromTestCase(TestGitData)
    return testsuite

def test_main():
    testsuite = suite()
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    result = runner.run(testsuite)

if __name__ == "__main__":
    test_main()

Response:
import unittest
import os
import sys
from gitdata import GitData
import simplejson as json

class TestGitData(unittest.TestCase):
    def test_fetch(self):
        gd = GitData(repo="./treenexus")

        study_id = 438
        study_nexson = gd.fetch_study(study_id)
        valid = 1
        try:
            json.loads(study_nexson)
        except:
            valid = 0
        self.assertTrue( valid, "fetch_study(%s) returned valid JSON" % study_id)

    def test_write(self):
        gd = GitData(repo="./treenexus")
        author   = "John Doe <john@doe.com>"
        content  = '{"foo":"bar"}'
        study_id = 9999
        branch   = "johndoe_study_%s" % study_id
        new_sha  = gd.write_study(study_id,content,branch,author)
        self.assertTrue( new_sha != "", "new_sha is non-empty")

    def test_branch_exists(self):
        gd = GitData(repo="./treenexus")
        exists = gd.branch_exists("nothisdoesnotexist")
        self.assertTrue( exists == 0, "branch does not exist")

        exists = gd.branch_exists("master")
        self.assertTrue( exists, "master branch exists")

def suite():
    loader = unittest.TestLoader()
    testsuite = loader.loadTestsFromTestCase(TestGitData)
    return testsuite

def test_main():
    testsuite = suite()
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    result = runner.run(testsuite)

if __name__ == "__main__":
    test_main()

Prompt:
Convert GitData tests to a unittest suite

from nose       import with_setup
from nose.tools import *
import os
import sys
from gitdata import GitData
import simplejson as json

def test_fetch():
    gd = GitData(repo="./treenexus")

    study_id = 438
    study_nexson = gd.fetch_study(study_id)
    valid = 1
    try:
        json.loads(study_nexson)
    except:
        valid = 0
    assert valid, "fetch_study(%s) returned valid JSON" % study_id

def test_write():
    gd = GitData(repo="./treenexus")
    author   = "John Doe <john@doe.com>"
    content  = '{"foo":"bar"}'
    study_id = 999
    branch   = "johndoe_study_%s" % study_id
    new_sha  = gd.write_study(study_id,content,branch,author)
    assert new_sha != "", "new_sha is non-empty"

def test_branch_exists():
    gd = GitData(repo="./treenexus")
    exists = gd.branch_exists("nothisdoesnotexist")
    assert exists == 0, "branch does not exist"

    exists = gd.branch_exists("master")
    assert exists, "master branch exists"

test_branch_exists()
test_fetch()
test_write()


from __future__ import absolute_import

from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue

@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
    def get_attrs(self, item_list, user):
        assert len(set(i.key for i in item_list)) < 2

        tagvalues = dict(
            (t.value, t)
            for t in TagValue.objects.filter(
                project=item_list[0].project,
                key=item_list[0].key,
                value__in=[i.value for i in item_list]
            )
        )

        result = {}
        for item in item_list:
            result[item] = {
                'name': tagvalues[item.value].get_label(),
            }
        return result

    def serialize(self, obj, attrs, user):
        d = {
            'name': attrs['name'],
            'key': obj.key,
            'value': obj.value,
            'count': obj.times_seen,
            'lastSeen': obj.last_seen,
            'firstSeen': obj.first_seen,
        }
        return d

Implement labels on group tag values

Implement labels on group tag values

Response:
from __future__ import absolute_import

from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue

@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
    def get_attrs(self, item_list, user):
        assert len(set(i.key for i in item_list)) < 2

        tagvalues = dict(
            (t.value, t)
            for t in TagValue.objects.filter(
                project=item_list[0].project,
                key=item_list[0].key,
                value__in=[i.value for i in item_list]
            )
        )

        result = {}
        for item in item_list:
            result[item] = {
                'name': tagvalues[item.value].get_label(),
            }
        return result

    def serialize(self, obj, attrs, user):
        d = {
            'name': attrs['name'],
            'key': obj.key,
            'value': obj.value,
            'count': obj.times_seen,
            'lastSeen': obj.last_seen,
            'firstSeen': obj.first_seen,
        }
        return d

Prompt:
Implement labels on group tag values

from __future__ import absolute_import

from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue

@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
    def serialize(self, obj, attrs, user):
        d = {
            'key': obj.key,
            'value': obj.value,
            'count': obj.times_seen,
            'lastSeen': obj.last_seen,
            'firstSeen': obj.first_seen,
        }
        return d


from databin.parsers.util import ParseException
from databin.parsers.simple import parse_csv, parse_tsv
from databin.parsers.psql import parse_psql

PARSERS = [
    ('Excel copy & paste', 'excel', parse_tsv),
    ('Comma-Separated Values', 'csv', parse_csv),
    ('Tab-Separated Values', 'tsv', parse_tsv),
    ('psql Shell', 'psql', parse_psql),
]

def parse(format, data):
    for name, key, func in PARSERS:
        if key == format:
            return func(data)
    raise ParseException()

def get_parsers():
    for name, key, func in PARSERS:
        yield (key, name)

Make excel format the default

Make excel format the default

Response:
from databin.parsers.util import ParseException
from databin.parsers.simple import parse_csv, parse_tsv
from databin.parsers.psql import parse_psql

PARSERS = [
    ('Excel copy & paste', 'excel', parse_tsv),
    ('Comma-Separated Values', 'csv', parse_csv),
    ('Tab-Separated Values', 'tsv', parse_tsv),
    ('psql Shell', 'psql', parse_psql),
]

def parse(format, data):
    for name, key, func in PARSERS:
        if key == format:
            return func(data)
    raise ParseException()

def get_parsers():
    for name, key, func in PARSERS:
        yield (key, name)

Prompt:
Make excel format the default

from databin.parsers.util import ParseException
from databin.parsers.simple import parse_csv, parse_tsv
from databin.parsers.psql import parse_psql

PARSERS = [
    ('Comma-Separated Values', 'csv', parse_csv),
    ('Tab-Separated Values', 'tsv', parse_tsv),
    ('Excel copy & paste', 'excel', parse_tsv),
    ('psql Shell', 'psql', parse_psql),
]

def parse(format, data):
    for name, key, func in PARSERS:
        if key == format:
            return func(data)
    raise ParseException()

def get_parsers():
    for name, key, func in PARSERS:
        yield (key, name)


# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
from . import cfop
# from . import document_cancel
# from . import document_correction
from . import document_invalidate_number
from . import spec_mixin

Response:
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
from . import cfop
# from . import document_cancel
# from . import document_correction
from . import document_invalidate_number
from . import spec_mixin

Prompt:
[REF] Disable import of document_cancel and document_correction

# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from . import res_country_state
from . import res_partner
from . import res_company
from . import product_product
from . import document_related
from . import document
from . import document_line
from . import res_city
from . import res_config_settings
from . import cfop
from . import document_cancel
from . import document_correction
from . import document_invalidate_number
from . import spec_mixin


import glob
import os
import unittest
import sys

def build_test_suite():
    suite = unittest.TestSuite()

    for test_case in glob.glob('tests/test_*.py'):
        modname = os.path.splitext(test_case)[0]
        modname = modname.replace('/', '.')
        module = __import__(modname, {}, {}, ['1'])
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    return suite

if __name__ == "__main__":
    suite = build_test_suite()
    runner = unittest.TextTestRunner()

    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())

Response:
import glob
import os
import unittest
import sys

def build_test_suite():
    suite = unittest.TestSuite()

    for test_case in glob.glob('tests/test_*.py'):
        modname = os.path.splitext(test_case)[0]
        modname = modname.replace('/', '.')
        module = __import__(modname, {}, {}, ['1'])
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    return suite

if __name__ == "__main__":
    suite = build_test_suite()
    runner = unittest.TextTestRunner()

    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())

Prompt:
Make unittest return exit code 1 on failure

This is to allow travis to catch test failures

import glob
import os
import unittest

def build_test_suite():
    suite = unittest.TestSuite()

    for test_case in glob.glob('tests/test_*.py'):
        modname = os.path.splitext(test_case)[0]
        modname = modname.replace('/', '.')
        module = __import__(modname, {}, {}, ['1'])
        suite.addTest(unittest.TestLoader().loadTestsFromModule(module))

    return suite

if __name__ == "__main__":
    suite = build_test_suite()
    runner = unittest.TextTestRunner()

    runner.run(suite)


from django.shortcuts import render
from django.utils.datastructures import SortedDict

def _get_key_details(conn, db):
    conn.execute_command('SELECT', db)
    keys = conn.keys()
    key_details = {}
    for key in keys:
        details = conn.execute_command('DEBUG', 'OBJECT', key)

        key_details[key] = {
            'type': conn.type(key),
            'details': dict(
                i.split(':') for i in details.split() if ':' in i
            ),
            'ttl': conn.ttl(key),
        }
    return key_details

def inspect(request, server):
    stats = server.stats
    if stats['status'] == 'UP':
        conn = server.connection
        databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
        database_details = SortedDict()
        for db in databases:
            database_details[db] = _get_key_details(conn, db)
    else:
        database_details = {}

    return render(request, "redisboard/inspect.html", {
        'databases': database_details,
        'original': server,
        'stats': stats,
        'app_label': 'redisboard',
    })

Response:
from django.shortcuts import render
from django.utils.datastructures import SortedDict

def _get_key_details(conn, db):
    conn.execute_command('SELECT', db)
    keys = conn.keys()
    key_details = {}
    for key in keys:
        details = conn.execute_command('DEBUG', 'OBJECT', key)

        key_details[key] = {
            'type': conn.type(key),
            'details': dict(
                i.split(':') for i in details.split() if ':' in i
            ),
            'ttl': conn.ttl(key),
        }
    return key_details

def inspect(request, server):
    stats = server.stats
    if stats['status'] == 'UP':
        conn = server.connection
        databases = sorted(name[2:] for name in conn.info() if name.startswith('db'))
        database_details = SortedDict()
        for db in databases:
            database_details[db] = _get_key_details(conn, db)
    else:
        database_details = {}

    return render(request, "redisboard/inspect.html", {
        'databases': database_details,
        'original': server,
        'stats': stats,
        'app_label': 'redisboard',
    })

Prompt:
Sort the database order in the inspect page.

from django.shortcuts import render

def _get_key_details(conn, db):
    conn.execute_command('SELECT', db)
    keys = conn.keys()
    key_details = {}
    for key in keys:
        details = conn.execute_command('DEBUG', 'OBJECT', key)

        key_details[key] = {
            'type': conn.type(key),
            'details': dict(
                i.split(':') for i in details.split() if ':' in i
            ),
            'ttl': conn.ttl(key),
        }
    return key_details

def inspect(request, server):
    stats = server.stats
    if stats['status'] == 'UP':
        conn = server.connection
        databases = [name[2:] for name in conn.info() if name.startswith('db')]
        database_details = {}
        for db in databases:
            database_details[db] = _get_key_details(conn, db)
    else:
        database_details = {}

    return render(request, "redisboard/inspect.html", {
        'databases': database_details,
        'original': server,
        'stats': stats,
        'app_label': 'redisboard',
    })


from zope.component import adapts
from zope.component import provideAdapter

from sboard.nodes import CreateView
from sboard.nodes import DetailsView
from sboard.nodes import TagListView

from .forms import PolicyIssueForm
from .interfaces import IVoting
from .interfaces import IPolicyIssue

class VotingView(DetailsView):
    adapts(IVoting)

    templates = {
        'details': 'votings/voting_details.html',
    }

provideAdapter(VotingView)

class CreatePolicyIssueView(CreateView):
    adapts(object, IPolicyIssue)

    form = PolicyIssueForm

provideAdapter(CreatePolicyIssueView, name="create")

provideAdapter(TagListView, (IPolicyIssue,))

Response:
from zope.component import adapts
from zope.component import provideAdapter

from sboard.nodes import CreateView
from sboard.nodes import DetailsView
from sboard.nodes import TagListView

from .forms import PolicyIssueForm
from .interfaces import IVoting
from .interfaces import IPolicyIssue

class VotingView(DetailsView):
    adapts(IVoting)

    templates = {
        'details': 'votings/voting_details.html',
    }

provideAdapter(VotingView)

class CreatePolicyIssueView(CreateView):
    adapts(object, IPolicyIssue)

    form = PolicyIssueForm

provideAdapter(CreatePolicyIssueView, name="create")

provideAdapter(TagListView, (IPolicyIssue,))

Prompt:
Use TagListView for IPolicyIssue as default view.

from zope.component import adapts
from zope.component import provideAdapter

from sboard.nodes import CreateView
from sboard.nodes import DetailsView

from .forms import PolicyIssueForm
from .interfaces import IVoting
from .interfaces import IPolicyIssue

class VotingView(DetailsView):
    adapts(IVoting)

    templates = {
        'details': 'votings/voting_details.html',
    }

provideAdapter(VotingView)

class CreatePolicyIssueView(CreateView):
    adapts(object, IPolicyIssue)

    form = PolicyIssueForm

provideAdapter(CreatePolicyIssueView, name="create")


from Cookie import SimpleCookie
from urlparse import parse_qs

from utils import MultiDict, cached_property

class Request(object):
    def __init__(self, event, context):
        self.event = event
        self.context = context

    @property
    def method(self):
        return self.event['httpMethod']

    @property
    def query(self):
        return self.event['queryStringParameters']

    @cached_property
    def post(self):
        return MultiDict(parse_qs(self.event.get('body', '') or ''))

    @cached_property
    def cookies(self):
        jar = SimpleCookie()
        if self.event['headers'].get('Cookie'):
            jar.load(self.event['headers']['Cookie'].encode('utf-8'))
        return jar

    @property
    def stage(self):
        return self.event['stage']

    @property
    def stageVar(self):
        return self.event['stageVariables']

    @property
    def params(self):
        return self.event['pathParameters']

Add cookies property to Request

Add cookies property to Request

Response:
from Cookie import SimpleCookie
from urlparse import parse_qs

from utils import MultiDict, cached_property

class Request(object):
    def __init__(self, event, context):
        self.event = event
        self.context = context

    @property
    def method(self):
        return self.event['httpMethod']

    @property
    def query(self):
        return self.event['queryStringParameters']

    @cached_property
    def post(self):
        return MultiDict(parse_qs(self.event.get('body', '') or ''))

    @cached_property
    def cookies(self):
        jar = SimpleCookie()
        if self.event['headers'].get('Cookie'):
            jar.load(self.event['headers']['Cookie'].encode('utf-8'))
        return jar

    @property
    def stage(self):
        return self.event['stage']

    @property
    def stageVar(self):
        return self.event['stageVariables']

    @property
    def params(self):
        return self.event['pathParameters']

Prompt:
Add cookies property to Request

from urlparse import parse_qs

from utils import cached_property, MultiDict

class Request(object):
    def __init__(self, event, context):
        self.event = event
        self.context = context

    @property
    def method(self):
        return self.event['httpMethod']

    @property
    def query(self):
        return self.event['queryStringParameters']

    @cached_property
    def post(self):
        return MultiDict(parse_qs(self.event.get('body', '') or ''))

    @property
    def stage(self):
        return self.event['stage']

    @property
    def stageVar(self):
        return self.event['stageVariables']

    @property
    def params(self):
        return self.event['pathParameters']


#!/usr/bin/env python
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requirements = [
]

test_requirements = [
]

setup(
    name='adb_android',
    version='0.2.0',
    description="Enables android adb in your python script",
    long_description='This python package is a wrapper for standard android adb\
    implementation. It allows you to execute android adb commands in your \
    python script.',
    author='Viktor Malyi',
    author_email='v.stratus@gmail.com',
    url='https://github.com/vmalyi/adb_android',
    packages=[
        'adb_android',
    ],
    package_dir={'adb_android':'adb_android'},
    include_package_data=True,
    install_requires=requirements,
    license="GNU",
    keywords='adb, android',
    #TODO: check compatibitily with >2.7
    classifiers=[
    'Development Status :: 4 - Beta',
    'Programming Language :: Python :: 2.7',
    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    'Topic :: Software Development :: Testing',
    'Intended Audience :: Developers'
    ],
    test_suite='tests',
)

Update package description and version

Update package description and version

Response:
#!/usr/bin/env python
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requirements = [
]

test_requirements = [
]

setup(
    name='adb_android',
    version='0.2.0',
    description="Enables android adb in your python script",
    long_description='This python package is a wrapper for standard android adb\
    implementation. It allows you to execute android adb commands in your \
    python script.',
    author='Viktor Malyi',
    author_email='v.stratus@gmail.com',
    url='https://github.com/vmalyi/adb_android',
    packages=[
        'adb_android',
    ],
    package_dir={'adb_android':'adb_android'},
    include_package_data=True,
    install_requires=requirements,
    license="GNU",
    keywords='adb, android',
    #TODO: check compatibitily with >2.7
    classifiers=[
    'Development Status :: 4 - Beta',
    'Programming Language :: Python :: 2.7',
    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    'Topic :: Software Development :: Testing',
    'Intended Audience :: Developers'
    ],
    test_suite='tests',
)

Prompt:
Update package description and version

#!/usr/bin/env python
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

requirements = [
]

test_requirements = [
]

setup(
    name='adb_android',
    version='0.1.0',
    description="Enables android adb in your python script",
    long_description='This package can be used by everyone who implements some \
    android-related stuff on Python and at the same time has to interact with \
    android adb. It makes interaction with android adb easier because of proper \
    error handling and some useful features.',
    author='Viktor Malyi',
    author_email='v.stratus@gmail.com',
    url='https://github.com/vmalyi/adb',
    packages=[
        'adb_android',
    ],
    package_dir={'adb_android':'adb_android'},
    include_package_data=True,
    install_requires=requirements,
    license="GNU",
    keywords='adb, android',
    #TODO: check compatibitily with >2.7
    classifiers=[
    'Development Status :: 4 - Beta',
    'Programming Language :: Python :: 2.7',
    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    'Topic :: Software Development :: Testing',
    'Intended Audience :: Developers'
    ],
    test_suite='tests',
)


import logging

from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response

# Import the Game Controller
from Game.GameController import GameController

class GameModes(MethodView):
    def get(self):
        logging.debug("GameModes: GET: Initializing GameObject")
        game_object = GameController()
        logging.debug("GameModes: GET: GameObject initialized to {}".format(game_object.save()))

        logging.debug("GameModes: GET: Checking if textmode flag set")
        if request.args.get('textmode', None):
            logging.debug("GameModes: GET: Responding with list of names")
            response_data = game_object.game_mode_names
        else:
            logging.debug("GameModes: GET: Responding with JSON object: {}".format(game_object.game_modes))
            response_data = [{"mode": gt.mode,
                              "digits": gt.digits,
                              "digit-type": gt.digit_type,
                              "guesses": gt.guesses_allowed
                             } for gt in game_object.game_modes]

        logging.debug("GameModes: GET: Return {}".format(response_data))
        return build_response(
            html_status=200,
            response_data=response_data,
            response_mimetype="application/json"
        )

Response:
import logging

from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response

# Import the Game Controller
from Game.GameController import GameController

class GameModes(MethodView):
    def get(self):
        logging.debug("GameModes: GET: Initializing GameObject")
        game_object = GameController()
        logging.debug("GameModes: GET: GameObject initialized to {}".format(game_object.save()))

        logging.debug("GameModes: GET: Checking if textmode flag set")
        if request.args.get('textmode', None):
            logging.debug("GameModes: GET: Responding with list of names")
            response_data = game_object.game_mode_names
        else:
            logging.debug("GameModes: GET: Responding with JSON object: {}".format(game_object.game_modes))
            response_data = [{"mode": gt.mode,
                              "digits": gt.digits,
                              "digit-type": gt.digit_type,
                              "guesses": gt.guesses_allowed
                             } for gt in game_object.game_modes]

        logging.debug("GameModes: GET: Return {}".format(response_data))
        return build_response(
            html_status=200,
            response_data=response_data,
            response_mimetype="application/json"
        )

Prompt:
Update logging for message output and consistency.

import logging

from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response

# Import the Game Controller
from Game.GameController import GameController

class GameModes(MethodView):
    def get(self):
        logging.debug("GameModes: GET: Initializing GameObject")
        game_object = GameController()
        logging.debug("GameModes: GET: GameObject initialized to {}".format(game_object.save()))

        logging.debug("GameModes: GET: Checking if textmode flag set")
        if request.args.get('textmode', None):
            logging.debug("GameModes: GET: Responding with list of names")
            response_data = game_object.game_mode_names
        else:
            logging.debug("GameModes: GET: Responding with JSON object")
            response_data = [{"mode": gt.mode,
                              "digits": gt.digits,
                              "digit-type": gt.digit_type,
                              "guesses": gt.guesses_allowed
                             } for gt in game_object.game_modes]

        logging.debug("GameModes: GET: Return {}".format(response_data))
        return build_response(
            html_status=200,
            response_data=response_data,
            response_mimetype="application/json"
        )


from twisted.web.server import Site, Request

class AddSecurityHeadersRequest(Request):
    CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)

class PixelatedSite(Site):

    requestFactory = AddSecurityHeadersRequest

    @classmethod
    def enable_csp_requests(cls):
        cls.requestFactory = AddSecurityHeadersRequest

    @classmethod
    def disable_csp_requests(cls):
        cls.requestFactory = Site.requestFactory

Rename class to match intent

Rename class to match intent

Response:
from twisted.web.server import Site, Request

class AddSecurityHeadersRequest(Request):
    CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)

class PixelatedSite(Site):

    requestFactory = AddSecurityHeadersRequest

    @classmethod
    def enable_csp_requests(cls):
        cls.requestFactory = AddSecurityHeadersRequest

    @classmethod
    def disable_csp_requests(cls):
        cls.requestFactory = Site.requestFactory

Prompt:
Rename class to match intent

from twisted.web.server import Site, Request

class AddCSPHeaderRequest(Request):
    CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'"

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)

class PixelatedSite(Site):

    requestFactory = AddCSPHeaderRequest

    @classmethod
    def enable_csp_requests(cls):
        cls.requestFactory = AddCSPHeaderRequest

    @classmethod
    def disable_csp_requests(cls):
        cls.requestFactory = Site.requestFactory


import sys

def add_all(nums):
	return sum(nums)

def multiply_all(nums):
	return reduce(lambda a, b: a * b, nums)

if __name__== '__main__':
	command = sys.argv[1]
	nums = map(float, sys.argv[2:])
	if command == 'add':
		print(add_all(nums))
	elif command == 'multiply':
		print(multiply_all(nums))

Fix bug in 'multiply' support

Fix bug in 'multiply' support

Response:
import sys

def add_all(nums):
	return sum(nums)

def multiply_all(nums):
	return reduce(lambda a, b: a * b, nums)

if __name__== '__main__':
	command = sys.argv[1]
	nums = map(float, sys.argv[2:])
	if command == 'add':
		print(add_all(nums))
	elif command == 'multiply':
		print(multiply_all(nums))

Prompt:
Fix bug in 'multiply' support

import sys

def add_all(nums):
	return sum(nums)

def multiply_all(nums):
	return reduce(lambda a, b: a * b, nums)

if __name__== '__main__':
	command = sys.argv[1]
	nums = map(float, sys.argv[2:])
	if command == 'add':
		print(add_all(nums))
	elif command == 'multiply':
		print(multiply_all(sums))


from flask import render_template
from flask.ext.login import login_required

from .. import app

@app.route('/')
@login_required
def index():
    return render_template('base.html')

Response:
from flask import render_template
from flask.ext.login import login_required

from .. import app

@app.route('/')
@login_required
def index():
    return render_template('base.html')

Prompt:
Remove extraneous imports in the base view package
from collections import OrderedDict
from urllib.parse import urlparse
import re

from flask import render_template, redirect, url_for, request, abort, jsonify,\
        flash, Markup, session
from flask.views import View
from flask.ext.login import login_user, login_required, logout_user, \
        current_user
from flask.ext.wtf import Form
from flask.ext.principal import identity_changed, AnonymousIdentity
from sqlalchemy.orm.exc import NoResultFound
from wtforms.fields import StringField, PasswordField, SelectField, \
        SubmitField, TextAreaField, HiddenField
from wtforms.fields.html5 import URLField, DecimalField
from wtforms.widgets import HiddenInput
from wtforms.validators import InputRequired, ValidationError, AnyOf, URL

from .. import app, auth_methods, db, requests_session, killmail_sources
from ..auth import SubmitRequestsPermission, ReviewRequestsPermission, \
        PayoutRequestsPermission, admin_permission
from ..auth.models import User, Group, Division, Pilot
from ..models import Request, Modifier, Action

@app.route('/')
@login_required
def index():
    return render_template('base.html')


from __future__ import unicode_literals
import logging

from django.core.management.base import BaseCommand

from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated

logger = logging.getLogger(__name__)

def update_share_preprint_modified_dates(dry_run=False):
    dates_updated = 0
    for preprint in PreprintService.objects.filter():
        if preprint.node.date_modified > preprint.date_modified:
            if not dry_run:
                on_preprint_updated(preprint._id)
            dates_updated += 1
    return dates_updated

class Command(BaseCommand):
    """
    Send more accurate preprint modified dates to Share (max of node.date_modified and preprint.date_modified)
    """
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Say how many preprint updates would be sent to share',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
            dates_updated = update_share_preprint_modified_dates()
            logger.info('Sent %d new preprint modified dates to Share' % dates_updated)

        else:
            dates_updated = update_share_preprint_modified_dates(dry_run=True)
            logger.info('Would have sent %d new preprint modified dates to Share' % dates_updated)

Add management command to update preprint share dates

Response:
from __future__ import unicode_literals
import logging

from django.core.management.base import BaseCommand

from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated

logger = logging.getLogger(__name__)

def update_share_preprint_modified_dates(dry_run=False):
    dates_updated = 0
    for preprint in PreprintService.objects.filter():
        if preprint.node.date_modified > preprint.date_modified:
            if not dry_run:
                on_preprint_updated(preprint._id)
            dates_updated += 1
    return dates_updated

class Command(BaseCommand):
    """
    Send more accurate preprint modified dates to Share (max of node.date_modified and preprint.date_modified)
    """
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--dry',
            action='store_true',
            dest='dry_run',
            help='Say how many preprint updates would be sent to share',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)
        if not dry_run:
            script_utils.add_file_logger(logger, __file__)
            dates_updated = update_share_preprint_modified_dates()
            logger.info('Sent %d new preprint modified dates to Share' % dates_updated)

        else:
            dates_updated = update_share_preprint_modified_dates(dry_run=True)
            logger.info('Would have sent %d new preprint modified dates to Share' % dates_updated)

Prompt: Add management command to update preprint share dates


from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View

from .pdf import generate_receipt_pdf

class ReceiptHTMLView(View):
    """Renders a receipt as HTML."""
    def get(self, request, pk):
        return HttpResponse(
            generate_receipt_pdf(pk, request, True),
        )

class ReceiptPDFView(View):
    """Renders a receipt as a PDF, prompting to download it."""

    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + \
            _('receipt %s.pdf' % pk)

        generate_receipt_pdf(pk, response)
        return response

class ReceiptPDFDisplayView(View):
    """
    Renders a receipt as a PDF.

    Browsers should render the file, rather than prompt to download it.
    """
    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        generate_receipt_pdf(pk, response)
        return response

Add a view to display PDF receipts

Response:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View

from .pdf import generate_receipt_pdf

class ReceiptHTMLView(View):
    """Renders a receipt as HTML."""
    def get(self, request, pk):
        return HttpResponse(
            generate_receipt_pdf(pk, request, True),
        )

class ReceiptPDFView(View):
    """Renders a receipt as a PDF, prompting to download it."""

    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + \
            _('receipt %s.pdf' % pk)

        generate_receipt_pdf(pk, response)
        return response

class ReceiptPDFDisplayView(View):
    """
    Renders a receipt as a PDF.

    Browsers should render the file, rather than prompt to download it.
    """
    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        generate_receipt_pdf(pk, response)
        return response

Prompt:
Add a view to display PDF receipts

Fixes #23
Closes !7
Closes !8

from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View

from .pdf import generate_receipt_pdf

class ReceiptHTMLView(View):

    def get(self, request, pk):
        return HttpResponse(
            generate_receipt_pdf(pk, request, True),
        )

class ReceiptPDFView(View):

    def get(self, request, pk):
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + \
            _('receipt %s.pdf' % pk)

        generate_receipt_pdf(pk, response)
        return response


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

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calibre_books.settings')

setup(
    name='calibre-books',
    author='Adam Bogdał',
    author_email='adam@bogdal.pl',
    description="Calibre server in Django",
    license='BSD',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.6',
        'django-bootstrap3>=4.8.2',
        'django-dropbox==0.0.2',
        'dj_database_url>=0.2.2',
        'python-memcached==1.53',
        'Pillow==2.5.2',
        'gunicorn==19.1.0',
        'psycopg2==2.5.3',

    ],
    entry_points={
        'console_scripts': ['manage.py = calibre_books:manage']},
)

Use pillow instead of ordinary pil

Use pillow instead of ordinary pil

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

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calibre_books.settings')

setup(
    name='calibre-books',
    author='Adam Bogdał',
    author_email='adam@bogdal.pl',
    description="Calibre server in Django",
    license='BSD',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.6',
        'django-bootstrap3>=4.8.2',
        'django-dropbox==0.0.2',
        'dj_database_url>=0.2.2',
        'python-memcached==1.53',
        'Pillow==2.5.2',
        'gunicorn==19.1.0',
        'psycopg2==2.5.3',

    ],
    entry_points={
        'console_scripts': ['manage.py = calibre_books:manage']},
)

Prompt:
Use pillow instead of ordinary pil

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

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'calibre_books.settings')

setup(
    name='calibre-books',
    author='Adam Bogdał',
    author_email='adam@bogdal.pl',
    description="Calibre server in Django",
    license='BSD',
    version='0.0.1',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'Django>=1.6',
        'django-bootstrap3>=4.8.2',
        'django-dropbox==0.0.2',
        'dj_database_url>=0.2.2',
        'python-memcached==1.53',
        'PIL==1.1.7',
        'gunicorn==19.1.0',
        'psycopg2==2.5.3',

    ],
    entry_points={
        'console_scripts': ['manage.py = calibre_books:manage']},
)


import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

from .base import *  # noqa
from .base import env

SECRET_KEY = env("SECRET_KEY")
# CELERY_BROKER_URL = env("CELERY_BROKER_URL")
USE_SCHEDULER = False

# if FRONTEND_URL == "http://testfrontend.it/":
#     raise ImproperlyConfigured("Please configure FRONTEND_URL for production")

SENTRY_DSN = env("SENTRY_DSN", default="")

if SENTRY_DSN:
    sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()])

SLACK_INCOMING_WEBHOOK_URL = env("SLACK_INCOMING_WEBHOOK_URL")

DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

AWS_STORAGE_BUCKET_NAME = env("AWS_MEDIA_BUCKET", None)
AWS_S3_REGION_NAME = env("AWS_REGION_NAME", "eu-central-1")
AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID", None)
AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY", None)

Add better default for s3 region

Add better default for s3 region

Response:
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

from .base import *  # noqa
from .base import env

SECRET_KEY = env("SECRET_KEY")
# CELERY_BROKER_URL = env("CELERY_BROKER_URL")
USE_SCHEDULER = False

# if FRONTEND_URL == "http://testfrontend.it/":
#     raise ImproperlyConfigured("Please configure FRONTEND_URL for production")

SENTRY_DSN = env("SENTRY_DSN", default="")

if SENTRY_DSN:
    sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()])

SLACK_INCOMING_WEBHOOK_URL = env("SLACK_INCOMING_WEBHOOK_URL")

DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

AWS_STORAGE_BUCKET_NAME = env("AWS_MEDIA_BUCKET", None)
AWS_S3_REGION_NAME = env("AWS_REGION_NAME", "eu-central-1")
AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID", None)
AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY", None)

Prompt:
Add better default for s3 region

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

from .base import *  # noqa
from .base import env

SECRET_KEY = env("SECRET_KEY")
# CELERY_BROKER_URL = env("CELERY_BROKER_URL")
USE_SCHEDULER = False

# if FRONTEND_URL == "http://testfrontend.it/":
#     raise ImproperlyConfigured("Please configure FRONTEND_URL for production")

SENTRY_DSN = env("SENTRY_DSN", default="")

if SENTRY_DSN:
    sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()])

SLACK_INCOMING_WEBHOOK_URL = env("SLACK_INCOMING_WEBHOOK_URL")

DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

AWS_STORAGE_BUCKET_NAME = env("AWS_MEDIA_BUCKET", None)
AWS_S3_REGION_NAME = env("AWS_REGION_NAME", None)
AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID", None)
AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY", None)


from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const

@httpdigest
def restore(request):
    user = User.from_django_user(request.user)
    restore_id = request.GET.get('since')
    return generate_restore_response(user, restore_id)

def xml_for_case(request, case_id, version="1.0"):
    """
    Test view to get the xml for a particular case
    """
    case = CommCareCase.get(case_id)
    return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
                                                const.CASE_ACTION_UPDATE],
                                         version), mimetype="text/xml")

Revert "moving httpresponse to view"

Response:
from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const

@httpdigest
def restore(request):
    user = User.from_django_user(request.user)
    restore_id = request.GET.get('since')
    return generate_restore_response(user, restore_id)

def xml_for_case(request, case_id, version="1.0"):
    """
    Test view to get the xml for a particular case
    """
    case = CommCareCase.get(case_id)
    return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
                                                const.CASE_ACTION_UPDATE],
                                         version), mimetype="text/xml")

Prompt:
Revert "moving httpresponse to view"

This reverts commit a6f501bb9de6382e35372996851916adac067fa0.

from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const

@httpdigest
def restore(request):
    user = User.from_django_user(request.user)
    restore_id = request.GET.get('since')
    return generate_restore_response(user, restore_id)

def xml_for_case(request, case_id, version="1.0"):
    """
    Test view to get the xml for a particular case
    """
    from django.http import HttpResponse
    case = CommCareCase.get(case_id)
    return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE,
                                                const.CASE_ACTION_UPDATE],
                                         version), mimetype="text/xml")


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

from django.utils.translation import ugettext_lazy as _

from horizon import tables

class ExecutionsTable(tables.DataTable):
    id = tables.Column("id",
                       verbose_name=_("ID"),
                       link=("horizon:mistral:executions:tasks"))
    wb_name = tables.Column("workbook_name", verbose_name=_("Workbook"))
    state = tables.Column("state", verbose_name=_("State"))

    class Meta:
        name = "executions"
        verbose_name = _("Executions")

class TaskTable(tables.DataTable):
    id = tables.Column("id", verbose_name=_("ID"))
    name = tables.Column("name", verbose_name=_("Name"))
    parameters = tables.Column("parameters", verbose_name=_("Parameters"))
    output = tables.Column("output", verbose_name=_("Output"))
    state = tables.Column("state", verbose_name=_("State"))

    class Meta:
        name = "tasks"
        verbose_name = _("Tasks")

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

from django.utils.translation import ugettext_lazy as _

from horizon import tables

class ExecutionsTable(tables.DataTable):
    id = tables.Column("id",
                       verbose_name=_("ID"),
                       link=("horizon:mistral:executions:tasks"))
    wb_name = tables.Column("workbook_name", verbose_name=_("Workbook"))
    state = tables.Column("state", verbose_name=_("State"))

    class Meta:
        name = "executions"
        verbose_name = _("Executions")

class TaskTable(tables.DataTable):
    id = tables.Column("id", verbose_name=_("ID"))
    name = tables.Column("name", verbose_name=_("Name"))
    parameters = tables.Column("parameters", verbose_name=_("Parameters"))
    output = tables.Column("output", verbose_name=_("Output"))
    state = tables.Column("state", verbose_name=_("State"))

    class Meta:
        name = "tasks"
        verbose_name = _("Tasks")

Prompt:
Add Task's output and parameters columns

Change-Id: I98f57a6a0178bb7258d82f3a165127f060f42f7b
Implements: blueprint mistral-ui

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

from django.utils.translation import ugettext_lazy as _

from horizon import tables

class ExecutionsTable(tables.DataTable):
    id = tables.Column("id",
                       verbose_name=_("ID"),
                       link=("horizon:mistral:executions:tasks"))
    wb_name = tables.Column("workbook_name", verbose_name=_("Workbook"))
    state = tables.Column("state", verbose_name=_("State"))

    class Meta:
        name = "executions"
        verbose_name = _("Executions")

class TaskTable(tables.DataTable):
    id = tables.Column("id", verbose_name=_("ID"))
    name = tables.Column("name", verbose_name=_("Name"))
    action = tables.Column("action", verbose_name=_("Action"))
    state = tables.Column("state", verbose_name=_("State"))

    class Meta:
        name = "tasks"
        verbose_name = _("Tasks")


#!/usr/bin/env python
"""roll simulates rolling polyhedral dice."""

# roll.py
# roll v1.0

# Michael McMahon

from random import randrange

# Die roll function
# This function rolls polyhedral dice.  Example: To roll a d8, use roll(8).

def roll(diefaces):
    """Simulate rolling polyhedral dice"""
    assert isinstance(diefaces, int) and diefaces >= 1
    return randrange(1, int(diefaces + 1))

Add assert to prevent invalid input

Add assert to prevent invalid input

Response:
#!/usr/bin/env python
"""roll simulates rolling polyhedral dice."""

# roll.py
# roll v1.0

# Michael McMahon

from random import randrange

# Die roll function
# This function rolls polyhedral dice.  Example: To roll a d8, use roll(8).

def roll(diefaces):
    """Simulate rolling polyhedral dice"""
    assert isinstance(diefaces, int) and diefaces >= 1
    return randrange(1, int(diefaces + 1))

Prompt:
Add assert to prevent invalid input

#!/usr/bin/env python
"""roll simulates rolling polyhedral dice."""
# roll.py

# Michael McMahon

from random import randrange

# Die roll function
# This function rolls polyhedral dice.  Example: To roll a d8, use roll(8).

def roll(diefaces):
    """Simulate rolling polyhedral dice"""
    return randrange(1, int(diefaces + 1))


from settings_common import *

PACKAGE_VERSION = "0.5"

DEBUG = TEMPLATE_DEBUG = True

DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp')

SERVE_STATIC_FILES = True

# the following is an idea from https://code.djangoproject.com/wiki/SplitSettings
# We have both local settings and common settings. They are used as follows:
# - common settings are shared data between normal settings and unit test settings
# - local settings are used on productive servers to keep the local
#   settings such as db passwords, etc out of version control
try:
    from settings_local import *
except ImportError:
    pass

Fix the path to external tools

Fix the path to external tools

Response:
from settings_common import *

PACKAGE_VERSION = "0.5"

DEBUG = TEMPLATE_DEBUG = True

DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', '..', 'tmp')

SERVE_STATIC_FILES = True

# the following is an idea from https://code.djangoproject.com/wiki/SplitSettings
# We have both local settings and common settings. They are used as follows:
# - common settings are shared data between normal settings and unit test settings
# - local settings are used on productive servers to keep the local
#   settings such as db passwords, etc out of version control
try:
    from settings_local import *
except ImportError:
    pass

Prompt:
Fix the path to external tools

from settings_common import *

PACKAGE_VERSION = "0.5"

DEBUG = TEMPLATE_DEBUG = True

DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline')
EXTERNAL_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp')

SERVE_STATIC_FILES = True

# the following is an idea from https://code.djangoproject.com/wiki/SplitSettings
# We have both local settings and common settings. They are used as follows:
# - common settings are shared data between normal settings and unit test settings
# - local settings are used on productive servers to keep the local
#   settings such as db passwords, etc out of version control
try:
    from settings_local import *
except ImportError:
    pass


from tw.api import Widget
from moksha.feed import Feed

class TestFeed(object):

    def test_feed_subclassing(self):
        class MyFeed(Feed):
            url = 'http://lewk.org/rss'
        feed = MyFeed()
        assert feed.url == 'http://lewk.org/rss'
        assert feed.num_entries() > 0
        for entry in feed.iterentries():
            pass
        for entry in feed.entries():
            pass

    def test_widget_children(self):
        class MyWidget(Widget):
            myfeedurl = 'http://lewk.org/rss'
            children = [Feed('myfeed', url=myfeedurl)]
            template = "mako:${c.myfeed()}"
        widget = MyWidget()
        assert widget.c.myfeed

    def test_feed_generator(self):
        feed = Feed(url='http://lewk.org/rss')
        iter = feed.iterentries()
        data = iter.next()
        assert iter.next()

Add some Feed test cases

Add some Feed test cases

Response:
from tw.api import Widget
from moksha.feed import Feed

class TestFeed(object):

    def test_feed_subclassing(self):
        class MyFeed(Feed):
            url = 'http://lewk.org/rss'
        feed = MyFeed()
        assert feed.url == 'http://lewk.org/rss'
        assert feed.num_entries() > 0
        for entry in feed.iterentries():
            pass
        for entry in feed.entries():
            pass

    def test_widget_children(self):
        class MyWidget(Widget):
            myfeedurl = 'http://lewk.org/rss'
            children = [Feed('myfeed', url=myfeedurl)]
            template = "mako:${c.myfeed()}"
        widget = MyWidget()
        assert widget.c.myfeed

    def test_feed_generator(self):
        feed = Feed(url='http://lewk.org/rss')
        iter = feed.iterentries()
        data = iter.next()
        assert iter.next()

Prompt: Add some Feed test cases


#!/usr/bin/env python

import os
import sqlite3
import sys

# helper
def usage():
  sys.stderr.write("USAGE: %s [PATH]\n" + \
                   "\n" + \
                   "Prints to stdout the format of the working copy at PATH.\n")

# parse argv
wc = (sys.argv[1:] + ['.'])[0]

# main()
entries = os.path.join(wc, '.svn', 'entries')
wc_db = os.path.join(wc, '.svn', 'wc.db')

if os.path.exists(entries):
  formatno = int(open(entries).readline())
elif os.path.exists(wc_db):
  formatno = sqlite3.connect(wc_db).execute('pragma user_version;').fetchone()[0]
else:
  usage()
  sys.exit(1)

# 1.0.x -> 1.3.x: format 4
# 1.4.x: format 8
# 1.5.x: format 9
# 1.6.x: format 10
# 1.7.x: format XXX
print("%s: %d" % (wc, formatno))

Add a helper script, ported to Python.

Add a helper script, ported to Python.

* tools/dev/wc-format.py:  New.
      Prints the working copy format of a given directory.

Response:
#!/usr/bin/env python

import os
import sqlite3
import sys

# helper
def usage():
  sys.stderr.write("USAGE: %s [PATH]\n" + \
                   "\n" + \
                   "Prints to stdout the format of the working copy at PATH.\n")

# parse argv
wc = (sys.argv[1:] + ['.'])[0]

# main()
entries = os.path.join(wc, '.svn', 'entries')
wc_db = os.path.join(wc, '.svn', 'wc.db')

if os.path.exists(entries):
  formatno = int(open(entries).readline())
elif os.path.exists(wc_db):
  formatno = sqlite3.connect(wc_db).execute('pragma user_version;').fetchone()[0]
else:
  usage()
  sys.exit(1)

# 1.0.x -> 1.3.x: format 4
# 1.4.x: format 8
# 1.5.x: format 9
# 1.6.x: format 10
# 1.7.x: format XXX
print("%s: %d" % (wc, formatno))

Prompt:
Add a helper script, ported to Python.

* tools/dev/wc-format.py:  New.
      Prints the working copy format of a given directory.


# Configuration settings

# ID of HPO to validate (see resources/hpo.csv)
hpo_id = 'hpo_id'

# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'

# sprint number being validated against
sprint_num = 0

# Submissions and logs stored here
# Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY)
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'

Add comment regarding freetds config

Add comment regarding freetds config

Response:
# Configuration settings

# ID of HPO to validate (see resources/hpo.csv)
hpo_id = 'hpo_id'

# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'

# sprint number being validated against
sprint_num = 0

# Submissions and logs stored here
# Note: Connecting to MSSQL from *nix may require FreeTDS configuration (see https://goo.gl/qKhusY)
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'

Prompt:
Add comment regarding freetds config

# Configuration settings

# ID of HPO to validate (see resources/hpo.csv)
hpo_id = 'hpo_id'

# location of files to validate, evaluate
csv_dir = 'path/to/csv_files'

# sprint number being validated against
sprint_num = 0

# Submissions and logs stored here
# For more examples and requirements see http://docs.sqlalchemy.org/en/latest/core/engines.html
conn_str = 'mssql+pymssql://localhost/pmi_sprint_1'


from numpy.testing import assert_allclose
from menpodetect.opencv import (load_opencv_frontal_face_detector,
                                load_opencv_eye_detector)
import menpo.io as mio

takeo = mio.import_builtin_asset.takeo_ppm()

def test_frontal_face_detector():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_frontal_face_detector()
    pcs = opencv_detector(takeo_copy)
    assert len(pcs) == 1
    assert takeo_copy.n_channels == 3
    assert takeo_copy.landmarks['opencv_0'][None].n_points == 4

def test_frontal_face_detector_min_neighbors():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_frontal_face_detector()
    pcs = opencv_detector(takeo_copy, min_neighbours=100)
    assert len(pcs) == 0
    assert takeo_copy.n_channels == 3

def test_eye_detector():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_eye_detector()
    pcs = opencv_detector(takeo_copy, min_size=(5, 5))
    assert_allclose(len(pcs),  1)
    assert takeo_copy.n_channels == 3
    assert takeo_copy.landmarks['opencv_0'][None].n_points == 4

Response:
from numpy.testing import assert_allclose
from menpodetect.opencv import (load_opencv_frontal_face_detector,
                                load_opencv_eye_detector)
import menpo.io as mio

takeo = mio.import_builtin_asset.takeo_ppm()

def test_frontal_face_detector():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_frontal_face_detector()
    pcs = opencv_detector(takeo_copy)
    assert len(pcs) == 1
    assert takeo_copy.n_channels == 3
    assert takeo_copy.landmarks['opencv_0'][None].n_points == 4

def test_frontal_face_detector_min_neighbors():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_frontal_face_detector()
    pcs = opencv_detector(takeo_copy, min_neighbours=100)
    assert len(pcs) == 0
    assert takeo_copy.n_channels == 3

def test_eye_detector():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_eye_detector()
    pcs = opencv_detector(takeo_copy, min_size=(5, 5))
    assert_allclose(len(pcs),  1)
    assert takeo_copy.n_channels == 3
    assert takeo_copy.landmarks['opencv_0'][None].n_points == 4

Prompt:
Use assert_allclose so we can see the appveyor failure

from menpodetect.opencv import (load_opencv_frontal_face_detector,
                                load_opencv_eye_detector)
import menpo.io as mio

takeo = mio.import_builtin_asset.takeo_ppm()

def test_frontal_face_detector():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_frontal_face_detector()
    pcs = opencv_detector(takeo_copy)
    assert len(pcs) == 1
    assert takeo_copy.n_channels == 3
    assert takeo_copy.landmarks['opencv_0'][None].n_points == 4

def test_frontal_face_detector_min_neighbors():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_frontal_face_detector()
    pcs = opencv_detector(takeo_copy, min_neighbours=100)
    assert len(pcs) == 0
    assert takeo_copy.n_channels == 3

def test_eye_detector():
    takeo_copy = takeo.copy()
    opencv_detector = load_opencv_eye_detector()
    pcs = opencv_detector(takeo_copy, min_size=(5, 5))
    assert len(pcs) == 1
    assert takeo_copy.n_channels == 3
    assert takeo_copy.landmarks['opencv_0'][None].n_points == 4


#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""

if __name__ == '__main__':
    exec('setup.py', dict(__name__='__main__',
                          __file__='setup.py', # needed in setup.py
                          force_setuptools=True))

Use `exec` instead of `execfile`.

Use `exec` instead of `execfile`.

Response:
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""

if __name__ == '__main__':
    exec('setup.py', dict(__name__='__main__',
                          __file__='setup.py', # needed in setup.py
                          force_setuptools=True))

Prompt:
Use `exec` instead of `execfile`.

#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""

if __name__ == '__main__':
    execfile('setup.py', dict(__name__='__main__',
                              __file__='setup.py', # needed in setup.py
                              force_setuptools=True))


#! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""

from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *

a = AtomSpace()
set_type_ctor_atomspace(a)

a = FloatValue([1.0, 2.0, 3.0])
b = FloatValue([1.0, 2.0, 3.0])
c = FloatValue(1.0)
print('{} == {}: {}'.format(a, b, a == b))
print('{} == {}: {}'.format(a, c, a == c))

featureValue = FloatValue([1.0, 2])
print('new value created: {}'.format(featureValue))

boundingBox = ConceptNode('boundingBox')
featureKey = PredicateNode('features')

boundingBox.set_value(featureKey, featureValue)
print('set value to atom: {}'.format(boundingBox))

value = boundingBox.get_value(featureKey)
print('get value from atom: {}'.format(value))

list = value.to_list()
print('get python list from value: {}'.format(list))

Response:
#! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""

from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *

a = AtomSpace()
set_type_ctor_atomspace(a)

a = FloatValue([1.0, 2.0, 3.0])
b = FloatValue([1.0, 2.0, 3.0])
c = FloatValue(1.0)
print('{} == {}: {}'.format(a, b, a == b))
print('{} == {}: {}'.format(a, c, a == c))

featureValue = FloatValue([1.0, 2])
print('new value created: {}'.format(featureValue))

boundingBox = ConceptNode('boundingBox')
featureKey = PredicateNode('features')

boundingBox.set_value(featureKey, featureValue)
print('set value to atom: {}'.format(boundingBox))

value = boundingBox.get_value(featureKey)
print('get value from atom: {}'.format(value))

list = value.to_list()
print('get python list from value: {}'.format(list))

Prompt:
Add example of Value to Python list conversion

#! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""

from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *

a = AtomSpace()
set_type_ctor_atomspace(a)

a = FloatValue([1.0, 2.0, 3.0])
b = FloatValue([1.0, 2.0, 3.0])
c = FloatValue(1.0)
print('{} == {}: {}'.format(a, b, a == b))
print('{} == {}: {}'.format(a, c, a == c))

featureValue = FloatValue([1.0, 2])
print('new value created: {}'.format(featureValue))

boundingBox = ConceptNode('boundingBox')
featureKey = PredicateNode('features')

boundingBox.set_value(featureKey, featureValue)
print('set value to atom: {}'.format(boundingBox))

print('get value from atom: {}'.format(boundingBox.get_value(featureKey)))


from seleniumbase import BaseCase

class MyTestClass(BaseCase):

    def test_basic(self):
        self.open("https://www.google.com/maps/@42.3598616,-71.0912631,15z")
        self.wait_for_element("#searchboxinput")
        self.wait_for_element("#minimap")
        self.wait_for_element("#zoom")

        # Create a website tour using the DriverJS library
        # Same as:  self.create_driverjs_tour()
        self.create_tour(theme="driverjs")
        self.add_tour_step("🗺 Welcome to Google Maps 🗺", "html",
                           title="✅ SeleniumBase Tours 🌎")
        self.add_tour_step("You can type a location into this Search box.",
                           "#searchboxinput")
        self.add_tour_step("Then click here to view it on the map.",
                           "#searchbox-searchbutton", alignment="bottom")
        self.add_tour_step("Or click here to get driving directions.",
                           "#searchbox-directions", alignment="bottom")
        self.add_tour_step("Use this button to get a Satellite view.",
                           "#minimap div.widget-minimap", alignment="right")
        self.add_tour_step("Click here to zoom in.",
                           "#widget-zoom-in", alignment="left")
        self.add_tour_step("Or click here to zoom out.",
                           "#widget-zoom-out", alignment="left")
        self.add_tour_step("Use the Menu button for more options.",
                           ".searchbox-hamburger-container", alignment="right")
        self.add_tour_step("Or click here to see more Google apps.",
                           '[title="Google apps"]', alignment="left")
        self.add_tour_step("Thanks for using SeleniumBase Tours", "html",
                           title="🚃 End of Guided Tour 🚃")
        self.export_tour()  # The default name for exports is "my_tour.js"
        self.play_tour(interval=0)  # If interval > 0, autoplay after N seconds

Add an example tour for DriverJS

Add an example tour for DriverJS

Response:
from seleniumbase import BaseCase

class MyTestClass(BaseCase):

    def test_basic(self):
        self.open("https://www.google.com/maps/@42.3598616,-71.0912631,15z")
        self.wait_for_element("#searchboxinput")
        self.wait_for_element("#minimap")
        self.wait_for_element("#zoom")

        # Create a website tour using the DriverJS library
        # Same as:  self.create_driverjs_tour()
        self.create_tour(theme="driverjs")
        self.add_tour_step("🗺 Welcome to Google Maps 🗺", "html",
                           title="✅ SeleniumBase Tours 🌎")
        self.add_tour_step("You can type a location into this Search box.",
                           "#searchboxinput")
        self.add_tour_step("Then click here to view it on the map.",
                           "#searchbox-searchbutton", alignment="bottom")
        self.add_tour_step("Or click here to get driving directions.",
                           "#searchbox-directions", alignment="bottom")
        self.add_tour_step("Use this button to get a Satellite view.",
                           "#minimap div.widget-minimap", alignment="right")
        self.add_tour_step("Click here to zoom in.",
                           "#widget-zoom-in", alignment="left")
        self.add_tour_step("Or click here to zoom out.",
                           "#widget-zoom-out", alignment="left")
        self.add_tour_step("Use the Menu button for more options.",
                           ".searchbox-hamburger-container", alignment="right")
        self.add_tour_step("Or click here to see more Google apps.",
                           '[title="Google apps"]', alignment="left")
        self.add_tour_step("Thanks for using SeleniumBase Tours", "html",
                           title="🚃 End of Guided Tour 🚃")
        self.export_tour()  # The default name for exports is "my_tour.js"
        self.play_tour(interval=0)  # If interval > 0, autoplay after N seconds

Prompt: Add an example tour for DriverJS


from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop

class WorkshopListView(ListView):
    template_name = 'workshops/list_workshops.html'
    model = Workshop
    context_object_name = 'workshops'

    def get_queryset(self):
        event = get_active_event()

        return (super().get_queryset()
                       .filter(event=event)
                       .prefetch_related('applicants__user', 'skill_level')
                       .order_by('starts_at', 'title'))

class WorkshopDetailView(DetailView):
    template_name = 'workshops/view_workshop.html'
    model = Workshop

    def get_queryset(self):
        return super().get_queryset().prefetch_related('applicants__user', 'skill_level')

Response:
from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop

class WorkshopListView(ListView):
    template_name = 'workshops/list_workshops.html'
    model = Workshop
    context_object_name = 'workshops'

    def get_queryset(self):
        event = get_active_event()

        return (super().get_queryset()
                       .filter(event=event)
                       .prefetch_related('applicants__user', 'skill_level')
                       .order_by('starts_at', 'title'))

class WorkshopDetailView(DetailView):
    template_name = 'workshops/view_workshop.html'
    model = Workshop

    def get_queryset(self):
        return super().get_queryset().prefetch_related('applicants__user', 'skill_level')

Prompt:
Order workshops by start date before title

from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop

class WorkshopListView(ListView):
    template_name = 'workshops/list_workshops.html'
    model = Workshop
    context_object_name = 'workshops'

    def get_queryset(self):
        event = get_active_event()

        return (super().get_queryset()
                       .filter(event=event)
                       .prefetch_related('applicants__user', 'skill_level')
                       .order_by('title'))

class WorkshopDetailView(DetailView):
    template_name = 'workshops/view_workshop.html'
    model = Workshop

    def get_queryset(self):
        return super().get_queryset().prefetch_related('applicants__user', 'skill_level')


# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project

from ansiblelint import AnsibleLintRule
import re

class VariableHasSpacesRule(AnsibleLintRule):
    id = '206'
    shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
    description = 'Variables should have spaces before and after: ``{{ var_name }}``'
    severity = 'LOW'
    tags = ['formatting']
    version_added = 'v4.0.0'

    variable_syntax = re.compile(r"{{.*}}")
    bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")

    def match(self, file, line):
        if not self.variable_syntax.search(line):
            return
        line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
        return self.bracket_regex.search(line_exclude_json)

Fix nested JSON obj false positive

Response:
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project

from ansiblelint import AnsibleLintRule
import re

class VariableHasSpacesRule(AnsibleLintRule):
    id = '206'
    shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
    description = 'Variables should have spaces before and after: ``{{ var_name }}``'
    severity = 'LOW'
    tags = ['formatting']
    version_added = 'v4.0.0'

    variable_syntax = re.compile(r"{{.*}}")
    bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")

    def match(self, file, line):
        if not self.variable_syntax.search(line):
            return
        line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
        return self.bracket_regex.search(line_exclude_json)

Prompt:
var-space-rule: Fix nested JSON obj false positive

When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
  set_fact:"{{ {'test': {'subtest': variable}} }}"

'variable}}' will raise a false positive [206] error.

This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.

Fixes: #665

Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com>

# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project

from ansiblelint import AnsibleLintRule
import re

class VariableHasSpacesRule(AnsibleLintRule):
    id = '206'
    shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
    description = 'Variables should have spaces before and after: ``{{ var_name }}``'
    severity = 'LOW'
    tags = ['formatting']
    version_added = 'v4.0.0'

    variable_syntax = re.compile(r"{{.*}}")
    bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")

    def match(self, file, line):
        if not self.variable_syntax.search(line):
            return
        return self.bracket_regex.search(line)


"""empty message

Revision ID: 1815829d365
Revises: 3fcddd64a72
Create Date: 2016-02-09 17:58:47.362133

"""

# revision identifiers, used by Alembic.
revision = '1815829d365'
down_revision = '3fcddd64a72'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    # create new unique index to include geo app ref
    op.execute("DROP INDEX title_abr_idx")
    op.execute("CREATE UNIQUE INDEX title_abr_geo_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'), (record->'data'->>'geometry_application_reference'))")
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.execute("DROP INDEX title_abr_geo_idx")
    op.execute("CREATE UNIQUE INDEX title_abr_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'))")
    ### end Alembic commands ###

Replace title_abr_idx with new unique index that includes geometry_application_reference

Response:
"""empty message

Revision ID: 1815829d365
Revises: 3fcddd64a72
Create Date: 2016-02-09 17:58:47.362133

"""

# revision identifiers, used by Alembic.
revision = '1815829d365'
down_revision = '3fcddd64a72'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    # create new unique index to include geo app ref
    op.execute("DROP INDEX title_abr_idx")
    op.execute("CREATE UNIQUE INDEX title_abr_geo_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'), (record->'data'->>'geometry_application_reference'))")
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.execute("DROP INDEX title_abr_geo_idx")
    op.execute("CREATE UNIQUE INDEX title_abr_idx ON records((record->'data'->>'title_number'),(record->'data'->>'application_reference'))")
    ### end Alembic commands ###

Prompt: Replace title_abr_idx with new unique index that includes geometry_application_reference


import argparse

parser = argparse.ArgumentParser()
parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases
parser.add_argument('--focus', type=str, default="")
parser.add_argument('--kernel_version', type=str, default="")
parser.add_argument('--k8s_version', type=str, default="")
parser.add_argument('--retrieve', type=str, default="focus")

args = parser.parse_args()

# Update kernel_version to expected format
args.kernel_version = args.kernel_version.replace('.', '')
if args.kernel_version == "netnext":
	args.kernel_version = "net-next"

print(args.__dict__[args.retrieve])

Response:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases
parser.add_argument('--focus', type=str, default="")
parser.add_argument('--kernel_version', type=str, default="")
parser.add_argument('--k8s_version', type=str, default="")
parser.add_argument('--retrieve', type=str, default="focus")

args = parser.parse_args()

# Update kernel_version to expected format
args.kernel_version = args.kernel_version.replace('.', '')
if args.kernel_version == "netnext":
	args.kernel_version = "net-next"

print(args.__dict__[args.retrieve])

Prompt:
test: Format test-only's kernel_version to avoid mistakes

I often try to start test-only builds with e.g.:

    test-only --kernel_version=4.19 --focus="..."

That fails because our tests expect "419". We can extend the Python
script used to parse argument to recognize that and update
kernel_version to the expected format.

Signed-off-by: Paul Chaignon <a027184a55211cd23e3f3094f1fdc728df5e0500@cilium.io>

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases
parser.add_argument('--focus', type=str, default="")
parser.add_argument('--kernel_version', type=str, default="")
parser.add_argument('--k8s_version', type=str, default="")
parser.add_argument('--retrieve', type=str, default="focus")

args = parser.parse_args()

print(args.__dict__[args.retrieve])