"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin

import requests

from src.authorization_tokens import authorization
from src.parsing import parse_token_clause

def post_data_to_user_intent_endpoint(context, payload=None):
    """Post data into the REST API endpoint for user-intent."""
    url = "/api/v1/user-intent"

    if payload is not None:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context),
                                         json=payload)
    else:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context))

@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
    """Post no payload into the REST API endpoint for user-intent."""
    post_data_to_user_intent_endpoint(context)

@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
    """Post empty into the REST API endpoint for user-intent."""
    payload = {}
    post_data_to_user_intent_endpoint(context, payload)

Response:
"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin

import requests

from src.authorization_tokens import authorization
from src.parsing import parse_token_clause

def post_data_to_user_intent_endpoint(context, payload=None):
    """Post data into the REST API endpoint for user-intent."""
    url = "/api/v1/user-intent"

    if payload is not None:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context),
                                         json=payload)
    else:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context))

@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
    """Post no payload into the REST API endpoint for user-intent."""
    post_data_to_user_intent_endpoint(context)

@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
    """Post empty into the REST API endpoint for user-intent."""
    payload = {}
    post_data_to_user_intent_endpoint(context, payload)

Prompt:
Fix - send JSON to the API, not raw data

"""Basic checks for the server API."""
from behave import then, when
from urllib.parse import urljoin

import requests

from src.authorization_tokens import authorization
from src.parsing import parse_token_clause

def post_data_to_user_intent_endpoint(context, payload=None):
    """Post data into the REST API endpoint for user-intent."""
    url = "/api/v1/user-intent"

    if payload is not None:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context),
                                         data=payload)
    else:
        context.response = requests.post(context.coreapi_url + url,
                                         headers=authorization(context))

@when('I call user-intent endpoint without any payload')
def check_user_intent_without_payload(context):
    """Post no payload into the REST API endpoint for user-intent."""
    post_data_to_user_intent_endpoint(context)

@when('I call user-intent endpoint with empty payload')
def check_user_intent_with_empty_payload(context):
    """Post empty into the REST API endpoint for user-intent."""
    payload = {}
    post_data_to_user_intent_endpoint(context, payload)


from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)

    def test_home_page_returns_correct_html(self):
        expected_html = render_to_string('home.html')
        request = HttpRequest()
        response = home(request)
        actual_html = response.content.decode()
        self.assertEqual(actual_html, expected_html)

Add test for home page html content

Add test for home page html content

Response:
from django.core.urlresolvers import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)

    def test_home_page_returns_correct_html(self):
        expected_html = render_to_string('home.html')
        request = HttpRequest()
        response = home(request)
        actual_html = response.content.decode()
        self.assertEqual(actual_html, expected_html)

Prompt:
Add test for home page html content

from django.core.urlresolvers import resolve
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)


from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from jsonfield import JSONField

@python_2_unicode_compatible
class KeyValue(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, db_index=True)
    value = JSONField()

    def __str__(self):
        return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

Response:
from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from jsonfield import JSONField

@python_2_unicode_compatible
class KeyValue(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, db_index=True)
    value = JSONField()

    def __str__(self):
        return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

Prompt:
Use @python_2_unicode_compatible rather than repeating methods

from django.contrib.auth.models import Group
from django.db import models

from jsonfield import JSONField

class KeyValue(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    key = models.CharField(max_length=64, db_index=True)
    value = JSONField()

    def __unicode__(self):
        return u'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)

    def __str__(self):
        return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)


"""yolk

Author: Rob Cakebread <cakebread at gmail>

License  : BSD

"""

__version__ = '0.6.2'

Increment patch version to 0.6.2

Increment patch version to 0.6.2

Response:
"""yolk

Author: Rob Cakebread <cakebread at gmail>

License  : BSD

"""

__version__ = '0.6.2'

Prompt:
Increment patch version to 0.6.2

"""yolk

Author: Rob Cakebread <cakebread at gmail>

License  : BSD

"""

__version__ = '0.6.1'


from django.conf import settings
from django.core.urlresolvers import reverse

TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"

# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY

# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD

# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL

Response:
from django.conf import settings
from django.core.urlresolvers import reverse

TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"

# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY

# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD

# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL

Prompt:
Remove unused import causing deprecation warning

Warning in the form:
RemovedInDjango19Warning: "ModelXYZ" doesn't declare an explicit app_label
Apparently this happens because it tries to import models before app
configuration runs

from django.conf import settings
from django.core.urlresolvers import reverse
from helios.views import election_shortcut

TEMPLATE_BASE = settings.HELIOS_TEMPLATE_BASE or "helios/templates/base.html"

# a setting to ensure that only admins can create an election
ADMIN_ONLY = settings.HELIOS_ADMIN_ONLY

# allow upload of voters via CSV?
VOTERS_UPLOAD = settings.HELIOS_VOTERS_UPLOAD

# allow emailing of voters?
VOTERS_EMAIL = settings.HELIOS_VOTERS_EMAIL


import pytest

import wee_slack

@pytest.mark.parametrize("text", [
    """
    * an item
    * another item
    """,
    "* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
    assert wee_slack.render_formatting(text) == text

Add tests for no formatting cases

Add tests for no formatting cases

Response:
import pytest

import wee_slack

@pytest.mark.parametrize("text", [
    """
    * an item
    * another item
    """,
    "* Run this command: `find . -name '*.exe'`",
])
def test_does_not_format(text):
    assert wee_slack.render_formatting(text) == text

Prompt: Add tests for no formatting cases


"""The WaveBlocks Project

This file is main script for running simulations with WaveBlocks.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import ParameterLoader

# Read the path for the configuration file we use for this simulation.
try:
    parametersfile = sys.argv[1]
except IndexError:
    raise ValueError("No configuration file given!")

print("Using configuration from file: " + parametersfile)

# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)

# Print the parameters that apply for this simulation
print(PA)

# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
    from WaveBlocksND import SimulationLoopFourier
    SL = SimulationLoopFourier(PA)

elif PA["algorithm"] == "hagedorn":
    from WaveBlocksND import SimulationLoopHagedorn
    SL = SimulationLoopHagedorn(PA)

elif PA["algorithm"] == "hagedorn_inhomog":
    from WaveBlocksND import SimulationLoopHagedornInhomogeneous
    SL = SimulationLoopHagedornInhomogeneous(PA)

# TODO: Add new algorithms here

else:
    raise ValueError("Invalid propagator algorithm.")

# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()

# End the simulation, close output files etc.
SL.end_simulation()

Response:
"""The WaveBlocks Project

This file is main script for running simulations with WaveBlocks.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import ParameterLoader

# Read the path for the configuration file we use for this simulation.
try:
    parametersfile = sys.argv[1]
except IndexError:
    raise ValueError("No configuration file given!")

print("Using configuration from file: " + parametersfile)

# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)

# Print the parameters that apply for this simulation
print(PA)

# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
    from WaveBlocksND import SimulationLoopFourier
    SL = SimulationLoopFourier(PA)

elif PA["algorithm"] == "hagedorn":
    from WaveBlocksND import SimulationLoopHagedorn
    SL = SimulationLoopHagedorn(PA)

elif PA["algorithm"] == "hagedorn_inhomog":
    from WaveBlocksND import SimulationLoopHagedornInhomogeneous
    SL = SimulationLoopHagedornInhomogeneous(PA)

# TODO: Add new algorithms here

else:
    raise ValueError("Invalid propagator algorithm.")

# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()

# End the simulation, close output files etc.
SL.end_simulation()

Prompt:
Enable inhomogeneous packets in the main simulation runner

"""The WaveBlocks Project

This file is main script for running simulations with WaveBlocks.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import ParameterLoader

# Read the path for the configuration file we use for this simulation.
try:
    parametersfile = sys.argv[1]
except IndexError:
    raise ValueError("No configuration file given!")

print("Using configuration from file: " + parametersfile)

# Set up the parameter provider singleton
PA = ParameterLoader().load_from_file(parametersfile)

# Print the parameters that apply for this simulation
print(PA)

# Decide which simulation loop to use
if PA["algorithm"] == "fourier":
    from WaveBlocksND import SimulationLoopFourier
    SL = SimulationLoopFourier(PA)

elif PA["algorithm"] == "hagedorn":
    from WaveBlocksND import SimulationLoopHagedorn
    SL = SimulationLoopHagedorn(PA)

# TODO: Add new algorithms here

else:
    raise ValueError("Invalid propagator algorithm.")

# Initialize and run the simulation
SL.prepare_simulation()
SL.run_simulation()

# End the simulation, close output files etc.
SL.end_simulation()


import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint

def multi_size(max_len):

	for n in [2**(n+1) for n in range(max_len)]:
		print 'Array size: %d' % n
		arr = [randint(0, 2**max_len) for n in range(n)]

		current_time = time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
		print 'Merge sort: %f' % (time.time() - current_time)

		current_time = time.time()
		quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
		print 'Quicksort: %f' % (time.time() - current_time)
		print '-----------------'

def fixed_time(sec, length):

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		mergesort.merge_sort.sort(arr)
		count += 1

	print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		quicksort.quicksort.sort(arr, 0, length)
		count += 1

	print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)

if __name__ == '__main__':

	if len(sys.argv) > 2:
		fixed_time(int(sys.argv[1]), int(sys.argv[2]))
	else:
		multi_size(int(sys.argv[1]))

Response:
import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint

def multi_size(max_len):

	for n in [2**(n+1) for n in range(max_len)]:
		print 'Array size: %d' % n
		arr = [randint(0, 2**max_len) for n in range(n)]

		current_time = time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr), n+1)
		print 'Merge sort: %f' % (time.time() - current_time)

		current_time = time.time()
		quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, n+1), n+1)
		print 'Quicksort: %f' % (time.time() - current_time)
		print '-----------------'

def fixed_time(sec, length):

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		mergesort.merge_sort.sort(arr)
		count += 1

	print 'Merge sort: %d %d-element arrays in %d seconds' % (count, length, sec)

	count = 0
	start = time.time()
	end = start + sec

	while time.time() < end:
		arr = [randint(0, length) for n in range(length)]
		quicksort.quicksort.sort(arr, 0, length)
		count += 1

	print 'Quicksort: %d %d-element arrays in %d seconds' % (count, length, sec)

if __name__ == '__main__':

	if len(sys.argv) > 2:
		fixed_time(int(sys.argv[1]), int(sys.argv[2]))
	else:
		multi_size(int(sys.argv[1]))

Prompt:
Allow comparison within a fixed time period

To get an idea of average run-time, I wanted to be able to test
mergesort and quicksort with the same inputs many times over;
now by specifying a time limit and array length, the script will
run each algorithm on as many times as possible on random arrays
and report how many arrays were sorted within the time period.

import mergesort.merge_sort
import quicksort.quicksort
import sys
import time
from random import randint

def main(max_len):

	for n in [2**(n+1) for n in range(max_len)]:
		print 'Array size: %d' % n
		arr = [randint(0, 2**max_len) for n in range(n)]

		current_time = time.time()
		quicksort.quicksort.check(mergesort.merge_sort.sort(arr))
		print 'Merge sort: %f' % (time.time() - current_time)

		current_time = time.time()
		quicksort.quicksort.check(quicksort.quicksort.sort(arr, 0, len(arr)))
		print 'Quicksort: %f' % (time.time() - current_time)
		print '-----------------'

if __name__ == '__main__':

	try:
		max_len = int(sys.argv[1])
	except (IndexError, ValueError):
		print 'Format: python sorting_test.py <log(max input)>'

	main(max_len)


"""
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip

class GeoLocator(object):
    """Geo locate IP addresses using the MaxMind database"""
    def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
                 ipv6_geo_path='/usr/share/GeoIP/GeoIPv6.dat'):
        self.ipv4_geo_path = ipv4_geo_path
        self.ipv6_geo_path = ipv6_geo_path

    @property
    def ipv4_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv4 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv4_geo'):
            self._ipv4_geo = pygeoip.GeoIP(filename=self.ipv4_geo_path, flags=1)
        return self._ipv4_geo

    @property
    def ipv6_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv6 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv6_geo'):
            self._ipv6_geo = pygeoip.GeoIP(filename=self.ipv6_geo_path, flags=1)
        return self._ipv6_geo

    def _check_if_ipv6(self, ip_address):
        """Return true if given ip_address is IPv6, false otherwise"""
        try:
            # socket.inet_pton throws an exception if it isn't a valid address
            # of the stated address class
            socket.inet_pton(socket.AF_INET6, ip_address)
            return True
        except:
            return False

    def find_country(self, ip_address):
        """Return best guess of country in which this IP address resides"""
        if self._check_if_ipv6(ip_address):
            return self.ipv6_geo.country_code_by_addr(ip_address)
        else:
            return self.ipv4_geo.country_code_by_addr(ip_address)

Response:
"""
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip

class GeoLocator(object):
    """Geo locate IP addresses using the MaxMind database"""
    def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
                 ipv6_geo_path='/usr/share/GeoIP/GeoIPv6.dat'):
        self.ipv4_geo_path = ipv4_geo_path
        self.ipv6_geo_path = ipv6_geo_path

    @property
    def ipv4_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv4 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv4_geo'):
            self._ipv4_geo = pygeoip.GeoIP(filename=self.ipv4_geo_path, flags=1)
        return self._ipv4_geo

    @property
    def ipv6_geo(self):
        """Return an instance of pygeoip.GeoIP loaded with IPv6 geolocation data.

        The data is stored in memory, and loaded up only when first requested"""
        if not hasattr(self, '_ipv6_geo'):
            self._ipv6_geo = pygeoip.GeoIP(filename=self.ipv6_geo_path, flags=1)
        return self._ipv6_geo

    def _check_if_ipv6(self, ip_address):
        """Return true if given ip_address is IPv6, false otherwise"""
        try:
            # socket.inet_pton throws an exception if it isn't a valid address
            # of the stated address class
            socket.inet_pton(socket.AF_INET6, ip_address)
            return True
        except:
            return False

    def find_country(self, ip_address):
        """Return best guess of country in which this IP address resides"""
        if self._check_if_ipv6(ip_address):
            return self.ipv6_geo.country_code_by_addr(ip_address)
        else:
            return self.ipv4_geo.country_code_by_addr(ip_address)

Prompt:
Move the Geo Location stuff into a class

#Using MaxMind, so import pygeoip
import pygeoip

def geolocate(ip_addresses):

  #Read in files, storing in memory for speed
  ip4_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIP.dat", flags = 1)
  ip6_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIPv6.dat", flags = 1)

  #Check type
  if not(isinstance(ip_addresses,list)):
    ip_addresses = [ip_addresses]

  #Construct output list
  output = []

  #For each entry in the input list, retrieve the country code and add it to the output object
  for entry in ip_addresses:

    if(bool(re.search(":",entry))):

      try:

        output.append(ip6_geo.country_code_by_addr(entry))

      except:

        output.append("Invalid")

    else:

      try:

        output.append(ip4_geo.country_code_by_addr(entry))

      except:

        output.append("Invalid")

  #Return
  return output


from flask import current_app
from functools import wraps
from hashlib import md5

from changes.ext.redis import UnableToGetLock
from changes.config import redis

def lock(func):
    @wraps(func)
    def wrapped(**kwargs):
        key = '{0}:{1}:{2}'.format(
            func.__module__,
            func.__name__,
            md5(
                '&'.join('{0}={1}'.format(k, repr(v))
                for k, v in sorted(kwargs.iteritems()))
            ).hexdigest()
        )
        try:
            with redis.lock(key, timeout=1, expire=300, nowait=True):
                return func(**kwargs)
        except UnableToGetLock:
            current_app.logger.warn('Unable to get lock for %s', key)

    return wrapped

Use __module__ to make @lock unique

Response:
from flask import current_app
from functools import wraps
from hashlib import md5

from changes.ext.redis import UnableToGetLock
from changes.config import redis

def lock(func):
    @wraps(func)
    def wrapped(**kwargs):
        key = '{0}:{1}:{2}'.format(
            func.__module__,
            func.__name__,
            md5(
                '&'.join('{0}={1}'.format(k, repr(v))
                for k, v in sorted(kwargs.iteritems()))
            ).hexdigest()
        )
        try:
            with redis.lock(key, timeout=1, expire=300, nowait=True):
                return func(**kwargs)
        except UnableToGetLock:
            current_app.logger.warn('Unable to get lock for %s', key)

    return wrapped

Prompt:
Use __module__ to make @lock unique

Summary: Fixes T49428.

Test Plan:
Hard to test on changes_dev because it can't run both handlers (no
place to send notifications to), but this seems simple enough...

Reviewers: armooo, kylec

Reviewed By: kylec

Subscribers: changesbot, mkedia, jukka, vishal

Maniphest Tasks: T49428

Differential Revision: https://tails.corp.dropbox.com/D122408

from flask import current_app
from functools import wraps
from hashlib import md5

from changes.ext.redis import UnableToGetLock
from changes.config import redis

def lock(func):
    @wraps(func)
    def wrapped(**kwargs):
        key = '{0}:{1}'.format(
            func.__name__,
            md5(
                '&'.join('{0}={1}'.format(k, repr(v))
                for k, v in sorted(kwargs.iteritems()))
            ).hexdigest()
        )
        try:
            with redis.lock(key, timeout=1, expire=300, nowait=True):
                return func(**kwargs)
        except UnableToGetLock:
            current_app.logger.warn('Unable to get lock for %s', key)

    return wrapped


from setuptools import setup, find_packages

setup(
    name='django-flatblocks',
    version='0.9',
    description='django-flatblocks acts like django.contrib.flatpages but '
                'for parts of a page; like an editable help box you want '
                'show alongside the main content.',
    long_description=open('README.rst').read(),
    keywords='django apps',
    license='New BSD License',
    author='Horst Gutmann',
    author_email='zerok@zerokspot.com',
    url='http://github.com/zerok/django-flatblocks/',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Plugins',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    packages=find_packages('flatblocks'),
    package_data={
        'flatblocks': [
            'templates/flatblocks/*.html',
            'locale/*/*/*.mo',
            'locale/*/*/*.po',
        ]
    },
    zip_safe=False,
    requires = [
        'Django (>=1.4)',
    ],
)

Remove kws: does not exist

Remove kws: does not exist

Response:
from setuptools import setup, find_packages

setup(
    name='django-flatblocks',
    version='0.9',
    description='django-flatblocks acts like django.contrib.flatpages but '
                'for parts of a page; like an editable help box you want '
                'show alongside the main content.',
    long_description=open('README.rst').read(),
    keywords='django apps',
    license='New BSD License',
    author='Horst Gutmann',
    author_email='zerok@zerokspot.com',
    url='http://github.com/zerok/django-flatblocks/',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Plugins',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    packages=find_packages('flatblocks'),
    package_data={
        'flatblocks': [
            'templates/flatblocks/*.html',
            'locale/*/*/*.mo',
            'locale/*/*/*.po',
        ]
    },
    zip_safe=False,
    requires = [
        'Django (>=1.4)',
    ],
)

Prompt:
Remove kws: does not exist

from setuptools import setup, find_packages

setup(
    name='django-flatblocks',
    version='0.9',
    description='django-flatblocks acts like django.contrib.flatpages but '
                'for parts of a page; like an editable help box you want '
                'show alongside the main content.',
    long_description=open('README.rst').read(),
    keywords='django apps',
    license='New BSD License',
    author='Horst Gutmann',
    author_email='zerok@zerokspot.com',
    url='http://github.com/zerok/django-flatblocks/',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Plugins',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    packages=find_packages('flatblocks'),
    package_data={
        'flatblocks': [
            'templates/flatblocks/*.html',
            'locale/*/*/*.mo',
            'locale/*/*/*.po',
        ]
    },
    zip_safe=False,
    requires = [
        'Django (>=1.4)',
    ],
    **kws
)


# Copyright (c) 2015, Daniele Venzano
#
# 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 flask import Blueprint

web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

import zoe_web.web.start
import zoe_web.web.status
import zoe_web.web.applications

from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION

@web_bp.context_processor
def inject_version():
    return {
        'zoe_version': ZOE_VERSION,
        'zoe_api_version': ZOE_API_VERSION,
    }

Fix version in web pages

Fix version in web pages

Response:
# Copyright (c) 2015, Daniele Venzano
#
# 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 flask import Blueprint

web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

import zoe_web.web.start
import zoe_web.web.status
import zoe_web.web.applications

from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION

@web_bp.context_processor
def inject_version():
    return {
        'zoe_version': ZOE_VERSION,
        'zoe_api_version': ZOE_API_VERSION,
    }

Prompt:
Fix version in web pages

# Copyright (c) 2015, Daniele Venzano
#
# 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 flask import Blueprint

web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

import zoe_web.web.start
import zoe_web.web.status
import zoe_web.web.applications

from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION

@web_bp.context_processor
def inject_version():
    return {
        'zoe_lib_version': ZOE_VERSION,
        'zoe_api_version': ZOE_API_VERSION,
    }


import requests, json, urllib

SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'

def getCOREMentions(identifier, **kwargs):
    """Return the number of mentions in CORE and a descriptor, as a tuple.

    Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
    params = {
        'api_key': API_KEY,
        'format': 'json',
    }
    params.update(kwargs)

    response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
    response.raise_for_status()

    results = response.json()
    score = results['ListRecords'][0]['total_hits']

    return score, 'mentions in Open Access articles (via http://core.ac.uk/)'

Response:
import requests, json, urllib

SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/'
API_KEY = 'FILL THIS IN'

def getCOREMentions(identifier, **kwargs):
    """Return the number of mentions in CORE and a descriptor, as a tuple.

    Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
    params = {
        'api_key': API_KEY,
        'format': 'json',
    }
    params.update(kwargs)

    response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
    response.raise_for_status()

    results = response.json()
    score = results['ListRecords'][0]['total_hits']

    return score, 'mentions in Open Access articles (via http://core.ac.uk/)'

Prompt:
Switch to using the v1 API to get total hits.

import requests, json, urllib

SEARCH_URL = 'http://core.ac.uk:80/api-v2/articles/search/'
API_KEY = 'FILL THIS IN'

def getCOREMentions(identifier, **kwargs):
    """Return the number of mentions in CORE and a descriptor, as a tuple.

    Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"""
    params = {
        'apiKey': API_KEY,
        'metadata': 'false',
        'pageSize': 100,
        'page': 1
    }
    params.update(kwargs)

    response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params)
    response.raise_for_status()

    results = response.json()

    return (len(results['data'] or []),
            'mentions in Open Access articles (via http://core.ac.uk/)')


import os, logging
from flask import Flask
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.debug("\nConfiguration\n%s\n" % app.config)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

# Validate config
for property_to_check in ['CASEWORK_URL', 'CHECK_URL']:
	if not app.config[property_to_check]:
		raise Exception('Missing %r configuation property.' % (property_to_check))

Set config logging in init to debug

Set config logging in init to debug

Response:
import os, logging
from flask import Flask
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.debug("\nConfiguration\n%s\n" % app.config)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

# Validate config
for property_to_check in ['CASEWORK_URL', 'CHECK_URL']:
	if not app.config[property_to_check]:
		raise Exception('Missing %r configuation property.' % (property_to_check))

Prompt:
Set config logging in init to debug

import os, logging
from flask import Flask
from raven.contrib.flask import Sentry

app = Flask(__name__)

app.config.from_object(os.environ.get('SETTINGS'))

app.logger.info("\nConfiguration\n%s\n" % app.config)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

if not app.debug:
    app.logger.addHandler(logging.StreamHandler())
    app.logger.setLevel(logging.INFO)

# Validate config
for property_to_check in ['CASEWORK_URL', 'CHECK_URL']:
	if not app.config[property_to_check]:
		raise Exception('Missing %r configuation property.' % (property_to_check))


import logging
import logging.handlers

# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)

# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
                                                backupCount=7)
tfh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)

Response:
import logging
import logging.handlers

# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)

# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
                                                backupCount=7)
tfh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)

Prompt:
Update log output so that it works more nicely with ELK

import logging
import logging.handlers

# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)

# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None,
                                                backupCount=5)
tfh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s: %(message)s - %(name)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)

# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)


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

import os.path

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

PYGMENTS_STYLE = 'default'

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

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

Update MathJax URL to 2.7.1

Update MathJax URL to 2.7.1

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

import os.path

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

PYGMENTS_STYLE = 'default'

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

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

Prompt:
Update MathJax URL to 2.7.1

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

import os.path

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

PYGMENTS_STYLE = 'default'

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

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


from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
        adzerk_srs = g.live_config.get("adzerk_srs")
        in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs
        if adzerk_all_the_things or in_adzerk_sr:
            url_key = "adzerk_https_url" if c.secure else "adzerk_url"
            site_name = getattr(c.site, "analytics_name", c.site.name)
            self.ad_url = g.config[url_key].format(
                subreddit=quote(site_name.lower()),
                origin=c.request_origin,
            )
            self.frame_id = "ad_main"

Response:
from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
        adzerk_srs = g.live_config.get("adzerk_srs")
        in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs
        if adzerk_all_the_things or in_adzerk_sr:
            url_key = "adzerk_https_url" if c.secure else "adzerk_url"
            site_name = getattr(c.site, "analytics_name", c.site.name)
            self.ad_url = g.config[url_key].format(
                subreddit=quote(site_name.lower()),
                origin=c.request_origin,
            )
            self.frame_id = "ad_main"

Prompt:
Use analytics name for subreddits if available.

This allows a catch-all for multis to be used.

from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)
        adzerk_all_the_things = g.live_config.get("adzerk_all_the_things")
        adzerk_srs = g.live_config.get("adzerk_srs")
        in_adzerk_sr = adzerk_srs and c.site.name.lower() in adzerk_srs
        if adzerk_all_the_things or in_adzerk_sr:
            url_key = "adzerk_https_url" if c.secure else "adzerk_url"
            self.ad_url = g.config[url_key].format(
                subreddit=quote(c.site.name.lower()),
                origin=c.request_origin,
            )
            self.frame_id = "ad_main"


# Run the _testcapi module tests (tests for the Python/C API):  by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.

import sys
import test_support
import _testcapi

for name in dir(_testcapi):
    if name.startswith('test_'):
        test = getattr(_testcapi, name)
        if test_support.verbose:
            print "internal", name
        try:
            test()
        except _testcapi.error:
            raise test_support.TestFailed, sys.exc_info()[1]

Response:
# Run the _testcapi module tests (tests for the Python/C API):  by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.

import sys
import test_support
import _testcapi

for name in dir(_testcapi):
    if name.startswith('test_'):
        test = getattr(_testcapi, name)
        if test_support.verbose:
            print "internal", name
        try:
            test()
        except _testcapi.error:
            raise test_support.TestFailed, sys.exc_info()[1]

Prompt:
Fix typo in comment (the module is now called _testcapi, not _test).

# Run the _testcapi module tests (tests for the Python/C API):  by defn,
# these are all functions _test exports whose name begins with 'test_'.

import sys
import test_support
import _testcapi

for name in dir(_testcapi):
    if name.startswith('test_'):
        test = getattr(_testcapi, name)
        if test_support.verbose:
            print "internal", name
        try:
            test()
        except _testcapi.error:
            raise test_support.TestFailed, sys.exc_info()[1]


import argparse
import hashlib
import logging
import os

import yaml

from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify

log = logging.getLogger("mklocale")

def cmdline(argv):
    logging.basicConfig(level=logging.INFO)
    ap = argparse.ArgumentParser()
    ap.add_argument("config")
    args = ap.parse_args()

    try:
        import requests_cache
        requests_cache.install_cache(
            os.path.realpath('./mklocale.%s.cache' % hashlib.md5(args.config).hexdigest()),
            expire_after=86400
        )
    except ImportError:
        pass
    os.chdir(os.path.dirname(args.config))
    with open(args.config, "r") as infp:
        config = yaml.safe_load(infp)
    catalogs = []
    for tx_config in listify(config.get("transifex")):
        catalogs.extend(transifex.read_catalogs(tx_config))
    for merged_catalog in merge_by_language(catalogs):
        targets = [
            t.format(lang=merged_catalog.locale)
            for t
            in listify(config["target"])
        ]
        for target_file in targets:
            write_catalog(target_file, merged_catalog)

Add optional use of requests_cache

Add optional use of requests_cache

Response:
import argparse
import hashlib
import logging
import os

import yaml

from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify

log = logging.getLogger("mklocale")

def cmdline(argv):
    logging.basicConfig(level=logging.INFO)
    ap = argparse.ArgumentParser()
    ap.add_argument("config")
    args = ap.parse_args()

    try:
        import requests_cache
        requests_cache.install_cache(
            os.path.realpath('./mklocale.%s.cache' % hashlib.md5(args.config).hexdigest()),
            expire_after=86400
        )
    except ImportError:
        pass
    os.chdir(os.path.dirname(args.config))
    with open(args.config, "r") as infp:
        config = yaml.safe_load(infp)
    catalogs = []
    for tx_config in listify(config.get("transifex")):
        catalogs.extend(transifex.read_catalogs(tx_config))
    for merged_catalog in merge_by_language(catalogs):
        targets = [
            t.format(lang=merged_catalog.locale)
            for t
            in listify(config["target"])
        ]
        for target_file in targets:
            write_catalog(target_file, merged_catalog)

Prompt:
Add optional use of requests_cache

import argparse
import logging

import yaml

from mklocale import transifex
from mklocale.cats import merge_by_language, write_catalog
from mklocale.utils import listify

log = logging.getLogger("mklocale")

def cmdline(argv):
    logging.basicConfig(level=logging.INFO)
    ap = argparse.ArgumentParser()
    ap.add_argument("config")
    args = ap.parse_args()
    with open(args.config, "r") as infp:
        config = yaml.safe_load(infp)
    catalogs = []
    for tx_config in listify(config.get("transifex")):
        catalogs.extend(transifex.read_catalogs(tx_config))
    for merged_catalog in merge_by_language(catalogs):
        targets = [
            t.format(lang=merged_catalog.locale)
            for t
            in listify(config["target"])
        ]
        for target_file in targets:
            write_catalog(target_file, merged_catalog)


"""
acute models.
"""
from django.db.models import fields

from opal import models

class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatment(models.Treatment): pass
class Investigation(models.Investigation): pass

class Clerking(models.EpisodeSubrecord):
    _icon = 'fa fa-user'
    _title = 'Seen by'

    referrer   = fields.CharField(max_length=200, blank=True, null=True)
    clerked_by = fields.CharField(max_length=200, blank=True, null=True)
    consultant = fields.CharField(max_length=200, blank=True, null=True)

class Plan(models.EpisodeSubrecord):
    _is_singleton = True
    _icon = 'fa fa-list-ol'

    plan = fields.TextField(blank=True, null=True)

class Rescuscitation(models.EpisodeSubrecord):
    _icon = 'fa fa-warning'

    status = fields.CharField(max_length=200, blank=True, null=True)

class NursingNotes(models.EpisodeSubrecord):
    _icon = 'fa fa-info-circle'

    notes = fields.TextField(blank=True, null=True)

class DischargeDue(models.EpisodeSubrecord):
    _icon = 'fa fa-calendar'

    date = fields.DateField(blank=True, null=True)

Rename Clerking -> Seen by

Rename Clerking -> Seen by

closes #1

Response:
"""
acute models.
"""
from django.db.models import fields

from opal import models

class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatment(models.Treatment): pass
class Investigation(models.Investigation): pass

class Clerking(models.EpisodeSubrecord):
    _icon = 'fa fa-user'
    _title = 'Seen by'

    referrer   = fields.CharField(max_length=200, blank=True, null=True)
    clerked_by = fields.CharField(max_length=200, blank=True, null=True)
    consultant = fields.CharField(max_length=200, blank=True, null=True)

class Plan(models.EpisodeSubrecord):
    _is_singleton = True
    _icon = 'fa fa-list-ol'

    plan = fields.TextField(blank=True, null=True)

class Rescuscitation(models.EpisodeSubrecord):
    _icon = 'fa fa-warning'

    status = fields.CharField(max_length=200, blank=True, null=True)

class NursingNotes(models.EpisodeSubrecord):
    _icon = 'fa fa-info-circle'

    notes = fields.TextField(blank=True, null=True)

class DischargeDue(models.EpisodeSubrecord):
    _icon = 'fa fa-calendar'

    date = fields.DateField(blank=True, null=True)

Prompt:
Rename Clerking -> Seen by

closes #1

"""
acute models.
"""
from django.db.models import fields

from opal import models

class Demographics(models.Demographics): pass
class Location(models.Location): pass
class Allergies(models.Allergies): pass
class Diagnosis(models.Diagnosis): pass
class PastMedicalHistory(models.PastMedicalHistory): pass
class Treatment(models.Treatment): pass
class Investigation(models.Investigation): pass

class Clerking(models.EpisodeSubrecord):
    _icon = 'fa fa-user'

    referrer   = fields.CharField(max_length=200, blank=True, null=True)
    clerked_by = fields.CharField(max_length=200, blank=True, null=True)
    consultant = fields.CharField(max_length=200, blank=True, null=True)

class Plan(models.EpisodeSubrecord):
    _is_singleton = True
    _icon = 'fa fa-list-ol'

    plan = fields.TextField(blank=True, null=True)

class Rescuscitation(models.EpisodeSubrecord):
    _icon = 'fa fa-warning'

    status = fields.CharField(max_length=200, blank=True, null=True)

class NursingNotes(models.EpisodeSubrecord):
    _icon = 'fa fa-info-circle'

    notes = fields.TextField(blank=True, null=True)

class DischargeDue(models.EpisodeSubrecord):
    _icon = 'fa fa-calendar'

    date = fields.DateField(blank=True, null=True)


#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""

import sys
import threading

from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run

def main():
    config = parse_arguments()
    set_default_repeat(config["ttr"])
    set_default_ttl(config["ttl"])
    set_default_duration(config["ttd"])
    message_queue = MessageQueue(config["limit"])
    module_class = load_module_from_conf(config)
    message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
    message_manager_thread = threading.Thread(target=message_manager.manage)
    message_manager_thread.daemon = True
    message_manager_thread.start()
    run(message_queue, config["ptl"])

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You killed me.")
        sys.exit(0)

Response:
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""

import sys
import threading

from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run

def main():
    config = parse_arguments()
    set_default_repeat(config["ttr"])
    set_default_ttl(config["ttl"])
    set_default_duration(config["ttd"])
    message_queue = MessageQueue(config["limit"])
    module_class = load_module_from_conf(config)
    message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
    message_manager_thread = threading.Thread(target=message_manager.manage)
    message_manager_thread.daemon = True
    message_manager_thread.start()
    run(message_queue, config["ptl"])

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You killed me.")
        sys.exit(0)

Prompt:
Update to load dynamically the module selected by user.

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""

import sys
import threading

from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run

from modules.printer.printer import Printer # To remove, has to be done dynamically

def main():
    config = parse_arguments()
    set_default_repeat(config["ttr"])
    set_default_ttl(config["ttl"])
    set_default_duration(config["ttd"])
    message_queue = MessageQueue(config["limit"])
    message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
    message_manager_thread = threading.Thread(target=message_manager.manage)
    message_manager_thread.daemon = True
    message_manager_thread.start()
    run(message_queue, config["ptl"])

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("You killed me.")
        sys.exit(0)


#!flask/bin/python
from flask import Blueprint, jsonify

api_si = Blueprint('api_si', __name__)

@api_si.route("/stock_indicators")
def get_stock_indicators():
    return jsonify(stock_indicators=[
        {"username": "alice", "user_id": 1},
        {"username": "bob", "user_id": 2}
    ])

Implement blueprints on stock indicators

Response:
#!flask/bin/python
from flask import Blueprint, jsonify

api_si = Blueprint('api_si', __name__)

@api_si.route("/stock_indicators")
def get_stock_indicators():
    return jsonify(stock_indicators=[
        {"username": "alice", "user_id": 1},
        {"username": "bob", "user_id": 2}
    ])

Prompt: Implement blueprints on stock indicators


#
# Copyright (c) SAS Institute 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.
#

"""
List image types
"""

from rbuild import pluginapi
from rbuild.pluginapi import command

class ListImageTypesCommand(command.ListCommand):
    help = "List image types"
    resource = "imagetypes"
    listFields = ("name", "description")

class ImageTypes(pluginapi.Plugin):
    name = 'imagetypes'

    def initialize(self):
        for command, subcommand, commandClass in (
                ('list', 'imagetypes', ListImageTypesCommand),
                ):
            cmd = self.handle.Commands.getCommandClass(command)
            cmd.registerSubCommand(subcommand, commandClass)

    def list(self):
        rb = self.handle.facade.rbuilder
        return [type for type in rb.getImageTypes() if type.name]

Response:
#
# Copyright (c) SAS Institute 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.
#

"""
List image types
"""

from rbuild import pluginapi
from rbuild.pluginapi import command

class ListImageTypesCommand(command.ListCommand):
    help = "List image types"
    resource = "imagetypes"
    listFields = ("name", "description")

class ImageTypes(pluginapi.Plugin):
    name = 'imagetypes'

    def initialize(self):
        for command, subcommand, commandClass in (
                ('list', 'imagetypes', ListImageTypesCommand),
                ):
            cmd = self.handle.Commands.getCommandClass(command)
            cmd.registerSubCommand(subcommand, commandClass)

    def list(self):
        rb = self.handle.facade.rbuilder
        return [type for type in rb.getImageTypes() if type.name]

Prompt:
Swap order of name and description when listing image types

Uses the same order as target types, which puts the most important information,
the name, in front.

Refs APPENG-3419

#
# Copyright (c) SAS Institute 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.
#

"""
List image types
"""

from rbuild import pluginapi
from rbuild.pluginapi import command

class ListImageTypesCommand(command.ListCommand):
    help = "List image types"
    resource = "imagetypes"
    listFields = ("description", "name")

class ImageTypes(pluginapi.Plugin):
    name = 'imagetypes'

    def initialize(self):
        for command, subcommand, commandClass in (
                ('list', 'imagetypes', ListImageTypesCommand),
                ):
            cmd = self.handle.Commands.getCommandClass(command)
            cmd.registerSubCommand(subcommand, commandClass)

    def list(self):
        rb = self.handle.facade.rbuilder
        return [type for type in rb.getImageTypes() if type.name]


"""Generic field extensions
"""
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import Implicit
from Acquisition import ImplicitAcquisitionWrapper
from archetypes.schemaextender.field import ExtensionField
from archetypes.schemaextender.field import ExtensionField
from archetypes.schemaextender.interfaces import IExtensionField
from Products.Archetypes.public import *
from Products.ATExtensions.ateapi import DateTimeField
from Products.ATExtensions.ateapi import RecordField, RecordsField
from zope.interface import implements

class ExtBooleanField(ExtensionField, BooleanField):

    "Field extender"

class ExtComputedField(ExtensionField, ComputedField):

    "Field extender"

class ExtDateTimeField(ExtensionField, DateTimeField):

    "Field extender"

class ExtIntegerField(ExtensionField, IntegerField):

    "Field extender"

class ExtLinesField(ExtensionField, LinesField):

    "Field extender"

class ExtRecordField(ExtensionField, RecordField):

    "Field extender"

class ExtRecordsField(ExtensionField, RecordsField):

    "Field extender"

class ExtReferenceField(ExtensionField, ReferenceField):

    "Field extender"

class ExtStringField(ExtensionField, StringField):

    "Field extender"

class ExtTextField(ExtensionField, TextField):

    "Field extender"

#
# Method Initialization
# apply default getters and setters to schemaextender fields.
#

def apply_default_methods(context):

    for field in context.schema.fields():
        fieldname = field.getName()
        if getattr(context, 'get'+fieldname, None) is None:
            setattr(context, 'get'+fieldname, field_getter(context, fieldname))
        if getattr(context, 'set'+fieldname, None) is None:
            setattr(context, 'set'+fieldname, field_setter(context, fieldname))

class field_getter:

    def __init__(self, context, fieldname, **kwargs):
        self.context = context
        self.fieldname = fieldname

    def __call__(self):
        return self.context.Schema()[self.fieldname].getAccessor(self.context)(**kwargs)

class field_setter:

    def __init__(self, context, fieldname):
        self.context = context
        self.fieldname = fieldname

    def __call__(self, value, **kwargs):
        return self.context.Schema()[self.fieldname].getMutator(self.context)(value, **kwargs)

Move schemaextender automatic getter and setter methods

Response:
"""Generic field extensions
"""
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import Implicit
from Acquisition import ImplicitAcquisitionWrapper
from archetypes.schemaextender.field import ExtensionField
from archetypes.schemaextender.field import ExtensionField
from archetypes.schemaextender.interfaces import IExtensionField
from Products.Archetypes.public import *
from Products.ATExtensions.ateapi import DateTimeField
from Products.ATExtensions.ateapi import RecordField, RecordsField
from zope.interface import implements

class ExtBooleanField(ExtensionField, BooleanField):

    "Field extender"

class ExtComputedField(ExtensionField, ComputedField):

    "Field extender"

class ExtDateTimeField(ExtensionField, DateTimeField):

    "Field extender"

class ExtIntegerField(ExtensionField, IntegerField):

    "Field extender"

class ExtLinesField(ExtensionField, LinesField):

    "Field extender"

class ExtRecordField(ExtensionField, RecordField):

    "Field extender"

class ExtRecordsField(ExtensionField, RecordsField):

    "Field extender"

class ExtReferenceField(ExtensionField, ReferenceField):

    "Field extender"

class ExtStringField(ExtensionField, StringField):

    "Field extender"

class ExtTextField(ExtensionField, TextField):

    "Field extender"

#
# Method Initialization
# apply default getters and setters to schemaextender fields.
#

def apply_default_methods(context):

    for field in context.schema.fields():
        fieldname = field.getName()
        if getattr(context, 'get'+fieldname, None) is None:
            setattr(context, 'get'+fieldname, field_getter(context, fieldname))
        if getattr(context, 'set'+fieldname, None) is None:
            setattr(context, 'set'+fieldname, field_setter(context, fieldname))

class field_getter:

    def __init__(self, context, fieldname, **kwargs):
        self.context = context
        self.fieldname = fieldname

    def __call__(self):
        return self.context.Schema()[self.fieldname].getAccessor(self.context)(**kwargs)

class field_setter:

    def __init__(self, context, fieldname):
        self.context = context
        self.fieldname = fieldname

    def __call__(self, value, **kwargs):
        return self.context.Schema()[self.fieldname].getMutator(self.context)(value, **kwargs)

Prompt: Move schemaextender automatic getter and setter methods


# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

"""Integration tests for Document"""

from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories

class TestDocument(TestCase):
  """Document test cases"""
  # pylint: disable=invalid-name

  def setUp(self):
    super(TestDocument, self).setUp()
    self.api = Api()

  def test_update_title(self):
    """Test update document title."""
    create_title = "test_title"
    update_title = "update_test_title"
    document = factories.DocumentFactory(title=create_title)
    response = self.api.put(document, {"title": update_title})
    self.assert200(response)
    self.assertEqual(all_models.Document.query.get(document.id).title,
                     update_title)

Add test on update document title

Add test on update document title

Response:
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

"""Integration tests for Document"""

from ggrc.models import all_models
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories

class TestDocument(TestCase):
  """Document test cases"""
  # pylint: disable=invalid-name

  def setUp(self):
    super(TestDocument, self).setUp()
    self.api = Api()

  def test_update_title(self):
    """Test update document title."""
    create_title = "test_title"
    update_title = "update_test_title"
    document = factories.DocumentFactory(title=create_title)
    response = self.api.put(document, {"title": update_title})
    self.assert200(response)
    self.assertEqual(all_models.Document.query.get(document.id).title,
                     update_title)

Prompt: Add test on update document title


from base_renderer import *
import re
import markdown

@renderer
class MarkdownRenderer(MarkupRenderer):
    FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$')

    def load_settings(self, renderer_options, global_setting):
        super(MarkdownRenderer, self).load_settings(renderer_options, global_setting)
        if 'extensions' in renderer_options:
            self.extensions = renderer_options['extensions']
        else:
            # Fallback to the default GFM style
            self.extensions = ['tables', 'strikeout', 'fenced_code', 'codehilite']
        if global_setting.mathjax_enabled:
            if 'mathjax' not in self.extensions:
                self.extensions.append('mathjax')

    @classmethod
    def is_enabled(cls, filename, syntax):
        if syntax == "text.html.markdown":
            return True
        return cls.FILENAME_PATTERN_RE.search(filename) is not None

    def render(self, text, **kwargs):
        return markdown.markdown(text, output_format='html5',
            extensions=self.extensions
        )

Add litcoffee to Markdown extensions

Add litcoffee to Markdown extensions

Response:
from base_renderer import *
import re
import markdown

@renderer
class MarkdownRenderer(MarkupRenderer):
    FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$')

    def load_settings(self, renderer_options, global_setting):
        super(MarkdownRenderer, self).load_settings(renderer_options, global_setting)
        if 'extensions' in renderer_options:
            self.extensions = renderer_options['extensions']
        else:
            # Fallback to the default GFM style
            self.extensions = ['tables', 'strikeout', 'fenced_code', 'codehilite']
        if global_setting.mathjax_enabled:
            if 'mathjax' not in self.extensions:
                self.extensions.append('mathjax')

    @classmethod
    def is_enabled(cls, filename, syntax):
        if syntax == "text.html.markdown":
            return True
        return cls.FILENAME_PATTERN_RE.search(filename) is not None

    def render(self, text, **kwargs):
        return markdown.markdown(text, output_format='html5',
            extensions=self.extensions
        )

Prompt:
Add litcoffee to Markdown extensions

from base_renderer import *
import re
import markdown

@renderer
class MarkdownRenderer(MarkupRenderer):
    FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$')

    def load_settings(self, renderer_options, global_setting):
        super(MarkdownRenderer, self).load_settings(renderer_options, global_setting)
        if 'extensions' in renderer_options:
            self.extensions = renderer_options['extensions']
        else:
            # Fallback to the default GFM style
            self.extensions = ['tables', 'strikeout', 'fenced_code', 'codehilite']
        if global_setting.mathjax_enabled:
            if 'mathjax' not in self.extensions:
                self.extensions.append('mathjax')

    @classmethod
    def is_enabled(cls, filename, syntax):
        if syntax == "text.html.markdown":
            return True
        return cls.FILENAME_PATTERN_RE.search(filename) is not None

    def render(self, text, **kwargs):
        return markdown.markdown(text, output_format='html5',
            extensions=self.extensions
        )


#!/usr/bin/env python
'''
File: fc2json.py
Author: Kristoffer Dalby
Description: Tiny script for converting flashcard format to json.
'''

import sys, json

file = sys.argv[1]
subject = file.split('.')[0]

data = {
    "subject": subject,
    "cards": {}
}

fc = [line.split(':') for line in open(file, 'r').read().splitlines()]
js = open(subject + ".json", 'w')

for line in fc:
    data["cards"][line[0]] = line[1]

js.write(json.dumps(data))

js.close()

Response:
#!/usr/bin/env python
'''
File: fc2json.py
Author: Kristoffer Dalby
Description: Tiny script for converting flashcard format to json.
'''

import sys, json

file = sys.argv[1]
subject = file.split('.')[0]

data = {
    "subject": subject,
    "cards": {}
}

fc = [line.split(':') for line in open(file, 'r').read().splitlines()]
js = open(subject + ".json", 'w')

for line in fc:
    data["cards"][line[0]] = line[1]

js.write(json.dumps(data))

js.close()

Prompt:
Use a real JS construct, WTF knows why this works in chromium.

#!/usr/bin/env python

import sys, json

file = sys.argv[1]
subject = file.split('.')[0]

data = {
    "subject": subject,
    "cards": {}
}

fc = [line.split(':') for line in open(file, 'r').read().splitlines()]
js = open(subject + ".json", 'w')

for line in fc:
    data["cards"][line[0]] = line[1]

js.write(json.dumps(data))

js.close()


# coding: utf-8

class UpdateInstances(object):

    @staticmethod
    def do():
        from dbaas_cloudstack.models import DatabaseInfraOffering
        from dbaas_cloudstack.models import PlanAttr

        infra_offerings = DatabaseInfraOffering.objects.all()

        for infra_offering in infra_offerings:
            plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
            strong_offering = infra_offering.offering
            weaker_offering = plan_attr.get_weaker_offering()

            for instance in infra_offering.databaseinfra.instances.all():
                if instance.is_database:
                    instance.offering = strong_offering
                else:
                    instance.oferring = weaker_offering

                instance.save()

Response:
# coding: utf-8

class UpdateInstances(object):

    @staticmethod
    def do():
        from dbaas_cloudstack.models import DatabaseInfraOffering
        from dbaas_cloudstack.models import PlanAttr

        infra_offerings = DatabaseInfraOffering.objects.all()

        for infra_offering in infra_offerings:
            plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
            strong_offering = infra_offering.offering
            weaker_offering = plan_attr.get_weaker_offering()

            for instance in infra_offering.databaseinfra.instances.all():
                if instance.is_database:
                    instance.offering = strong_offering
                else:
                    instance.oferring = weaker_offering

                instance.save()

Prompt:
Fix script to update offering on instances

# coding: utf-8

class UpdateInstances(object):

    @staticmethod
    def do():
        from dbaas_cloudstack.models import DatabaseInfraOffering
        from dbaas_cloudstack.models import PlanAttr

        infra_offerings = DatabaseInfraOffering.objects.all()

        for infra_offering in infra_offerings:
            plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan)
            strong_offering = infra_offering.offering
            weaker_offering = plan_attr.get_weaker_offering()

            for instance in infra_offering.databaseinfra.instances.all():
                if instance.is_database:
                    instance.offering = weaker_offering
                else:
                    instance.oferring = strong_offering

                instance.save()


import pytest
from pml import cs

class InvalidControlSystem(cs.ControlSystem):
    """
    Extends ControlSystem without implementing required methods.
    """
    def __init__(self):
        pass

def test_ControlSystem_throws_NotImplememtedError():
    with pytest.raises(NotImplementedError):
        cs.ControlSystem()

def test_InvalidControlSystem_throws_NotImplementedError():
    ics = InvalidControlSystem()
    with pytest.raises(NotImplementedError):
        ics.get('dummy')
    with pytest.raises(NotImplementedError):
        ics.put('dummy', 1)

def test_NullControlSystem_throws_no_errors():
    ncs = cs.NullControlSystem()
    ncs.get('dummy')
    ncs.put('dummy', 1)

Add simple tests for pml/cs.py.

Add simple tests for pml/cs.py.

Response:
import pytest
from pml import cs

class InvalidControlSystem(cs.ControlSystem):
    """
    Extends ControlSystem without implementing required methods.
    """
    def __init__(self):
        pass

def test_ControlSystem_throws_NotImplememtedError():
    with pytest.raises(NotImplementedError):
        cs.ControlSystem()

def test_InvalidControlSystem_throws_NotImplementedError():
    ics = InvalidControlSystem()
    with pytest.raises(NotImplementedError):
        ics.get('dummy')
    with pytest.raises(NotImplementedError):
        ics.put('dummy', 1)

def test_NullControlSystem_throws_no_errors():
    ncs = cs.NullControlSystem()
    ncs.get('dummy')
    ncs.put('dummy', 1)

Prompt: Add simple tests for pml/cs.py.


from distutils.core import setup

setup(
    name="pocketlint",
    description="Pocket-lint a composite linter and style checker.",
    version="0.5.8",
    maintainer="Curtis C. Hovey",
    maintainer_email="sinzui.is@verizon.net",
    url="https://launchpad.net/pocket-lint",
    packages=[
        'pocketlint', 'pocketlint/contrib', 'pocketlint/contrib/pyflakes'],
    scripts=['scripts/pocketlint'],
    )

Increment version to suport Python 2.6.

Increment version to suport Python 2.6.

Response:
from distutils.core import setup

setup(
    name="pocketlint",
    description="Pocket-lint a composite linter and style checker.",
    version="0.5.8",
    maintainer="Curtis C. Hovey",
    maintainer_email="sinzui.is@verizon.net",
    url="https://launchpad.net/pocket-lint",
    packages=[
        'pocketlint', 'pocketlint/contrib', 'pocketlint/contrib/pyflakes'],
    scripts=['scripts/pocketlint'],
    )

Prompt:
Increment version to suport Python 2.6.
from distutils.core import setup

setup(
    name="pocketlint",
    description="Pocket-lint a composite linter and style checker.",
    version="0.5.7",
    maintainer="Curtis C. Hovey",
    maintainer_email="sinzui.is@verizon.net",
    url="https://launchpad.net/pocket-lint",
    packages=[
        'pocketlint', 'pocketlint/contrib', 'pocketlint/contrib/pyflakes'],
    scripts=['scripts/pocketlint'],
    )


from datetime import datetime
from django.utils import timezone
import calendar
import pytz

DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'

def parse_date_string_with_or_without_time(date_string):
    try:
        return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
    except ValueError:
        # If the time is not included, try again with date only
        return datetime.strptime(date_string.strip(), '%Y-%m-%d')

def unix_timestamp(d=None):
    if d is None:
        d = timezone.now()
        return calendar.timegm(d.utctimetuple())
    else:
        return calendar.timegm(d.timetuple())

def datesafe_eq(obj1, obj2):
    """
    If two objects are dates, but don't both have the same
    timezone awareness status, compare them in a timezone-safe way.
    Otherwise, compare them with regular equality.
    """
    if isinstance(obj1, datetime) and not timezone.is_aware(obj1):
        obj1 = timezone.make_aware(obj1, pytz.UTC)

    if isinstance(obj2, datetime) and not timezone.is_aware(obj2):
        obj2 = timezone.make_aware(obj2, pytz.UTC)

    return obj1 == obj2

def make_aware(value):
    if value is None or timezone.is_aware(value):
        return value
    else:
        return timezone.make_aware(value, timezone.utc)

Response:
from datetime import datetime
from django.utils import timezone
import calendar
import pytz

DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'

def parse_date_string_with_or_without_time(date_string):
    try:
        return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
    except ValueError:
        # If the time is not included, try again with date only
        return datetime.strptime(date_string.strip(), '%Y-%m-%d')

def unix_timestamp(d=None):
    if d is None:
        d = timezone.now()
        return calendar.timegm(d.utctimetuple())
    else:
        return calendar.timegm(d.timetuple())

def datesafe_eq(obj1, obj2):
    """
    If two objects are dates, but don't both have the same
    timezone awareness status, compare them in a timezone-safe way.
    Otherwise, compare them with regular equality.
    """
    if isinstance(obj1, datetime) and not timezone.is_aware(obj1):
        obj1 = timezone.make_aware(obj1, pytz.UTC)

    if isinstance(obj2, datetime) and not timezone.is_aware(obj2):
        obj2 = timezone.make_aware(obj2, pytz.UTC)

    return obj1 == obj2

def make_aware(value):
    if value is None or timezone.is_aware(value):
        return value
    else:
        return timezone.make_aware(value, timezone.utc)

Prompt:
Add function for nullsafe, tzsafe comparison

from datetime import datetime
from django.utils import timezone
import calendar
import pytz

DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'

def parse_date_string_with_or_without_time(date_string):
    try:
        return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
    except ValueError:
        # If the time is not included, try again with date only
        return datetime.strptime(date_string.strip(), '%Y-%m-%d')

def unix_timestamp(d=None):
    if d is None:
        d = timezone.now()
        return calendar.timegm(d.utctimetuple())
    else:
        return calendar.timegm(d.timetuple())

def datesafe_eq(obj1, obj2):
    """
    If two objects are dates, but don't both have the same
    timezone awareness status, compare them in a timezone-safe way.
    Otherwise, compare them with regular equality.
    """
    if isinstance(obj1, datetime) and not timezone.is_aware(obj1):
        obj1 = timezone.make_aware(obj1, pytz.UTC)

    if isinstance(obj2, datetime) and not timezone.is_aware(obj2):
        obj2 = timezone.make_aware(obj2, pytz.UTC)

    return obj1 == obj2


#!/usr/bin/env python
from opentreetesting import test_http_json_method, config
import datetime
import codecs
import json
import sys
import os

# this makes it easier to test concurrent pushes to different branches
if len(sys.argv) > 1:
    study_id = sys.argv[1]
else:
    study_id = 1003

DOMAIN = config('host', 'apihost')
SUBMIT_URI = DOMAIN + '/v1/study/%s' % study_id
inpf = codecs.open('../nexson-validator/tests/single/input/1003.json', 'rU', encoding='utf-8')
n = json.load(inpf)
# refresh a timestamp so that the test generates a commit
m = n['nexml']['meta']
short_list = [i for i in m if i.get('@property') == 'bogus_timestamp']
if short_list:
    el = short_list[0]
else:
    el = {'@property': 'bogus_timestamp', '@xsi:type': 'nex:LiteralMeta'}
    m.append(el)
el['$'] = datetime.datetime.utcnow().isoformat()

data = { 'nexson' : n,
         'auth_token': 'bogus'
}
if test_http_json_method(SUBMIT_URI,
                         'PUT',
                         data=data,
                         expected_status=400):
    sys.exit(0)
sys.exit(1)

Add a test for invalid PUTs which do not have a valid auth_token

Response:
#!/usr/bin/env python
from opentreetesting import test_http_json_method, config
import datetime
import codecs
import json
import sys
import os

# this makes it easier to test concurrent pushes to different branches
if len(sys.argv) > 1:
    study_id = sys.argv[1]
else:
    study_id = 1003

DOMAIN = config('host', 'apihost')
SUBMIT_URI = DOMAIN + '/v1/study/%s' % study_id
inpf = codecs.open('../nexson-validator/tests/single/input/1003.json', 'rU', encoding='utf-8')
n = json.load(inpf)
# refresh a timestamp so that the test generates a commit
m = n['nexml']['meta']
short_list = [i for i in m if i.get('@property') == 'bogus_timestamp']
if short_list:
    el = short_list[0]
else:
    el = {'@property': 'bogus_timestamp', '@xsi:type': 'nex:LiteralMeta'}
    m.append(el)
el['$'] = datetime.datetime.utcnow().isoformat()

data = { 'nexson' : n,
         'auth_token': 'bogus'
}
if test_http_json_method(SUBMIT_URI,
                         'PUT',
                         data=data,
                         expected_status=400):
    sys.exit(0)
sys.exit(1)

Prompt: Add a test for invalid PUTs which do not have a valid auth_token


import os

from google.appengine.ext.webapp import template
from base_controller import CacheableHandler

class EventWizardHandler(CacheableHandler):
    CACHE_VERSION = 1
    CACHE_KEY_FORMAT = "event_wizard"

    def __init__(self, *args, **kw):
        super(EventWizardHandler, self).__init__(*args, **kw)
        self.cache_expiration = 60 * 60

    def _render(self, *args, **kw):
        path = os.path.join(os.path.dirname(__file__), "../templates/eventwizard.html")

        return template.render(path, self.template_values)

class ReactEventWizardHandler(CacheableHandler):
    CACHE_VERSION = 1
    CACHE_KEY_FORMAT = "event_wizard_react"

    def __init__(self, *args, **kw):
        super(ReactEventWizardHandler, self).__init__(*args, **kw)
        self.cache_expiration = 60 * 60

    def _render(self, *args, **kw):
        path = os.path.join(os.path.dirname(__file__), "../templates/react-eventwizard.html")

        return template.render(path, self.template_values)

Fix event wizard cache keys

Fix event wizard cache keys

Response:
import os

from google.appengine.ext.webapp import template
from base_controller import CacheableHandler

class EventWizardHandler(CacheableHandler):
    CACHE_VERSION = 1
    CACHE_KEY_FORMAT = "event_wizard"

    def __init__(self, *args, **kw):
        super(EventWizardHandler, self).__init__(*args, **kw)
        self.cache_expiration = 60 * 60

    def _render(self, *args, **kw):
        path = os.path.join(os.path.dirname(__file__), "../templates/eventwizard.html")

        return template.render(path, self.template_values)

class ReactEventWizardHandler(CacheableHandler):
    CACHE_VERSION = 1
    CACHE_KEY_FORMAT = "event_wizard_react"

    def __init__(self, *args, **kw):
        super(ReactEventWizardHandler, self).__init__(*args, **kw)
        self.cache_expiration = 60 * 60

    def _render(self, *args, **kw):
        path = os.path.join(os.path.dirname(__file__), "../templates/react-eventwizard.html")

        return template.render(path, self.template_values)

Prompt:
Fix event wizard cache keys

import os

from google.appengine.ext.webapp import template
from base_controller import CacheableHandler

class EventWizardHandler(CacheableHandler):
    CACHE_VERSION = 1
    CACHE_KEY_FORMAT = "event_wizard"

    def __init__(self, *args, **kw):
        super(EventWizardHandler, self).__init__(*args, **kw)
        self.cache_expiration = 60 * 60

    def _render(self, *args, **kw):
        path = os.path.join(os.path.dirname(__file__), "../templates/eventwizard.html")

        return template.render(path, self.template_values)

class ReactEventWizardHandler(CacheableHandler):
    CACHE_VERSION = 1
    CACHE_KEY_FORMAT = "event_wizard"

    def __init__(self, *args, **kw):
        super(ReactEventWizardHandler, self).__init__(*args, **kw)
        self.cache_expiration = 60 * 60

    def _render(self, *args, **kw):
        path = os.path.join(os.path.dirname(__file__), "../templates/react-eventwizard.html")

        return template.render(path, self.template_values)


# -*- coding: utf-8 -*-
'''
    :codauthor: :email:`Mike Place <mp@saltstack.com>`
'''

# Import Salt Testing libs
from salttesting.unit import skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
ensure_in_syspath('../')

# Import salt libs
import integration
from salt import fileclient

@skipIf(NO_MOCK, NO_MOCK_REASON)
class FileClientTest(integration.ModuleCase):

    def setUp(self):
        self.file_client = fileclient.Client(self.master_opts)

    def test_file_list_emptydirs(self):
        '''
        Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
        '''
        with self.assertRaises(NotImplementedError):
            self.file_client.file_list_emptydirs()

    def test_get_file(self):
        '''
        Ensure that the fileclient class won't allow a direct call to get_file()
        '''
        with self.assertRaises(NotImplementedError):
            self.file_client.get_file(None)

    def test_get_file_client(self):
        with patch.dict(self.minion_opts, {'file_client': 'remote'}):
            with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
                ret = fileclient.get_file_client(self.minion_opts)
                self.assertEqual('remote_client', ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(FileClientTest)

Response:
# -*- coding: utf-8 -*-
'''
    :codauthor: :email:`Mike Place <mp@saltstack.com>`
'''

# Import Salt Testing libs
from salttesting.unit import skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
ensure_in_syspath('../')

# Import salt libs
import integration
from salt import fileclient

@skipIf(NO_MOCK, NO_MOCK_REASON)
class FileClientTest(integration.ModuleCase):

    def setUp(self):
        self.file_client = fileclient.Client(self.master_opts)

    def test_file_list_emptydirs(self):
        '''
        Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
        '''
        with self.assertRaises(NotImplementedError):
            self.file_client.file_list_emptydirs()

    def test_get_file(self):
        '''
        Ensure that the fileclient class won't allow a direct call to get_file()
        '''
        with self.assertRaises(NotImplementedError):
            self.file_client.get_file(None)

    def test_get_file_client(self):
        with patch.dict(self.minion_opts, {'file_client': 'remote'}):
            with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
                ret = fileclient.get_file_client(self.minion_opts)
                self.assertEqual('remote_client', ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(FileClientTest)

Prompt:
Remove unused imports & Skip if no mock available

# -*- coding: utf-8 -*-
'''
    :codauthor: :email:`Mike Place <mp@saltstack.com>`
'''

# Import Salt Testing libs
from salttesting.helpers import (ensure_in_syspath, destructiveTest)
from salttesting.mock import MagicMock, patch
ensure_in_syspath('../')

# Import salt libs
import integration
from salt import fileclient

# Import Python libs
import os

class FileClientTest(integration.ModuleCase):

    def setUp(self):
        self.file_client = fileclient.Client(self.master_opts)

    def test_file_list_emptydirs(self):
        '''
        Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
        '''
        with self.assertRaises(NotImplementedError):
            self.file_client.file_list_emptydirs()

    def test_get_file(self):
        '''
        Ensure that the fileclient class won't allow a direct call to get_file()
        '''
        with self.assertRaises(NotImplementedError):
            self.file_client.get_file(None)

    def test_get_file_client(self):
        with patch.dict(self.minion_opts, {'file_client': 'remote'}):
            with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
                ret = fileclient.get_file_client(self.minion_opts)
                self.assertEqual('remote_client', ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(FileClientTest)


from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils

class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
    """Clone environment and translate settings to the given release."""

    columns = env_commands.EnvShow.columns

    def get_parser(self, prog_name):
        parser = super(EnvClone, self).get_parser(prog_name)
        parser.add_argument('name',
                            type=str,
                            help='Name of the new environment.')
        parser.add_argument('release',
                            type=int,
                            help='ID of the release of the new environment.')
        return parser

    def take_action(self, parsed_args):
        # TODO(akscram): While the clone procedure is not a part of
        #                fuelclient.objects.Environment the connection
        #                colled directly.
        new_env = self.client._entity_wrapper.connection.post_request(
            "clusters/{0}/upgrade/clone".format(parsed_args.id),
            {
                'name': parsed_args.name,
                'release_id': parsed_args.release,
            }
        )
        new_env = data_utils.get_display_data_single(self.columns, new_env)
        return (self.columns, new_env)

Response:
from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils

class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
    """Clone environment and translate settings to the given release."""

    columns = env_commands.EnvShow.columns

    def get_parser(self, prog_name):
        parser = super(EnvClone, self).get_parser(prog_name)
        parser.add_argument('name',
                            type=str,
                            help='Name of the new environment.')
        parser.add_argument('release',
                            type=int,
                            help='ID of the release of the new environment.')
        return parser

    def take_action(self, parsed_args):
        # TODO(akscram): While the clone procedure is not a part of
        #                fuelclient.objects.Environment the connection
        #                colled directly.
        new_env = self.client._entity_wrapper.connection.post_request(
            "clusters/{0}/upgrade/clone".format(parsed_args.id),
            {
                'name': parsed_args.name,
                'release_id': parsed_args.release,
            }
        )
        new_env = data_utils.get_display_data_single(self.columns, new_env)
        return (self.columns, new_env)

Prompt:
Call fuelclient directly passing over the object

from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils

class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
    """Clone environment and translate settings to the given release."""

    columns = env_commands.EnvShow.columns

    def get_parser(self, prog_name):
        parser = super(EnvClone, self).get_parser(prog_name)
        parser.add_argument('name',
                            type=str,
                            help='Name of the new environment.')
        parser.add_argument('release',
                            type=int,
                            help='ID of the release of the new environment.')
        return parser

    def take_action(self, parsed_args):
        new_env = self.client.connection.post_request(
            "clusters/{0}/upgrade/clone".format(parsed_args.id),
            {
                'name': parsed_args.name,
                'release_id': parsed_args.release,
            }
        )
        new_env = data_utils.get_display_data_single(self.columns, new_env)
        return (self.columns, new_env)


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

from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event

class blog_feed(Feed):
    title = "Instanssi.org Blogi"
    link = "http://instanssi.org"
    description = "Instanssi-demopartyn uusimmat uutiset."

    def get_object(self, request, event_id):
        return get_object_or_404(Event, pk=event_id)

    def items(self, obj):
        entries = []
        for entry in BlogEntry.objects.filter(event=obj, public=True).order_by('date'):
            entry.event_url = obj.mainurl
            entries.append(entry)
        return entries

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.text

    def item_link(self, item):
        print item.event_url
        if item.event_url and len(item.event_url) > 0:
            return item.event_url + '#blog'+str(item.id)
        return "http://instanssi.org/#blog"+str(item.id)

Sort by date, remove post limit.

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

from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event

class blog_feed(Feed):
    title = "Instanssi.org Blogi"
    link = "http://instanssi.org"
    description = "Instanssi-demopartyn uusimmat uutiset."

    def get_object(self, request, event_id):
        return get_object_or_404(Event, pk=event_id)

    def items(self, obj):
        entries = []
        for entry in BlogEntry.objects.filter(event=obj, public=True).order_by('date'):
            entry.event_url = obj.mainurl
            entries.append(entry)
        return entries

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.text

    def item_link(self, item):
        print item.event_url
        if item.event_url and len(item.event_url) > 0:
            return item.event_url + '#blog'+str(item.id)
        return "http://instanssi.org/#blog"+str(item.id)

Prompt:
ext_blog: Sort by date, remove post limit.

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

from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.shortcuts import get_object_or_404
from Instanssi.ext_blog.models import BlogEntry
from Instanssi.kompomaatti.models import Event

class blog_feed(Feed):
    title = "Instanssi.org Blogi"
    link = "http://instanssi.org"
    description = "Instanssi-demopartyn uusimmat uutiset."

    def get_object(self, request, event_id):
        return get_object_or_404(Event, pk=event_id)

    def items(self, obj):
        entries = []
        for entry in BlogEntry.objects.filter(event=obj, public=True).order_by('-date')[:10]:
            entry.event_url = obj.mainurl
            entries.append(entry)
        return entries

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.text

    def item_link(self, item):
        print item.event_url
        if item.event_url and len(item.event_url) > 0:
            return item.event_url + '#blog'+str(item.id)
        return "http://instanssi.org/#blog"+str(item.id)