import time
import datetime
import subprocess
import json
import sys
import re

PING_RTT_REGEX = re.compile('rtt.+=\s*([\d.]+)')

def get_status(ip, timeout):
    t0 = time.time()
    error = subprocess.call(['ping', '-c', '1', '-W', str(timeout), ip],
                            stdout=sys.stderr.fileno(),
                            stderr=sys.stderr.fileno())
    delay = time.time() - t0
    return None if error else delay

def log_status(hosts, timeout):
    now = datetime.datetime.now().isoformat(timespec='seconds')
    processes = []
    for host in hosts:
        processes.append(subprocess.Popen(
            ['ping', '-qnc', '1', '-W', str(timeout), host],
            stdout=subprocess.PIPE))
    results = dict(time=now)
    for host, process in zip(hosts, processes):
        if process.wait():
            results[host] = None
        else:
            last_line = list(process.stdout)[-1].strip().decode('utf8')
            results[host] = float(PING_RTT_REGEX.match(last_line).group(1))
    return results

TIMEOUT = 2
INTERVAL = 15
HOSTS = ['localhost', '192.168.1.1', '1.1.1.1', '8.8.8.8', 'www.google.co.uk']

if __name__ == '__main__':
    t0 = time.time()
    while True:
        time.sleep(max(0, t0 + INTERVAL - time.time()))
        t0 = time.time()
        print(json.dumps(log_status(HOSTS, timeout=TIMEOUT)), flush=True)

Add simple script for logging to diagnose WAN vs LAN connection issues

Response:
import time
import datetime
import subprocess
import json
import sys
import re

PING_RTT_REGEX = re.compile('rtt.+=\s*([\d.]+)')

def get_status(ip, timeout):
    t0 = time.time()
    error = subprocess.call(['ping', '-c', '1', '-W', str(timeout), ip],
                            stdout=sys.stderr.fileno(),
                            stderr=sys.stderr.fileno())
    delay = time.time() - t0
    return None if error else delay

def log_status(hosts, timeout):
    now = datetime.datetime.now().isoformat(timespec='seconds')
    processes = []
    for host in hosts:
        processes.append(subprocess.Popen(
            ['ping', '-qnc', '1', '-W', str(timeout), host],
            stdout=subprocess.PIPE))
    results = dict(time=now)
    for host, process in zip(hosts, processes):
        if process.wait():
            results[host] = None
        else:
            last_line = list(process.stdout)[-1].strip().decode('utf8')
            results[host] = float(PING_RTT_REGEX.match(last_line).group(1))
    return results

TIMEOUT = 2
INTERVAL = 15
HOSTS = ['localhost', '192.168.1.1', '1.1.1.1', '8.8.8.8', 'www.google.co.uk']

if __name__ == '__main__':
    t0 = time.time()
    while True:
        time.sleep(max(0, t0 + INTERVAL - time.time()))
        t0 = time.time()
        print(json.dumps(log_status(HOSTS, timeout=TIMEOUT)), flush=True)

Prompt: Add simple script for logging to diagnose WAN vs LAN connection issues


# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-09-06 23:31
from __future__ import unicode_literals

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

class Migration(migrations.Migration):

    dependencies = [
        ('infrastructure', '0015_financialyear_active'),
    ]

    operations = [
        migrations.CreateModel(
            name='AnnualSpendFile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('document', models.FileField(upload_to='annual/')),
                ('status', models.IntegerField(default=3)),
                ('financial_year', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='infrastructure.FinancialYear')),
            ],
        ),
        migrations.AlterField(
            model_name='budgetphase',
            name='code',
            field=models.CharField(blank=True, max_length=10),
        ),
    ]

Add migration for annual spend changes

Add migration for annual spend changes

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-09-06 23:31
from __future__ import unicode_literals

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

class Migration(migrations.Migration):

    dependencies = [
        ('infrastructure', '0015_financialyear_active'),
    ]

    operations = [
        migrations.CreateModel(
            name='AnnualSpendFile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('document', models.FileField(upload_to='annual/')),
                ('status', models.IntegerField(default=3)),
                ('financial_year', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='infrastructure.FinancialYear')),
            ],
        ),
        migrations.AlterField(
            model_name='budgetphase',
            name='code',
            field=models.CharField(blank=True, max_length=10),
        ),
    ]

Prompt: Add migration for annual spend changes


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

import requests

def getHeaders(url):
    r = requests.head(url)
    if r.status_code != 200:
        print("Server returned %s" % r.status_code)
        return None
    return r.headers

def fetchRangeToFile(url, byte_range, destination_path):
    print("Fetching: %s range: %s to: %s" %
          (url, byte_range, destination_path))
    headers = {'Range': ("bytes=%s-%s" %
               (byte_range[0], byte_range[1]))}
    r = requests.get(url, headers=headers, stream=True)
    with open(destination_path, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()

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

import requests

def getHeaders(url):
    r = requests.head(url)
    if r.status_code != 200:
        print("Server returned %s" % r.status_code)
        return None
    return r.headers

def fetchRangeToFile(url, byte_range, destination_path):
    print("Fetching: %s range: %s to: %s" %
          (url, byte_range, destination_path))
    headers = {'Range': ("bytes=%s-%s" %
               (byte_range[0], byte_range[1]))}
    r = requests.get(url, headers=headers, stream=True)
    with open(destination_path, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()

Prompt:
Fix print with subsition instead of concat

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

import requests

def getHeaders(url):
    r = requests.head(url)
    if r.status_code != 200:
        print("Server returned" + r.status_code)
        return None
    return r.headers

def fetchRangeToFile(url, byte_range, destination_path):
    print("Fetching: %s range: %s to: %s" %
          (url, byte_range, destination_path))
    headers = {'Range': ("bytes=%s-%s" %
               (byte_range[0], byte_range[1]))}
    r = requests.get(url, headers=headers, stream=True)
    with open(destination_path, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()


from ceph_deploy.hosts import suse
from ceph_deploy.hosts.suse.install import map_components

class TestSuseInit(object):
    def setup(self):
        self.host = suse

    def test_choose_init_default(self):
        self.host.release = None
        init_type = self.host.choose_init()
        assert init_type == "sysvinit"

    def test_choose_init_SLE_11(self):
        self.host.release = '11'
        init_type = self.host.choose_init()
        assert init_type == "sysvinit"

    def test_choose_init_SLE_12(self):
        self.host.release = '12'
        init_type = self.host.choose_init()
        assert init_type == "systemd"

    def test_choose_init_openSUSE_13_1(self):
        self.host.release = '13.1'
        init_type = self.host.choose_init()
        assert init_type == "systemd"

class TestSuseMapComponents(object):
    def test_valid(self):
        pkgs = map_components(['ceph-osd', 'ceph-common', 'ceph-radosgw'])
        assert 'ceph' in pkgs
        assert 'ceph-common' in pkgs
        assert 'ceph-radosgw' in pkgs
        assert 'ceph-osd' not in pkgs

    def test_invalid(self):
        pkgs = map_components(['not-provided', 'ceph-mon'])
        assert 'not-provided' not in pkgs
        assert 'ceph' in pkgs

Response:
from ceph_deploy.hosts import suse
from ceph_deploy.hosts.suse.install import map_components

class TestSuseInit(object):
    def setup(self):
        self.host = suse

    def test_choose_init_default(self):
        self.host.release = None
        init_type = self.host.choose_init()
        assert init_type == "sysvinit"

    def test_choose_init_SLE_11(self):
        self.host.release = '11'
        init_type = self.host.choose_init()
        assert init_type == "sysvinit"

    def test_choose_init_SLE_12(self):
        self.host.release = '12'
        init_type = self.host.choose_init()
        assert init_type == "systemd"

    def test_choose_init_openSUSE_13_1(self):
        self.host.release = '13.1'
        init_type = self.host.choose_init()
        assert init_type == "systemd"

class TestSuseMapComponents(object):
    def test_valid(self):
        pkgs = map_components(['ceph-osd', 'ceph-common', 'ceph-radosgw'])
        assert 'ceph' in pkgs
        assert 'ceph-common' in pkgs
        assert 'ceph-radosgw' in pkgs
        assert 'ceph-osd' not in pkgs

    def test_invalid(self):
        pkgs = map_components(['not-provided', 'ceph-mon'])
        assert 'not-provided' not in pkgs
        assert 'ceph' in pkgs

Prompt:
Add tests for component to SUSE package mapping

Signed-off-by: David Disseldorp <589a549dc9f982d9f46aeeb82a09ab6d87ccf1d8@suse.de>

from ceph_deploy.hosts import suse

class TestSuseInit(object):
    def setup(self):
        self.host = suse

    def test_choose_init_default(self):
        self.host.release = None
        init_type = self.host.choose_init()
        assert init_type == "sysvinit"

    def test_choose_init_SLE_11(self):
        self.host.release = '11'
        init_type = self.host.choose_init()
        assert init_type == "sysvinit"

    def test_choose_init_SLE_12(self):
        self.host.release = '12'
        init_type = self.host.choose_init()
        assert init_type == "systemd"

    def test_choose_init_openSUSE_13_1(self):
        self.host.release = '13.1'
        init_type = self.host.choose_init()
        assert init_type == "systemd"


#!/usr/bin/env python
# -*- coding: utf8 -*-
import os.path
from setuptools import setup, find_packages

def get_version():
    """
    Loads the current module version from version.py and returns
    it.

    :returns: module version identifier.
    :rtype: str
    """
    local_results = {}
    version_file_path = os.path.join('pytextql', 'version.py')

    # This is compatible with py3k which removed execfile.
    with open(version_file_path, 'rb') as fin:
        # Compiling instead of passing the text straight to exec
        # associates any errors with the correct file name.
        code = compile(fin.read(), version_file_path, 'exec')
        exec(code, {}, local_results)

    return local_results['__version__']

if __name__ == '__main__':
    with open('README.md', 'rb') as readme:
        long_description = readme.read()

    setup(
        name='pytextql',
        version=get_version(),
        long_description=long_description,
        packages=find_packages(),
        include_package_data=True,
        install_requires=[
            'docopt'
        ],
        scripts=[
            'pytextql/pytextql'
        ]
    )

Use README.md for the long description.

Use README.md for the long description.

Response:
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os.path
from setuptools import setup, find_packages

def get_version():
    """
    Loads the current module version from version.py and returns
    it.

    :returns: module version identifier.
    :rtype: str
    """
    local_results = {}
    version_file_path = os.path.join('pytextql', 'version.py')

    # This is compatible with py3k which removed execfile.
    with open(version_file_path, 'rb') as fin:
        # Compiling instead of passing the text straight to exec
        # associates any errors with the correct file name.
        code = compile(fin.read(), version_file_path, 'exec')
        exec(code, {}, local_results)

    return local_results['__version__']

if __name__ == '__main__':
    with open('README.md', 'rb') as readme:
        long_description = readme.read()

    setup(
        name='pytextql',
        version=get_version(),
        long_description=long_description,
        packages=find_packages(),
        include_package_data=True,
        install_requires=[
            'docopt'
        ],
        scripts=[
            'pytextql/pytextql'
        ]
    )

Prompt:
Use README.md for the long description.

#!/usr/bin/env python
# -*- coding: utf8 -*-
import os.path
from setuptools import setup, find_packages

def get_version():
    """
    Loads the current module version from version.py and returns
    it.

    :returns: module version identifier.
    :rtype: str
    """
    local_results = {}
    version_file_path = os.path.join('pytextql', 'version.py')

    # This is compatible with py3k which removed execfile.
    with open(version_file_path, 'rb') as fin:
        # Compiling instead of passing the text straight to exec
        # associates any errors with the correct file name.
        code = compile(fin.read(), version_file_path, 'exec')
        exec(code, {}, local_results)

    return local_results['__version__']

if __name__ == '__main__':
    setup(
        name='pytextql',
        version=get_version(),
        long_description=__doc__,
        packages=find_packages(),
        include_package_data=True,
        install_requires=[
            'docopt'
        ],
        scripts=[
            'pytextql/pytextql'
        ]
    )


# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""ActiveMaster definition."""

from config_bootstrap import Master

class TryServerANGLE(Master.Master4a):
  project_name = 'ANGLE Try Server'
  master_port = 21403
  slave_port = 31403
  master_port_alt = 41403
  buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/'
  gerrit_host = 'https://chromium-review.googlesource.com'
  service_account_file = 'service-account-chromium-tryserver.json'
  buildbucket_bucket = 'master.tryserver.chromium.linux'

Response:
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""ActiveMaster definition."""

from config_bootstrap import Master

class TryServerANGLE(Master.Master4a):
  project_name = 'ANGLE Try Server'
  master_port = 21403
  slave_port = 31403
  master_port_alt = 41403
  buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/'
  gerrit_host = 'https://chromium-review.googlesource.com'
  service_account_file = 'service-account-chromium-tryserver.json'
  buildbucket_bucket = 'master.tryserver.chromium.linux'

Prompt:
Add buildbucket service account to Angle master.

BUG=577560
TBR=nodir@chromium.org

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

git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298368 0039d316-1c4b-4281-b951-d872f2087c98

# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""ActiveMaster definition."""

from config_bootstrap import Master

class TryServerANGLE(Master.Master4a):
  project_name = 'ANGLE Try Server'
  master_port = 21403
  slave_port = 31403
  master_port_alt = 41403
  buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/'
  gerrit_host = 'https://chromium-review.googlesource.com'


from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox

class TestCheckBox(TestCase):

    def test_checkbox(self):
        """
        Test the checkbox
        :return:    void
        """

        changed_checkbox = []

        def change_handler(checkbox):
            changed_checkbox.append(checkbox)

        checkbox = CheckBox(self.rand_str(), on_change=change_handler)

        self.assert_is_instance(checkbox, ACheckBox)
        for value in [True, False, True]:
            previous_count = len(changed_checkbox)
            checkbox.value = value
            self.assert_equal(value, checkbox.value)
            self.assert_equal(previous_count + 1, len(changed_checkbox))
            self.assert_equal(checkbox, changed_checkbox[-1])

Check if checkbox value has updated.

Check if checkbox value has updated.

Response:
from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox

class TestCheckBox(TestCase):

    def test_checkbox(self):
        """
        Test the checkbox
        :return:    void
        """

        changed_checkbox = []

        def change_handler(checkbox):
            changed_checkbox.append(checkbox)

        checkbox = CheckBox(self.rand_str(), on_change=change_handler)

        self.assert_is_instance(checkbox, ACheckBox)
        for value in [True, False, True]:
            previous_count = len(changed_checkbox)
            checkbox.value = value
            self.assert_equal(value, checkbox.value)
            self.assert_equal(previous_count + 1, len(changed_checkbox))
            self.assert_equal(checkbox, changed_checkbox[-1])

Prompt:
Check if checkbox value has updated.

from scriptcore.testing.testcase import TestCase
from scriptcore.console.asciimatics.widgets.checkbox import CheckBox
from asciimatics.widgets import CheckBox as ACheckBox

class TestCheckBox(TestCase):

    def test_checkbox(self):
        """
        Test the checkbox
        :return:    void
        """

        changed_checkbox = []

        def change_handler(checkbox):
            changed_checkbox.append(checkbox)

        checkbox = CheckBox(self.rand_str(), on_change=change_handler)

        self.assert_is_instance(checkbox, ACheckBox)
        for value in [True, False, True]:
            previous_count = len(changed_checkbox)
            checkbox.value = value
            self.assert_equal(previous_count + 1, len(changed_checkbox))
            self.assert_equal(checkbox, changed_checkbox[-1])


# Generated by Django 2.2.16 on 2020-12-18 09:12

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("organisations", "0058_remove_division_organisation_fk"),
    ]

    operations = [
        migrations.AlterField(
            model_name="organisation",
            name="organisation_type",
            field=models.CharField(
                choices=[
                    ("combined-authority", "combined-authority"),
                    ("sp", "sp"),
                    ("gla", "gla"),
                    ("local-authority", "local-authority"),
                    ("naw", "naw"),
                    ("senedd", "senedd"),
                    ("nia", "nia"),
                    ("parl", "parl"),
                    ("police-area", "police-area"),
                    ("sp", "sp"),
                    ("europarl", "europarl"),
                ],
                default="local-authority",
                max_length=255,
            ),
        ),
    ]

Add 'senedd' to choices for organisation_type

Response:
# Generated by Django 2.2.16 on 2020-12-18 09:12

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("organisations", "0058_remove_division_organisation_fk"),
    ]

    operations = [
        migrations.AlterField(
            model_name="organisation",
            name="organisation_type",
            field=models.CharField(
                choices=[
                    ("combined-authority", "combined-authority"),
                    ("sp", "sp"),
                    ("gla", "gla"),
                    ("local-authority", "local-authority"),
                    ("naw", "naw"),
                    ("senedd", "senedd"),
                    ("nia", "nia"),
                    ("parl", "parl"),
                    ("police-area", "police-area"),
                    ("sp", "sp"),
                    ("europarl", "europarl"),
                ],
                default="local-authority",
                max_length=255,
            ),
        ),
    ]

Prompt: Add 'senedd' to choices for organisation_type


import sys

from .. import SetWallpaper

class LXDESetWallpaper(SetWallpaper):
    def __init__(self, config):
        super(LXDESetWallpaper, self).__init__(config)
        self.cycle = 0

    def platform_check(self):
        return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'

    def set(self):
        import os

        # TODO: Find a better solution than cycling
        #       - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
        os.system(\
                'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))

        self.cycle += 1

Response:
import sys

from .. import SetWallpaper

class LXDESetWallpaper(SetWallpaper):
    def __init__(self, config):
        super(LXDESetWallpaper, self).__init__(config)
        self.cycle = 0

    def platform_check(self):
        return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'

    def set(self):
        import os

        # TODO: Find a better solution than cycling
        #       - Cause: --set-wallpaper doesn't reload the file if the arguments are the same
        os.system(\
                'pcmanfm --set-wallpaper=%s --wallpaper-mode=%s' % (self.config['wallpaper'], 'fit' if self.cycle % 2 else 'center'))

        self.cycle += 1

Prompt:
Revert "Conforming LXDESetWallpaper plugin to conform with keep option (DarwinSetWallpaper), also FastForward merge"

This reverts commit 7212d223fe95d3042348bb29d9bd353308be2347.

I really should learn to test before I push to github.

import os
import sys

from .. import SetWallpaper

class LXDESetWallpaper(SetWallpaper):
    def __init__(self, config):
        super(LXDESetWallpaper, self).__init__(config)

    def platform_check(self):
        return sys.platform == 'linux2' and self.config['linux.desktop-environment'] == 'lxde'

    def set(self):
        os.system('pcmanfm --set-wallpaper=%s')
        if not self.config['keep']:
            logging.warning("LXDESetWallpaper works better if you configure "
                            "the keep plugin (e.g. --keep=2)")


from __future__ import absolute_import
from __future__ import unicode_literals

from django.conf.urls import patterns, include, url

from .views import *

urlpatterns = patterns('',
    url(r'^pjson/push$', pjson_provider_push,  name="pjson_provider_push"),
    url(r'^fhir/practitioner/push$', fhir_practitioner_push,  name="fhir_practitioner_push"),
    url(r'^fhir/organization/push$', fhir_organization_push,  name="fhir_organization_push"),
    url(r'^fhir/practitioner/update$', fhir_practitioner_update,  name="fhir_practitioner_update"),
    url(r'^fhir/organization/update$', fhir_organization_update,  name="fhir_organization_update"),

)

Response:
from __future__ import absolute_import
from __future__ import unicode_literals

from django.conf.urls import patterns, include, url

from .views import *

urlpatterns = patterns('',
    url(r'^pjson/push$', pjson_provider_push,  name="pjson_provider_push"),
    url(r'^fhir/practitioner/push$', fhir_practitioner_push,  name="fhir_practitioner_push"),
    url(r'^fhir/organization/push$', fhir_organization_push,  name="fhir_organization_push"),
    url(r'^fhir/practitioner/update$', fhir_practitioner_update,  name="fhir_practitioner_update"),
    url(r'^fhir/organization/update$', fhir_organization_update,  name="fhir_organization_update"),

)

Prompt:
Add url for update vs. push for pract and org

from __future__ import absolute_import
from __future__ import unicode_literals

from django.conf.urls import patterns, include, url

from .views import *

urlpatterns = patterns('',
    url(r'^pjson/push$', pjson_provider_push,  name="pjson_provider_push"),
    url(r'^fhir/practitioner/push$', fhir_practitioner_push,  name="fhir_practitioner_push"),
    url(r'^fhir/organization/push$', fhir_organization_push,  name="fhir_organization_push"),

)


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

setup(
    name='blanc-basic-pages',
    version='0.2.1',
    description='Blanc Basic Pages for Django',
    long_description=open('README.rst').read(),
    url='https://github.com/blancltd/blanc-basic-pages',
    maintainer='Alex Tomkins',
    maintainer_email='alex@blanc.ltd.uk',
    platforms=['any'],
    install_requires=[
        'django-mptt>=0.6.1',
        'django-mptt-admin>=0.1.8',
    ],
    packages=find_packages(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
    ],
    license='BSD',
)

Fix dependencies for Django 1.7

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

setup(
    name='blanc-basic-pages',
    version='0.2.1',
    description='Blanc Basic Pages for Django',
    long_description=open('README.rst').read(),
    url='https://github.com/blancltd/blanc-basic-pages',
    maintainer='Alex Tomkins',
    maintainer_email='alex@blanc.ltd.uk',
    platforms=['any'],
    install_requires=[
        'django-mptt>=0.6.1',
        'django-mptt-admin>=0.1.8',
    ],
    packages=find_packages(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
    ],
    license='BSD',
)

Prompt:
Fix dependencies for Django 1.7

Older versions of django-mptt will generate warnings

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

setup(
    name='blanc-basic-pages',
    version='0.2.1',
    description='Blanc Basic Pages for Django',
    long_description=open('README.rst').read(),
    url='https://github.com/blancltd/blanc-basic-pages',
    maintainer='Alex Tomkins',
    maintainer_email='alex@blanc.ltd.uk',
    platforms=['any'],
    install_requires=[
        'django-mptt>=0.6.0',
        'django-mptt-admin==0.1.8',
    ],
    packages=find_packages(),
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
    ],
    license='BSD',
)


#!/usr/bin/env python

import sys
from os.path import basename, dirname, join
import re

INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')
WREN_DIR = dirname(dirname(realpath(__file__)))

seen_files = set()
out = sys.stdout

# Prints a plain text file, adding comment markers.
def add_comment_file(filename):
  with open(filename, 'r') as f:
    for line in f:
      out.write('// ')
      out.write(line)

# Prints the given C source file, recursively resolving local #includes.
def add_file(filename):
  bname = basename(filename)
  # Only include each file at most once.
  if bname in seen_files:
    return
  seen_files.add(bname)
  path = dirname(filename)

  out.write('// Begin file "{0}"\n'.format(filename))
  with open(filename, 'r') as f:
    for line in f:
      m = INCLUDE_PATTERN.match(line)
      if m:
        add_file(join(path, m.group(1)))
      else:
        out.write(line)
  out.write('// End file "{0}"\n'.format(filename))

# Print license on top.
add_comment_file(join(WREN_DIR, 'LICENSE'))
out.write('\n')
# Source files.
for f in sys.argv[1:]:
  add_file(f)

Response:
#!/usr/bin/env python

import sys
from os.path import basename, dirname, join
import re

INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')
WREN_DIR = dirname(dirname(realpath(__file__)))

seen_files = set()
out = sys.stdout

# Prints a plain text file, adding comment markers.
def add_comment_file(filename):
  with open(filename, 'r') as f:
    for line in f:
      out.write('// ')
      out.write(line)

# Prints the given C source file, recursively resolving local #includes.
def add_file(filename):
  bname = basename(filename)
  # Only include each file at most once.
  if bname in seen_files:
    return
  seen_files.add(bname)
  path = dirname(filename)

  out.write('// Begin file "{0}"\n'.format(filename))
  with open(filename, 'r') as f:
    for line in f:
      m = INCLUDE_PATTERN.match(line)
      if m:
        add_file(join(path, m.group(1)))
      else:
        out.write(line)
  out.write('// End file "{0}"\n'.format(filename))

# Print license on top.
add_comment_file(join(WREN_DIR, 'LICENSE'))
out.write('\n')
# Source files.
for f in sys.argv[1:]:
  add_file(f)

Prompt:
Print LICENSE on top of the amalgamation

#!/usr/bin/env python

import sys
from os.path import basename, dirname, join
import re

INCLUDE_PATTERN = re.compile(r'^\s*#include "([\w.]+)"')

seen_files = set()
out = sys.stdout

def add_file(filename):
  bname = basename(filename)
  # Only include each file at most once.
  if bname in seen_files:
    return
  seen_files.add(bname)
  path = dirname(filename)

  out.write('// Begin file "{0}"\n'.format(filename))
  with open(filename, 'r') as f:
    for line in f:
      m = INCLUDE_PATTERN.match(line)
      if m:
        add_file(join(path, m.group(1)))
      else:
        out.write(line)
  out.write('// End file "{0}"\n'.format(filename))

for f in sys.argv[1:]:
  add_file(f)


#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals

def safe_input(prompt):
    """Return user input after catching KeyboardInterrupt and EOFError"""
    try:
        reply = raw_input(prompt)
    except (EOFError, KeyboardInterrupt):
        quit()
    else:
        return reply.decode('utf-8')  # Convert input to unicode

prompt = "Input a Lisp style statement '(test)': "
reply = safe_input(prompt)

def check_statement(value):
    open_index = [i for i, val in enumerate(reply) if val == "("]
    close_index = [i for i, val in enumerate(reply) if val == ")"]

    paren_total_broken = [a < b for a, b in zip(open_index, close_index)]

    if paren_total_broken.find(False):
        return -1
    else:
        return 0

Response:
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals

def safe_input(prompt):
    """Return user input after catching KeyboardInterrupt and EOFError"""
    try:
        reply = raw_input(prompt)
    except (EOFError, KeyboardInterrupt):
        quit()
    else:
        return reply.decode('utf-8')  # Convert input to unicode

prompt = "Input a Lisp style statement '(test)': "
reply = safe_input(prompt)

def check_statement(value):
    open_index = [i for i, val in enumerate(reply) if val == "("]
    close_index = [i for i, val in enumerate(reply) if val == ")"]

    paren_total_broken = [a < b for a, b in zip(open_index, close_index)]

    if paren_total_broken.find(False):
        return -1
    else:
        return 0

Prompt:
Add function for broken and groundwork for other objectives

#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals

def safe_input(prompt):
    """Return user input after catching KeyboardInterrupt and EOFError"""
    try:
        reply = raw_input(prompt)
    except (EOFError, KeyboardInterrupt):
        quit()
    else:
        return reply.decode('utf-8')  # Convert input to unicode

prompt = "Input a Lisp style statement '(test)': "
reply = safe_input(prompt)

def check_statement(value):
    where_open = value.find("(")
    where_close = value.find(")")

    if ((where_open == -1) and where_close != -1) or (where_open > where_close):
        return -1


from os.path import abspath, join, dirname
import random

__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'

full_path = lambda filename: abspath(join(dirname(__file__), filename))

FILES = {
    'first:male': full_path('dist.male.first'),
    'first:female': full_path('dist.female.first'),
    'last': full_path('dist.all.last'),
}

def get_name(filename):
    selected = random.random() * 90
    with open(filename) as name_file:
        for line in name_file:
            name, _, cummulative, _ = line.split()
            if float(cummulative) > selected:
                return name

def get_first_name(gender=None):
    if gender not in ('male', 'female'):
        gender = random.choice(('male', 'female'))
    return get_name(FILES['first:%s' % gender]).capitalize()

def get_last_name():
    return get_name(FILES['last']).capitalize()

def get_full_name(gender=None):
    return unicode("%s %s").format(get_first_name(gender), get_last_name())

Fix unicode string syntax for Python 3

Fix unicode string syntax for Python 3

Response:
from os.path import abspath, join, dirname
import random

__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'

full_path = lambda filename: abspath(join(dirname(__file__), filename))

FILES = {
    'first:male': full_path('dist.male.first'),
    'first:female': full_path('dist.female.first'),
    'last': full_path('dist.all.last'),
}

def get_name(filename):
    selected = random.random() * 90
    with open(filename) as name_file:
        for line in name_file:
            name, _, cummulative, _ = line.split()
            if float(cummulative) > selected:
                return name

def get_first_name(gender=None):
    if gender not in ('male', 'female'):
        gender = random.choice(('male', 'female'))
    return get_name(FILES['first:%s' % gender]).capitalize()

def get_last_name():
    return get_name(FILES['last']).capitalize()

def get_full_name(gender=None):
    return unicode("%s %s").format(get_first_name(gender), get_last_name())

Prompt:
Fix unicode string syntax for Python 3

from os.path import abspath, join, dirname
import random

__title__ = 'names'
__version__ = '0.2'
__author__ = 'Trey Hunner'
__license__ = 'MIT'

full_path = lambda filename: abspath(join(dirname(__file__), filename))

FILES = {
    'first:male': full_path('dist.male.first'),
    'first:female': full_path('dist.female.first'),
    'last': full_path('dist.all.last'),
}

def get_name(filename):
    selected = random.random() * 90
    with open(filename) as name_file:
        for line in name_file:
            name, _, cummulative, _ = line.split()
            if float(cummulative) > selected:
                return name

def get_first_name(gender=None):
    if gender not in ('male', 'female'):
        gender = random.choice(('male', 'female'))
    return get_name(FILES['first:%s' % gender]).capitalize()

def get_last_name():
    return get_name(FILES['last']).capitalize()

def get_full_name(gender=None):
    return u"%s %s" % (get_first_name(gender), get_last_name())


from __future__ import unicode_literals

from django_evolution.mutations import AddField
from django.db import models

MUTATIONS = [
    AddField('ChangeDescription', 'user', models.ForeignKey, null=True,
             related_model='auth.User'),
]

Response:
from __future__ import unicode_literals

from django_evolution.mutations import AddField
from django.db import models

MUTATIONS = [
    AddField('ChangeDescription', 'user', models.ForeignKey, null=True,
             related_model='auth.User'),
]

Prompt:
Fix evolution for change description users

Trivial change

from __future__ import unicode_literals

from django_evolution.mutations import AddField
from django.db import models

MUTATIONS = [
    AddField('ChangeDescription', 'user', models.ForeignKey, blank=True,
             related_model='auth.User'),
]


from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword

class TextBoxKeywords(LibraryComponent):
    @keyword
    def input_text_to_textbox(self, locator, input_value):
        """
        Writes text to a textbox.

        ``locator`` is the locator of the text box.

        ``input_value`` is the text to write.
        """
        textBox = self.state._get_typed_item_by_locator(TextBox, locator)
        textBox.Text = input_value

    @keyword
    def verify_text_in_textbox(self, locator, expected):
        """
        Verifies text in a text box.

        ``locator`` is the locator of the text box.

        ``expected`` is the expected text of the text box.
        """
        textbox = self.state._get_typed_item_by_locator(TextBox, locator)
        self.state._verify_value(expected, textbox.Text)

    @keyword
    def get_text_from_textbox(self, locator):
        """
        Gets text from text box.

        ``locator`` is the locator of the text box.

        """
        textbox = self.state._get_typed_item_by_locator(TextBox, locator)
        return textbox.Text

Change to better argument name

Change to better argument name

Response:
from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword

class TextBoxKeywords(LibraryComponent):
    @keyword
    def input_text_to_textbox(self, locator, input_value):
        """
        Writes text to a textbox.

        ``locator`` is the locator of the text box.

        ``input_value`` is the text to write.
        """
        textBox = self.state._get_typed_item_by_locator(TextBox, locator)
        textBox.Text = input_value

    @keyword
    def verify_text_in_textbox(self, locator, expected):
        """
        Verifies text in a text box.

        ``locator`` is the locator of the text box.

        ``expected`` is the expected text of the text box.
        """
        textbox = self.state._get_typed_item_by_locator(TextBox, locator)
        self.state._verify_value(expected, textbox.Text)

    @keyword
    def get_text_from_textbox(self, locator):
        """
        Gets text from text box.

        ``locator`` is the locator of the text box.

        """
        textbox = self.state._get_typed_item_by_locator(TextBox, locator)
        return textbox.Text

Prompt:
Change to better argument name

from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword

class TextBoxKeywords(LibraryComponent):
    @keyword
    def input_text_to_textbox(self, locator, input):
        """
        Writes text to a textbox.

        ``locator`` is the locator of the text box.

        ``input`` is the text to write.
        """
        textBox = self.state._get_typed_item_by_locator(TextBox, locator)
        textBox.Text = input

    @keyword
    def verify_text_in_textbox(self, locator, expected):
        """
        Verifies text in a text box.

        ``locator`` is the locator of the text box.

        ``expected`` is the expected text of the text box.
        """
        textbox = self.state._get_typed_item_by_locator(TextBox, locator)
        self.state._verify_value(expected, textbox.Text)

    @keyword
    def get_text_from_textbox(self, locator):
        """
        Gets text from text box.

        ``locator`` is the locator of the text box.

        """
        textbox = self.state._get_typed_item_by_locator(TextBox, locator)
        return textbox.Text


#!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##########################################################################

import boto3
import os
from subprocess import call

ec2 = boto3.resource('ec2')

filters = [{'Name': 'instance-state-name', 'Values': ['running']}]
if "EC2_KEY_NAME" in os.environ:
    filters.append({'Name': 'key-name', 'Values': [os.environ['EC2_KEY_NAME']]})

instances = ec2.instances.filter(Filters=filters)

ids = [instance.id for instance in instances]
print("Terminating:", ids)

ec2.instances.filter(InstanceIds=ids).terminate()

##########################################################################

Add import statement for os

Add import statement for os

Response:
#!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##########################################################################

import boto3
import os
from subprocess import call

ec2 = boto3.resource('ec2')

filters = [{'Name': 'instance-state-name', 'Values': ['running']}]
if "EC2_KEY_NAME" in os.environ:
    filters.append({'Name': 'key-name', 'Values': [os.environ['EC2_KEY_NAME']]})

instances = ec2.instances.filter(Filters=filters)

ids = [instance.id for instance in instances]
print("Terminating:", ids)

ec2.instances.filter(InstanceIds=ids).terminate()

##########################################################################

Prompt:
Add import statement for os
#!/usr/bin/env python
##########################################################################
# scripts/ec2/terminate_all.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE file.
##########################################################################

import boto3
from subprocess import call

ec2 = boto3.resource('ec2')

filters = [{'Name': 'instance-state-name', 'Values': ['running']}]
if "EC2_KEY_NAME" in os.environ:
    filters.append({'Name': 'key-name', 'Values': [os.environ['EC2_KEY_NAME']]})

instances = ec2.instances.filter(Filters=filters)

ids = [instance.id for instance in instances]
print("Terminating:", ids)

ec2.instances.filter(InstanceIds=ids).terminate()

##########################################################################


import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person

class Preferences(models.Model):
    user = models.OneToOneField(User, related_name='preferences')
    address = models.CharField(max_length=100, blank=True, null=True)
    lat = models.FloatField(null=True, blank=True)
    lon = models.FloatField(null=True, blank=True)
    apikey = models.UUIDField(default=uuid.uuid4)

class PersonFollow(models.Model):
    user = models.ForeignKey(User, related_name='person_follows')
    person = models.ForeignKey(Person, related_name='follows')

class TopicFollow(models.Model):
    user = models.ForeignKey(User, related_name='topic_follows')
    topic = models.CharField(max_length=100)

class LocationFollow(models.Model):
    user = models.ForeignKey(User, related_name='location_follows')
    location = models.CharField(max_length=100)

Allow address to be null

Allow address to be null

Response:
import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person

class Preferences(models.Model):
    user = models.OneToOneField(User, related_name='preferences')
    address = models.CharField(max_length=100, blank=True, null=True)
    lat = models.FloatField(null=True, blank=True)
    lon = models.FloatField(null=True, blank=True)
    apikey = models.UUIDField(default=uuid.uuid4)

class PersonFollow(models.Model):
    user = models.ForeignKey(User, related_name='person_follows')
    person = models.ForeignKey(Person, related_name='follows')

class TopicFollow(models.Model):
    user = models.ForeignKey(User, related_name='topic_follows')
    topic = models.CharField(max_length=100)

class LocationFollow(models.Model):
    user = models.ForeignKey(User, related_name='location_follows')
    location = models.CharField(max_length=100)

Prompt:
Allow address to be null

import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person

from django.contrib.auth.models import User

class Preferences(models.Model):
    user = models.OneToOneField(User, related_name='preferences')
    address = models.CharField(max_length=100, blank=True)
    lat = models.FloatField(null=True, blank=True)
    lon = models.FloatField(null=True, blank=True)
    apikey = models.UUIDField(default=uuid.uuid4)

class PersonFollow(models.Model):
    user = models.ForeignKey(User, related_name='person_follows')
    person = models.ForeignKey(Person, related_name='follows')

class TopicFollow(models.Model):
    user = models.ForeignKey(User, related_name='topic_follows')
    topic = models.CharField(max_length=100)

class LocationFollow(models.Model):
    user = models.ForeignKey(User, related_name='location_follows')
    location = models.CharField(max_length=100)


# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenUpgrade module for Odoo
#    @copyright 2015-Today: Odoo Community Association
#    @author: Stephane LE CORNEC
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openupgradelib import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    # because path of report has changed, we need to reload it
    openupgrade.load_data(
        cr, 'stock_picking_list', 'report/report_data.xml')

ADD mig scripts for picking list

ADD mig scripts for picking list

Response:
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenUpgrade module for Odoo
#    @copyright 2015-Today: Odoo Community Association
#    @author: Stephane LE CORNEC
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openupgradelib import openupgrade

@openupgrade.migrate()
def migrate(cr, version):
    # because path of report has changed, we need to reload it
    openupgrade.load_data(
        cr, 'stock_picking_list', 'report/report_data.xml')

Prompt: ADD mig scripts for picking list


import os
from tempfile import mkstemp
import time

class atomic_write(object):
    """Perform an atomic write to a file.

    Use as::

        with atomic_write('/my_file') as f:
            f.write('foo')

    """

    def __init__(self, filepath):
        """
        :type filepath: str
        """
        self.filepath = filepath

    def __enter__(self):
        """
        :rtype: File
        """
        _, self.temp = mkstemp(dir=os.getcwd())
        self.f = open(self.temp, 'w')
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()
        if exc_type is None:
            os.rename(self.temp, self.filepath)

def wait_for_files(*filepath, sleep_interval=0.1):
    """Wait for the existence of files.

    Warning: use ``atomic_write`` to write the file, since this function
    doesn't check that the file is complete.

    :type filepath: str
    :type sleep_interval: float
    :rtype: None
    """
    while not all(os.path.exists(f) for f in filepath):
        time.sleep(sleep_interval)

Allow waiting for multiple files

Allow waiting for multiple files

Response:
import os
from tempfile import mkstemp
import time

class atomic_write(object):
    """Perform an atomic write to a file.

    Use as::

        with atomic_write('/my_file') as f:
            f.write('foo')

    """

    def __init__(self, filepath):
        """
        :type filepath: str
        """
        self.filepath = filepath

    def __enter__(self):
        """
        :rtype: File
        """
        _, self.temp = mkstemp(dir=os.getcwd())
        self.f = open(self.temp, 'w')
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()
        if exc_type is None:
            os.rename(self.temp, self.filepath)

def wait_for_files(*filepath, sleep_interval=0.1):
    """Wait for the existence of files.

    Warning: use ``atomic_write`` to write the file, since this function
    doesn't check that the file is complete.

    :type filepath: str
    :type sleep_interval: float
    :rtype: None
    """
    while not all(os.path.exists(f) for f in filepath):
        time.sleep(sleep_interval)

Prompt:
Allow waiting for multiple files
import os
from tempfile import mkstemp
import time

class atomic_write(object):
    """Perform an atomic write to a file.

    Use as::

        with atomic_write('/my_file') as f:
            f.write('foo')

    """

    def __init__(self, filepath):
        """
        :type filepath: str
        """
        self.filepath = filepath

    def __enter__(self):
        """
        :rtype: File
        """
        _, self.temp = mkstemp(dir=os.getcwd())
        self.f = open(self.temp, 'w')
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()
        if exc_type is None:
            os.rename(self.temp, self.filepath)

def wait_for_file(filepath, sleep_interval=0.1):
    """Wait for the existence of a file.

    Warning: use ``atomic_write`` to write the file, since this function
    doesn't check that the file is complete.

    :type filepath: str
    :type sleep_interval: float
    :rtype: None
    """
    while not os.path.exists(filepath):
        time.sleep(sleep_interval)


import datetime

class Cache:
    EXPIRE_IN = 'expire_in'
    VALUE = 'value'

    def __init__(self):
        self.lock = False
        self.store = {}

    def get(self, key):
        """Gets a value based upon a key."""
        self._check_expiry(key)
        return self.store[key][Cache.VALUE]

    def set(self, expire_in, *args):
        """Sets a dictionary to the cache with a timedelta expiration."""
        for arg in args:
            if isinstance(arg, dict):
                for k,v in arg.items():
                    self._set(k, v, expire_in)
            else:
                for v in arg:
                    self._set(v[0], v[1], expire_in)

    def has(self, key):
        """Returns whether a key is in the cache."""
        self._check_expiry(key)
        return key in self.store

    def _set(self, key, value, expire_in):
        self.store[key] = {
            Cache.EXPIRE_IN: datetime.datetime.now() + expire_in,
            Cache.VALUE: value
        }

    def _check_expiry(self, key):
        """Removes a key/value pair if it's expired."""
        if not self.lock and key in self.store and datetime.datetime.now() > self.store[key][Cache.EXPIRE_IN]:
            self.store.pop(key, None)

Change signature of set() method.

Change signature of set() method.

Response:
import datetime

class Cache:
    EXPIRE_IN = 'expire_in'
    VALUE = 'value'

    def __init__(self):
        self.lock = False
        self.store = {}

    def get(self, key):
        """Gets a value based upon a key."""
        self._check_expiry(key)
        return self.store[key][Cache.VALUE]

    def set(self, expire_in, *args):
        """Sets a dictionary to the cache with a timedelta expiration."""
        for arg in args:
            if isinstance(arg, dict):
                for k,v in arg.items():
                    self._set(k, v, expire_in)
            else:
                for v in arg:
                    self._set(v[0], v[1], expire_in)

    def has(self, key):
        """Returns whether a key is in the cache."""
        self._check_expiry(key)
        return key in self.store

    def _set(self, key, value, expire_in):
        self.store[key] = {
            Cache.EXPIRE_IN: datetime.datetime.now() + expire_in,
            Cache.VALUE: value
        }

    def _check_expiry(self, key):
        """Removes a key/value pair if it's expired."""
        if not self.lock and key in self.store and datetime.datetime.now() > self.store[key][Cache.EXPIRE_IN]:
            self.store.pop(key, None)

Prompt:
Change signature of set() method.

import datetime

class Cache:
    EXPIRE_IN = 'expire_in'

    def __init__(self):
        self.store = {}

    def get(self, key):
        """Gets a value based upon a key."""
        self._check_expiry(key)
        return self.store[key]['value']

    def set(self, dictionary, expire_in):
        """Sets a dictionary to the cache with a timedelta expiration."""
        for key in dictionary.keys():
            self.store[key] = {
                Cache.EXPIRE_IN: datetime.datetime.now() + expire_in,
                'value': dictionary[key]
            }

    def has(self, key):
        """Returns whether a key is in the cache."""
        self._check_expiry(key)
        return key in self.store

    def _check_expiry(self, key):
        """Removes a key/value pair if it's expired."""
        if key in self.store and datetime.datetime.now() > self.store[key][Cache.EXPIRE_IN]:
            self.store.pop(key, None)


#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 19.08.2017 16:13
:Licence GNUv3
Part of grammpy-transforms

"""

from unittest import main, TestCase
from grammpy import *
from grammpy_transforms import *

class S(Nonterminal): pass
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class D(Nonterminal): pass
class Rules(Rule):
    rules = [([S], [A, B]),
             ([S], [C]),
             ([A], ['a', A]),
             ([A], ['a']),
             ([B], ['b', B]),
             ([C], ['c']),
             ([D], ['b', 'c'])]

class CycleTest(TestCase):
    def test_cycleTest(self):
        g = Grammar(terminals=['a', 'b', 'c'],
                    nonterminals=[S, A, B, C, D],
                    rules=[Rules],
                    start_symbol=S)
        self.assertEqual(g.rules_count(), 7)
        com = ContextFree.remove_useless_symbols(g)
        self.assertTrue(com.have_term('c'))
        self.assertFalse(com.have_term('a'))
        self.assertFalse(com.have_term('b'))
        self.assertTrue(com.have_nonterm([S, C]))
        self.assertFalse(com.have_nonterm(A))
        self.assertFalse(com.have_nonterm(B))
        self.assertFalse(com.have_nonterm(D))
        self.assertEqual(com.rules_count(), 2)

    def test_cycleTestShouldNotChange(self):
        g = Grammar(terminals=['a', 'b', 'c'],
                    nonterminals=[S, A, B, C, D],
                    rules=[Rules],
                    start_symbol=S)
        self.assertEqual(g.rules_count(), 7)
        ContextFree.remove_useless_symbols(g)
        self.assertTrue(g.have_term(['a', 'b', 'c']))
        self.assertTrue(g.have_nonterm([S, A, B, C, D]))
        self.assertEqual(g.rules_count(), 7)

    def test_cycleTestShouldChange(self):
        g = Grammar(terminals=['a', 'b', 'c'],
                    nonterminals=[S, A, B, C, D],
                    rules=[Rules],
                    start_symbol=S)
        self.assertEqual(g.rules_count(), 7)
        ContextFree.remove_useless_symbols(g, transform_grammar=True)
        self.assertTrue(g.have_term('c'))
        self.assertFalse(g.have_term('a'))
        self.assertFalse(g.have_term('b'))
        self.assertTrue(g.have_nonterm([S, C]))
        self.assertFalse(g.have_nonterm(A))
        self.assertFalse(g.have_nonterm(B))
        self.assertFalse(g.have_nonterm(D))
        self.assertEqual(g.rules_count(), 2)

Add cycle test of remove useless symbols

Response:
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 19.08.2017 16:13
:Licence GNUv3
Part of grammpy-transforms

"""

from unittest import main, TestCase
from grammpy import *
from grammpy_transforms import *

class S(Nonterminal): pass
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class D(Nonterminal): pass
class Rules(Rule):
    rules = [([S], [A, B]),
             ([S], [C]),
             ([A], ['a', A]),
             ([A], ['a']),
             ([B], ['b', B]),
             ([C], ['c']),
             ([D], ['b', 'c'])]

class CycleTest(TestCase):
    def test_cycleTest(self):
        g = Grammar(terminals=['a', 'b', 'c'],
                    nonterminals=[S, A, B, C, D],
                    rules=[Rules],
                    start_symbol=S)
        self.assertEqual(g.rules_count(), 7)
        com = ContextFree.remove_useless_symbols(g)
        self.assertTrue(com.have_term('c'))
        self.assertFalse(com.have_term('a'))
        self.assertFalse(com.have_term('b'))
        self.assertTrue(com.have_nonterm([S, C]))
        self.assertFalse(com.have_nonterm(A))
        self.assertFalse(com.have_nonterm(B))
        self.assertFalse(com.have_nonterm(D))
        self.assertEqual(com.rules_count(), 2)

    def test_cycleTestShouldNotChange(self):
        g = Grammar(terminals=['a', 'b', 'c'],
                    nonterminals=[S, A, B, C, D],
                    rules=[Rules],
                    start_symbol=S)
        self.assertEqual(g.rules_count(), 7)
        ContextFree.remove_useless_symbols(g)
        self.assertTrue(g.have_term(['a', 'b', 'c']))
        self.assertTrue(g.have_nonterm([S, A, B, C, D]))
        self.assertEqual(g.rules_count(), 7)

    def test_cycleTestShouldChange(self):
        g = Grammar(terminals=['a', 'b', 'c'],
                    nonterminals=[S, A, B, C, D],
                    rules=[Rules],
                    start_symbol=S)
        self.assertEqual(g.rules_count(), 7)
        ContextFree.remove_useless_symbols(g, transform_grammar=True)
        self.assertTrue(g.have_term('c'))
        self.assertFalse(g.have_term('a'))
        self.assertFalse(g.have_term('b'))
        self.assertTrue(g.have_nonterm([S, C]))
        self.assertFalse(g.have_nonterm(A))
        self.assertFalse(g.have_nonterm(B))
        self.assertFalse(g.have_nonterm(D))
        self.assertEqual(g.rules_count(), 2)

Prompt: Add cycle test of remove useless symbols


from twisted.plugin import IPlugin
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class InvisibleMode(ModuleData, Mode):
    implements(IPlugin, IModuleData, IMode)

    name = "InvisibleMode"
    core = True
    affectedActions = [ "showchanneluser", "showuser" ]

    def actions(self):
        return [ ("modeactioncheck-user-i-showchanneluser", 1, self.isInvisibleChan),
                ("modeactioncheck-user-i-showuser", 1, self.isInvisibleUser) ]

    def userModes(self):
        return [ ("i", ModeType.NoParam, self) ]

    def isInvisibleChan(self, user, channel, fromUser, userSeeing):
        if "i" in user.modes:
            return True
        return None

    def isInvisibleUser(self, user, fromUser, userSeeing):
        if "i" in user.modes:
            return True
        return None

    def apply(self, actionName, user, param, *params):
        if actionName == "showchanneluser":
            return self.applyChannels(user, *params)
        return self.applyUsers(user, *params)

    def applyChannels(self, user, channel, fromUser, sameUser):
        if user != sameUser:
            return None
        if not channel or fromUser not in channel.users:
            return False
        return None

    def applyUsers(self, user, fromUser, sameUser):
        if user != sameUser:
            return None
        for channel in fromUser.channels:
            if user in channel.users:
                return None
        return False

invisibleMode = InvisibleMode()

Response:
from twisted.plugin import IPlugin
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class InvisibleMode(ModuleData, Mode):
    implements(IPlugin, IModuleData, IMode)

    name = "InvisibleMode"
    core = True
    affectedActions = [ "showchanneluser", "showuser" ]

    def actions(self):
        return [ ("modeactioncheck-user-i-showchanneluser", 1, self.isInvisibleChan),
                ("modeactioncheck-user-i-showuser", 1, self.isInvisibleUser) ]

    def userModes(self):
        return [ ("i", ModeType.NoParam, self) ]

    def isInvisibleChan(self, user, channel, fromUser, userSeeing):
        if "i" in user.modes:
            return True
        return None

    def isInvisibleUser(self, user, fromUser, userSeeing):
        if "i" in user.modes:
            return True
        return None

    def apply(self, actionName, user, param, *params):
        if actionName == "showchanneluser":
            return self.applyChannels(user, *params)
        return self.applyUsers(user, *params)

    def applyChannels(self, user, channel, fromUser, sameUser):
        if user != sameUser:
            return None
        if not channel or fromUser not in channel.users:
            return False
        return None

    def applyUsers(self, user, fromUser, sameUser):
        if user != sameUser:
            return None
        for channel in fromUser.channels:
            if user in channel.users:
                return None
        return False

invisibleMode = InvisibleMode()

Prompt:
Make the invisible check action not necessarily require an accompanying channel

from twisted.plugin import IPlugin
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class InvisibleMode(ModuleData, Mode):
    implements(IPlugin, IModuleData, IMode)

    name = "InvisibleMode"
    core = True
    affectedActions = [ "showchanneluser" ]

    def actions(self):
        return [ ("modeactioncheck-user-i-showchanneluser", 1, self.isInvisible) ]

    def userModes(self):
        return [ ("i", ModeType.NoParam, self) ]

    def isInvisible(self, user, channel, fromUser, userSeeing):
        if "i" in user.modes:
            return True
        return None

    def apply(self, actionName, user, param, channel, fromUser, sameUser):
        if user != sameUser:
            return None
        if not channel or fromUser not in channel.users:
            return False
        return None

invisibleMode = InvisibleMode()


#!/usr/bin/python
import time
import rospy

from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader

def main():
    c = ConfigReader("demo_config")
    c.parse_all()
    s = ArmController('right', c.right_angles, c.push_thresh)
    while not rospy.is_shutdown():
        s.step()

if __name__ == "__main__":
    main()

Enable ctrl-c control with rospy

Enable ctrl-c control with rospy

Response:
#!/usr/bin/python
import time
import rospy

from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader

def main():
    c = ConfigReader("demo_config")
    c.parse_all()
    s = ArmController('right', c.right_angles, c.push_thresh)
    while not rospy.is_shutdown():
        s.step()

if __name__ == "__main__":
    main()

Prompt:
Enable ctrl-c control with rospy

#!/usr/bin/python

from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader

def main():
    c = ConfigReader("demo_config")
    c.parse_all()
    s = ArmController('right', c.right_angles, c.push_thresh)
    s.move_loop()

if __name__ == "__main__":
    main()


from __future__ import unicode_literals

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction

from waldur_core.core.utils import DryRunCommand

User = get_user_model()

class Command(DryRunCommand):
    help_text = 'Append civil number with country code for OpenID users.'

    def handle(self, dry_run, *args, **options):
        conf = settings.WALDUR_AUTH_OPENID
        country_code = conf['COUNTRY_CODE']
        registration_method = conf['NAME']

        with transaction.atomic():
            users = User.objects.filter(registration_method=registration_method)\
                .exclude(civil_number__startswith=country_code)\
                .exclude(civil_number='') \
                .exclude(civil_number=None)
            count = users.count()
            for user in users:
                new_civil_number = '%s%s' % (country_code, user.civil_number)
                self.stdout.write('Username: %s, before: %s, after: %s' % (
                    user.username, user.civil_number, new_civil_number))
                if not dry_run:
                    user.civil_number = new_civil_number
                    user.save(update_fields=['civil_number'])

        self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))

Print out civil_number before and after

Response:
from __future__ import unicode_literals

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction

from waldur_core.core.utils import DryRunCommand

User = get_user_model()

class Command(DryRunCommand):
    help_text = 'Append civil number with country code for OpenID users.'

    def handle(self, dry_run, *args, **options):
        conf = settings.WALDUR_AUTH_OPENID
        country_code = conf['COUNTRY_CODE']
        registration_method = conf['NAME']

        with transaction.atomic():
            users = User.objects.filter(registration_method=registration_method)\
                .exclude(civil_number__startswith=country_code)\
                .exclude(civil_number='') \
                .exclude(civil_number=None)
            count = users.count()
            for user in users:
                new_civil_number = '%s%s' % (country_code, user.civil_number)
                self.stdout.write('Username: %s, before: %s, after: %s' % (
                    user.username, user.civil_number, new_civil_number))
                if not dry_run:
                    user.civil_number = new_civil_number
                    user.save(update_fields=['civil_number'])

        self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))

Prompt:
Print out civil_number before and after [WAL-2172]

from __future__ import unicode_literals

from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction

from waldur_core.core.utils import DryRunCommand

User = get_user_model()

class Command(DryRunCommand):
    help_text = 'Append civil number with country code for OpenID users.'

    def handle(self, dry_run, *args, **options):
        conf = settings.WALDUR_AUTH_OPENID
        country_code = conf['COUNTRY_CODE']
        registration_method = conf['NAME']

        with transaction.atomic():
            users = User.objects.filter(registration_method=registration_method)\
                .exclude(civil_number__startswith=country_code)\
                .exclude(civil_number='') \
                .exclude(civil_number=None)
            count = users.count()
            if not dry_run:
                for user in users:
                    user.civil_number = '%s%s' % (country_code, user.civil_number)
                    user.save(update_fields=['civil_number'])

        self.stdout.write(self.style.SUCCESS('Civil numbers have been updated for %s users.' % count))


'''Test Span.as_doc() doesn't segfault'''
from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy

def test_issue1537():
    string = 'The sky is blue . The man is pink . The dog is purple .'
    doc = Doc(Vocab(), words=string.split())
    doc[0].sent_start = True
    for word in doc[1:]:
        if word.nbor(-1).text == '.':
            word.sent_start = True
        else:
            word.sent_start = False

    sents = list(doc.sents)
    sent0 = sents[0].as_doc()
    sent1 = sents[1].as_doc()
    assert isinstance(sent0, Doc)
    assert isinstance(sent1, Doc)

# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
#    nlp = load_spacy('en')
#    doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
#    sents = [s.as_doc() for s in doc.sents]
#    print(list(sents[0].noun_chunks))
#    print(list(sents[1].noun_chunks))

Fix unicode error in new test

Fix unicode error in new test

Response:
'''Test Span.as_doc() doesn't segfault'''
from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy

def test_issue1537():
    string = 'The sky is blue . The man is pink . The dog is purple .'
    doc = Doc(Vocab(), words=string.split())
    doc[0].sent_start = True
    for word in doc[1:]:
        if word.nbor(-1).text == '.':
            word.sent_start = True
        else:
            word.sent_start = False

    sents = list(doc.sents)
    sent0 = sents[0].as_doc()
    sent1 = sents[1].as_doc()
    assert isinstance(sent0, Doc)
    assert isinstance(sent1, Doc)

# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
#    nlp = load_spacy('en')
#    doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
#    sents = [s.as_doc() for s in doc.sents]
#    print(list(sents[0].noun_chunks))
#    print(list(sents[1].noun_chunks))

Prompt:
Fix unicode error in new test

'''Test Span.as_doc() doesn't segfault'''
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy

def test_issue1537():
    string = 'The sky is blue . The man is pink . The dog is purple .'
    doc = Doc(Vocab(), words=string.split())
    doc[0].sent_start = True
    for word in doc[1:]:
        if word.nbor(-1).text == '.':
            word.sent_start = True
        else:
            word.sent_start = False

    sents = list(doc.sents)
    sent0 = sents[0].as_doc()
    sent1 = sents[1].as_doc()
    assert isinstance(sent0, Doc)
    assert isinstance(sent1, Doc)

# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
#    nlp = load_spacy('en')
#    doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
#    sents = [s.as_doc() for s in doc.sents]
#    print(list(sents[0].noun_chunks))
#    print(list(sents[1].noun_chunks))


from .tabulate import _text_type

def pad(field, total, char=u" "):
    return field + (char * (total - len(field)))

def get_separator(num, header_len, data_len):

    sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
    return sep

def expanded_table(rows, headers):
    header_len = max([len(x) for x in headers])
    max_row_len = 0
    results = []

    padded_headers = [pad(x, header_len) + u" |" for x in headers]
    header_len += 2

    for row in rows:
        row_len = max([len(_text_type(x)) for x in row])
        row_result = []
        if row_len > max_row_len:
            max_row_len = row_len

        for header, value in zip(padded_headers, row):
            if value is None: value = '<null>'
            row_result.append(u"%s %s" % (header, value))

        results.append('\n'.join(row_result))

    output = []
    for i, result in enumerate(results):
        output.append(get_separator(i, header_len, max_row_len))
        output.append(result)
        output.append('\n')

    return ''.join(output)

Response:
from .tabulate import _text_type

def pad(field, total, char=u" "):
    return field + (char * (total - len(field)))

def get_separator(num, header_len, data_len):

    sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
    return sep

def expanded_table(rows, headers):
    header_len = max([len(x) for x in headers])
    max_row_len = 0
    results = []

    padded_headers = [pad(x, header_len) + u" |" for x in headers]
    header_len += 2

    for row in rows:
        row_len = max([len(_text_type(x)) for x in row])
        row_result = []
        if row_len > max_row_len:
            max_row_len = row_len

        for header, value in zip(padded_headers, row):
            if value is None: value = '<null>'
            row_result.append(u"%s %s" % (header, value))

        results.append('\n'.join(row_result))

    output = []
    for i, result in enumerate(results):
        output.append(get_separator(i, header_len, max_row_len))
        output.append(result)
        output.append('\n')

    return ''.join(output)

Prompt:
Make the null value consistent between vertical and tabular output.

from .tabulate import _text_type

def pad(field, total, char=u" "):
    return field + (char * (total - len(field)))

def get_separator(num, header_len, data_len):

    sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
    return sep

def expanded_table(rows, headers):
    header_len = max([len(x) for x in headers])
    max_row_len = 0
    results = []

    padded_headers = [pad(x, header_len) + u" |" for x in headers]
    header_len += 2

    for row in rows:
        row_len = max([len(_text_type(x)) for x in row])
        row_result = []
        if row_len > max_row_len:
            max_row_len = row_len

        for header, value in zip(padded_headers, row):
            row_result.append(u"%s %s" % (header, value))

        results.append('\n'.join(row_result))

    output = []
    for i, result in enumerate(results):
        output.append(get_separator(i, header_len, max_row_len))
        output.append(result)
        output.append('\n')

    return ''.join(output)


from django import template
from django.conf import settings

from .utils import get_menu_from_apps
from .. import defaults
from ..menu import generate_menu

register = template.Library()

@register.simple_tag(takes_context=True)
def get_menu(context, menu_name):
    """
    Returns a consumable menu list for a given menu_name found in settings.py.
    Else it returns an empty list.

    Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the
    menus.py's 'MENUS' dict.
    :param context: Template context
    :param menu_name: String, name of the menu to be found
    :return: Generated menu
    """
    menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND)
    menu_from_apps = get_menu_from_apps(menu_name)
    # If there isn't a menu on settings but there is menu from apps we built menu from apps
    if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list = menu_from_apps
    # It there is a menu on settings and also on apps we merge both menus
    elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list += menu_from_apps
    return generate_menu(context['request'], menu_list)

Response:
from django import template
from django.conf import settings

from .utils import get_menu_from_apps
from .. import defaults
from ..menu import generate_menu

register = template.Library()

@register.simple_tag(takes_context=True)
def get_menu(context, menu_name):
    """
    Returns a consumable menu list for a given menu_name found in settings.py.
    Else it returns an empty list.

    Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the
    menus.py's 'MENUS' dict.
    :param context: Template context
    :param menu_name: String, name of the menu to be found
    :return: Generated menu
    """
    menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND)
    menu_from_apps = get_menu_from_apps(menu_name)
    # If there isn't a menu on settings but there is menu from apps we built menu from apps
    if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list = menu_from_apps
    # It there is a menu on settings and also on apps we merge both menus
    elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list += menu_from_apps
    return generate_menu(context['request'], menu_list)

Prompt:
Use simple_tag instead of assignment_tag

The assignment_tag is depraceted and in django-2.0 removed.

Signed-off-by: Frantisek Lachman <bae095a6f6bdabf882218c81fdc3947ea1c10590@gmail.com>

from django import template
from django.conf import settings

from .utils import get_menu_from_apps
from .. import defaults
from ..menu import generate_menu

register = template.Library()

@register.assignment_tag(takes_context=True)
def get_menu(context, menu_name):
    """
    Returns a consumable menu list for a given menu_name found in settings.py.
    Else it returns an empty list.

    Update, March 18 2017: Now the function get the menu list from settings and append more items if found on the
    menus.py's 'MENUS' dict.
    :param context: Template context
    :param menu_name: String, name of the menu to be found
    :return: Generated menu
    """
    menu_list = getattr(settings, menu_name, defaults.MENU_NOT_FOUND)
    menu_from_apps = get_menu_from_apps(menu_name)
    # If there isn't a menu on settings but there is menu from apps we built menu from apps
    if menu_list == defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list = menu_from_apps
    # It there is a menu on settings and also on apps we merge both menus
    elif menu_list != defaults.MENU_NOT_FOUND and menu_from_apps:
        menu_list += menu_from_apps
    return generate_menu(context['request'], menu_list)


from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter

class GeoCodePipeline(object):

    def open_spider(self, spider):
        geolocator = Photon(timeout=5)
        self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)

    def process_item(self, item, spider):

        for crime in item["crimes"]:
            place = crime["place"]
            latitude, longitude = self.__geocode_address(place)
            crime["latitude"] = latitude
            crime["longitude"] = longitude
        return item

    def __geocode_address(self, place):
        if place is None:
            return None, None

        location = self.__geocodeFunc(place)
        if location is not None:
            return location.latitude, location.longitude
        else:
            return None, None

Response:
from geopy import Nominatim, Photon
from geopy.extra.rate_limiter import RateLimiter

class GeoCodePipeline(object):

    def open_spider(self, spider):
        geolocator = Photon(timeout=5)
        self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)

    def process_item(self, item, spider):

        for crime in item["crimes"]:
            place = crime["place"]
            latitude, longitude = self.__geocode_address(place)
            crime["latitude"] = latitude
            crime["longitude"] = longitude
        return item

    def __geocode_address(self, place):
        if place is None:
            return None, None

        location = self.__geocodeFunc(place)
        if location is not None:
            return location.latitude, location.longitude
        else:
            return None, None

Prompt:
Use Phonon instead of Nominatim for geo coding

Phonon is more fault tolerant to spelling mistakes.

from geopy import Nominatim
from geopy.extra.rate_limiter import RateLimiter

class GeoCodePipeline(object):

    def open_spider(self, spider):
        geolocator = Nominatim(timeout=5)
        self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2)

    def process_item(self, item, spider):

        for crime in item["crimes"]:
            place = crime["place"]
            latitude, longitude = self.__geocode_address(place)
            crime["latitude"] = latitude
            crime["longitude"] = longitude
        return item

    def __geocode_address(self, place):
        if place is None:
            return None, None

        location = self.__geocodeFunc(place)
        if location is not None:
            return location.latitude, location.longitude
        else:
            return None, None


import boto3

from bluecanary.exceptions import NamespaceError
from bluecanary.utilities import throttle

@throttle()
def set_cloudwatch_alarm(identifier, **kwargs):
    if not kwargs.get('Dimensions'):
        kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs)

    if not kwargs.get('AlarmName'):
        kwargs['AlarmName'] = '{}_{}'.format(identifier,
                                             kwargs.get('MetricName'))

    if kwargs.get('AlarmNameModifier'):
        kwargs['AlarmName'] = '{}_{}'.format(kwargs.get('AlarmName'),
                                             kwargs.get('AlarmNameModifier'))
        del(kwargs['AlarmNameModifier'])

    cloudwatch_client = boto3.client('cloudwatch')

    return cloudwatch_client.put_metric_alarm(**kwargs)

def _get_dimensions(identifier, **kwargs):

    base_dimensions = {
        'AWS/ELB': [{u'Name': 'LoadBalancerName', u'Value': identifier}],
        'AWS/EC2': [{u'Name': 'InstanceId', u'Value': identifier}],
    }

    try:
        return base_dimensions[kwargs.get('Namespace')]
    except KeyError:
        message = ('Namespace "{}" is not supported by Blue Canary. '
                   'If you are using a plugin that supports this Namespace '
                   'please ensure that the plugin alarm class does not return '
                   'None when calling the "get_dimensions" method.'
                   .format(kwargs.get('Namespace')))
        raise NamespaceError(message)

Response:
import boto3

from bluecanary.exceptions import NamespaceError
from bluecanary.utilities import throttle

@throttle()
def set_cloudwatch_alarm(identifier, **kwargs):
    if not kwargs.get('Dimensions'):
        kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs)

    if not kwargs.get('AlarmName'):
        kwargs['AlarmName'] = '{}_{}'.format(identifier,
                                             kwargs.get('MetricName'))

    if kwargs.get('AlarmNameModifier'):
        kwargs['AlarmName'] = '{}_{}'.format(kwargs.get('AlarmName'),
                                             kwargs.get('AlarmNameModifier'))
        del(kwargs['AlarmNameModifier'])

    cloudwatch_client = boto3.client('cloudwatch')

    return cloudwatch_client.put_metric_alarm(**kwargs)

def _get_dimensions(identifier, **kwargs):

    base_dimensions = {
        'AWS/ELB': [{u'Name': 'LoadBalancerName', u'Value': identifier}],
        'AWS/EC2': [{u'Name': 'InstanceId', u'Value': identifier}],
    }

    try:
        return base_dimensions[kwargs.get('Namespace')]
    except KeyError:
        message = ('Namespace "{}" is not supported by Blue Canary. '
                   'If you are using a plugin that supports this Namespace '
                   'please ensure that the plugin alarm class does not return '
                   'None when calling the "get_dimensions" method.'
                   .format(kwargs.get('Namespace')))
        raise NamespaceError(message)

Prompt:
Allow multiple alarms for same metric type

import boto3

from bluecanary.exceptions import NamespaceError
from bluecanary.utilities import throttle

@throttle()
def set_cloudwatch_alarm(identifier, **kwargs):
    if not kwargs.get('Dimensions'):
        kwargs['Dimensions'] = _get_dimensions(identifier, **kwargs)

    if not kwargs.get('AlarmName'):
        kwargs['AlarmName'] = '{}_{}'.format(identifier, kwargs.get('MetricName'))

    cloudwatch_client = boto3.client('cloudwatch')

    return cloudwatch_client.put_metric_alarm(**kwargs)

def _get_dimensions(identifier, **kwargs):

    base_dimensions = {
        'AWS/ELB': [{u'Name': 'LoadBalancerName', u'Value': identifier}],
        'AWS/EC2': [{u'Name': 'InstanceId', u'Value': identifier}],
    }

    try:
        return base_dimensions[kwargs.get('Namespace')]
    except KeyError:
        message = ('Namespace "{}" is not supported by Blue Canary. '
                   'If you are using a plugin that supports this Namespace '
                   'please ensure that the plugin alarm class does not return '
                   'None when calling the "get_dimensions" method.'
                   .format(kwargs.get('Namespace')))
        raise NamespaceError(message)


"""
For examples of dadi's usage, see the examples directory in the source
distribution.

Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()

import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
import Numerics
import PhiManip
# Protect import of Plotting in case matplotlib not installed.
try:
    import Plotting
except ImportError:
    pass

# We do it this way so it's easier to reload.
import Spectrum_mod
Spectrum = Spectrum_mod.Spectrum

try:
    # This is to try and ensure we have a nice __SVNVERSION__ attribute, so
    # when we get bug reports, we know what version they were using. The
    # svnversion file is created by setup.py.
    import os
    _directory = os.path.dirname(Integration.__file__)
    _svn_file = os.path.join(_directory, 'svnversion')
    __SVNVERSION__ = file(_svn_file).read().strip()
except:
    __SVNVERSION__ = 'Unknown'

# When doing arithmetic with Spectrum objects (which are masked arrays), we
# often have masked values which generate annoying arithmetic warnings. Here
# we tell numpy to ignore such warnings. This puts greater onus on the user to
# check results, but for our use case I think it's the better default.
import numpy
numpy.seterr(all='ignore')

Response:
"""
For examples of dadi's usage, see the examples directory in the source
distribution.

Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()

import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
import Numerics
import PhiManip
# Protect import of Plotting in case matplotlib not installed.
try:
    import Plotting
except ImportError:
    pass

# We do it this way so it's easier to reload.
import Spectrum_mod
Spectrum = Spectrum_mod.Spectrum

try:
    # This is to try and ensure we have a nice __SVNVERSION__ attribute, so
    # when we get bug reports, we know what version they were using. The
    # svnversion file is created by setup.py.
    import os
    _directory = os.path.dirname(Integration.__file__)
    _svn_file = os.path.join(_directory, 'svnversion')
    __SVNVERSION__ = file(_svn_file).read().strip()
except:
    __SVNVERSION__ = 'Unknown'

# When doing arithmetic with Spectrum objects (which are masked arrays), we
# often have masked values which generate annoying arithmetic warnings. Here
# we tell numpy to ignore such warnings. This puts greater onus on the user to
# check results, but for our use case I think it's the better default.
import numpy
numpy.seterr(all='ignore')

Prompt:
Hide spurious numpy warnings about divide by zeros and nans.

git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@429 979d6bd5-6d4d-0410-bece-f567c23bd345

"""
For examples of dadi's usage, see the examples directory in the source
distribution.

Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()

import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
import Numerics
import PhiManip
# Protect import of Plotting in case matplotlib not installed.
try:
    import Plotting
except ImportError:
    pass

# We do it this way so it's easier to reload.
import Spectrum_mod
Spectrum = Spectrum_mod.Spectrum

try:
    # This is to try and ensure we have a nice __SVNVERSION__ attribute, so
    # when we get bug reports, we know what version they were using. The
    # svnversion file is created by setup.py.
    import os
    _directory = os.path.dirname(Integration.__file__)
    _svn_file = os.path.join(_directory, 'svnversion')
    __SVNVERSION__ = file(_svn_file).read().strip()
except:
    __SVNVERSION__ = 'Unknown'


import discord
import duckbot_settings
import random
from discord.ext import commands

_DESCRIPTION = '''quack'''

bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()

@bot.event
async def on_ready():
	print('logged in: %s (%s)' % (bot.user.name, bot.user.id))

	oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
	print('invite me: %s' % oauth_url)

	print('Channels:')

	channels = bot.get_all_channels()
	for channel in channels:
		print('%s (%s)' % (channel.name, channel.id))
		if channel.name == 'botspam':
			await bot.send_message(channel, 'quack!! (ready to roll)')

@bot.command()
async def roll():
	lower_bound = 1
	upper_boundb = 6
	await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))

bot.run(duckbot_settings.TOKEN)

Add a real roll command

Add a real roll command

Response:
import discord
import duckbot_settings
import random
from discord.ext import commands

_DESCRIPTION = '''quack'''

bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()

@bot.event
async def on_ready():
	print('logged in: %s (%s)' % (bot.user.name, bot.user.id))

	oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
	print('invite me: %s' % oauth_url)

	print('Channels:')

	channels = bot.get_all_channels()
	for channel in channels:
		print('%s (%s)' % (channel.name, channel.id))
		if channel.name == 'botspam':
			await bot.send_message(channel, 'quack!! (ready to roll)')

@bot.command()
async def roll():
	lower_bound = 1
	upper_boundb = 6
	await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))

bot.run(duckbot_settings.TOKEN)

Prompt:
Add a real roll command

import discord
import duckbot_settings
import random
from discord.ext import commands

_DESCRIPTION = '''quack'''

bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)

@bot.event
async def on_ready():
	print('logged in: %s (%s)' % (bot.user.name, bot.user.id))

	oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
	print('invite me: %s' % oauth_url)

	print('Channels:')

	channels = bot.get_all_channels()
	for channel in channels:
		print('%s (%s)' % (channel.name, channel.id))
		if channel.name == 'botspam':
			await bot.send_message(channel, 'quack!! (ready to roll)')

@bot.command()
async def roll():
	await bot.say('pretending to roll')

bot.run(duckbot_settings.TOKEN)


from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil

from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile

class Command(BaseCommand):
    help = 'Construct web export of an annotated volume'

    def add_arguments(self, parser):
        parser.add_argument('pid', nargs='+', type=str)
        parser.add_argument('--static', action='store_true', default=False,
            help='Generate built (static) site instead of jekyll site')
        parser.add_argument('--tei',
            help='Use the specified TEI file instead of generating it')

    def handle(self, *args, **options):
        print args
        repo = Repository()
        for pid in options['pid']:
            vol = repo.get_object(pid, type=Volume)
            if options['tei']:
                tei = load_xmlobject_from_file(options['tei'], Facsimile)
            else:
                tei = annotate.annotated_tei(vol.generate_volume_tei(),
                    vol.annotations())
            zipfile = export.website(vol, tei, static=options['static'])
            zipfilename = '%s-annotated-site.zip' % vol.noid
            shutil.copyfile(zipfile.name, zipfilename)

            print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)

Response:
from eulfedora.server import Repository
from eulxml.xmlmap import load_xmlobject_from_file
from django.core.management.base import BaseCommand
import shutil

from readux.books import annotate, export
from readux.books.models import Volume
from readux.books.tei import Facsimile

class Command(BaseCommand):
    help = 'Construct web export of an annotated volume'

    def add_arguments(self, parser):
        parser.add_argument('pid', nargs='+', type=str)
        parser.add_argument('--static', action='store_true', default=False,
            help='Generate built (static) site instead of jekyll site')
        parser.add_argument('--tei',
            help='Use the specified TEI file instead of generating it')

    def handle(self, *args, **options):
        print args
        repo = Repository()
        for pid in options['pid']:
            vol = repo.get_object(pid, type=Volume)
            if options['tei']:
                tei = load_xmlobject_from_file(options['tei'], Facsimile)
            else:
                tei = annotate.annotated_tei(vol.generate_volume_tei(),
                    vol.annotations())
            zipfile = export.website(vol, tei, static=options['static'])
            zipfilename = '%s-annotated-site.zip' % vol.noid
            shutil.copyfile(zipfile.name, zipfilename)

            print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)

Prompt:
Add an option to pass in generated TEI, for speed & troubleshooting

from eulfedora.server import Repository
from django.core.management.base import BaseCommand
import shutil

from readux.books import annotate, export
from readux.books.models import Volume

class Command(BaseCommand):
    help = 'Construct web export of an annotated volume'

    def add_arguments(self, parser):
        parser.add_argument('pid', nargs='+', type=str)
        parser.add_argument('--static', action='store_true', default=False,
            help='Generate built (static) site instead of jekyll site')

    def handle(self, *args, **options):
        print args
        repo = Repository()
        for pid in options['pid']:
            vol = repo.get_object(pid, type=Volume)
            tei = annotate.annotated_tei(vol.generate_volume_tei(),
                vol.annotations())
            zipfile = export.website(vol, tei, static=options['static'])
            zipfilename = '%s-annotated-site.zip' % pid
            shutil.copyfile(zipfile.name, zipfilename)

            print 'Export for %s complete, zipfile is %s' % (vol.noid, zipfilename)