from datetime import timedelta

import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField

from timed.serializers import PkDictSerializer

class MyPkDictSerializer(PkDictSerializer):
    test_duration = DurationField()
    test_nr = IntegerField()

    class Meta:
        pk_key = 'test_nr'
        resource_name = 'my-resource'

@pytest.fixture
def data():
    return {
        'test_nr': 123,
        'test_duration': timedelta(hours=1),
        'invalid_field': '1234'
    }

def test_pk_dict_serializer_single(data):
    serializer = MyPkDictSerializer(data)

    expected_data = {
        'test_duration': '01:00:00',
        'test_nr': 123,
    }

    assert expected_data == serializer.data

def test_pk_dict_serializer_many(data):
    list_data = [
        data,
        data
    ]
    serializer = MyPkDictSerializer(list_data, many=True)

    expected_data = [
        {
            'test_duration': '01:00:00',
            'test_nr': 123,
        },
        {
            'test_duration': '01:00:00',
            'test_nr': 123,
        },
    ]

    assert expected_data == serializer.data

Add unit test for pk dict serializer

Add unit test for pk dict serializer

Response:
<REPLACE_OLD>  <REPLACE_NEW> from datetime import timedelta

import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField

from timed.serializers import PkDictSerializer

class MyPkDictSerializer(PkDictSerializer):
    test_duration = DurationField()
    test_nr = IntegerField()

    class Meta:
        pk_key = 'test_nr'
        resource_name = 'my-resource'

@pytest.fixture
def data():
    return {
        'test_nr': 123,
        'test_duration': timedelta(hours=1),
        'invalid_field': '1234'
    }

def test_pk_dict_serializer_single(data):
    serializer = MyPkDictSerializer(data)

    expected_data = {
        'test_duration': '01:00:00',
        'test_nr': 123,
    }

    assert expected_data == serializer.data

def test_pk_dict_serializer_many(data):
    list_data = [
        data,
        data
    ]
    serializer = MyPkDictSerializer(list_data, many=True)

    expected_data = [
        {
            'test_duration': '01:00:00',
            'test_nr': 123,
        },
        {
            'test_duration': '01:00:00',
            'test_nr': 123,
        },
    ]

    assert expected_data == serializer.data
 <REPLACE_END> <|endoftext|> from datetime import timedelta

import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField

from timed.serializers import PkDictSerializer

class MyPkDictSerializer(PkDictSerializer):
    test_duration = DurationField()
    test_nr = IntegerField()

    class Meta:
        pk_key = 'test_nr'
        resource_name = 'my-resource'

@pytest.fixture
def data():
    return {
        'test_nr': 123,
        'test_duration': timedelta(hours=1),
        'invalid_field': '1234'
    }

def test_pk_dict_serializer_single(data):
    serializer = MyPkDictSerializer(data)

    expected_data = {
        'test_duration': '01:00:00',
        'test_nr': 123,
    }

    assert expected_data == serializer.data

def test_pk_dict_serializer_many(data):
    list_data = [
        data,
        data
    ]
    serializer = MyPkDictSerializer(list_data, many=True)

    expected_data = [
        {
            'test_duration': '01:00:00',
            'test_nr': 123,
        },
        {
            'test_duration': '01:00:00',
            'test_nr': 123,
        },
    ]

    assert expected_data == serializer.data

Prompt: Add unit test for pk dict serializer


import optparse
import subprocess

def table_checksum(user, password, host):
    args = ['/usr/bin/pt-table-checksum', '-u', user, '-p', password]
    if host:
        args.extend(['-h', host])

    proc = subprocess.Popen(args, stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    return (proc.return_code, out, err)

def main():
    usage = "Usage: %prog [-h] [-H] username password"

    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-H', '--host', action='store', dest='host',
                      default=None)
    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.print_help()
        raise SystemExit(True)

    (status, _, err) = table_checksum(args[0], args[1], options.host)
    if status != 0:
        print "status err %s" % err
        raise SystemExit(True)

    print "status ok"

if __name__ == '__main__':
    main()

Use pt-table-checksum to check for galera consistency

Response:
<INSERT> import optparse
import subprocess

def table_checksum(user, password, host):
 <INSERT_END> <INSERT>   args = ['/usr/bin/pt-table-checksum', '-u', user, '-p', password]
    if host:
        args.extend(['-h', host])

    proc = subprocess.Popen(args, stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    return (proc.return_code, out, err)

def main():
    usage = "Usage: %prog [-h] [-H] username password"

    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-H', '--host', action='store', dest='host',
                      default=None)
    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.print_help()
        raise SystemExit(True)

    (status, _, err) = table_checksum(args[0], args[1], options.host)
    if status != 0:
        print "status err %s" % err
        raise SystemExit(True)

    print "status ok"

if __name__ == '__main__':
    main()
 <INSERT_END> <|endoftext|> import optparse
import subprocess

def table_checksum(user, password, host):
    args = ['/usr/bin/pt-table-checksum', '-u', user, '-p', password]
    if host:
        args.extend(['-h', host])

    proc = subprocess.Popen(args, stderr=subprocess.PIPE)
    (out, err) = proc.communicate()
    return (proc.return_code, out, err)

def main():
    usage = "Usage: %prog [-h] [-H] username password"

    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-H', '--host', action='store', dest='host',
                      default=None)
    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.print_help()
        raise SystemExit(True)

    (status, _, err) = table_checksum(args[0], args[1], options.host)
    if status != 0:
        print "status err %s" % err
        raise SystemExit(True)

    print "status ok"

if __name__ == '__main__':
    main()

Prompt: Use pt-table-checksum to check for galera consistency


import attr

__all__ = ["make_tohu_items_class"]

def make_tohu_items_class(clsname, field_names):
    """
    Parameters
    ----------
    clsname: string
        Name of the class to be created.

    field_names: list of strings
        Names of the field attributes of the class to be created.
    """
    item_cls = attr.make_class(clsname, {name: attr.ib() for name in field_names}, repr=True, cmp=True, frozen=True)
    func_eq_orig = item_cls.__eq__

    def func_eq_new(self, other):
        """
        Custom __eq__() method which also allows comparisons with
        tuples and dictionaries. This is mostly for convenience
        during testing.
        """

        if isinstance(other, self.__class__):
            return func_eq_orig(self, other)
        else:
            if isinstance(other, tuple):
                return attr.astuple(self) == other
            elif isinstance(other, dict):
                return attr.asdict(self) == other
            else:
                raise TypeError(
                    f"Tohu items have types that cannot be compared: "
                    "{self.__class__.__name__}, {other.__class__.__name__}"
                )

    item_cls.__eq__ = func_eq_new
    item_cls.field_names = field_names
    item_cls.as_dict = lambda self: attr.asdict(self)
    item_cls.as_tuple = lambda self: attr.astuple(self)
    item_cls.is_unset = False
    return item_cls

Response:
<INSERT> item_cls.is_unset = False
    <INSERT_END> <|endoftext|> import attr

__all__ = ["make_tohu_items_class"]

def make_tohu_items_class(clsname, field_names):
    """
    Parameters
    ----------
    clsname: string
        Name of the class to be created.

    field_names: list of strings
        Names of the field attributes of the class to be created.
    """
    item_cls = attr.make_class(clsname, {name: attr.ib() for name in field_names}, repr=True, cmp=True, frozen=True)
    func_eq_orig = item_cls.__eq__

    def func_eq_new(self, other):
        """
        Custom __eq__() method which also allows comparisons with
        tuples and dictionaries. This is mostly for convenience
        during testing.
        """

        if isinstance(other, self.__class__):
            return func_eq_orig(self, other)
        else:
            if isinstance(other, tuple):
                return attr.astuple(self) == other
            elif isinstance(other, dict):
                return attr.asdict(self) == other
            else:
                raise TypeError(
                    f"Tohu items have types that cannot be compared: "
                    "{self.__class__.__name__}, {other.__class__.__name__}"
                )

    item_cls.__eq__ = func_eq_new
    item_cls.field_names = field_names
    item_cls.as_dict = lambda self: attr.asdict(self)
    item_cls.as_tuple = lambda self: attr.astuple(self)
    item_cls.is_unset = False
    return item_cls

Prompt:
Add attribute 'is_unset' so that the interface is consistent with MissingTohuItemsCls

import attr

__all__ = ["make_tohu_items_class"]

def make_tohu_items_class(clsname, field_names):
    """
    Parameters
    ----------
    clsname: string
        Name of the class to be created.

    field_names: list of strings
        Names of the field attributes of the class to be created.
    """
    item_cls = attr.make_class(clsname, {name: attr.ib() for name in field_names}, repr=True, cmp=True, frozen=True)
    func_eq_orig = item_cls.__eq__

    def func_eq_new(self, other):
        """
        Custom __eq__() method which also allows comparisons with
        tuples and dictionaries. This is mostly for convenience
        during testing.
        """

        if isinstance(other, self.__class__):
            return func_eq_orig(self, other)
        else:
            if isinstance(other, tuple):
                return attr.astuple(self) == other
            elif isinstance(other, dict):
                return attr.asdict(self) == other
            else:
                raise TypeError(
                    f"Tohu items have types that cannot be compared: "
                    "{self.__class__.__name__}, {other.__class__.__name__}"
                )

    item_cls.__eq__ = func_eq_new
    item_cls.field_names = field_names
    item_cls.as_dict = lambda self: attr.asdict(self)
    item_cls.as_tuple = lambda self: attr.astuple(self)
    return item_cls


#!/usr/bin/env python

import os

component = os.getenv("COMPONENT")

if component == "ocaml":
    print "/repos/xen-dist-ocaml.hg"
if component == "api-libs":
    print "/repos/xen-api-libs-specs"

Response:
<REPLACE_OLD> "/repos/xen-api-libs-rpm-buildroot"

 <REPLACE_NEW> "/repos/xen-api-libs-specs"

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import os

component = os.getenv("COMPONENT")

if component == "ocaml":
    print "/repos/xen-dist-ocaml.hg"
if component == "api-libs":
    print "/repos/xen-api-libs-specs"

Prompt:
Change name of config repo for api-libs component

Signed-off-by: Jon Ludlam <e7e3380887a8f95cc9dc4f0d51dedc7e849a287a@eu.citrix.com>

#!/usr/bin/env python

import os

component = os.getenv("COMPONENT")

if component == "ocaml":
    print "/repos/xen-dist-ocaml.hg"
if component == "api-libs":
    print "/repos/xen-api-libs-rpm-buildroot"


from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess

logging.basicConfig()
scheduler = BlockingScheduler()

@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
    print("Run notifier")
    subprocess.check_call(
        "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
        shell=True)

# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
#     print("Run notifier")
#     subprocess.run(
#         "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
#         shell=True,
#         check=True)

scheduler.start()

Change call method for Python2.7

Change call method for Python2.7

Response:
<REPLACE_OLD> subprocess.run(
 <REPLACE_NEW> subprocess.check_call(
 <REPLACE_END> <REPLACE_OLD> shell=True,
        check=True)

# <REPLACE_NEW> shell=True)

# <REPLACE_END> <|endoftext|> from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess

logging.basicConfig()
scheduler = BlockingScheduler()

@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
    print("Run notifier")
    subprocess.check_call(
        "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
        shell=True)

# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
#     print("Run notifier")
#     subprocess.run(
#         "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
#         shell=True,
#         check=True)

scheduler.start()

Prompt:
Change call method for Python2.7

from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess

logging.basicConfig()
scheduler = BlockingScheduler()

@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
    print("Run notifier")
    subprocess.run(
        "notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
        shell=True,
        check=True)

# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
#     print("Run notifier")
#     subprocess.run(
#         "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
#         shell=True,
#         check=True)

scheduler.start()


from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task

class PSStats(RemoteStats):

    METRICS = (
        ("rss", 1024),    # kB -> B
        ("vsize", 1024),
    )

    PS_CMD = "ps -eo pid,rss,vsize,comm | " \
        "grep {} | grep -v grep | sort -n -k 2 | tail -n 1"

    TOP_CMD = "top -b n2 -d1 -p {0} | grep ^{0}"

    @parallel_task(server_side=True)
    def get_server_samples(self, process):
        return self.get_samples(process)

    @parallel_task(server_side=False)
    def get_client_samples(self, process):
        return self.get_samples(process)

    def get_samples(self, process):
        samples = {}

        stdout = self.run(self.PS_CMD.format(process))
        if stdout:
            for i, value in enumerate(stdout.split()[1:1 + len(self.METRICS)]):
                metric, multiplier = self.METRICS[i]
                title = "{}_{}".format(process, metric)
                samples[title] = float(value) * multiplier
            pid = stdout.split()[0]
        else:
            return samples

        stdout = self.run(self.TOP_CMD.format(pid))
        if stdout:
            title = "{}_cpu".format(process)
            samples[title] = float(stdout.split()[8])
        return samples

Use more precise grep expression

Response:
<REPLACE_OLD> {0}"

 <REPLACE_NEW> ^{0}"

 <REPLACE_END> <|endoftext|> from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task

class PSStats(RemoteStats):

    METRICS = (
        ("rss", 1024),    # kB -> B
        ("vsize", 1024),
    )

    PS_CMD = "ps -eo pid,rss,vsize,comm | " \
        "grep {} | grep -v grep | sort -n -k 2 | tail -n 1"

    TOP_CMD = "top -b n2 -d1 -p {0} | grep ^{0}"

    @parallel_task(server_side=True)
    def get_server_samples(self, process):
        return self.get_samples(process)

    @parallel_task(server_side=False)
    def get_client_samples(self, process):
        return self.get_samples(process)

    def get_samples(self, process):
        samples = {}

        stdout = self.run(self.PS_CMD.format(process))
        if stdout:
            for i, value in enumerate(stdout.split()[1:1 + len(self.METRICS)]):
                metric, multiplier = self.METRICS[i]
                title = "{}_{}".format(process, metric)
                samples[title] = float(value) * multiplier
            pid = stdout.split()[0]
        else:
            return samples

        stdout = self.run(self.TOP_CMD.format(pid))
        if stdout:
            title = "{}_cpu".format(process)
            samples[title] = float(stdout.split()[8])
        return samples

Prompt:
Use more precise grep expression

Otherwise we match wrong lines when memory stats contain PID.

Change-Id: I924c1b151ddaad8209445a514bf02a7af5d2e0e0
Reviewed-on: http://review.couchbase.org/79848
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Tested-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>

from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task

class PSStats(RemoteStats):

    METRICS = (
        ("rss", 1024),    # kB -> B
        ("vsize", 1024),
    )

    PS_CMD = "ps -eo pid,rss,vsize,comm | " \
        "grep {} | grep -v grep | sort -n -k 2 | tail -n 1"

    TOP_CMD = "top -b n2 -d1 -p {0} | grep {0}"

    @parallel_task(server_side=True)
    def get_server_samples(self, process):
        return self.get_samples(process)

    @parallel_task(server_side=False)
    def get_client_samples(self, process):
        return self.get_samples(process)

    def get_samples(self, process):
        samples = {}

        stdout = self.run(self.PS_CMD.format(process))
        if stdout:
            for i, value in enumerate(stdout.split()[1:1 + len(self.METRICS)]):
                metric, multiplier = self.METRICS[i]
                title = "{}_{}".format(process, metric)
                samples[title] = float(value) * multiplier
            pid = stdout.split()[0]
        else:
            return samples

        stdout = self.run(self.TOP_CMD.format(pid))
        if stdout:
            title = "{}_cpu".format(process)
            samples[title] = float(stdout.split()[8])
        return samples


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

from __future__ import absolute_import, unicode_literals

from peewee import Model, IntegerField, CharField

from zhihudaily.configs import Config

class BaseModel(Model):
    class Meta:
        database = Config.database

class Zhihudaily(BaseModel):
    date = IntegerField()
    json_news = CharField()
    display_date = CharField()

def create_tables():
    Config.database.connect()
    Config.database.create_tables([Zhihudaily])

Fix bug when create the datebase table

Fix bug when create the datebase table

Response:
<REPLACE_OLD> database.connect()
 <REPLACE_NEW> Config.database.connect()
 <REPLACE_END> <REPLACE_OLD> database.create_tables([Zhihudaily])
 <REPLACE_NEW> Config.database.create_tables([Zhihudaily])
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, unicode_literals

from peewee import Model, IntegerField, CharField

from zhihudaily.configs import Config

class BaseModel(Model):
    class Meta:
        database = Config.database

class Zhihudaily(BaseModel):
    date = IntegerField()
    json_news = CharField()
    display_date = CharField()

def create_tables():
    Config.database.connect()
    Config.database.create_tables([Zhihudaily])

Prompt:
Fix bug when create the datebase table

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

from __future__ import absolute_import, unicode_literals

from peewee import Model, IntegerField, CharField

from zhihudaily.configs import Config

class BaseModel(Model):
    class Meta:
        database = Config.database

class Zhihudaily(BaseModel):
    date = IntegerField()
    json_news = CharField()
    display_date = CharField()

def create_tables():
    database.connect()
    database.create_tables([Zhihudaily])


import binascii

from django.shortcuts import render
from django.contrib import messages
from django.core.mail import send_mail

from contact.forms import ContactForm

# Create your views here.

def contact(request):
    form_init = {
            'username': request.user.username,
            'ip_address': request.META.get('REMOTE_ADDR'),
            'email': request.user.email,
            }

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            messages.success(request, 'Success!')
        else:
            messages.error(request, 'Boo! Hiss!')
    else:
        form = ContactForm(initial=form_init)

    return render(request, 'contact/contact.html', {'form': form})

Clean up import, pre-fill email address

Response:
<REPLACE_OLD> render, redirect, get_object_or_404
from <REPLACE_NEW> render
from <REPLACE_END> <DELETE> django.db import IntegrityError, transaction
from django.conf import settings
from django.template.loader import render_to_string
from <DELETE_END> <REPLACE_OLD> send_mail
from django.core.urlresolvers import reverse
from django.http import Http404

from <REPLACE_NEW> send_mail

from <REPLACE_END> <INSERT> 'email': request.user.email,
            <INSERT_END> <REPLACE_OLD> messages.success('Success!')
 <REPLACE_NEW> messages.success(request, 'Success!')
 <REPLACE_END> <REPLACE_OLD> messages.error('Boo! <REPLACE_NEW> messages.error(request, 'Boo! <REPLACE_END> <|endoftext|> import binascii

from django.shortcuts import render
from django.contrib import messages
from django.core.mail import send_mail

from contact.forms import ContactForm

# Create your views here.

def contact(request):
    form_init = {
            'username': request.user.username,
            'ip_address': request.META.get('REMOTE_ADDR'),
            'email': request.user.email,
            }

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            messages.success(request, 'Success!')
        else:
            messages.error(request, 'Boo! Hiss!')
    else:
        form = ContactForm(initial=form_init)

    return render(request, 'contact/contact.html', {'form': form})

Prompt:
Clean up import, pre-fill email address

If user is logged in, their email address is automatically filled in for them.

Also fixed an error with the messages usage, namely I forgot to pass in the request object.

import binascii

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.db import IntegrityError, transaction
from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.http import Http404

from contact.forms import ContactForm

# Create your views here.

def contact(request):
    form_init = {
            'username': request.user.username,
            'ip_address': request.META.get('REMOTE_ADDR'),
            }

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            messages.success('Success!')
        else:
            messages.error('Boo! Hiss!')
    else:
        form = ContactForm(initial=form_init)

    return render(request, 'contact/contact.html', {'form': form})


from django.contrib import admin
from .models import Tviit

class TviitAdmin(admin.ModelAdmin):
    readonly_fields=('uuid',)

admin.site.register(Tviit, TviitAdmin)

Add uuid to be readable in Admin-panel

Add uuid to be readable in Admin-panel

Response:
<REPLACE_OLD> Tviit

admin.site.register(Tviit) <REPLACE_NEW> Tviit

class TviitAdmin(admin.ModelAdmin):
    readonly_fields=('uuid',)

admin.site.register(Tviit, TviitAdmin) <REPLACE_END> <|endoftext|> from django.contrib import admin
from .models import Tviit

class TviitAdmin(admin.ModelAdmin):
    readonly_fields=('uuid',)

admin.site.register(Tviit, TviitAdmin)

Prompt:
Add uuid to be readable in Admin-panel

from django.contrib import admin
from .models import Tviit

admin.site.register(Tviit)


#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

import os
import unittest

import SCons.Tool.javac

class pathoptTestCase(unittest.TestCase):
    def assert_pathopt(self, expect, path):
        popt = SCons.Tool.javac.pathopt('-foopath', 'FOOPATH')
        env = {'FOOPATH': path}
        actual = popt(None, None, env, None)
        self.assertEquals(expect, actual)

    def test_unset(self):
        self.assert_pathopt([], None)
        self.assert_pathopt([], '')

    def test_str(self):
        self.assert_pathopt(['-foopath', '/foo/bar'],
                            '/foo/bar')

    def test_list_str(self):
        self.assert_pathopt(['-foopath', '/foo%s/bar' % os.pathsep],
                            ['/foo', '/bar'])

    def test_uses_pathsep(self):
        save = os.pathsep
        try:
            os.pathsep = '!'
            self.assert_pathopt(['-foopath', 'foo!bar'],
                                ['foo', 'bar'])
        finally:
            os.pathsep = save

    def test_default(self):
        popt = SCons.Tool.javac.pathopt('-foopath', 'FOOPATH', default='DPATH')
        env = {'FOOPATH': ['/foo', '/bar'],
               'DPATH': '/baz'}

        expect = ['-foopath', os.pathsep.join(['/foo', '/bar', '/baz'])]
        actual = popt(None, None, env, None)
        self.assertEquals(expect, actual)

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

Add unit tests for SCons.Tool.javac (pathopt class only). This carefully avoids known bugs in order to have passing tests.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

import os
import unittest

import SCons.Tool.javac

class pathoptTestCase(unittest.TestCase):
    def assert_pathopt(self, expect, path):
        popt = SCons.Tool.javac.pathopt('-foopath', 'FOOPATH')
        env = {'FOOPATH': path}
        actual = popt(None, None, env, None)
        self.assertEquals(expect, actual)

    def test_unset(self):
        self.assert_pathopt([], None)
        self.assert_pathopt([], '')

    def test_str(self):
        self.assert_pathopt(['-foopath', '/foo/bar'],
                            '/foo/bar')

    def test_list_str(self):
        self.assert_pathopt(['-foopath', '/foo%s/bar' % os.pathsep],
                            ['/foo', '/bar'])

    def test_uses_pathsep(self):
        save = os.pathsep
        try:
            os.pathsep = '!'
            self.assert_pathopt(['-foopath', 'foo!bar'],
                                ['foo', 'bar'])
        finally:
            os.pathsep = save

    def test_default(self):
        popt = SCons.Tool.javac.pathopt('-foopath', 'FOOPATH', default='DPATH')
        env = {'FOOPATH': ['/foo', '/bar'],
               'DPATH': '/baz'}

        expect = ['-foopath', os.pathsep.join(['/foo', '/bar', '/baz'])]
        actual = popt(None, None, env, None)
        self.assertEquals(expect, actual)

if __name__ == "__main__":
    unittest.main()
 <REPLACE_END> <|endoftext|> #
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

import os
import unittest

import SCons.Tool.javac

class pathoptTestCase(unittest.TestCase):
    def assert_pathopt(self, expect, path):
        popt = SCons.Tool.javac.pathopt('-foopath', 'FOOPATH')
        env = {'FOOPATH': path}
        actual = popt(None, None, env, None)
        self.assertEquals(expect, actual)

    def test_unset(self):
        self.assert_pathopt([], None)
        self.assert_pathopt([], '')

    def test_str(self):
        self.assert_pathopt(['-foopath', '/foo/bar'],
                            '/foo/bar')

    def test_list_str(self):
        self.assert_pathopt(['-foopath', '/foo%s/bar' % os.pathsep],
                            ['/foo', '/bar'])

    def test_uses_pathsep(self):
        save = os.pathsep
        try:
            os.pathsep = '!'
            self.assert_pathopt(['-foopath', 'foo!bar'],
                                ['foo', 'bar'])
        finally:
            os.pathsep = save

    def test_default(self):
        popt = SCons.Tool.javac.pathopt('-foopath', 'FOOPATH', default='DPATH')
        env = {'FOOPATH': ['/foo', '/bar'],
               'DPATH': '/baz'}

        expect = ['-foopath', os.pathsep.join(['/foo', '/bar', '/baz'])]
        actual = popt(None, None, env, None)
        self.assertEquals(expect, actual)

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

Prompt:
Add unit tests for SCons.Tool.javac (pathopt class only).
This carefully avoids known bugs in order to have passing tests.


"""
Interactive Crossfilter
=======================
This example shows a multi-panel view of the same data, where you can interactively
select a portion of the data in any of the panels to highlight that portion in any
of the other panels.
"""
# category: interactive charts
import altair as alt
from vega_datasets import data

source = alt.UrlData(
    data.flights_2k.url,
    format={'parse': {'date': 'date'}}
)

brush = alt.selection(type='interval', encodings=['x'])

# Define the base chart, with the common parts of the
# background and highlights
base = alt.Chart().mark_bar().encode(
    x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)),
    y='count()'
).properties(
    width=160,
    height=130
)

# gray background with selection
background = base.encode(
    color=alt.value('#ddd')
).add_selection(brush)

# blue highlights on the transformed data
highlight = base.transform_filter(brush)

# layer the two charts & repeat
alt.layer(
    background,
    highlight,
    data=source
).transform_calculate(
    "time",
    "hours(datum.date)"
).repeat(column=["distance", "delay", "time"])

Update crossfilter to gray/blue scheme

Response:
<REPLACE_OLD> blue <REPLACE_NEW> gray <REPLACE_END> <REPLACE_OLD> base.add_selection(brush)

# yellow <REPLACE_NEW> base.encode(
    color=alt.value('#ddd')
).add_selection(brush)

# blue <REPLACE_END> <REPLACE_OLD> base.encode(
    color=alt.value('goldenrod')
).transform_filter(brush)

# <REPLACE_NEW> base.transform_filter(brush)

# <REPLACE_END> <|endoftext|> """
Interactive Crossfilter
=======================
This example shows a multi-panel view of the same data, where you can interactively
select a portion of the data in any of the panels to highlight that portion in any
of the other panels.
"""
# category: interactive charts
import altair as alt
from vega_datasets import data

source = alt.UrlData(
    data.flights_2k.url,
    format={'parse': {'date': 'date'}}
)

brush = alt.selection(type='interval', encodings=['x'])

# Define the base chart, with the common parts of the
# background and highlights
base = alt.Chart().mark_bar().encode(
    x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)),
    y='count()'
).properties(
    width=160,
    height=130
)

# gray background with selection
background = base.encode(
    color=alt.value('#ddd')
).add_selection(brush)

# blue highlights on the transformed data
highlight = base.transform_filter(brush)

# layer the two charts & repeat
alt.layer(
    background,
    highlight,
    data=source
).transform_calculate(
    "time",
    "hours(datum.date)"
).repeat(column=["distance", "delay", "time"])

Prompt:
Update crossfilter to gray/blue scheme

Same as in https://vega.github.io/editor/#/examples/vega-lite/interactive_layered_crossfilter
"""
Interactive Crossfilter
=======================
This example shows a multi-panel view of the same data, where you can interactively
select a portion of the data in any of the panels to highlight that portion in any
of the other panels.
"""
# category: interactive charts
import altair as alt
from vega_datasets import data

source = alt.UrlData(
    data.flights_2k.url,
    format={'parse': {'date': 'date'}}
)

brush = alt.selection(type='interval', encodings=['x'])

# Define the base chart, with the common parts of the
# background and highlights
base = alt.Chart().mark_bar().encode(
    x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)),
    y='count()'
).properties(
    width=160,
    height=130
)

# blue background with selection
background = base.add_selection(brush)

# yellow highlights on the transformed data
highlight = base.encode(
    color=alt.value('goldenrod')
).transform_filter(brush)

# layer the two charts & repeat
alt.layer(
    background,
    highlight,
    data=source
).transform_calculate(
    "time",
    "hours(datum.date)"
).repeat(column=["distance", "delay", "time"])


# -*- coding: utf-8 -*-
import string

def sanitise_string(messy_str):
    """Whitelist characters in a string"""
    valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
    return u''.join(char for char in messy_str if char in valid_chars).strip()

class Service(object):
    def __init__(self, numeric_id, detailed_data):
        self.numeric_id = numeric_id
        self.detailed_data = detailed_data

    def attribute_exists(self, key):
        return key in self.detailed_data

    def get_datum(self, key):
        datum = self.handle_bad_data(self.get(key))
        return datum

    def get(self, key):
        return self.detailed_data[key]

    def identifier(self):
        """Return a unique identifier for the service"""
        return self.get('Slug')

    def service_title(self):
        return self.get('Name of service')

    def abbreviated_department(self):
        return self.get('Abbr')

    def handle_bad_data(self, datum):
        # TODO: Should we be more explicit about non-requested (***) data?
        if datum == '' or datum == '-' or datum == '***':
            return None
        elif not isinstance(datum, (int, long, float, complex)):
            # If the value we get from the spreadsheet is not numeric, send
            # that to Backdrop as a null data point
            print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier())
            return None
        else:
            return datum

Response:
<INSERT> print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier())
            <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
import string

def sanitise_string(messy_str):
    """Whitelist characters in a string"""
    valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
    return u''.join(char for char in messy_str if char in valid_chars).strip()

class Service(object):
    def __init__(self, numeric_id, detailed_data):
        self.numeric_id = numeric_id
        self.detailed_data = detailed_data

    def attribute_exists(self, key):
        return key in self.detailed_data

    def get_datum(self, key):
        datum = self.handle_bad_data(self.get(key))
        return datum

    def get(self, key):
        return self.detailed_data[key]

    def identifier(self):
        """Return a unique identifier for the service"""
        return self.get('Slug')

    def service_title(self):
        return self.get('Name of service')

    def abbreviated_department(self):
        return self.get('Abbr')

    def handle_bad_data(self, datum):
        # TODO: Should we be more explicit about non-requested (***) data?
        if datum == '' or datum == '-' or datum == '***':
            return None
        elif not isinstance(datum, (int, long, float, complex)):
            # If the value we get from the spreadsheet is not numeric, send
            # that to Backdrop as a null data point
            print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier())
            return None
        else:
            return datum

Prompt:
Add log message if data we can't parse appears

If the datum isn't numeric and doesn't match the 'no data' pattern,
something has gone horribly wrong.

# -*- coding: utf-8 -*-
import string

def sanitise_string(messy_str):
    """Whitelist characters in a string"""
    valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
    return u''.join(char for char in messy_str if char in valid_chars).strip()

class Service(object):
    def __init__(self, numeric_id, detailed_data):
        self.numeric_id = numeric_id
        self.detailed_data = detailed_data

    def attribute_exists(self, key):
        return key in self.detailed_data

    def get_datum(self, key):
        datum = self.handle_bad_data(self.get(key))
        return datum

    def get(self, key):
        return self.detailed_data[key]

    def identifier(self):
        """Return a unique identifier for the service"""
        return self.get('Slug')

    def service_title(self):
        return self.get('Name of service')

    def abbreviated_department(self):
        return self.get('Abbr')

    def handle_bad_data(self, datum):
        # TODO: Should we be more explicit about non-requested (***) data?
        if datum == '' or datum == '-' or datum == '***':
            return None
        elif not isinstance(datum, (int, long, float, complex)):
            # If the value we get from the spreadsheet is not numeric, send
            # that to Backdrop as a null data point
            return None
        else:
            return datum


from django.views.generic.list import MultipleObjectMixin

__all__ = ('FilterFormMixin',)

class FilterFormMixin(MultipleObjectMixin):
    """
    Mixin that adds filtering behaviour for Class Based Views.
    Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
    get_context_data(self, **kwargs) method.
    """
    filter_form_cls = None
    use_filter_chaining = False

    def get_filter(self):
        return self.filter_form_cls(self.request.GET,
                                    runtime_context=self.get_runtime_context(),
                                    use_filter_chaining=self.use_filter_chaining)

    def get_queryset(self):
        qs = super(FilterFormMixin, self).get_queryset()
        qs = self.get_filter().filter(qs).distinct()
        return qs

    def get_context_data(self, **kwargs):
        context = super(FilterFormMixin, self).get_context_data(**kwargs)
        context['filterform'] = self.get_filter()
        return context

    def get_runtime_context(self):
        return {'user': self.request.user}

Response:
<DELETE> try:
    <DELETE_END> <REPLACE_OLD> django.views.generic.base <REPLACE_NEW> django.views.generic.list <REPLACE_END> <REPLACE_OLD> ContextMixin as mixin_base
except ImportError:
    mixin_base = object

__all__ <REPLACE_NEW> MultipleObjectMixin

__all__ <REPLACE_END> <REPLACE_OLD> FilterFormMixin(mixin_base):
 <REPLACE_NEW> FilterFormMixin(MultipleObjectMixin):
 <REPLACE_END> <|endoftext|> from django.views.generic.list import MultipleObjectMixin

__all__ = ('FilterFormMixin',)

class FilterFormMixin(MultipleObjectMixin):
    """
    Mixin that adds filtering behaviour for Class Based Views.
    Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
    get_context_data(self, **kwargs) method.
    """
    filter_form_cls = None
    use_filter_chaining = False

    def get_filter(self):
        return self.filter_form_cls(self.request.GET,
                                    runtime_context=self.get_runtime_context(),
                                    use_filter_chaining=self.use_filter_chaining)

    def get_queryset(self):
        qs = super(FilterFormMixin, self).get_queryset()
        qs = self.get_filter().filter(qs).distinct()
        return qs

    def get_context_data(self, **kwargs):
        context = super(FilterFormMixin, self).get_context_data(**kwargs)
        context['filterform'] = self.get_filter()
        return context

    def get_runtime_context(self):
        return {'user': self.request.user}

Prompt:
Set base class for view mixin to MultipleObjectMixin

try:
    from django.views.generic.base import ContextMixin as mixin_base
except ImportError:
    mixin_base = object

__all__ = ('FilterFormMixin',)

class FilterFormMixin(mixin_base):
    """
    Mixin that adds filtering behaviour for Class Based Views.
    Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and
    get_context_data(self, **kwargs) method.
    """
    filter_form_cls = None
    use_filter_chaining = False

    def get_filter(self):
        return self.filter_form_cls(self.request.GET,
                                    runtime_context=self.get_runtime_context(),
                                    use_filter_chaining=self.use_filter_chaining)

    def get_queryset(self):
        qs = super(FilterFormMixin, self).get_queryset()
        qs = self.get_filter().filter(qs).distinct()
        return qs

    def get_context_data(self, **kwargs):
        context = super(FilterFormMixin, self).get_context_data(**kwargs)
        context['filterform'] = self.get_filter()
        return context

    def get_runtime_context(self):
        return {'user': self.request.user}


# coding=utf-8

import types
import pprint
import config

class Driver(object):

    def __init__(self):
        self.driver_type = self.__class__.__name__
        # Get credentials from conf files for CMDB
        pass

    def get_driver_type(self):
            return self.driver_type

    def get_ci(self,ci):
        pass

    def push_ci(self,ci):
        pass

class Itop(Driver):

    def get_ci(self,ci):
        print "Get from itop"
        return True

    def push_ci(self):
        pass

class Redfish(Driver):

    def get_ci(self,ci):
        print "Get from redfish"
        return True

class Ironic(Driver):
    pass

class Mondorescue(Driver):
    pass

class Fakecmdb(Driver):
    pass

class Fakeprovider(Driver):

    def get_ci(self,ci):
        import app
        # Simulate a driver that will provide Manager data.

        # TODO a connect method must be implemented as

        # Assuming the connection is ok.

        # Now create a manager model from reference model.
        ci.ci_type = "Manager"
        ci.data = config.alexandria.model.Manager.copy()

        if ci.data is config.alexandria.model.Manager:
            print "identical"

        pp = pprint.PrettyPrinter(indent=4)

        pp.pprint(ci.data)

class DriverCollection(list):
    pass

Response:
<INSERT> pprint
import <INSERT_END> <REPLACE_OLD> config.alexandria.model.Manager

class <REPLACE_NEW> config.alexandria.model.Manager.copy()

        if ci.data is config.alexandria.model.Manager:
            print "identical"

        pp = pprint.PrettyPrinter(indent=4)

        pp.pprint(ci.data)

class <REPLACE_END> <|endoftext|> # coding=utf-8

import types
import pprint
import config

class Driver(object):

    def __init__(self):
        self.driver_type = self.__class__.__name__
        # Get credentials from conf files for CMDB
        pass

    def get_driver_type(self):
            return self.driver_type

    def get_ci(self,ci):
        pass

    def push_ci(self,ci):
        pass

class Itop(Driver):

    def get_ci(self,ci):
        print "Get from itop"
        return True

    def push_ci(self):
        pass

class Redfish(Driver):

    def get_ci(self,ci):
        print "Get from redfish"
        return True

class Ironic(Driver):
    pass

class Mondorescue(Driver):
    pass

class Fakecmdb(Driver):
    pass

class Fakeprovider(Driver):

    def get_ci(self,ci):
        import app
        # Simulate a driver that will provide Manager data.

        # TODO a connect method must be implemented as

        # Assuming the connection is ok.

        # Now create a manager model from reference model.
        ci.ci_type = "Manager"
        ci.data = config.alexandria.model.Manager.copy()

        if ci.data is config.alexandria.model.Manager:
            print "identical"

        pp = pprint.PrettyPrinter(indent=4)

        pp.pprint(ci.data)

class DriverCollection(list):
    pass

Prompt:
Copy reference object example.
This commit is just implemented to validate the medhod.
But this is not conveniant, because reference models must not be
changed.
So next step is to make them private attributes.

# coding=utf-8

import types
import config

class Driver(object):

    def __init__(self):
        self.driver_type = self.__class__.__name__
        # Get credentials from conf files for CMDB
        pass

    def get_driver_type(self):
            return self.driver_type

    def get_ci(self,ci):
        pass

    def push_ci(self,ci):
        pass

class Itop(Driver):

    def get_ci(self,ci):
        print "Get from itop"
        return True

    def push_ci(self):
        pass

class Redfish(Driver):

    def get_ci(self,ci):
        print "Get from redfish"
        return True

class Ironic(Driver):
    pass

class Mondorescue(Driver):
    pass

class Fakecmdb(Driver):
    pass

class Fakeprovider(Driver):

    def get_ci(self,ci):
        import app
        # Simulate a driver that will provide Manager data.

        # TODO a connect method must be implemented as

        # Assuming the connection is ok.

        # Now create a manager model from reference model.
        ci.ci_type = "Manager"
        ci.data = config.alexandria.model.Manager

class DriverCollection(list):
    pass


import os
import sys
import setuptools
if sys.version_info[0] < 3:
    from codecs import open

def local_file(name):
    return os.path.relpath(os.path.join(os.path.dirname(__file__), name))

README = local_file("README.rst")

with open(local_file("src/stratis_cli/_version.py")) as o:
        exec(o.read())

setuptools.setup(
    name='stratis-cli',
    version=__version__,
    author='Anne Mulhern',
    author_email='amulhern@redhat.com',
    description='prototype stratis cli',
    long_description=open(README, encoding='utf-8').read(),
    platforms=['Linux'],
    license='GPL 2+',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Libraries',
        ],
    install_requires = [
        'dbus-python'
    ],
    package_dir={"": "src"},
    packages=setuptools.find_packages("src"),
    scripts=['bin/stratis']
    )

Make stratis an installable script.

Response:
<INSERT> scripts=['bin/stratis']
    <INSERT_END> <|endoftext|> import os
import sys
import setuptools
if sys.version_info[0] < 3:
    from codecs import open

def local_file(name):
    return os.path.relpath(os.path.join(os.path.dirname(__file__), name))

README = local_file("README.rst")

with open(local_file("src/stratis_cli/_version.py")) as o:
        exec(o.read())

setuptools.setup(
    name='stratis-cli',
    version=__version__,
    author='Anne Mulhern',
    author_email='amulhern@redhat.com',
    description='prototype stratis cli',
    long_description=open(README, encoding='utf-8').read(),
    platforms=['Linux'],
    license='GPL 2+',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Libraries',
        ],
    install_requires = [
        'dbus-python'
    ],
    package_dir={"": "src"},
    packages=setuptools.find_packages("src"),
    scripts=['bin/stratis']
    )

Prompt:
Make stratis an installable script.

Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>

import os
import sys
import setuptools
if sys.version_info[0] < 3:
    from codecs import open

def local_file(name):
    return os.path.relpath(os.path.join(os.path.dirname(__file__), name))

README = local_file("README.rst")

with open(local_file("src/stratis_cli/_version.py")) as o:
        exec(o.read())

setuptools.setup(
    name='stratis-cli',
    version=__version__,
    author='Anne Mulhern',
    author_email='amulhern@redhat.com',
    description='prototype stratis cli',
    long_description=open(README, encoding='utf-8').read(),
    platforms=['Linux'],
    license='GPL 2+',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Software Development :: Libraries',
        ],
    install_requires = [
        'dbus-python'
    ],
    package_dir={"": "src"},
    packages=setuptools.find_packages("src"),
    )


import sympy

x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2

df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))

xs = sympy.solve([df_dx1, df_dx2], [x1, x2])

H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
lambda_xs = H_xs.eigenvals()

count = 0
for i in lambda_xs.keys():
    if i.evalf() <= 0:
        count += 1

if count == 0:
    print 'Local minima'
elif count == len(lambda_xs.keys()):
    print 'Lacal maxima'
else:
    print 'Saddle point'

Response:
<REPLACE_OLD> (x2,xs[0][1])])

flag <REPLACE_NEW> (x2,xs[0][1])])
lambda_xs <REPLACE_END> <REPLACE_OLD> True
for <REPLACE_NEW> H_xs.eigenvals()

count = 0
for <REPLACE_END> <REPLACE_OLD> H_xs.eigenvals().keys():
 <REPLACE_NEW> lambda_xs.keys():
 <REPLACE_END> <REPLACE_OLD> flag = False
        break

if flag:
 <REPLACE_NEW> count += 1

if count == 0:
 <REPLACE_END> <REPLACE_OLD> 'Stationary point'
else:
 <REPLACE_NEW> 'Local minima'
elif count == len(lambda_xs.keys()):
    print 'Lacal maxima'
else:
 <REPLACE_END> <|endoftext|> import sympy

x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2

df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))

xs = sympy.solve([df_dx1, df_dx2], [x1, x2])

H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])
lambda_xs = H_xs.eigenvals()

count = 0
for i in lambda_xs.keys():
    if i.evalf() <= 0:
        count += 1

if count == 0:
    print 'Local minima'
elif count == len(lambda_xs.keys()):
    print 'Lacal maxima'
else:
    print 'Saddle point'

Prompt:
Fix decision about minima, maxima and saddle point

import sympy

x1, x2 = sympy.symbols('x1 x2')
f = 100*(x2 - x1**2)**2 + (1-x1)**2

df_dx1 = sympy.diff(f,x1)
df_dx2 = sympy.diff(f,x2)
H = sympy.hessian(f, (x1, x2))

xs = sympy.solve([df_dx1, df_dx2], [x1, x2])

H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])])

flag = True
for i in H_xs.eigenvals().keys():
    if i.evalf() <= 0:
        flag = False
        break

if flag:
    print 'Stationary point'
else:
    print 'Saddle point'


import app.selector as selector
import app.applier as applier

from app.rules import rules

def rule_representation(rule):
    '''Takes a Rule and returns a list of strings which represent it, in the
    form [name, target, replacement, environment]'''
    return [rule.name, rule.target, rule.replacement, rule.environments[0][1]]

def rewrite(words, rewrite_rules, to='ipa'):
    '''Rewrite a list of words according to a list of tuple rules of form
    (plain, ipa), in direction given by target.'''
    modified = []

    for word in words:
        for rule in rewrite_rules:
            if to == 'ipa':
                word = word.replace(rule[0], rule[1])
            elif to == 'plain':
                word = word.replace(rule[1], rule[0])
        modified.append(word)

    return modified

def evolve(words, generations=5, rewrite_rules=[]):
    '''Evolves the language specified by:

        words: list [strings]

    for the given number of generations. One sound change is applied per
    generation.'''

    # Apply the given transcription rules
    words = rewrite(words, rewrite_rules, to='ipa')

    changes = []

    for _ in range(generations):

        # Try to select a valid rule
        try:
            sound_change = selector.select_rule(words, rules)
        # If there aren't any, finish early by breaking from the loop.
        except ValueError:
            break

        changes.append(rule_representation(sound_change))
        print(sound_change)
        words = applier.apply_rule(words, sound_change)

    # Convert back to orthographic representation using the given transcription
    # rules
    words = rewrite(words, rewrite_rules, to='plain')

    return words, changes

Add transcription to and from IPA

Add transcription to and from IPA

Response:
<INSERT> rewrite(words, rewrite_rules, to='ipa'):
    '''Rewrite a list of words according to a list of tuple rules of form
    (plain, ipa), in direction given by target.'''
    modified = []

    for word in words:
        for rule in rewrite_rules:
            if to == 'ipa':
                word = word.replace(rule[0], rule[1])
            elif to == 'plain':
                word = word.replace(rule[1], rule[0])
        modified.append(word)

    return modified

def <INSERT_END> <INSERT>    # Apply the given transcription rules
    words = rewrite(words, rewrite_rules, to='ipa')

 <INSERT_END> <INSERT> # Convert back to orthographic representation using the given transcription
    # rules
    words = rewrite(words, rewrite_rules, to='plain')

    <INSERT_END> <|endoftext|> import app.selector as selector
import app.applier as applier

from app.rules import rules

def rule_representation(rule):
    '''Takes a Rule and returns a list of strings which represent it, in the
    form [name, target, replacement, environment]'''
    return [rule.name, rule.target, rule.replacement, rule.environments[0][1]]

def rewrite(words, rewrite_rules, to='ipa'):
    '''Rewrite a list of words according to a list of tuple rules of form
    (plain, ipa), in direction given by target.'''
    modified = []

    for word in words:
        for rule in rewrite_rules:
            if to == 'ipa':
                word = word.replace(rule[0], rule[1])
            elif to == 'plain':
                word = word.replace(rule[1], rule[0])
        modified.append(word)

    return modified

def evolve(words, generations=5, rewrite_rules=[]):
    '''Evolves the language specified by:

        words: list [strings]

    for the given number of generations. One sound change is applied per
    generation.'''

    # Apply the given transcription rules
    words = rewrite(words, rewrite_rules, to='ipa')

    changes = []

    for _ in range(generations):

        # Try to select a valid rule
        try:
            sound_change = selector.select_rule(words, rules)
        # If there aren't any, finish early by breaking from the loop.
        except ValueError:
            break

        changes.append(rule_representation(sound_change))
        print(sound_change)
        words = applier.apply_rule(words, sound_change)

    # Convert back to orthographic representation using the given transcription
    # rules
    words = rewrite(words, rewrite_rules, to='plain')

    return words, changes

Prompt:
Add transcription to and from IPA

import app.selector as selector
import app.applier as applier

from app.rules import rules

def rule_representation(rule):
    '''Takes a Rule and returns a list of strings which represent it, in the
    form [name, target, replacement, environment]'''
    return [rule.name, rule.target, rule.replacement, rule.environments[0][1]]

def evolve(words, generations=5, rewrite_rules=[]):
    '''Evolves the language specified by:

        words: list [strings]

    for the given number of generations. One sound change is applied per
    generation.'''

    changes = []

    for _ in range(generations):

        # Try to select a valid rule
        try:
            sound_change = selector.select_rule(words, rules)
        # If there aren't any, finish early by breaking from the loop.
        except ValueError:
            break

        changes.append(rule_representation(sound_change))
        print(sound_change)
        words = applier.apply_rule(words, sound_change)

    return words, changes


from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format

import re

sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
                                message="Must be valid sha1 sum")
tag_regex = re.compile(r'^[A-Za-z][\w\-\.]+[A-Za-z]$')

def tag_validator(value):
    if not tag_regex.match(value):
        msg = "Must be letters and numbers separated "
        msg += "by dashes, dots, or underscores"
        raise ValidationError(msg)
    if not check_ref_format('refs/tags/' + value):
        msg = "Invalid tag. Tags must adhere to ref formats defined here: "
        msg += "https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"
        raise ValidationError(msg)

Make dulwich check the tag.

Make dulwich check the tag.

Response:
<REPLACE_OLD> RegexValidator

sha1_validator <REPLACE_NEW> RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format

import re

sha1_validator <REPLACE_END> <REPLACE_OLD> sum")
tag_validator <REPLACE_NEW> sum")
tag_regex <REPLACE_END> <REPLACE_OLD> RegexValidator(regex="^[A-Za-z][\w\-\.]+[A-Za-z]$",
 <REPLACE_NEW> re.compile(r'^[A-Za-z][\w\-\.]+[A-Za-z]$')

def tag_validator(value):
    if not tag_regex.match(value):
 <REPLACE_END> <INSERT> msg = "Must be letters and numbers separated "
 <INSERT_END> <INSERT> msg += "by dashes, dots, or underscores"
 <INSERT_END> <INSERT> raise ValidationError(msg)
    if not check_ref_format('refs/tags/' + value):
 <INSERT_END> <REPLACE_OLD>   message="Must be letters and numbers" +
 <REPLACE_NEW> msg = "Invalid tag. Tags must adhere to ref formats defined here: "
 <REPLACE_END> <INSERT> msg += "https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"
 <INSERT_END> <REPLACE_OLD>                 " separated by dashes, dots, or underscores")
 <REPLACE_NEW> raise ValidationError(msg)
 <REPLACE_END> <|endoftext|> from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format

import re

sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
                                message="Must be valid sha1 sum")
tag_regex = re.compile(r'^[A-Za-z][\w\-\.]+[A-Za-z]$')

def tag_validator(value):
    if not tag_regex.match(value):
        msg = "Must be letters and numbers separated "
        msg += "by dashes, dots, or underscores"
        raise ValidationError(msg)
    if not check_ref_format('refs/tags/' + value):
        msg = "Invalid tag. Tags must adhere to ref formats defined here: "
        msg += "https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"
        raise ValidationError(msg)

Prompt:
Make dulwich check the tag.

from django.core.validators import RegexValidator

sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
                                message="Must be valid sha1 sum")
tag_validator = RegexValidator(regex="^[A-Za-z][\w\-\.]+[A-Za-z]$",
                               message="Must be letters and numbers" +
                               " separated by dashes, dots, or underscores")


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

import unittest

from tricircle.common import exceptions
from tricircle.common import utils

class TricircleUtilsTestCase(unittest.TestCase):
    def test_check_string_length(self):
        self.assertIsNone(utils.check_string_length(
                          'test', 'name', max_len=255))
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          11, 'name', max_len=255)
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          '', 'name', min_len=1)
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          'a' * 256, 'name', max_len=255)

Add utils's check_string_length test case

1. What is the problem
Tricircle does not have utils module's test case

2. What is the solution to the problem
Implement related test case

3. What the features need to be implemented to the Tricircle
No new features

Change-Id: I42e54cfe310349578ae0605789249acbc349f5e4

Response:
<REPLACE_OLD>  <REPLACE_NEW>
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import unittest

from tricircle.common import exceptions
from tricircle.common import utils

class TricircleUtilsTestCase(unittest.TestCase):
    def test_check_string_length(self):
        self.assertIsNone(utils.check_string_length(
                          'test', 'name', max_len=255))
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          11, 'name', max_len=255)
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          '', 'name', min_len=1)
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          'a' * 256, 'name', max_len=255)
 <REPLACE_END> <|endoftext|>
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import unittest

from tricircle.common import exceptions
from tricircle.common import utils

class TricircleUtilsTestCase(unittest.TestCase):
    def test_check_string_length(self):
        self.assertIsNone(utils.check_string_length(
                          'test', 'name', max_len=255))
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          11, 'name', max_len=255)
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          '', 'name', min_len=1)
        self.assertRaises(exceptions.InvalidInput,
                          utils.check_string_length,
                          'a' * 256, 'name', max_len=255)

Prompt:
Add utils's check_string_length test case

1. What is the problem
Tricircle does not have utils module's test case

2. What is the solution to the problem
Implement related test case

3. What the features need to be implemented to the Tricircle
No new features

Change-Id: I42e54cfe310349578ae0605789249acbc349f5e4


#!/usr/bin/env python

import json
import rethinkdb as r
import sys
import optparse

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-p", "--port", dest="port",
                      help="rethinkdb port", default=30815)
    parser.add_option("-f", "--file", dest="filename",
                      help="json file", type="string")
    (options, args) = parser.parse_args()
    if options.filename is None:
        print "You must specify json file"
        sys.exit(1)
    conn = r.connect('localhost', int(options.port), db='materialscommons')
    json_data = open(options.filename)
    print "Loading template file: %s" % (options.filename)
    data = json.load(json_data)
    existing = r.table('templates').get(data['id']).run(conn)
    if existing:
        r.table('templates').get(data['id']).delete().run(conn)
        r.table('templates').insert(data).run(conn)
        print 'template deleted and re-inserted into the database'
    else:
        r.table('templates').insert(data).run(conn)
        print 'template inserted into the database'

Response:
<INSERT> print "Loading template file: %s" % (options.filename)
    <INSERT_END> <|endoftext|> #!/usr/bin/env python

import json
import rethinkdb as r
import sys
import optparse

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-p", "--port", dest="port",
                      help="rethinkdb port", default=30815)
    parser.add_option("-f", "--file", dest="filename",
                      help="json file", type="string")
    (options, args) = parser.parse_args()
    if options.filename is None:
        print "You must specify json file"
        sys.exit(1)
    conn = r.connect('localhost', int(options.port), db='materialscommons')
    json_data = open(options.filename)
    print "Loading template file: %s" % (options.filename)
    data = json.load(json_data)
    existing = r.table('templates').get(data['id']).run(conn)
    if existing:
        r.table('templates').get(data['id']).delete().run(conn)
        r.table('templates').insert(data).run(conn)
        print 'template deleted and re-inserted into the database'
    else:
        r.table('templates').insert(data).run(conn)
        print 'template inserted into the database'

Prompt:
Update script to show which file it is loading.

#!/usr/bin/env python

import json
import rethinkdb as r
import sys
import optparse

if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option("-p", "--port", dest="port",
                      help="rethinkdb port", default=30815)
    parser.add_option("-f", "--file", dest="filename",
                      help="json file", type="string")
    (options, args) = parser.parse_args()
    if options.filename is None:
        print "You must specify json file"
        sys.exit(1)
    conn = r.connect('localhost', int(options.port), db='materialscommons')
    json_data = open(options.filename)
    data = json.load(json_data)
    existing = r.table('templates').get(data['id']).run(conn)
    if existing:
        r.table('templates').get(data['id']).delete().run(conn)
        r.table('templates').insert(data).run(conn)
        print 'template deleted and re-inserted into the database'
    else:
        r.table('templates').insert(data).run(conn)
        print 'template inserted into the database'


# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.

import logging
from awx import __version__ as tower_version

# Prepare the AWX environment.
from awx import prepare_env
prepare_env()

from django.core.wsgi import get_wsgi_application

"""
WSGI config for AWX project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""

logger = logging.getLogger('awx.main.models.jobs')
try:
    fd = open("/var/lib/awx/.tower_version", "r")
    if fd.read().strip() != tower_version:
        raise Exception()
except Exception:
    logger.error("Missing or incorrect metadata for Tower version.  Ensure Tower was installed using the setup playbook.")
    raise Exception("Missing or incorrect metadata for Tower version.  Ensure Tower was installed using the setup playbook.")

# Return the default Django WSGI application.
application = get_wsgi_application()

Response:
<DELETE> django.core.wsgi import get_wsgi_application
from awx import prepare_env
from <DELETE_END> <REPLACE_OLD> tower_version

"""
WSGI <REPLACE_NEW> tower_version

# Prepare the AWX environment.
from awx import prepare_env
prepare_env()

from django.core.wsgi import get_wsgi_application

"""
WSGI <REPLACE_END> <REPLACE_OLD> see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""

# Prepare the AWX environment.
prepare_env()

logger <REPLACE_NEW> see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""

logger <REPLACE_END> <|endoftext|> # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.

import logging
from awx import __version__ as tower_version

# Prepare the AWX environment.
from awx import prepare_env
prepare_env()

from django.core.wsgi import get_wsgi_application

"""
WSGI config for AWX project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""

logger = logging.getLogger('awx.main.models.jobs')
try:
    fd = open("/var/lib/awx/.tower_version", "r")
    if fd.read().strip() != tower_version:
        raise Exception()
except Exception:
    logger.error("Missing or incorrect metadata for Tower version.  Ensure Tower was installed using the setup playbook.")
    raise Exception("Missing or incorrect metadata for Tower version.  Ensure Tower was installed using the setup playbook.")

# Return the default Django WSGI application.
application = get_wsgi_application()

Prompt:
Fix import error by calling prepare_env first

# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.

import logging
from django.core.wsgi import get_wsgi_application
from awx import prepare_env
from awx import __version__ as tower_version

"""
WSGI config for AWX project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""

# Prepare the AWX environment.
prepare_env()

logger = logging.getLogger('awx.main.models.jobs')
try:
    fd = open("/var/lib/awx/.tower_version", "r")
    if fd.read().strip() != tower_version:
        raise Exception()
except Exception:
    logger.error("Missing or incorrect metadata for Tower version.  Ensure Tower was installed using the setup playbook.")
    raise Exception("Missing or incorrect metadata for Tower version.  Ensure Tower was installed using the setup playbook.")

# Return the default Django WSGI application.
application = get_wsgi_application()


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

"""
test_generalwords
----------------------------------

All the tests for the generalword module. Simple module, simple tests.
"""

import unittest

from generalwords import get_word

class TestGeneralwords(unittest.TestCase):
    def setUp(self):
        pass

    def test_get_word(self):
        self.assertIsNotNone(get_word)

    def test_get_word_is_somewhat_random(self):
        sample_size = 100
        words = set(get_word() for i in range(sample_size))
        self.assertAlmostEqual(len(words), sample_size,
                               delta=int((sample_size * 0.1)))

    def tearDown(self):
        pass

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

Response:
<REPLACE_OLD> {get_word() <REPLACE_NEW> set(get_word() <REPLACE_END> <REPLACE_OLD> range(sample_size)}
 <REPLACE_NEW> range(sample_size))
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
test_generalwords
----------------------------------

All the tests for the generalword module. Simple module, simple tests.
"""

import unittest

from generalwords import get_word

class TestGeneralwords(unittest.TestCase):
    def setUp(self):
        pass

    def test_get_word(self):
        self.assertIsNotNone(get_word)

    def test_get_word_is_somewhat_random(self):
        sample_size = 100
        words = set(get_word() for i in range(sample_size))
        self.assertAlmostEqual(len(words), sample_size,
                               delta=int((sample_size * 0.1)))

    def tearDown(self):
        pass

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

Prompt:
Remove set-comprehensions so that tests will pass on 2.6

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

"""
test_generalwords
----------------------------------

All the tests for the generalword module. Simple module, simple tests.
"""

import unittest

from generalwords import get_word

class TestGeneralwords(unittest.TestCase):
    def setUp(self):
        pass

    def test_get_word(self):
        self.assertIsNotNone(get_word)

    def test_get_word_is_somewhat_random(self):
        sample_size = 100
        words = {get_word() for i in range(sample_size)}
        self.assertAlmostEqual(len(words), sample_size,
                               delta=int((sample_size * 0.1)))

    def tearDown(self):
        pass

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


import numpy as np
import pytest
import xray

from aospy_user import SpharmInterface

@pytest.fixture
def compute_vrtdiv(u, v):
    sphint = SpharmInterface(u, v)
    sphint.make_vectorwind()
    sphint.make_spharmt()

    vort, divg = sphint.vectorwind.vrtdiv()
    return sphint.to_xray(vort), sphint.to_xray(divg)

def test_vrtdiv():
    path = ('/archive/Spencer.Hill/am2/am2clim_reyoi/gfdl.ncrc2-default-prod/'
            'pp/atmos_level/ts/monthly/1yr/atmos_level.198301-198312.')

    # Vertically defined, sigma levels.
    u_arr = xray.open_dataset(path + 'ucomp.nc').ucomp
    v_arr = xray.open_dataset(path + 'vcomp.nc').vcomp
    vort, divg = compute_vrtdiv(u_arr, v_arr)
    assert vort.shape == u_arr.shape
    assert divg.shape == u_arr.shape
    np.testing.assert_array_equal(u_arr.lat, vort.lat)
    np.testing.assert_array_equal(u_arr.lon, vort.lon)
    np.testing.assert_array_equal(u_arr.time, vort.time)
    np.testing.assert_array_equal(u_arr.pfull, vort.pfull)

    # Not vertically defined.
    u0 = u_arr[:,0]
    v0 = v_arr[:,0]
    vort0, divg0 = compute_vrtdiv(u0, v0)
    assert vort0.shape == u0.shape
    assert divg0.shape == u0.shape

    # Dummy case: zeros everywhere
    u_arr_zeros = xray.DataArray(np.zeros_like(u_arr.values), dims=u_arr.dims,
                                 coords=u_arr.coords)
    v_arr_zeros = u_arr_zeros.copy()
    vort_zeros, divg_zeros = compute_vrtdiv(u_arr_zeros, v_arr_zeros)
    assert not vort_zeros.any()
    assert not divg_zeros.any()

Copy over tests from aospy-obj-lib

Copy over tests from aospy-obj-lib

Response:
<REPLACE_OLD>  <REPLACE_NEW> import numpy as np
import pytest
import xray

from aospy_user import SpharmInterface

@pytest.fixture
def compute_vrtdiv(u, v):
    sphint = SpharmInterface(u, v)
    sphint.make_vectorwind()
    sphint.make_spharmt()

    vort, divg = sphint.vectorwind.vrtdiv()
    return sphint.to_xray(vort), sphint.to_xray(divg)

def test_vrtdiv():
    path = ('/archive/Spencer.Hill/am2/am2clim_reyoi/gfdl.ncrc2-default-prod/'
            'pp/atmos_level/ts/monthly/1yr/atmos_level.198301-198312.')

    # Vertically defined, sigma levels.
    u_arr = xray.open_dataset(path + 'ucomp.nc').ucomp
    v_arr = xray.open_dataset(path + 'vcomp.nc').vcomp
    vort, divg = compute_vrtdiv(u_arr, v_arr)
    assert vort.shape == u_arr.shape
    assert divg.shape == u_arr.shape
    np.testing.assert_array_equal(u_arr.lat, vort.lat)
    np.testing.assert_array_equal(u_arr.lon, vort.lon)
    np.testing.assert_array_equal(u_arr.time, vort.time)
    np.testing.assert_array_equal(u_arr.pfull, vort.pfull)

    # Not vertically defined.
    u0 = u_arr[:,0]
    v0 = v_arr[:,0]
    vort0, divg0 = compute_vrtdiv(u0, v0)
    assert vort0.shape == u0.shape
    assert divg0.shape == u0.shape

    # Dummy case: zeros everywhere
    u_arr_zeros = xray.DataArray(np.zeros_like(u_arr.values), dims=u_arr.dims,
                                 coords=u_arr.coords)
    v_arr_zeros = u_arr_zeros.copy()
    vort_zeros, divg_zeros = compute_vrtdiv(u_arr_zeros, v_arr_zeros)
    assert not vort_zeros.any()
    assert not divg_zeros.any()
 <REPLACE_END> <|endoftext|> import numpy as np
import pytest
import xray

from aospy_user import SpharmInterface

@pytest.fixture
def compute_vrtdiv(u, v):
    sphint = SpharmInterface(u, v)
    sphint.make_vectorwind()
    sphint.make_spharmt()

    vort, divg = sphint.vectorwind.vrtdiv()
    return sphint.to_xray(vort), sphint.to_xray(divg)

def test_vrtdiv():
    path = ('/archive/Spencer.Hill/am2/am2clim_reyoi/gfdl.ncrc2-default-prod/'
            'pp/atmos_level/ts/monthly/1yr/atmos_level.198301-198312.')

    # Vertically defined, sigma levels.
    u_arr = xray.open_dataset(path + 'ucomp.nc').ucomp
    v_arr = xray.open_dataset(path + 'vcomp.nc').vcomp
    vort, divg = compute_vrtdiv(u_arr, v_arr)
    assert vort.shape == u_arr.shape
    assert divg.shape == u_arr.shape
    np.testing.assert_array_equal(u_arr.lat, vort.lat)
    np.testing.assert_array_equal(u_arr.lon, vort.lon)
    np.testing.assert_array_equal(u_arr.time, vort.time)
    np.testing.assert_array_equal(u_arr.pfull, vort.pfull)

    # Not vertically defined.
    u0 = u_arr[:,0]
    v0 = v_arr[:,0]
    vort0, divg0 = compute_vrtdiv(u0, v0)
    assert vort0.shape == u0.shape
    assert divg0.shape == u0.shape

    # Dummy case: zeros everywhere
    u_arr_zeros = xray.DataArray(np.zeros_like(u_arr.values), dims=u_arr.dims,
                                 coords=u_arr.coords)
    v_arr_zeros = u_arr_zeros.copy()
    vort_zeros, divg_zeros = compute_vrtdiv(u_arr_zeros, v_arr_zeros)
    assert not vort_zeros.any()
    assert not divg_zeros.any()

Prompt: Copy over tests from aospy-obj-lib


from decimal import *
from django.conf import settings
from currencies.models import Currency

def calculate_price(price, currency):
    try:
        factor = Currency.objects.get(code__exact=currency).factor
    except Currency.DoesNotExist:
        if settings.DEBUG:
            raise
        else:
            factor = Decimal('0.0')
    new_price = Decimal(price) * factor
    return new_price.quantize(Decimal('.01'), rounding=ROUND_UP)

Simplify a raise in debug mode

Simplify a raise in debug mode

Response:
<REPLACE_OLD> raise Currency.DoesNotExist
 <REPLACE_NEW> raise
 <REPLACE_END> <|endoftext|> from decimal import *
from django.conf import settings
from currencies.models import Currency

def calculate_price(price, currency):
    try:
        factor = Currency.objects.get(code__exact=currency).factor
    except Currency.DoesNotExist:
        if settings.DEBUG:
            raise
        else:
            factor = Decimal('0.0')
    new_price = Decimal(price) * factor
    return new_price.quantize(Decimal('.01'), rounding=ROUND_UP)

Prompt:
Simplify a raise in debug mode

from decimal import *
from django.conf import settings
from currencies.models import Currency

def calculate_price(price, currency):
    try:
        factor = Currency.objects.get(code__exact=currency).factor
    except Currency.DoesNotExist:
        if settings.DEBUG:
            raise Currency.DoesNotExist
        else:
            factor = Decimal('0.0')
    new_price = Decimal(price) * factor
    return new_price.quantize(Decimal('.01'), rounding=ROUND_UP)


from django import template

register = template.Library()

@register.filter
def post_process_fieldsets(fieldset):
    """
    Removes a few fields from FeinCMS admin inlines, those being
    ``id``, ``DELETE`` and ``ORDER`` currently.
    """

    excluded_fields = ('id', 'DELETE', 'ORDER')
    fieldset.fields = [f for f in fieldset.form.fields.keys() if f not in excluded_fields]

    for line in fieldset:
        yield line

Response:
<DELETE> process = fieldset.model_admin.verbose_name_plural.startswith('Feincms_Inline:')
    if process:
        # Exclude special fields and the primary key
        <DELETE_END> <DELETE>     <DELETE_END> <|endoftext|> from django import template

register = template.Library()

@register.filter
def post_process_fieldsets(fieldset):
    """
    Removes a few fields from FeinCMS admin inlines, those being
    ``id``, ``DELETE`` and ``ORDER`` currently.
    """

    excluded_fields = ('id', 'DELETE', 'ORDER')
    fieldset.fields = [f for f in fieldset.form.fields.keys() if f not in excluded_fields]

    for line in fieldset:
        yield line

Prompt:
Fix post_process_fieldsets: This filter is only called for FeinCMS inlines anyway

Thanks to mjl for the report and help in fixing the issue.

from django import template

register = template.Library()

@register.filter
def post_process_fieldsets(fieldset):
    """
    Removes a few fields from FeinCMS admin inlines, those being
    ``id``, ``DELETE`` and ``ORDER`` currently.
    """

    process = fieldset.model_admin.verbose_name_plural.startswith('Feincms_Inline:')
    if process:
        # Exclude special fields and the primary key
        excluded_fields = ('id', 'DELETE', 'ORDER')
        fieldset.fields = [f for f in fieldset.form.fields.keys() if f not in excluded_fields]

    for line in fieldset:
        yield line


import logging

from django import forms

from readthedocs.builds.models import VersionAlias, Version
from readthedocs.core.utils import trigger_build
from readthedocs.projects.models import Project
from readthedocs.projects.tasks import clear_artifacts

log = logging.getLogger(__name__)

class AliasForm(forms.ModelForm):

    class Meta:
        model = VersionAlias
        fields = (
            'project',
            'from_slug',
            'to_slug',
            'largest',
        )

    def __init__(self, instance=None, *args, **kwargs):
        super(AliasForm, self).__init__(instance=instance, *args, **kwargs)
        if instance:
            self.fields['project'].queryset = (Project.objects
                                               .filter(pk=instance.project.pk))

class VersionForm(forms.ModelForm):

    class Meta:
        model = Version
        fields = ['active', 'privacy_level', 'tags']

    def save(self, *args, **kwargs):
        obj = super(VersionForm, self).save(*args, **kwargs)
        if obj.active and not obj.built and not obj.uploaded:
            trigger_build(project=obj.project, version=obj)

    def clean(self):
        cleaned_data = super(VersionForm, self).clean()
        if self.instance.pk is not None:  # new instance only
            if self.instance.active is True and cleaned_data['active'] is False:
                log.info('Removing files for version %s' % self.instance.slug)
                clear_artifacts.delay(version_pk=self.instance.pk)
                self.instance.built = False
        return cleaned_data

Handle built state tracking on versions

Handle built state tracking on versions

Response:
<REPLACE_OLD> clear_artifacts.delay(version_pk=[self.instance.pk])
 <REPLACE_NEW> clear_artifacts.delay(version_pk=self.instance.pk)
                self.instance.built = False
 <REPLACE_END> <|endoftext|> import logging

from django import forms

from readthedocs.builds.models import VersionAlias, Version
from readthedocs.core.utils import trigger_build
from readthedocs.projects.models import Project
from readthedocs.projects.tasks import clear_artifacts

log = logging.getLogger(__name__)

class AliasForm(forms.ModelForm):

    class Meta:
        model = VersionAlias
        fields = (
            'project',
            'from_slug',
            'to_slug',
            'largest',
        )

    def __init__(self, instance=None, *args, **kwargs):
        super(AliasForm, self).__init__(instance=instance, *args, **kwargs)
        if instance:
            self.fields['project'].queryset = (Project.objects
                                               .filter(pk=instance.project.pk))

class VersionForm(forms.ModelForm):

    class Meta:
        model = Version
        fields = ['active', 'privacy_level', 'tags']

    def save(self, *args, **kwargs):
        obj = super(VersionForm, self).save(*args, **kwargs)
        if obj.active and not obj.built and not obj.uploaded:
            trigger_build(project=obj.project, version=obj)

    def clean(self):
        cleaned_data = super(VersionForm, self).clean()
        if self.instance.pk is not None:  # new instance only
            if self.instance.active is True and cleaned_data['active'] is False:
                log.info('Removing files for version %s' % self.instance.slug)
                clear_artifacts.delay(version_pk=self.instance.pk)
                self.instance.built = False
        return cleaned_data

Prompt:
Handle built state tracking on versions
import logging

from django import forms

from readthedocs.builds.models import VersionAlias, Version
from readthedocs.core.utils import trigger_build
from readthedocs.projects.models import Project
from readthedocs.projects.tasks import clear_artifacts

log = logging.getLogger(__name__)

class AliasForm(forms.ModelForm):

    class Meta:
        model = VersionAlias
        fields = (
            'project',
            'from_slug',
            'to_slug',
            'largest',
        )

    def __init__(self, instance=None, *args, **kwargs):
        super(AliasForm, self).__init__(instance=instance, *args, **kwargs)
        if instance:
            self.fields['project'].queryset = (Project.objects
                                               .filter(pk=instance.project.pk))

class VersionForm(forms.ModelForm):

    class Meta:
        model = Version
        fields = ['active', 'privacy_level', 'tags']

    def save(self, *args, **kwargs):
        obj = super(VersionForm, self).save(*args, **kwargs)
        if obj.active and not obj.built and not obj.uploaded:
            trigger_build(project=obj.project, version=obj)

    def clean(self):
        cleaned_data = super(VersionForm, self).clean()
        if self.instance.pk is not None:  # new instance only
            if self.instance.active is True and cleaned_data['active'] is False:
                log.info('Removing files for version %s' % self.instance.slug)
                clear_artifacts.delay(version_pk=[self.instance.pk])
        return cleaned_data


__author__ = 'tom'
from setuptools import setup

# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pythonhosted.org use
# 'python setup.py upload_sphinx'. Both uploads require 'python setup.py register' to be run, and will
# only work for Tom as they need the pypi account credentials.

setup(
    name='approxeng.input',
    version='0.6',
    description='Python game controller support using evDev for Raspberry Pi and other Linux systems',
    classifiers=['Programming Language :: Python :: 2.7'],
    url='https://github.com/ApproxEng/approxeng.input/',
    author='Tom Oinn',
    author_email='tomoinn@gmail.com',
    license='ASL2.0',
    packages=['approxeng.input'],
    install_requires=['evdev==0.6.4'],
    include_package_data=True,
    test_suite='nose.collector',
    tests_require=['nose'],
    dependency_links=[],
    zip_safe=False)

Change to use evdev 0.6.4

Response:
<REPLACE_OLD> install_requires=['evdev==0.5.0'],
 <REPLACE_NEW> install_requires=['evdev==0.6.4'],
 <REPLACE_END> <|endoftext|> __author__ = 'tom'
from setuptools import setup

# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pythonhosted.org use
# 'python setup.py upload_sphinx'. Both uploads require 'python setup.py register' to be run, and will
# only work for Tom as they need the pypi account credentials.

setup(
    name='approxeng.input',
    version='0.6',
    description='Python game controller support using evDev for Raspberry Pi and other Linux systems',
    classifiers=['Programming Language :: Python :: 2.7'],
    url='https://github.com/ApproxEng/approxeng.input/',
    author='Tom Oinn',
    author_email='tomoinn@gmail.com',
    license='ASL2.0',
    packages=['approxeng.input'],
    install_requires=['evdev==0.6.4'],
    include_package_data=True,
    test_suite='nose.collector',
    tests_require=['nose'],
    dependency_links=[],
    zip_safe=False)

Prompt:
Change to use evdev 0.6.4

Signed-off-by: tom <3abfbc22eec6ecd173d744487905db1fa6a502d5@gmail.com>

__author__ = 'tom'
from setuptools import setup

# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pythonhosted.org use
# 'python setup.py upload_sphinx'. Both uploads require 'python setup.py register' to be run, and will
# only work for Tom as they need the pypi account credentials.

setup(
    name='approxeng.input',
    version='0.6',
    description='Python game controller support using evDev for Raspberry Pi and other Linux systems',
    classifiers=['Programming Language :: Python :: 2.7'],
    url='https://github.com/ApproxEng/approxeng.input/',
    author='Tom Oinn',
    author_email='tomoinn@gmail.com',
    license='ASL2.0',
    packages=['approxeng.input'],
    install_requires=['evdev==0.5.0'],
    include_package_data=True,
    test_suite='nose.collector',
    tests_require=['nose'],
    dependency_links=[],
    zip_safe=False)


def test_cxx_import():
    from microscopes.mixture.model import \
        state, \
        bind, \
        initialize, \
        deserialize
    assert state
    assert bind
    assert initialize
    assert deserialize

Response:
<DELETE> fixed_state, <DELETE_END> <DELETE> bind_fixed, <DELETE_END> <DELETE> initialize_fixed, <DELETE_END> <REPLACE_OLD> deserialize, deserialize_fixed
 <REPLACE_NEW> deserialize
 <REPLACE_END> <REPLACE_OLD> state and fixed_state
 <REPLACE_NEW> state
 <REPLACE_END> <REPLACE_OLD> bind and bind_fixed
 <REPLACE_NEW> bind
 <REPLACE_END> <REPLACE_OLD> initialize and initialize_fixed
 <REPLACE_NEW> initialize
 <REPLACE_END> <REPLACE_OLD> deserialize and deserialize_fixed
 <REPLACE_NEW> deserialize
 <REPLACE_END> <|endoftext|> def test_cxx_import():
    from microscopes.mixture.model import \
        state, \
        bind, \
        initialize, \
        deserialize
    assert state
    assert bind
    assert initialize
    assert deserialize

Prompt:
Remove fixed references from test_cxx.py

def test_cxx_import():
    from microscopes.mixture.model import \
        state, fixed_state, \
        bind, bind_fixed, \
        initialize, initialize_fixed, \
        deserialize, deserialize_fixed
    assert state and fixed_state
    assert bind and bind_fixed
    assert initialize and initialize_fixed
    assert deserialize and deserialize_fixed