# 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 uuid

from openstack.network.v2 import security_group
from openstack.network.v2 import security_group_rule
from openstack.tests.functional import base

class TestSecurityGroupRule(base.BaseFunctionalTest):

    NAME = uuid.uuid4().hex
    IPV4 = 'IPv4'
    PROTO = 'tcp'
    PORT = 22
    DIR = 'ingress'
    ID = None
    RULE_ID = None

    @classmethod
    def setUpClass(cls):
        super(TestSecurityGroupRule, cls).setUpClass()
        sot = cls.conn.network.create_security_group(name=cls.NAME)
        assert isinstance(sot, security_group.SecurityGroup)
        cls.assertIs(cls.NAME, sot.name)
        cls.ID = sot.id
        rul = cls.conn.network.create_security_group_rule(
            direction=cls.DIR, ethertype=cls.IPV4,
            port_range_max=cls.PORT, port_range_min=cls.PORT,
            protocol=cls.PROTO, security_group_id=cls.ID)
        assert isinstance(rul, security_group_rule.SecurityGroupRule)
        cls.assertIs(cls.ID, rul.security_group_id)
        cls.RULE_ID = rul.id

    @classmethod
    def tearDownClass(cls):
        sot = cls.conn.network.delete_security_group_rule(cls.RULE_ID,
                                                          ignore_missing=False)
        cls.assertIs(None, sot)
        sot = cls.conn.network.delete_security_group(cls.ID,
                                                     ignore_missing=False)
        cls.assertIs(None, sot)

    def test_find(self):
        sot = self.conn.network.find_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)

    def test_get(self):
        sot = self.conn.network.get_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)
        self.assertEqual(self.DIR, sot.direction)
        self.assertEqual(self.PROTO, sot.protocol)
        self.assertEqual(self.PORT, sot.port_range_min)
        self.assertEqual(self.PORT, sot.port_range_max)
        self.assertEqual(self.ID, sot.security_group_id)

    def test_list(self):
        ids = [o.id for o in self.conn.network.security_group_rules()]
        self.assertIn(self.RULE_ID, ids)

Add functional tests for security group rule

Tests:
test_find
test_get
test_list

Change-Id: If54342ec8c57b926a5217d888a43dcd98223bd69

Response:
<REPLACE_OLD>  <REPLACE_NEW> # 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 uuid

from openstack.network.v2 import security_group
from openstack.network.v2 import security_group_rule
from openstack.tests.functional import base

class TestSecurityGroupRule(base.BaseFunctionalTest):

    NAME = uuid.uuid4().hex
    IPV4 = 'IPv4'
    PROTO = 'tcp'
    PORT = 22
    DIR = 'ingress'
    ID = None
    RULE_ID = None

    @classmethod
    def setUpClass(cls):
        super(TestSecurityGroupRule, cls).setUpClass()
        sot = cls.conn.network.create_security_group(name=cls.NAME)
        assert isinstance(sot, security_group.SecurityGroup)
        cls.assertIs(cls.NAME, sot.name)
        cls.ID = sot.id
        rul = cls.conn.network.create_security_group_rule(
            direction=cls.DIR, ethertype=cls.IPV4,
            port_range_max=cls.PORT, port_range_min=cls.PORT,
            protocol=cls.PROTO, security_group_id=cls.ID)
        assert isinstance(rul, security_group_rule.SecurityGroupRule)
        cls.assertIs(cls.ID, rul.security_group_id)
        cls.RULE_ID = rul.id

    @classmethod
    def tearDownClass(cls):
        sot = cls.conn.network.delete_security_group_rule(cls.RULE_ID,
                                                          ignore_missing=False)
        cls.assertIs(None, sot)
        sot = cls.conn.network.delete_security_group(cls.ID,
                                                     ignore_missing=False)
        cls.assertIs(None, sot)

    def test_find(self):
        sot = self.conn.network.find_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)

    def test_get(self):
        sot = self.conn.network.get_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)
        self.assertEqual(self.DIR, sot.direction)
        self.assertEqual(self.PROTO, sot.protocol)
        self.assertEqual(self.PORT, sot.port_range_min)
        self.assertEqual(self.PORT, sot.port_range_max)
        self.assertEqual(self.ID, sot.security_group_id)

    def test_list(self):
        ids = [o.id for o in self.conn.network.security_group_rules()]
        self.assertIn(self.RULE_ID, ids)
 <REPLACE_END> <|endoftext|> # 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 uuid

from openstack.network.v2 import security_group
from openstack.network.v2 import security_group_rule
from openstack.tests.functional import base

class TestSecurityGroupRule(base.BaseFunctionalTest):

    NAME = uuid.uuid4().hex
    IPV4 = 'IPv4'
    PROTO = 'tcp'
    PORT = 22
    DIR = 'ingress'
    ID = None
    RULE_ID = None

    @classmethod
    def setUpClass(cls):
        super(TestSecurityGroupRule, cls).setUpClass()
        sot = cls.conn.network.create_security_group(name=cls.NAME)
        assert isinstance(sot, security_group.SecurityGroup)
        cls.assertIs(cls.NAME, sot.name)
        cls.ID = sot.id
        rul = cls.conn.network.create_security_group_rule(
            direction=cls.DIR, ethertype=cls.IPV4,
            port_range_max=cls.PORT, port_range_min=cls.PORT,
            protocol=cls.PROTO, security_group_id=cls.ID)
        assert isinstance(rul, security_group_rule.SecurityGroupRule)
        cls.assertIs(cls.ID, rul.security_group_id)
        cls.RULE_ID = rul.id

    @classmethod
    def tearDownClass(cls):
        sot = cls.conn.network.delete_security_group_rule(cls.RULE_ID,
                                                          ignore_missing=False)
        cls.assertIs(None, sot)
        sot = cls.conn.network.delete_security_group(cls.ID,
                                                     ignore_missing=False)
        cls.assertIs(None, sot)

    def test_find(self):
        sot = self.conn.network.find_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)

    def test_get(self):
        sot = self.conn.network.get_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)
        self.assertEqual(self.DIR, sot.direction)
        self.assertEqual(self.PROTO, sot.protocol)
        self.assertEqual(self.PORT, sot.port_range_min)
        self.assertEqual(self.PORT, sot.port_range_max)
        self.assertEqual(self.ID, sot.security_group_id)

    def test_list(self):
        ids = [o.id for o in self.conn.network.security_group_rules()]
        self.assertIn(self.RULE_ID, ids)

Prompt:
Add functional tests for security group rule

Tests:
test_find
test_get
test_list

Change-Id: If54342ec8c57b926a5217d888a43dcd98223bd69


#  Copyright 2015-2016 Masayuki Yamamoto
#
#  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.
"""Unittest of configuration loading."""

import os
import unittest
from unittest import mock

from yanico import config

class TestUserPath(unittest.TestCase):
    """Test for yanico.config.user_path()."""

    @mock.patch.dict(os.environ, {'HOME': 'spam'})
    def test_path(self):
        """Expect filepath joinning '.yanico.conf' under $HOME."""
        if os.sep == '\\':
            expect = 'spam\\.yanico.conf'
        elif os.sep == '/':
            expect = 'spam/.yanico.conf'
        result = config.user_path()
        self.assertEqual(result, expect)

Add test case for user path

Response:
<REPLACE_OLD> unittest

class <REPLACE_NEW> os
import unittest
from unittest import mock

from yanico import config

class <REPLACE_END> <REPLACE_OLD> yanico.config.user_path()."""
 <REPLACE_NEW> yanico.config.user_path()."""

    @mock.patch.dict(os.environ, {'HOME': 'spam'})
    def test_path(self):
        """Expect filepath joinning '.yanico.conf' under $HOME."""
        if os.sep == '\\':
            expect = 'spam\\.yanico.conf'
        elif os.sep == '/':
            expect = 'spam/.yanico.conf'
        result = config.user_path()
        self.assertEqual(result, expect)
 <REPLACE_END> <|endoftext|> #  Copyright 2015-2016 Masayuki Yamamoto
#
#  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.
"""Unittest of configuration loading."""

import os
import unittest
from unittest import mock

from yanico import config

class TestUserPath(unittest.TestCase):
    """Test for yanico.config.user_path()."""

    @mock.patch.dict(os.environ, {'HOME': 'spam'})
    def test_path(self):
        """Expect filepath joinning '.yanico.conf' under $HOME."""
        if os.sep == '\\':
            expect = 'spam\\.yanico.conf'
        elif os.sep == '/':
            expect = 'spam/.yanico.conf'
        result = config.user_path()
        self.assertEqual(result, expect)

Prompt:
Add test case for user path

Expect filepath joinning '.yanico.conf' under $HOME.

#  Copyright 2015-2016 Masayuki Yamamoto
#
#  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.
"""Unittest of configuration loading."""

import unittest

class TestUserPath(unittest.TestCase):
    """Test for yanico.config.user_path()."""


"""
raven.transport.requests
~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from raven.conf import defaults
from raven.transport.http import HTTPTransport

try:
    import requests
    has_requests = True
except:
    has_requests = False

class RequestsHTTPTransport(HTTPTransport):

    scheme = ['requests+http', 'requests+https']

    def __init__(self, parsed_url, timeout=defaults.TIMEOUT, verify_ssl=True,
                 ca_certs=defaults.CA_BUNDLE):
        if not has_requests:
            raise ImportError('RequestsHTTPTransport requires requests.')

        super(RequestsHTTPTransport, self).__init__(parsed_url,
                                                    timeout=timeout,
                                                    verify_ssl=verify_ssl,
                                                    ca_certs=ca_certs)

        # remove the requests+ from the protocol, as it is not a real protocol
        self._url = self._url.split('+', 1)[-1]

    def send(self, data, headers):
        if self.verify_ssl:
            # If SSL verification is enabled use the provided CA bundle to
            # perform the verification.
            self.verify_ssl = self.ca_certs
        requests.post(self._url, data=data, headers=headers,
                      verify=self.verify_ssl, timeout=self.timeout)

Response:
<INSERT> raven.conf import defaults
from <INSERT_END> <REPLACE_OLD> parsed_url):
 <REPLACE_NEW> parsed_url, timeout=defaults.TIMEOUT, verify_ssl=True,
                 ca_certs=defaults.CA_BUNDLE):
 <REPLACE_END> <REPLACE_OLD> self).__init__(parsed_url)

 <REPLACE_NEW> self).__init__(parsed_url,
                                                    timeout=timeout,
                                                    verify_ssl=verify_ssl,
                                                    ca_certs=ca_certs)

 <REPLACE_END> <INSERT> if self.verify_ssl:
            # If SSL verification is enabled use the provided CA bundle to
            # perform the verification.
            self.verify_ssl = self.ca_certs
        <INSERT_END> <REPLACE_OLD> headers=headers)
 <REPLACE_NEW> headers=headers,
                      verify=self.verify_ssl, timeout=self.timeout)
 <REPLACE_END> <|endoftext|> """
raven.transport.requests
~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from raven.conf import defaults
from raven.transport.http import HTTPTransport

try:
    import requests
    has_requests = True
except:
    has_requests = False

class RequestsHTTPTransport(HTTPTransport):

    scheme = ['requests+http', 'requests+https']

    def __init__(self, parsed_url, timeout=defaults.TIMEOUT, verify_ssl=True,
                 ca_certs=defaults.CA_BUNDLE):
        if not has_requests:
            raise ImportError('RequestsHTTPTransport requires requests.')

        super(RequestsHTTPTransport, self).__init__(parsed_url,
                                                    timeout=timeout,
                                                    verify_ssl=verify_ssl,
                                                    ca_certs=ca_certs)

        # remove the requests+ from the protocol, as it is not a real protocol
        self._url = self._url.split('+', 1)[-1]

    def send(self, data, headers):
        if self.verify_ssl:
            # If SSL verification is enabled use the provided CA bundle to
            # perform the verification.
            self.verify_ssl = self.ca_certs
        requests.post(self._url, data=data, headers=headers,
                      verify=self.verify_ssl, timeout=self.timeout)

Prompt:
Add support for the verify_ssl, ca_certs and timeout parameters for the request transport.

"""
raven.transport.requests
~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from raven.transport.http import HTTPTransport

try:
    import requests
    has_requests = True
except:
    has_requests = False

class RequestsHTTPTransport(HTTPTransport):

    scheme = ['requests+http', 'requests+https']

    def __init__(self, parsed_url):
        if not has_requests:
            raise ImportError('RequestsHTTPTransport requires requests.')

        super(RequestsHTTPTransport, self).__init__(parsed_url)

        # remove the requests+ from the protocol, as it is not a real protocol
        self._url = self._url.split('+', 1)[-1]

    def send(self, data, headers):
        requests.post(self._url, data=data, headers=headers)


import requests

class ZabbixError(Exception):
    pass

class Api(object):
    def __init__(self, server='http://localhost/zabbix'):
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
        self.url = server + '/api_jsonrpc.php'
        self.auth = ''
        self.id = 0

    def do_request(self, method, params=None):
        json_payload = {
            'jsonrpc': '2.0',
            'method': method,
            'params': params or {},
            'auth': self.auth,
            'id': self.id,
        }
        self.id += 1
        response = self.session.post(self.url, data = json.dumps(json_payload))

        if response.status_code != 200:
            raise ZabbixError("HTTP ERROR %S: %S" % (response.status, response.reason))
        if response.text == '':
            raise ZabbixError("Received empty response")

        return response.json()

Response:
<INSERT> ZabbixError(Exception):
    pass

class <INSERT_END> <INSERT>    def do_request(self, method, params=None):
        json_payload = {
            'jsonrpc': '2.0',
            'method': method,
            'params': params or {},
            'auth': self.auth,
            'id': self.id,
        }
        self.id += 1
        response = self.session.post(self.url, data = json.dumps(json_payload))

        if response.status_code != 200:
            raise ZabbixError("HTTP ERROR %S: %S" % (response.status, response.reason))
        if response.text == '':
            raise ZabbixError("Received empty response")

        return response.json()

 <INSERT_END> <|endoftext|> import requests

class ZabbixError(Exception):
    pass

class Api(object):
    def __init__(self, server='http://localhost/zabbix'):
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
        self.url = server + '/api_jsonrpc.php'
        self.auth = ''
        self.id = 0

    def do_request(self, method, params=None):
        json_payload = {
            'jsonrpc': '2.0',
            'method': method,
            'params': params or {},
            'auth': self.auth,
            'id': self.id,
        }
        self.id += 1
        response = self.session.post(self.url, data = json.dumps(json_payload))

        if response.status_code != 200:
            raise ZabbixError("HTTP ERROR %S: %S" % (response.status, response.reason))
        if response.text == '':
            raise ZabbixError("Received empty response")

        return response.json()

Prompt:
Create do_requestion function to be used by other methods.

import requests

class Api(object):
    def __init__(self, server='http://localhost/zabbix'):
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
        self.url = server + '/api_jsonrpc.php'
        self.auth = ''
        self.id = 0


from pymouse import PyMouse
import time
# This script demonstrates the possibility to use a mouse as an unbound sensor.
# To do that the cursor position is brought back to the middle of the screen at each step, and the distance moved by the mouse are integrated
# This script is intended to be used with a second external mouse.
# This can be achieved using MPX, and inverting the laptop mouse and externa mouse.
# Warning: it may be difficult to stop this script with the mouse, so be sure you are able to do it with keyboard command!
cursor = PyMouse()
x = 0
y = 0
screen_size = cursor.screen_size()
cursor.move(screen_size[0]/2, screen_size[1]/2)
while True:
  p = cursor.position()
  x = x + p[0] - screen_size[0]/2
  y = y + p[1] - screen_size[1]/2
  print x, y, p[0] - s[0]/2, p[1] - s[1]/2
  cursor.move(screen_size[0]/2, screen_size[1]/	2)
  time.sleep(0.01)

Add a test to check if an optical mouse can be used as a course sensor

Response:
<INSERT> from pymouse import PyMouse
import time
# This script demonstrates the possibility to use a mouse as an unbound sensor.
# To do that the cursor position is brought back to the middle of the screen at each step, and the distance moved by the mouse are integrated
# This script is intended to be used with a second external mouse.
# This can be achieved using MPX, and inverting the laptop mouse and externa mouse.
# Warning: it may be difficult to stop this script with the mouse, so be sure you are able to do it with keyboard command!
cursor = PyMouse()
x = 0
y = 0
screen_size = cursor.screen_size()
cursor.move(screen_size[0]/2, screen_size[1]/2)
while True:
 <INSERT_END> <INSERT> p = cursor.position()
  x = x + p[0] - screen_size[0]/2
  y = y + p[1] - screen_size[1]/2
  print x, y, p[0] - s[0]/2, p[1] - s[1]/2
  cursor.move(screen_size[0]/2, screen_size[1]/	2)
  time.sleep(0.01)

 <INSERT_END> <|endoftext|> from pymouse import PyMouse
import time
# This script demonstrates the possibility to use a mouse as an unbound sensor.
# To do that the cursor position is brought back to the middle of the screen at each step, and the distance moved by the mouse are integrated
# This script is intended to be used with a second external mouse.
# This can be achieved using MPX, and inverting the laptop mouse and externa mouse.
# Warning: it may be difficult to stop this script with the mouse, so be sure you are able to do it with keyboard command!
cursor = PyMouse()
x = 0
y = 0
screen_size = cursor.screen_size()
cursor.move(screen_size[0]/2, screen_size[1]/2)
while True:
  p = cursor.position()
  x = x + p[0] - screen_size[0]/2
  y = y + p[1] - screen_size[1]/2
  print x, y, p[0] - s[0]/2, p[1] - s[1]/2
  cursor.move(screen_size[0]/2, screen_size[1]/	2)
  time.sleep(0.01)

Prompt: Add a test to check if an optical mouse can be used as a course sensor


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r"^$", views.request_view, name="request_site"),
    url(r"^approve$", views.approve_view, name="approve_site"),
    url(r"^admin$", views.approve_admin_view, name="admin_site")
]

Use r-strings for URL regexes

Use r-strings for URL regexes

Response:
<REPLACE_OLD> url("^$", <REPLACE_NEW> url(r"^$", <REPLACE_END> <REPLACE_OLD> url("^approve$", <REPLACE_NEW> url(r"^approve$", <REPLACE_END> <REPLACE_OLD> url("^admin$", <REPLACE_NEW> url(r"^admin$", <REPLACE_END> <|endoftext|> from django.conf.urls import url

from . import views

urlpatterns = [
    url(r"^$", views.request_view, name="request_site"),
    url(r"^approve$", views.approve_view, name="approve_site"),
    url(r"^admin$", views.approve_admin_view, name="admin_site")
]

Prompt:
Use r-strings for URL regexes

from django.conf.urls import url

from . import views

urlpatterns = [
    url("^$", views.request_view, name="request_site"),
    url("^approve$", views.approve_view, name="approve_site"),
    url("^admin$", views.approve_admin_view, name="admin_site")
]


import binascii
import datetime
import <error descr="No module named 'nonexistent'">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)

Response:
<REPLACE_OLD> nonexistent">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)
 <REPLACE_NEW> 'nonexistent'">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)
 <REPLACE_END> <|endoftext|> import binascii
import datetime
import <error descr="No module named 'nonexistent'">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)

Prompt:
i18n: Fix test data in an env test on skeleton generation

GitOrigin-RevId: 7be12c5b3b3a333e7e3afebe45fe32770bbdfa81
import binascii
import datetime
import <error descr="No module named nonexistent">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)


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

"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

from collections import Counter

from ..shop.models import PaymentState

def count_ordered_articles(article):
    """Count how often the article has been ordered, grouped by the
    order's payment state.
    """
    # Ensure every payment state is present in the resulting dictionary,
    # even if no orders of the corresponding payment state exist for the
    # article.
    counter = Counter({state: 0 for state in PaymentState})

    for order_item in article.order_items:
        counter[order_item.order.payment_state] += order_item.quantity

    return dict(counter)

Response:
<INSERT> # Ensure every payment state is present in the resulting dictionary,
    # even if no orders of the corresponding payment state exist for the
    # article.
    <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

from collections import Counter

from ..shop.models import PaymentState

def count_ordered_articles(article):
    """Count how often the article has been ordered, grouped by the
    order's payment state.
    """
    # Ensure every payment state is present in the resulting dictionary,
    # even if no orders of the corresponding payment state exist for the
    # article.
    counter = Counter({state: 0 for state in PaymentState})

    for order_item in article.order_items:
        counter[order_item.order.payment_state] += order_item.quantity

    return dict(counter)

Prompt:
Make sure every payment state is present in the counter.

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

"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

from collections import Counter

from ..shop.models import PaymentState

def count_ordered_articles(article):
    """Count how often the article has been ordered, grouped by the
    order's payment state.
    """
    counter = Counter({state: 0 for state in PaymentState})

    for order_item in article.order_items:
        counter[order_item.order.payment_state] += order_item.quantity

    return dict(counter)


from time import time
from itertools import permutations

DIGITS = '1234567890'
DIVS = [2, 3, 5, 7, 11, 13, 17]

def check_divs(pandigital):
    for i in range(1, 8):
        if int(pandigital[i:i+3]) % DIVS[i-1]:
            return False
    return True

def main():
    print sum(
        [int(''.join(p)) for p in permutations(DIGITS) if check_divs(''.join(p))]
    )

if __name__ == '__main__':
    t = time()
    main()
    print 'Time:', time() - t

Add problem 42, pandigital substrings divisible by first primes

Response:
<INSERT> from time import time
from itertools import permutations

DIGITS = '1234567890'
DIVS = [2, 3, 5, 7, 11, 13, 17]

def check_divs(pandigital):
 <INSERT_END> <INSERT>   for i in range(1, 8):
        if int(pandigital[i:i+3]) % DIVS[i-1]:
            return False
    return True

def main():
    print sum(
        [int(''.join(p)) for p in permutations(DIGITS) if check_divs(''.join(p))]
    )

if __name__ == '__main__':
    t = time()
    main()
    print 'Time:', time() - t
 <INSERT_END> <|endoftext|> from time import time
from itertools import permutations

DIGITS = '1234567890'
DIVS = [2, 3, 5, 7, 11, 13, 17]

def check_divs(pandigital):
    for i in range(1, 8):
        if int(pandigital[i:i+3]) % DIVS[i-1]:
            return False
    return True

def main():
    print sum(
        [int(''.join(p)) for p in permutations(DIGITS) if check_divs(''.join(p))]
    )

if __name__ == '__main__':
    t = time()
    main()
    print 'Time:', time() - t

Prompt: Add problem 42, pandigital substrings divisible by first primes


"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants

class Version(object):
    """Representation of an IATI Standard Version Number."""

    def __init__(self, version_string):
        """Initialise a Version Number.

        Args:
            version_string (str): A string representation of an IATI version number.

        Raises:
            TypeError: If an attempt to pass something that is not a string is made.
            ValueError: If a provided string is not a version number.

        """
        if not isinstance(version_string, str):
            raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))

        if not version_string in iati.constants.STANDARD_VERSIONS:
            raise ValueError('A valid version number must be specified.')

Response:
<REPLACE_OLD> Number."""
 <REPLACE_NEW> Number.

        Args:
            version_string (str): A string representation of an IATI version number.

        Raises:
            TypeError: If an attempt to pass something that is not a string is made.
            ValueError: If a provided string is not a version number.

        """
 <REPLACE_END> <|endoftext|> """A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants

class Version(object):
    """Representation of an IATI Standard Version Number."""

    def __init__(self, version_string):
        """Initialise a Version Number.

        Args:
            version_string (str): A string representation of an IATI version number.

        Raises:
            TypeError: If an attempt to pass something that is not a string is made.
            ValueError: If a provided string is not a version number.

        """
        if not isinstance(version_string, str):
            raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))

        if not version_string in iati.constants.STANDARD_VERSIONS:
            raise ValueError('A valid version number must be specified.')

Prompt:
Document the current state of the Version class.

"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants

class Version(object):
    """Representation of an IATI Standard Version Number."""

    def __init__(self, version_string):
        """Initialise a Version Number."""
        if not isinstance(version_string, str):
            raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))

        if not version_string in iati.constants.STANDARD_VERSIONS:
            raise ValueError('A valid version number must be specified.')


import numpy as np

from sklearn.datasets import make_classification
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge

from sklearn.utils.testing import assert_array_almost_equal

X, y = make_classification(n_classes=2, random_state=0)
Y = np.array([y, y]).T

def test_kernel_ridge():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed():
    K = np.dot(X, X.T)
    pred = KernelRidge(kernel="linear").fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed_sample_weight():
    K = np.dot(X, X.T)
    K2 = K.copy()
    sw = np.ones(X.shape[0]) / float(X.shape[0])
    KernelRidge(kernel="precomputed").fit(K, y, sample_weight=sw)
    assert_array_almost_equal(K, K2)

def test_kernel_ridge_multi_output():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X)
    assert_array_almost_equal(pred, pred2)

    pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    pred3 = np.array([pred3, pred3]).T
    assert_array_almost_equal(pred2, pred3)

TEST Added tests for KernelRidge based on @mblondel's code in lightning

Response:
<INSERT> import numpy as np

from sklearn.datasets import make_classification
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge

from sklearn.utils.testing import assert_array_almost_equal

X, y = make_classification(n_classes=2, random_state=0)
Y = np.array([y, y]).T

def test_kernel_ridge():
 <INSERT_END> <INSERT>   pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed():
    K = np.dot(X, X.T)
    pred = KernelRidge(kernel="linear").fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed_sample_weight():
    K = np.dot(X, X.T)
    K2 = K.copy()
    sw = np.ones(X.shape[0]) / float(X.shape[0])
    KernelRidge(kernel="precomputed").fit(K, y, sample_weight=sw)
    assert_array_almost_equal(K, K2)

def test_kernel_ridge_multi_output():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X)
    assert_array_almost_equal(pred, pred2)

    pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    pred3 = np.array([pred3, pred3]).T
    assert_array_almost_equal(pred2, pred3)
 <INSERT_END> <|endoftext|> import numpy as np

from sklearn.datasets import make_classification
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge

from sklearn.utils.testing import assert_array_almost_equal

X, y = make_classification(n_classes=2, random_state=0)
Y = np.array([y, y]).T

def test_kernel_ridge():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed():
    K = np.dot(X, X.T)
    pred = KernelRidge(kernel="linear").fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed_sample_weight():
    K = np.dot(X, X.T)
    K2 = K.copy()
    sw = np.ones(X.shape[0]) / float(X.shape[0])
    KernelRidge(kernel="precomputed").fit(K, y, sample_weight=sw)
    assert_array_almost_equal(K, K2)

def test_kernel_ridge_multi_output():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X)
    assert_array_almost_equal(pred, pred2)

    pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    pred3 = np.array([pred3, pred3]).T
    assert_array_almost_equal(pred2, pred3)

Prompt: TEST Added tests for KernelRidge based on @mblondel's code in lightning


import numpy as np
from numpy.testing import *

def check_float_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(float(x)))

def test_float_types():
    """ Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.float, np.double, np.longdouble] :
        yield check_float_type, t

def check_complex_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(complex(x)))
        assert_equal(str(tp(x*1j)), str(complex(x*1j)))
        assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)))

def test_complex_types():
    """Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.cfloat, np.cdouble, np.clongdouble] :
        yield check_complex_type, t

if __name__ == "__main__":
    run_module_suite()

Response:
<REPLACE_OLD> *

class TestPrint(TestCase):

    def test_float_types(self) :
     <REPLACE_NEW> *

def check_float_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(float(x)))

def test_float_types():
 <REPLACE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <REPLACE_OLD>  <REPLACE_NEW> yield check_float_type, t

def check_complex_type(tp):
 <REPLACE_END> <REPLACE_OLD>         assert_equal(str(t(x)), str(float(x)))

    def test_complex_types(self) :
     <REPLACE_NEW> assert_equal(str(tp(x)), str(complex(x)))
        assert_equal(str(tp(x*1j)), str(complex(x*1j)))
        assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)))

def test_complex_types():
 <REPLACE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <REPLACE_OLD>     for x in [0, 1,-1, 1e10, 1e20] :
                assert_equal(str(t(x)), str(complex(x)))
                assert_equal(str(t(x*1j)), str(complex(x*1j)))
                assert_equal(str(t(x + x*1j)), str(complex(x + x*1j)))

if <REPLACE_NEW> yield check_complex_type, t

if <REPLACE_END> <|endoftext|> import numpy as np
from numpy.testing import *

def check_float_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(float(x)))

def test_float_types():
    """ Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.float, np.double, np.longdouble] :
        yield check_float_type, t

def check_complex_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(complex(x)))
        assert_equal(str(tp(x*1j)), str(complex(x*1j)))
        assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)))

def test_complex_types():
    """Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.cfloat, np.cdouble, np.clongdouble] :
        yield check_complex_type, t

if __name__ == "__main__":
    run_module_suite()

Prompt:
Use parametric tests for format tests so that it is clearer which type is failing.

import numpy as np
from numpy.testing import *

class TestPrint(TestCase):

    def test_float_types(self) :
        """ Check formatting.

            This is only for the str function, and only for simple types.
            The precision of np.float and np.longdouble aren't the same as the
            python float precision.

        """
        for t in [np.float, np.double, np.longdouble] :
            for x in [0, 1,-1, 1e10, 1e20] :
                assert_equal(str(t(x)), str(float(x)))

    def test_complex_types(self) :
        """Check formatting.

            This is only for the str function, and only for simple types.
            The precision of np.float and np.longdouble aren't the same as the
            python float precision.

        """
        for t in [np.cfloat, np.cdouble, np.clongdouble] :
            for x in [0, 1,-1, 1e10, 1e20] :
                assert_equal(str(t(x)), str(complex(x)))
                assert_equal(str(t(x*1j)), str(complex(x*1j)))
                assert_equal(str(t(x + x*1j)), str(complex(x + x*1j)))

if __name__ == "__main__":
    run_module_suite()


#!/usr/bin/env python

'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''

class Item(object):
    def __init__(self, value, next_item=None):
        self.value = value
        self.next_item = next_item

    def __str__(self):
        return self.value

class Stack(object):
    def __init__(self, top=None):
        self.top = top

    def push(self, value):
        item = Item(value)
        item.next_item = self.top
        self.top = item

    def pop(self):
        try:
            pop_item = self.top
            self.top = pop_item.next_item
            return pop_item.value
        except AttributeError:
            raise ValueError('No items in stack')

    def peek(self):
        return self.top.value

Add pop method on Stack class

Add pop method on Stack class

Response:
<REPLACE_OLD> pass

 <REPLACE_NEW> try:
            pop_item = self.top
            self.top = pop_item.next_item
            return pop_item.value
        except AttributeError:
            raise ValueError('No items in stack')

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

'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''

class Item(object):
    def __init__(self, value, next_item=None):
        self.value = value
        self.next_item = next_item

    def __str__(self):
        return self.value

class Stack(object):
    def __init__(self, top=None):
        self.top = top

    def push(self, value):
        item = Item(value)
        item.next_item = self.top
        self.top = item

    def pop(self):
        try:
            pop_item = self.top
            self.top = pop_item.next_item
            return pop_item.value
        except AttributeError:
            raise ValueError('No items in stack')

    def peek(self):
        return self.top.value

Prompt:
Add pop method on Stack class

#!/usr/bin/env python

'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''

class Item(object):
    def __init__(self, value, next_item=None):
        self.value = value
        self.next_item = next_item

    def __str__(self):
        return self.value

class Stack(object):
    def __init__(self, top=None):
        self.top = top

    def push(self, value):
        item = Item(value)
        item.next_item = self.top
        self.top = item

    def pop(self):
        pass

    def peek(self):
        return self.top.value


import unittest

from githubtrending import trending as githubtrending

from . import data

class TestGithubTrending(unittest.TestCase):

    def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = githubtrending.read_page(url)
            self.assertEqual(status_code, expected_status_code)

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

Add test case for read_page

Test: Add test case for read_page

Response:
<INSERT> import unittest

from githubtrending import trending as githubtrending

from . import data

class TestGithubTrending(unittest.TestCase):

 <INSERT_END> <INSERT>   def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = githubtrending.read_page(url)
            self.assertEqual(status_code, expected_status_code)

if __name__ == '__main__':
    unittest.main() <INSERT_END> <|endoftext|> import unittest

from githubtrending import trending as githubtrending

from . import data

class TestGithubTrending(unittest.TestCase):

    def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = githubtrending.read_page(url)
            self.assertEqual(status_code, expected_status_code)

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

Prompt: Test: Add test case for read_page


#!python
# coding=utf-8

def isstr(s):
    try:
        return isinstance(s, basestring)
    except NameError:
        return isinstance(s, str)

def cf_safe_name(name):
    import re
    if isstr(name):
        if re.match('^[0-9_]', name):
            # Add a letter to the front
            name = "v_{}".format(name)
        return re.sub(r'[^_a-zA-Z0-9]', "_", name)

Fix cf_safe_name for python 2.7

Fix cf_safe_name for python 2.7

Response:
<INSERT> isstr(s):
    try:
        return isinstance(s, basestring)
    except NameError:
        return isinstance(s, str)

def <INSERT_END> <REPLACE_OLD> isinstance(name, str):
 <REPLACE_NEW> isstr(name):
 <REPLACE_END> <|endoftext|> #!python
# coding=utf-8

def isstr(s):
    try:
        return isinstance(s, basestring)
    except NameError:
        return isinstance(s, str)

def cf_safe_name(name):
    import re
    if isstr(name):
        if re.match('^[0-9_]', name):
            # Add a letter to the front
            name = "v_{}".format(name)
        return re.sub(r'[^_a-zA-Z0-9]', "_", name)

Prompt:
Fix cf_safe_name for python 2.7

#!python
# coding=utf-8

def cf_safe_name(name):
    import re
    if isinstance(name, str):
        if re.match('^[0-9_]', name):
            # Add a letter to the front
            name = "v_{}".format(name)
        return re.sub(r'[^_a-zA-Z0-9]', "_", name)


"""Configuration."""

import logging
import os
import re

from google.appengine.ext.appstats import recording

logging.info('Loading %s from %s', __name__, __file__)

# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
  app = recording.appstats_wsgi_middleware(app)
  return app

# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'

# Custom Appstats path normalization.
def appstats_normalize_path(path):
    if path.startswith('/user/'):
        return '/user/X'
    if path.startswith('/user_popup/'):
        return '/user_popup/X'
    if path.startswith('/rss/'):
        i = path.find('/', 5)
        if i > 0:
            return path[:i] + '/X'
    return re.sub(r'\d+', 'X', path)

# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')

# Fail early if we can't import Django 1.x.  Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
             django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"

Switch Django version from 1.0 to 1.1

Switch Django version from 1.0 to 1.1

Response:
<REPLACE_OLD> '1.0')

# <REPLACE_NEW> '1.1')

# <REPLACE_END> <|endoftext|> """Configuration."""

import logging
import os
import re

from google.appengine.ext.appstats import recording

logging.info('Loading %s from %s', __name__, __file__)

# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
  app = recording.appstats_wsgi_middleware(app)
  return app

# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'

# Custom Appstats path normalization.
def appstats_normalize_path(path):
    if path.startswith('/user/'):
        return '/user/X'
    if path.startswith('/user_popup/'):
        return '/user_popup/X'
    if path.startswith('/rss/'):
        i = path.find('/', 5)
        if i > 0:
            return path[:i] + '/X'
    return re.sub(r'\d+', 'X', path)

# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')

# Fail early if we can't import Django 1.x.  Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
             django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"

Prompt:
Switch Django version from 1.0 to 1.1

"""Configuration."""

import logging
import os
import re

from google.appengine.ext.appstats import recording

logging.info('Loading %s from %s', __name__, __file__)

# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
  app = recording.appstats_wsgi_middleware(app)
  return app

# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'

# Custom Appstats path normalization.
def appstats_normalize_path(path):
    if path.startswith('/user/'):
        return '/user/X'
    if path.startswith('/user_popup/'):
        return '/user_popup/X'
    if path.startswith('/rss/'):
        i = path.find('/', 5)
        if i > 0:
            return path[:i] + '/X'
    return re.sub(r'\d+', 'X', path)

# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')

# Fail early if we can't import Django 1.x.  Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
             django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"


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

import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog

def uibei(order, energy_lo, temp, chem_potential):
    """
    Upper incomplete Bose-Einstein integral.
    """
    kT = temp * constants.k_B

    reduced_energy_lo = energy_lo / kT
    reduced_chem_potential = chem_potential / kT

    prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \
        (constants.h**3 * constants.c**2)

    summand = 0

    for indx in range(1, order + 2):
        expt = (reduced_chem_potential - reduced_energy_lo).decompose()
        term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1)
        summand += term

    return summand

Add first draft of upper incomplete Bose-Einstein integral

Response:
<INSERT> # -*- coding: utf-8 -*-

import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog

def uibei(order, energy_lo, temp, chem_potential):
 <INSERT_END> <INSERT>   """
    Upper incomplete Bose-Einstein integral.
    """
    kT = temp * constants.k_B

    reduced_energy_lo = energy_lo / kT
    reduced_chem_potential = chem_potential / kT

    prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \
        (constants.h**3 * constants.c**2)

    summand = 0

    for indx in range(1, order + 2):
        expt = (reduced_chem_potential - reduced_energy_lo).decompose()
        term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1)
        summand += term

    return summand
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog

def uibei(order, energy_lo, temp, chem_potential):
    """
    Upper incomplete Bose-Einstein integral.
    """
    kT = temp * constants.k_B

    reduced_energy_lo = energy_lo / kT
    reduced_chem_potential = chem_potential / kT

    prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \
        (constants.h**3 * constants.c**2)

    summand = 0

    for indx in range(1, order + 2):
        expt = (reduced_chem_potential - reduced_energy_lo).decompose()
        term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1)
        summand += term

    return summand

Prompt: Add first draft of upper incomplete Bose-Einstein integral


try:
    import wpilib
except ImportError:
    from pyfrc import wpilib

import timed_shoot

class HotShootAutonomous(timed_shoot.TimedShootAutonomous):
    '''
        Based on the TimedShootAutonomous mode. Modified to allow
        shooting based on whether the hot goal is enabled or not.
    '''

    DEFAULT = False
    MODE_NAME = "Hot Aim shoot"

    def __init__(self, components):
        super().__init__(components)

        wpilib.SmartDashboard.PutNumber('DriveStrafeSpeed', 0.5)
        wpilib.SmartDashboard.PutBoolean('IsHotLeft', False)
        wpilib.SmartDashboard.PutBoolean('IsHotRight', False)

    def on_enable(self):
        '''these are called when autonomous starts'''

        super().on_enable()

        self.drive_strafe_speed = wpilib.SmartDashboard.GetNumber('DriveStrafeSpeed')

        print("-> Drive strafe:", self.drive_strafe_speed)

        self.decided = False
        self.start_time = None

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, time_elapsed):
        '''The actual autonomous program'''

        # decide if it's hot or not
        if not self.decided:
            self.hotLeft = wpilib.SmartDashboard.GetBoolean("IsHotLeft")
            self.hotRight = wpilib.SmartDashboard.GetBoolean("IsHotRight")

            if (self.hotLeft or self.hotRight) and not (self.hotLeft and self.hotRight):
                self.decided = True

                if self.hotLeft:
                    self.drive_strafe_speed *= -1

            elif time_elapsed > 6:
                # at 6 seconds, give up and shoot anyways
                self.decided = True

        # always keep the arm down
        self.intake.armDown()

        # wait a split second for the arm to come down, then
        # keep bringing the catapult down so we're ready to go
        if time_elapsed > 0.3:
            self.catapult.pulldown()

        # wait some period before we start driving
        if time_elapsed < self.drive_wait:
            pass

        else:

            if self.decided:

                # only set this once, so we can calculate time from this
                # point on
                if self.start_time is None:
                    self.start_time = time_elapsed

                time_elapsed = time_elapsed - self.start_time

                if time_elapsed < self.drive_time:
                    # Drive slowly forward for N seconds
                    self.drive.move(self.drive_strafe_speed, self.drive_speed, 0)

                elif time_elapsed < self.drive_time + 1.0:
                    # Finally, fire and keep firing for 1 seconds
                    self.catapult.launchNoSensor()

Add an autonomous mode to strafe and shoot. Doesn't work

Response:
<REPLACE_OLD>  <REPLACE_NEW>
try:
    import wpilib
except ImportError:
    from pyfrc import wpilib

import timed_shoot

class HotShootAutonomous(timed_shoot.TimedShootAutonomous):
    '''
        Based on the TimedShootAutonomous mode. Modified to allow
        shooting based on whether the hot goal is enabled or not.
    '''

    DEFAULT = False
    MODE_NAME = "Hot Aim shoot"

    def __init__(self, components):
        super().__init__(components)

        wpilib.SmartDashboard.PutNumber('DriveStrafeSpeed', 0.5)
        wpilib.SmartDashboard.PutBoolean('IsHotLeft', False)
        wpilib.SmartDashboard.PutBoolean('IsHotRight', False)

    def on_enable(self):
        '''these are called when autonomous starts'''

        super().on_enable()

        self.drive_strafe_speed = wpilib.SmartDashboard.GetNumber('DriveStrafeSpeed')

        print("-> Drive strafe:", self.drive_strafe_speed)

        self.decided = False
        self.start_time = None

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, time_elapsed):
        '''The actual autonomous program'''

        # decide if it's hot or not
        if not self.decided:
            self.hotLeft = wpilib.SmartDashboard.GetBoolean("IsHotLeft")
            self.hotRight = wpilib.SmartDashboard.GetBoolean("IsHotRight")

            if (self.hotLeft or self.hotRight) and not (self.hotLeft and self.hotRight):
                self.decided = True

                if self.hotLeft:
                    self.drive_strafe_speed *= -1

            elif time_elapsed > 6:
                # at 6 seconds, give up and shoot anyways
                self.decided = True

        # always keep the arm down
        self.intake.armDown()

        # wait a split second for the arm to come down, then
        # keep bringing the catapult down so we're ready to go
        if time_elapsed > 0.3:
            self.catapult.pulldown()

        # wait some period before we start driving
        if time_elapsed < self.drive_wait:
            pass

        else:

            if self.decided:

                # only set this once, so we can calculate time from this
                # point on
                if self.start_time is None:
                    self.start_time = time_elapsed

                time_elapsed = time_elapsed - self.start_time

                if time_elapsed < self.drive_time:
                    # Drive slowly forward for N seconds
                    self.drive.move(self.drive_strafe_speed, self.drive_speed, 0)

                elif time_elapsed < self.drive_time + 1.0:
                    # Finally, fire and keep firing for 1 seconds
                    self.catapult.launchNoSensor()
 <REPLACE_END> <|endoftext|>
try:
    import wpilib
except ImportError:
    from pyfrc import wpilib

import timed_shoot

class HotShootAutonomous(timed_shoot.TimedShootAutonomous):
    '''
        Based on the TimedShootAutonomous mode. Modified to allow
        shooting based on whether the hot goal is enabled or not.
    '''

    DEFAULT = False
    MODE_NAME = "Hot Aim shoot"

    def __init__(self, components):
        super().__init__(components)

        wpilib.SmartDashboard.PutNumber('DriveStrafeSpeed', 0.5)
        wpilib.SmartDashboard.PutBoolean('IsHotLeft', False)
        wpilib.SmartDashboard.PutBoolean('IsHotRight', False)

    def on_enable(self):
        '''these are called when autonomous starts'''

        super().on_enable()

        self.drive_strafe_speed = wpilib.SmartDashboard.GetNumber('DriveStrafeSpeed')

        print("-> Drive strafe:", self.drive_strafe_speed)

        self.decided = False
        self.start_time = None

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, time_elapsed):
        '''The actual autonomous program'''

        # decide if it's hot or not
        if not self.decided:
            self.hotLeft = wpilib.SmartDashboard.GetBoolean("IsHotLeft")
            self.hotRight = wpilib.SmartDashboard.GetBoolean("IsHotRight")

            if (self.hotLeft or self.hotRight) and not (self.hotLeft and self.hotRight):
                self.decided = True

                if self.hotLeft:
                    self.drive_strafe_speed *= -1

            elif time_elapsed > 6:
                # at 6 seconds, give up and shoot anyways
                self.decided = True

        # always keep the arm down
        self.intake.armDown()

        # wait a split second for the arm to come down, then
        # keep bringing the catapult down so we're ready to go
        if time_elapsed > 0.3:
            self.catapult.pulldown()

        # wait some period before we start driving
        if time_elapsed < self.drive_wait:
            pass

        else:

            if self.decided:

                # only set this once, so we can calculate time from this
                # point on
                if self.start_time is None:
                    self.start_time = time_elapsed

                time_elapsed = time_elapsed - self.start_time

                if time_elapsed < self.drive_time:
                    # Drive slowly forward for N seconds
                    self.drive.move(self.drive_strafe_speed, self.drive_speed, 0)

                elif time_elapsed < self.drive_time + 1.0:
                    # Finally, fire and keep firing for 1 seconds
                    self.catapult.launchNoSensor()

Prompt: Add an autonomous mode to strafe and shoot. Doesn't work


import bz2
import urllib.request
import os
import os.path

DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024

def download_and_unbzip(url, dest_file):
    source = urllib.request.urlopen(url)
    decompressor = bz2.BZ2Decompressor()
    with open(dest_file, 'wb') as dest_file:
        while True:
            data = source.read(CHUNK)
            if not data:
                break
            dest_file.write(decompressor.decompress(data))

if __name__ == '__main__':
    if not os.path.isdir(DATA_DIR):
        os.mkdir(DATA_DIR)
    download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)

Create dir before data downloading

Create dir before data downloading

Response:
<REPLACE_OLD> urllib.request

OPEN_CORPORA_URL <REPLACE_NEW> urllib.request
import os
import os.path

DATA_DIR = 'data'
OPEN_CORPORA_URL <REPLACE_END> <INSERT> if not os.path.isdir(DATA_DIR):
        os.mkdir(DATA_DIR)
    <INSERT_END> <|endoftext|> import bz2
import urllib.request
import os
import os.path

DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024

def download_and_unbzip(url, dest_file):
    source = urllib.request.urlopen(url)
    decompressor = bz2.BZ2Decompressor()
    with open(dest_file, 'wb') as dest_file:
        while True:
            data = source.read(CHUNK)
            if not data:
                break
            dest_file.write(decompressor.decompress(data))

if __name__ == '__main__':
    if not os.path.isdir(DATA_DIR):
        os.mkdir(DATA_DIR)
    download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)

Prompt:
Create dir before data downloading

import bz2
import urllib.request

OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024

def download_and_unbzip(url, dest_file):
    source = urllib.request.urlopen(url)
    decompressor = bz2.BZ2Decompressor()
    with open(dest_file, 'wb') as dest_file:
        while True:
            data = source.read(CHUNK)
            if not data:
                break
            dest_file.write(decompressor.decompress(data))

if __name__ == '__main__':
    download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)


from djet import assertions, restframework
from rest_framework import status
import djoser.constants
import djoser.utils
import djoser.views

class RootViewTest(restframework.APIViewTestCase,
                   assertions.StatusCodeAssertionsMixin):
    view_class = djoser.views.RootView

    def test_get_should_return_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, response.data)

    def test_all_urlpattern_names_are_in_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        for urlpattern_name in urlpattern_names:
            self.assertIn(urlpattern_name, response.data)

    def test_non_existent_urlpattern_results_in_empty_string(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)

        urlpattern_names = ['non-existent-urlpattern']
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, {urlpattern_names[0]: ''})

Add test for non existent url pattern

Add test for non existent url pattern

Response:
<REPLACE_OLD> response.data)
 <REPLACE_NEW> response.data)

    def test_non_existent_urlpattern_results_in_empty_string(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)

        urlpattern_names = ['non-existent-urlpattern']
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, {urlpattern_names[0]: ''})
 <REPLACE_END> <|endoftext|> from djet import assertions, restframework
from rest_framework import status
import djoser.constants
import djoser.utils
import djoser.views

class RootViewTest(restframework.APIViewTestCase,
                   assertions.StatusCodeAssertionsMixin):
    view_class = djoser.views.RootView

    def test_get_should_return_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, response.data)

    def test_all_urlpattern_names_are_in_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        for urlpattern_name in urlpattern_names:
            self.assertIn(urlpattern_name, response.data)

    def test_non_existent_urlpattern_results_in_empty_string(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)

        urlpattern_names = ['non-existent-urlpattern']
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, {urlpattern_names[0]: ''})

Prompt:
Add test for non existent url pattern

from djet import assertions, restframework
from rest_framework import status
import djoser.constants
import djoser.utils
import djoser.views

class RootViewTest(restframework.APIViewTestCase,
                   assertions.StatusCodeAssertionsMixin):
    view_class = djoser.views.RootView

    def test_get_should_return_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, response.data)

    def test_all_urlpattern_names_are_in_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        for urlpattern_name in urlpattern_names:
            self.assertIn(urlpattern_name, response.data)


# Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})

    @api.model
    def create(self, vals):
        if vals.get('warehouse_id', False):
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', vals['warehouse_id'])], limit=1)
            if picking_type_id:
                vals.update({'picking_type_id': picking_type_id.id})
        return super().create(vals)

Set Picking Type in Create

Response:
<INSERT> picking_type_id.id})

    @api.model
    def create(self, vals):
        if vals.get('warehouse_id', False):
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', vals['warehouse_id'])], limit=1)
            if picking_type_id:
                vals.update({'picking_type_id': <INSERT_END> <INSERT>        return super().create(vals)
 <INSERT_END> <|endoftext|> # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})

    @api.model
    def create(self, vals):
        if vals.get('warehouse_id', False):
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', vals['warehouse_id'])], limit=1)
            if picking_type_id:
                vals.update({'picking_type_id': picking_type_id.id})
        return super().create(vals)

Prompt:
[IMP] Set Picking Type in Create

[IMP] Flake8

# Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})


from django.shortcuts import render_to_response
from django.template import RequestContext

from feincms.models import Page

def handler(request, path):
    page = Page.objects.page_for_path_or_404(path)

    return render_to_response(page.template.path, {
        'page': page,
        }, context_instance=RequestContext(request))

Add basic cms page handler

Add basic cms page handler

Response:
<INSERT> from django.shortcuts import render_to_response
from django.template import RequestContext

from feincms.models import Page

def handler(request, path):
 <INSERT_END> <INSERT>   page = Page.objects.page_for_path_or_404(path)

    return render_to_response(page.template.path, {
        'page': page,
        }, context_instance=RequestContext(request))

 <INSERT_END> <|endoftext|> from django.shortcuts import render_to_response
from django.template import RequestContext

from feincms.models import Page

def handler(request, path):
    page = Page.objects.page_for_path_or_404(path)

    return render_to_response(page.template.path, {
        'page': page,
        }, context_instance=RequestContext(request))

Prompt: Add basic cms page handler


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

from tempest.lib import decorators

from senlin.tests.tempest.api import base
from senlin.tests.tempest.common import constants

class TestProfileDelete(base.BaseSenlinTest):

    @classmethod
    def resource_setup(cls):
        super(TestProfileDelete, cls).resource_setup()
        # Create profile
        cls.profile = cls.create_profile(constants.spec_nova_server)

    @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27')
    def test_delete_policy(self):
        # Verify resp of policy delete API
        res = self.client.delete_obj('profiles', self.profile['id'])
        self.assertEqual(204, res['status'])
        self.assertIsNone(res['body'])

Add API tests for profile delete

Add API tests for profile delete

Add API tests for profile delete

Change-Id: I47a733ce203ba76fc57080a1b086661720e83930

Response:
<INSERT> # 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
#
# <INSERT_END> <INSERT>     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from tempest.lib import decorators

from senlin.tests.tempest.api import base
from senlin.tests.tempest.common import constants

class TestProfileDelete(base.BaseSenlinTest):

    @classmethod
    def resource_setup(cls):
        super(TestProfileDelete, cls).resource_setup()
        # Create profile
        cls.profile = cls.create_profile(constants.spec_nova_server)

    @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27')
    def test_delete_policy(self):
        # Verify resp of policy delete API
        res = self.client.delete_obj('profiles', self.profile['id'])
        self.assertEqual(204, res['status'])
        self.assertIsNone(res['body'])
 <INSERT_END> <|endoftext|> # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from tempest.lib import decorators

from senlin.tests.tempest.api import base
from senlin.tests.tempest.common import constants

class TestProfileDelete(base.BaseSenlinTest):

    @classmethod
    def resource_setup(cls):
        super(TestProfileDelete, cls).resource_setup()
        # Create profile
        cls.profile = cls.create_profile(constants.spec_nova_server)

    @decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27')
    def test_delete_policy(self):
        # Verify resp of policy delete API
        res = self.client.delete_obj('profiles', self.profile['id'])
        self.assertEqual(204, res['status'])
        self.assertIsNone(res['body'])

Prompt:
Add API tests for profile delete

Add API tests for profile delete

Change-Id: I47a733ce203ba76fc57080a1b086661720e83930


import unittest

import simulation_parameters as sim_param

from generators.transaction_generator.customer_transaction_parameters_generator import CustomerTransactionParameters
from generators.transaction_generator.customer_transaction_parameters_generator import CustomerTransactionParametersGenerator

class TestCustomerTransactionParametersGenerator(unittest.TestCase):
    def test_generate(self):
        generator = CustomerTransactionParametersGenerator()

        trans_params = generator.generate()

        self.assertIsInstance(trans_params, CustomerTransactionParameters)
        self.assertIsInstance(trans_params.pet_counts, dict)

        total_count = sum(trans_params.pet_counts.values())
        self.assertTrue(total_count >= sim_param.MIN_PETS)
        self.assertTrue(total_count <= sim_param.MAX_PETS)

        self.assertTrue(trans_params.average_transaction_trigger_time >= sim_param.TRANSACTION_TRIGGER_TIME_MIN)
        self.assertTrue(trans_params.average_transaction_trigger_time <= sim_param.TRANSACTION_TRIGGER_TIME_MAX)

        self.assertTrue(trans_params.average_purchase_trigger_time >= sim_param.PURCHASE_TRIGGER_TIME_MIN)
        self.assertTrue(trans_params.average_purchase_trigger_time <= sim_param.PURCHASE_TRIGGER_TIME_MAX)

Add unit tests for customer transaction parameters generator.py

Response:
<INSERT> import unittest

import simulation_parameters as sim_param

from generators.transaction_generator.customer_transaction_parameters_generator import CustomerTransactionParameters
from generators.transaction_generator.customer_transaction_parameters_generator import CustomerTransactionParametersGenerator

class TestCustomerTransactionParametersGenerator(unittest.TestCase):
 <INSERT_END> <INSERT>   def test_generate(self):
        generator = CustomerTransactionParametersGenerator()

        trans_params = generator.generate()

        self.assertIsInstance(trans_params, CustomerTransactionParameters)
        self.assertIsInstance(trans_params.pet_counts, dict)

        total_count = sum(trans_params.pet_counts.values())
        self.assertTrue(total_count >= sim_param.MIN_PETS)
        self.assertTrue(total_count <= sim_param.MAX_PETS)

        self.assertTrue(trans_params.average_transaction_trigger_time >= sim_param.TRANSACTION_TRIGGER_TIME_MIN)
        self.assertTrue(trans_params.average_transaction_trigger_time <= sim_param.TRANSACTION_TRIGGER_TIME_MAX)

        self.assertTrue(trans_params.average_purchase_trigger_time >= sim_param.PURCHASE_TRIGGER_TIME_MIN)
        self.assertTrue(trans_params.average_purchase_trigger_time <= sim_param.PURCHASE_TRIGGER_TIME_MAX)
 <INSERT_END> <|endoftext|> import unittest

import simulation_parameters as sim_param

from generators.transaction_generator.customer_transaction_parameters_generator import CustomerTransactionParameters
from generators.transaction_generator.customer_transaction_parameters_generator import CustomerTransactionParametersGenerator

class TestCustomerTransactionParametersGenerator(unittest.TestCase):
    def test_generate(self):
        generator = CustomerTransactionParametersGenerator()

        trans_params = generator.generate()

        self.assertIsInstance(trans_params, CustomerTransactionParameters)
        self.assertIsInstance(trans_params.pet_counts, dict)

        total_count = sum(trans_params.pet_counts.values())
        self.assertTrue(total_count >= sim_param.MIN_PETS)
        self.assertTrue(total_count <= sim_param.MAX_PETS)

        self.assertTrue(trans_params.average_transaction_trigger_time >= sim_param.TRANSACTION_TRIGGER_TIME_MIN)
        self.assertTrue(trans_params.average_transaction_trigger_time <= sim_param.TRANSACTION_TRIGGER_TIME_MAX)

        self.assertTrue(trans_params.average_purchase_trigger_time >= sim_param.PURCHASE_TRIGGER_TIME_MIN)
        self.assertTrue(trans_params.average_purchase_trigger_time <= sim_param.PURCHASE_TRIGGER_TIME_MAX)

Prompt: Add unit tests for customer transaction parameters generator.py


class Algorithm:
	"""
	Algorithm Class

	Base class for the page substitution algorithms.
	"""
	def __init__(self, input = []):
		"""
		Algorithm Constructor.

		Parameters
		----------
		input : list
			A list containing the the input page swap.
		"""
		if not input: #If the list is empty throw an exception.
			raise ValueError("The list must not be empty") #throws the exception.
		self.blocks = input[0] #Store the page frames size.
		self.pages = input[1:] #Store the pages to swap.
		self.missingPages = self.blocks #Count the lack of pages.

	def removeChuncks(self, list, start, stop):
		"""
		Remove a piece of a list.

		Parameters
		----------
		list : list
			The list to delete the elements
		start : int
			start point.
		stop : int
			stop point.
		"""
		del list[start:stop] #Delete range

	def preparePageFrame(self):
		"""
		Prepare the page frames.

		Returns
		-------
		list
			The list with initialized Page frames
		"""
		pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user.
		iterator = 0
		for i in range(0, len(self.pages)):
			if self.pages[i] not in pageFrame:
				pageFrame[iterator] = self.pages[i]
				iterator = iterator + 1
				if iterator == self.blocks:
					self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame
					break

		return pageFrame #Return the list

Fix logic error under preparePageFrames

Fix logic error under preparePageFrames

Response:
<REPLACE_OLD> [self.pages[x] for x in range(0, self.blocks)] <REPLACE_NEW> [None] * self.blocks <REPLACE_END> <REPLACE_OLD> user.
		self.removeChuncks(self.pages, <REPLACE_NEW> user.
		iterator = 0
		for i in range(0, len(self.pages)):
			if self.pages[i] not in pageFrame:
				pageFrame[iterator] = self.pages[i]
				iterator = iterator + 1
				if iterator == self.blocks:
					self.removeChuncks(self.pages, <REPLACE_END> <REPLACE_OLD> self.blocks) <REPLACE_NEW> i) <REPLACE_END> <REPLACE_OLD> frame
		return <REPLACE_NEW> frame
					break

		return <REPLACE_END> <|endoftext|> class Algorithm:
	"""
	Algorithm Class

	Base class for the page substitution algorithms.
	"""
	def __init__(self, input = []):
		"""
		Algorithm Constructor.

		Parameters
		----------
		input : list
			A list containing the the input page swap.
		"""
		if not input: #If the list is empty throw an exception.
			raise ValueError("The list must not be empty") #throws the exception.
		self.blocks = input[0] #Store the page frames size.
		self.pages = input[1:] #Store the pages to swap.
		self.missingPages = self.blocks #Count the lack of pages.

	def removeChuncks(self, list, start, stop):
		"""
		Remove a piece of a list.

		Parameters
		----------
		list : list
			The list to delete the elements
		start : int
			start point.
		stop : int
			stop point.
		"""
		del list[start:stop] #Delete range

	def preparePageFrame(self):
		"""
		Prepare the page frames.

		Returns
		-------
		list
			The list with initialized Page frames
		"""
		pageFrame = [None] * self.blocks #Create the page frame with elements passed by the user.
		iterator = 0
		for i in range(0, len(self.pages)):
			if self.pages[i] not in pageFrame:
				pageFrame[iterator] = self.pages[i]
				iterator = iterator + 1
				if iterator == self.blocks:
					self.removeChuncks(self.pages, 0, i) #Remove part of the list that is on the page frame
					break

		return pageFrame #Return the list

Prompt:
Fix logic error under preparePageFrames

class Algorithm:
	"""
	Algorithm Class

	Base class for the page substitution algorithms.
	"""
	def __init__(self, input = []):
		"""
		Algorithm Constructor.

		Parameters
		----------
		input : list
			A list containing the the input page swap.
		"""
		if not input: #If the list is empty throw an exception.
			raise ValueError("The list must not be empty") #throws the exception.
		self.blocks = input[0] #Store the page frames size.
		self.pages = input[1:] #Store the pages to swap.
		self.missingPages = self.blocks #Count the lack of pages.

	def removeChuncks(self, list, start, stop):
		"""
		Remove a piece of a list.

		Parameters
		----------
		list : list
			The list to delete the elements
		start : int
			start point.
		stop : int
			stop point.
		"""
		del list[start:stop] #Delete range

	def preparePageFrame(self):
		"""
		Prepare the page frames.

		Returns
		-------
		list
			The list with initialized Page frames
		"""
		pageFrame = [self.pages[x] for x in range(0, self.blocks)] #Create the page frame with elements passed by the user.
		self.removeChuncks(self.pages, 0, self.blocks) #Remove part of the list that is on the page frame
		return pageFrame #Return the list


# -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018  Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only

import os
from marv_cli import setup_logging
setup_logging(os.environ.get('MARV_LOGLEVEL', 'info'))

config = os.environ['MARV_CONFIG']
app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/'

import marv.app
import marv.site
site = marv.site.Site(config)
site.load_for_web()
application = marv.app.create_app(site, app_root=app_root, checkdb=True)

Response:
<REPLACE_OLD> os.environ['MARV_APPLICATION_ROOT']

import <REPLACE_NEW> os.environ.get('MARV_APPLICATION_ROOT') or '/'

import <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018  Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only

import os
from marv_cli import setup_logging
setup_logging(os.environ.get('MARV_LOGLEVEL', 'info'))

config = os.environ['MARV_CONFIG']
app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/'

import marv.app
import marv.site
site = marv.site.Site(config)
site.load_for_web()
application = marv.app.create_app(site, app_root=app_root, checkdb=True)

Prompt:
[marv] Make fetching application root from env less error-prone

# -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018  Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only

import os
from marv_cli import setup_logging
setup_logging(os.environ.get('MARV_LOGLEVEL', 'info'))

config = os.environ['MARV_CONFIG']
app_root = os.environ['MARV_APPLICATION_ROOT']

import marv.app
import marv.site
site = marv.site.Site(config)
site.load_for_web()
application = marv.app.create_app(site, app_root=app_root, checkdb=True)


#!/usr/bin/env python
#
# Tests for dakota_utils.write.
#
# Call with:
#   $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)

from nose.tools import *
import os
import tempfile
import shutil
from dakota_utils.file import touch, remove
from dakota_utils.write import *

nonfile = 'fbwiBVBVFVBvVB.txt'

def setup_module():
    print('Write tests:')
    os.environ['_test_tmp_dir'] = tempfile.mkdtemp()

def teardown_module():
    shutil.rmtree(os.environ['_test_tmp_dir'])

@raises(TypeError)
def test_strip_interface_column_no_input():
    '''
    Tests for no input parameter to strip_interface_column().
    '''
    strip_interface_column()

@raises(IOError)
def test_strip_interface_column_file_does_not_exist():
    '''
    Tests for nonexistent input to strip_interface_column().
    '''
    strip_interface_column(nonfile)

Add unit tests for write module

Add unit tests for write module

Response:
<INSERT> #!/usr/bin/env python
#
# Tests for dakota_utils.write.
#
# Call with:
# <INSERT_END> <INSERT>  $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)

from nose.tools import *
import os
import tempfile
import shutil
from dakota_utils.file import touch, remove
from dakota_utils.write import *

nonfile = 'fbwiBVBVFVBvVB.txt'

def setup_module():
    print('Write tests:')
    os.environ['_test_tmp_dir'] = tempfile.mkdtemp()

def teardown_module():
    shutil.rmtree(os.environ['_test_tmp_dir'])

@raises(TypeError)
def test_strip_interface_column_no_input():
    '''
    Tests for no input parameter to strip_interface_column().
    '''
    strip_interface_column()

@raises(IOError)
def test_strip_interface_column_file_does_not_exist():
    '''
    Tests for nonexistent input to strip_interface_column().
    '''
    strip_interface_column(nonfile)

 <INSERT_END> <|endoftext|> #!/usr/bin/env python
#
# Tests for dakota_utils.write.
#
# Call with:
#   $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)

from nose.tools import *
import os
import tempfile
import shutil
from dakota_utils.file import touch, remove
from dakota_utils.write import *

nonfile = 'fbwiBVBVFVBvVB.txt'

def setup_module():
    print('Write tests:')
    os.environ['_test_tmp_dir'] = tempfile.mkdtemp()

def teardown_module():
    shutil.rmtree(os.environ['_test_tmp_dir'])

@raises(TypeError)
def test_strip_interface_column_no_input():
    '''
    Tests for no input parameter to strip_interface_column().
    '''
    strip_interface_column()

@raises(IOError)
def test_strip_interface_column_file_does_not_exist():
    '''
    Tests for nonexistent input to strip_interface_column().
    '''
    strip_interface_column(nonfile)

Prompt: Add unit tests for write module


from skimage import data
from skimage.filter import canny

from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.overlayplugin import OverlayPlugin

image = data.camera()
# Note: ImageViewer must be called before Plugin b/c it starts the event loop.
viewer = ImageViewer(image)
# You can create a UI for a filter just by passing a filter function...
plugin = OverlayPlugin(image_filter=canny)
# ... and adding widgets to adjust parameter values.
plugin += Slider('sigma', 0, 5, update_on='release')
plugin += Slider('low threshold', 0, 255, update_on='release')
plugin += Slider('high threshold', 0, 255, update_on='release')
# Finally, attach the plugin to the image viewer.
viewer += plugin
viewer.show()

Add example of adding widgets to plugin

ENH: Add example of adding widgets to plugin

Response:
<REPLACE_OLD>  <REPLACE_NEW> from skimage import data
from skimage.filter import canny

from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.overlayplugin import OverlayPlugin

image = data.camera()
# Note: ImageViewer must be called before Plugin b/c it starts the event loop.
viewer = ImageViewer(image)
# You can create a UI for a filter just by passing a filter function...
plugin = OverlayPlugin(image_filter=canny)
# ... and adding widgets to adjust parameter values.
plugin += Slider('sigma', 0, 5, update_on='release')
plugin += Slider('low threshold', 0, 255, update_on='release')
plugin += Slider('high threshold', 0, 255, update_on='release')
# Finally, attach the plugin to the image viewer.
viewer += plugin
viewer.show()
 <REPLACE_END> <|endoftext|> from skimage import data
from skimage.filter import canny

from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.overlayplugin import OverlayPlugin

image = data.camera()
# Note: ImageViewer must be called before Plugin b/c it starts the event loop.
viewer = ImageViewer(image)
# You can create a UI for a filter just by passing a filter function...
plugin = OverlayPlugin(image_filter=canny)
# ... and adding widgets to adjust parameter values.
plugin += Slider('sigma', 0, 5, update_on='release')
plugin += Slider('low threshold', 0, 255, update_on='release')
plugin += Slider('high threshold', 0, 255, update_on='release')
# Finally, attach the plugin to the image viewer.
viewer += plugin
viewer.show()

Prompt: ENH: Add example of adding widgets to plugin


import os
import shutil

def main():
    cwd = os.getcwd()
    if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
        print 'This script must be run in \"FRENSIE/scipts\"'
        print 'Your CWD is', cwd
        return 1

    os.chdir('../../')
    os.mkdir('frensie_build_tree')
    #os.renames('FRENSIE', 'frensie_build_tree/FRENSIE')
    os.symlink(os.path.abspath('FRENSIE'), 'frensie_build_tree/FRENSIE')
    os.chdir('frensie_build_tree')
    os.symlink('FRENSIE', 'src')
    os.mkdir('deps')
    os.mkdir('deps/install')
    os.mkdir('deps/tars')
    os.mkdir('build')
    shutil.copyfile('src/scripts/makefile.deps', 'deps/makefile')
    shutil.copyfile('src/scripts/lazy.sh', 'deps/lazy.sh')
    shutil.copyfile('src/scripts/frensie.sh', 'build/frensie.sh')
    #shutil.copyfile('src/scripts/source_deps.sh', 'build/source_deps.sh')

    print """
To build dependencies move necessary tars to deps/tars.
cd to frensie_build_tree/deps and run make all.

To once all dependecies exist in frensie_build_tree/deps/install
cd to frensie_build_tree/build and run bash frensie.sh
"""

if __name__ == '__main__':
    main()

Update to copy new scripts

Update to copy new scripts

Response:
<INSERT> shutil.copyfile('src/scripts/lazy.sh', 'deps/lazy.sh')
    <INSERT_END> <INSERT>
    #shutil.copyfile('src/scripts/source_deps.sh', 'build/source_deps.sh') <INSERT_END> <|endoftext|> import os
import shutil

def main():
    cwd = os.getcwd()
    if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
        print 'This script must be run in \"FRENSIE/scipts\"'
        print 'Your CWD is', cwd
        return 1

    os.chdir('../../')
    os.mkdir('frensie_build_tree')
    #os.renames('FRENSIE', 'frensie_build_tree/FRENSIE')
    os.symlink(os.path.abspath('FRENSIE'), 'frensie_build_tree/FRENSIE')
    os.chdir('frensie_build_tree')
    os.symlink('FRENSIE', 'src')
    os.mkdir('deps')
    os.mkdir('deps/install')
    os.mkdir('deps/tars')
    os.mkdir('build')
    shutil.copyfile('src/scripts/makefile.deps', 'deps/makefile')
    shutil.copyfile('src/scripts/lazy.sh', 'deps/lazy.sh')
    shutil.copyfile('src/scripts/frensie.sh', 'build/frensie.sh')
    #shutil.copyfile('src/scripts/source_deps.sh', 'build/source_deps.sh')

    print """
To build dependencies move necessary tars to deps/tars.
cd to frensie_build_tree/deps and run make all.

To once all dependecies exist in frensie_build_tree/deps/install
cd to frensie_build_tree/build and run bash frensie.sh
"""

if __name__ == '__main__':
    main()

Prompt:
Update to copy new scripts

import os
import shutil

def main():
    cwd = os.getcwd()
    if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
        print 'This script must be run in \"FRENSIE/scipts\"'
        print 'Your CWD is', cwd
        return 1

    os.chdir('../../')
    os.mkdir('frensie_build_tree')
    #os.renames('FRENSIE', 'frensie_build_tree/FRENSIE')
    os.symlink(os.path.abspath('FRENSIE'), 'frensie_build_tree/FRENSIE')
    os.chdir('frensie_build_tree')
    os.symlink('FRENSIE', 'src')
    os.mkdir('deps')
    os.mkdir('deps/install')
    os.mkdir('deps/tars')
    os.mkdir('build')
    shutil.copyfile('src/scripts/makefile.deps', 'deps/makefile')
    shutil.copyfile('src/scripts/frensie.sh', 'build/frensie.sh')

    print """
To build dependencies move necessary tars to deps/tars.
cd to frensie_build_tree/deps and run make all.

To once all dependecies exist in frensie_build_tree/deps/install
cd to frensie_build_tree/build and run bash frensie.sh
"""

if __name__ == '__main__':
    main()


"""
Project Euler Problem 6
=======================

The sum of the squares of the first ten natural numbers is,
                       1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is,
                    (1 + 2 + ... + 10)^2 = 55^2 = 3025

Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.

Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""

def task(numbers):
    return sum(numbers) ** 2 - sum(n ** 2 for n in numbers)

def test_task():
    assert task(range(1, 10 + 1)) == 2640

print(task(range(1, 100 + 1)))

Add solution and unit tests for problem 6

Response:
<INSERT> """
Project Euler Problem 6
=======================

The sum of the squares of the first ten natural numbers is,
 <INSERT_END> <INSERT>                      1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is,
                    (1 + 2 + ... + 10)^2 = 55^2 = 3025

Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.

Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""

def task(numbers):
    return sum(numbers) ** 2 - sum(n ** 2 for n in numbers)

def test_task():
    assert task(range(1, 10 + 1)) == 2640

print(task(range(1, 100 + 1)))
 <INSERT_END> <|endoftext|> """
Project Euler Problem 6
=======================

The sum of the squares of the first ten natural numbers is,
                       1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is,
                    (1 + 2 + ... + 10)^2 = 55^2 = 3025

Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.

Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""

def task(numbers):
    return sum(numbers) ** 2 - sum(n ** 2 for n in numbers)

def test_task():
    assert task(range(1, 10 + 1)) == 2640

print(task(range(1, 100 + 1)))

Prompt: Add solution and unit tests for problem 6