"""Facility to render node graphs using pydot"""
import os

import pydot
from kitchen.settings import STATIC_ROOT, REPO

def generate_node_map(nodes):
    """Generates a graphviz nodemap"""
    graph = pydot.Dot(graph_type='digraph')
    graph_nodes = {}
    # Create nodes
    for node in nodes:
        label = node['name'] + "\n" + "\n".join(
            [role for role in node['role'] \
                if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX'])])
        node_el = pydot.Node(label,
                             shape="box",
                             style="filled",
                             fillcolor="lightyellow",
                             fontsize="8")
        graph_nodes[node['name']] = node_el
        graph.add_node(node_el)
    # Create links
    for node in nodes:
        for attr in node.keys():
            try:
                client_roles = node[attr]['client_roles']
            except (TypeError, KeyError):
                continue
            for client_node in nodes:
                if set.intersection(
                        set(client_roles), set(client_node['roles'])):
                    edge = pydot.Edge(graph_nodes[client_node['name']],
                                      graph_nodes[node['name']],
                                      fontsize="7")
                    edge.set_label(attr)
                    graph.add_edge(edge)
    # Generate graph
    graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))

Response:
<REPLACE_OLD> if isinstance(node[attr], dict) and 'client_roles' in node[attr]:
     <REPLACE_NEW> try:
                client_roles = node[attr]['client_roles']
            except (TypeError, KeyError):
                continue
 <REPLACE_END> <DELETE>     <DELETE_END> <REPLACE_OLD> set.intersection(set(node[attr]['client_roles']),
                                        <REPLACE_NEW> set.intersection(
                        set(client_roles), <REPLACE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <|endoftext|> """Facility to render node graphs using pydot"""
import os

import pydot
from kitchen.settings import STATIC_ROOT, REPO

def generate_node_map(nodes):
    """Generates a graphviz nodemap"""
    graph = pydot.Dot(graph_type='digraph')
    graph_nodes = {}
    # Create nodes
    for node in nodes:
        label = node['name'] + "\n" + "\n".join(
            [role for role in node['role'] \
                if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX'])])
        node_el = pydot.Node(label,
                             shape="box",
                             style="filled",
                             fillcolor="lightyellow",
                             fontsize="8")
        graph_nodes[node['name']] = node_el
        graph.add_node(node_el)
    # Create links
    for node in nodes:
        for attr in node.keys():
            try:
                client_roles = node[attr]['client_roles']
            except (TypeError, KeyError):
                continue
            for client_node in nodes:
                if set.intersection(
                        set(client_roles), set(client_node['roles'])):
                    edge = pydot.Edge(graph_nodes[client_node['name']],
                                      graph_nodes[node['name']],
                                      fontsize="7")
                    edge.set_label(attr)
                    graph.add_edge(edge)
    # Generate graph
    graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))

Prompt:
Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated

"""Facility to render node graphs using pydot"""
import os

import pydot
from kitchen.settings import STATIC_ROOT, REPO

def generate_node_map(nodes):
    """Generates a graphviz nodemap"""
    graph = pydot.Dot(graph_type='digraph')
    graph_nodes = {}
    # Create nodes
    for node in nodes:
        label = node['name'] + "\n" + "\n".join(
            [role for role in node['role'] \
                if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX'])])
        node_el = pydot.Node(label,
                             shape="box",
                             style="filled",
                             fillcolor="lightyellow",
                             fontsize="8")
        graph_nodes[node['name']] = node_el
        graph.add_node(node_el)
    # Create links
    for node in nodes:
        for attr in node.keys():
            if isinstance(node[attr], dict) and 'client_roles' in node[attr]:
                for client_node in nodes:
                    if set.intersection(set(node[attr]['client_roles']),
                                        set(client_node['roles'])):
                        edge = pydot.Edge(graph_nodes[client_node['name']],
                                          graph_nodes[node['name']],
                                          fontsize="7")
                        edge.set_label(attr)
                        graph.add_edge(edge)
    # Generate graph
    graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))


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

# All files in this directory should be moved to catapult/base/ after moving
# to the new repo.

Add catapult_base folder to tools/telemetry to make the refactor easier.

This will make some of the refactoring more obvious and easy to review, as
well as making the needed reafctoring after moving to the catapult repo easier.

BUG=473414

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#333399}

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

# All files in this directory should be moved to catapult/base/ after moving
# to the new repo.
 <REPLACE_END> <|endoftext|> # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# All files in this directory should be moved to catapult/base/ after moving
# to the new repo.

Prompt:
Add catapult_base folder to tools/telemetry to make the refactor easier.

This will make some of the refactoring more obvious and easy to review, as
well as making the needed reafctoring after moving to the catapult repo easier.

BUG=473414

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#333399}


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

# Copyright (c) 2015 Ericsson AB
#
# 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 umsgpack
from message_coder import MessageCoderBase

umsgpack.compatibility = True

# set of functions to encode/decode data tokens to/from a json description
class MessageCoder(MessageCoderBase):

    def encode(self, data):
        return umsgpack.packb(data)

    def decode(self, data):
        data = umsgpack.unpackb(data)
        return data

Use umsgpack package for msgpack coder

Response:
<REPLACE_OLD> msgpack
from <REPLACE_NEW> umsgpack
from <REPLACE_END> <REPLACE_OLD> MessageCoderBase

# <REPLACE_NEW> MessageCoderBase

umsgpack.compatibility = True

# <REPLACE_END> <REPLACE_OLD> msgpack.packb(data)

 <REPLACE_NEW> umsgpack.packb(data)

 <REPLACE_END> <REPLACE_OLD> msgpack.unpackb(data)
 <REPLACE_NEW> umsgpack.unpackb(data)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

# Copyright (c) 2015 Ericsson AB
#
# 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 umsgpack
from message_coder import MessageCoderBase

umsgpack.compatibility = True

# set of functions to encode/decode data tokens to/from a json description
class MessageCoder(MessageCoderBase):

    def encode(self, data):
        return umsgpack.packb(data)

    def decode(self, data):
        data = umsgpack.unpackb(data)
        return data

Prompt:
coder/msgpack: Use umsgpack package for msgpack coder

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

# Copyright (c) 2015 Ericsson AB
#
# 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 msgpack
from message_coder import MessageCoderBase

# set of functions to encode/decode data tokens to/from a json description
class MessageCoder(MessageCoderBase):

    def encode(self, data):
        return msgpack.packb(data)

    def decode(self, data):
        data = msgpack.unpackb(data)
        return data


from txircd.modbase import Mode

class SecretMode(Mode):
	def listOutput(self, command, data):
		if command != "LIST":
			return data
		cdata = data["cdata"]
		if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
			data["cdata"].clear()
	# other +s stuff is hiding in other modules.

class Spawner(object):
	def __init__(self, ircd):
		self.ircd = ircd
		self.mode_s = None

	def spawn(self):
		self.mode_s = SecretMode()
		return {
			"modes": {
				"cns": self.mode_s
			},
			"actions": {
				"commandextra": [self.mode_s.listOutput]
			}
		}

	def cleanup(self):
		self.ircd.removeMode("cns")
		self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)

Response:
<REPLACE_OLD> data["user"].channels:
			data["cdata"] = {}
	# <REPLACE_NEW> data["user"].channels:
			data["cdata"].clear()
	# <REPLACE_END> <|endoftext|> from txircd.modbase import Mode

class SecretMode(Mode):
	def listOutput(self, command, data):
		if command != "LIST":
			return data
		cdata = data["cdata"]
		if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
			data["cdata"].clear()
	# other +s stuff is hiding in other modules.

class Spawner(object):
	def __init__(self, ircd):
		self.ircd = ircd
		self.mode_s = None

	def spawn(self):
		self.mode_s = SecretMode()
		return {
			"modes": {
				"cns": self.mode_s
			},
			"actions": {
				"commandextra": [self.mode_s.listOutput]
			}
		}

	def cleanup(self):
		self.ircd.removeMode("cns")
		self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)

Prompt:
Make +s actually definitely clear the cdata dictionary

from txircd.modbase import Mode

class SecretMode(Mode):
	def listOutput(self, command, data):
		if command != "LIST":
			return data
		cdata = data["cdata"]
		if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels:
			data["cdata"] = {}
	# other +s stuff is hiding in other modules.

class Spawner(object):
	def __init__(self, ircd):
		self.ircd = ircd
		self.mode_s = None

	def spawn(self):
		self.mode_s = SecretMode()
		return {
			"modes": {
				"cns": self.mode_s
			},
			"actions": {
				"commandextra": [self.mode_s.listOutput]
			}
		}

	def cleanup(self):
		self.ircd.removeMode("cns")
		self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)


Fix a lint required empty lines issue

Fix a lint required empty lines issue

Response:
<REPLACE_OLD> read_text

class <REPLACE_NEW> read_text

class <REPLACE_END> <|endoftext|> from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text

class MdConverter(KnowledgePostConverter):
    _registry_keys = [MD]

    def from_file(self, filename):
        self.kp_write(read_text(filename))

Prompt:
Fix a lint required empty lines issue

from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text

class MdConverter(KnowledgePostConverter):
    _registry_keys = [MD]

    def from_file(self, filename):
        self.kp_write(read_text(filename))


Reformat test to a standard style.

Reformat test to a standard style.

Response:
<REPLACE_OLD> """Test <REPLACE_NEW> # -*- coding: utf-8 -*-
"""Test <REPLACE_END> <REPLACE_OLD> module."""

from <REPLACE_NEW> module."""

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from <REPLACE_END> <REPLACE_OLD> dreload

@dec.skipif_not_numpy
def <REPLACE_NEW> dreload

#-----------------------------------------------------------------------------
# Test functions begin
#-----------------------------------------------------------------------------

@dec.skipif_not_numpy
def <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""Test suite for the deepreload module."""

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload

#-----------------------------------------------------------------------------
# Test functions begin
#-----------------------------------------------------------------------------

@dec.skipif_not_numpy
def test_deepreload_numpy():
    import numpy
    exclude = [
        # Standard exclusions:
        'sys', 'os.path', '__builtin__', '__main__',
        # Test-related exclusions:
        'unittest',
        ]
    dreload(numpy, exclude=exclude)

Prompt:
Reformat test to a standard style.

"""Test suite for the deepreload module."""

from IPython.testing import decorators as dec
from IPython.lib.deepreload import reload as dreload

@dec.skipif_not_numpy
def test_deepreload_numpy():
    import numpy
    exclude = [
        # Standard exclusions:
        'sys', 'os.path', '__builtin__', '__main__',
        # Test-related exclusions:
        'unittest',
        ]
    dreload(numpy, exclude=exclude)


import subprocess
import sys
import setup_util
import os

def start(args):
  subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
                   + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
  return 0
def stop():
  p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
  out, err = p.communicate()
  for line in out.splitlines():
    if 'gunicorn' in line:
      try:
        pid = int(line.split(None, 2)[1])
        os.kill(pid, 9)
      except OSError:
        pass

  return 0

Response:
<REPLACE_OLD> subprocess.Popen("gunicorn <REPLACE_NEW> subprocess.Popen('gunicorn <REPLACE_END> <INSERT> --worker-class="egg:meinheld#gunicorn_worker" <INSERT_END> <REPLACE_OLD> " <REPLACE_NEW> '
                   <REPLACE_END> <REPLACE_OLD> 0 <REPLACE_NEW> 0
 <REPLACE_END> <|endoftext|>
import subprocess
import sys
import setup_util
import os

def start(args):
  subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w '
                   + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
  return 0
def stop():
  p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
  out, err = p.communicate()
  for line in out.splitlines():
    if 'gunicorn' in line:
      try:
        pid = int(line.split(None, 2)[1])
        os.kill(pid, 9)
      except OSError:
        pass

  return 0

Prompt:
wsgi: Use meinheld worker (same as other Python Frameworks)

import subprocess
import sys
import setup_util
import os

def start(args):
  subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi")
  return 0
def stop():
  p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
  out, err = p.communicate()
  for line in out.splitlines():
    if 'gunicorn' in line:
      try:
        pid = int(line.split(None, 2)[1])
        os.kill(pid, 9)
      except OSError:
        pass

  return 0


# -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your url patterns (usually in your root urls.conf; `somewhere`
may be any path, except the one used for true posts).
"""

try:
    from django.conf.urls import patterns
except ImportError:
    from django.conf.urls.defaults import patterns

urlpatterns = patterns('',
                       (r'^post$', 'djangospam.cookie.views.spammer_view'),)

Add support for Django 1.4 and up

Response:
<REPLACE_OLD> posts).
"""

from <REPLACE_NEW> posts).
"""

try:
    from django.conf.urls import patterns
except ImportError:
    from <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your url patterns (usually in your root urls.conf; `somewhere`
may be any path, except the one used for true posts).
"""

try:
    from django.conf.urls import patterns
except ImportError:
    from django.conf.urls.defaults import patterns

urlpatterns = patterns('',
                       (r'^post$', 'djangospam.cookie.views.spammer_view'),)

Prompt:
Add support for Django 1.4 and up

* Module django.conf.urls.defaults has been moved to django.conf.urls in
version 1.4.

Commit references issue #3.

# -*- coding: utf-8 -*-
"""URL for setting SPAM value to the `djangospam.cookie` cookie.
You must also add `(r"^somewhere/", include("djangospam.cookie.urls")`
to your url patterns (usually in your root urls.conf; `somewhere`
may be any path, except the one used for true posts).
"""

from django.conf.urls.defaults import patterns

urlpatterns = patterns('',
                       (r'^post$', 'djangospam.cookie.views.spammer_view'),)


import pytest

from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS

@pytest.mark.parametrize('divisor', (
    2,
    3,
    4,
    5,
    6,
    10,
    100,
))
def test_divisible(divisor):
    assert NUM_BUCKETS % divisor == 0

def test_at_least_three_buckets_per_percent():
    assert NUM_BUCKETS / 100 >= 3

def test_can_get_empty_bucket_from_old_format():
    session = Session({'buckets/1': []})
    bucket = session.get(Bucket, 1)
    # Force bucket to a string in order to reify the fields. This validates
    # that the fields are accessible.
    str(bucket)

Use an explicit test here

Use an explicit test here

Response:
<REPLACE_OLD> assert not bucket.needs_constraints()
 <REPLACE_NEW> # Force bucket to a string in order to reify the fields. This validates
    # that the fields are accessible.
    str(bucket)
 <REPLACE_END> <|endoftext|> import pytest

from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS

@pytest.mark.parametrize('divisor', (
    2,
    3,
    4,
    5,
    6,
    10,
    100,
))
def test_divisible(divisor):
    assert NUM_BUCKETS % divisor == 0

def test_at_least_three_buckets_per_percent():
    assert NUM_BUCKETS / 100 >= 3

def test_can_get_empty_bucket_from_old_format():
    session = Session({'buckets/1': []})
    bucket = session.get(Bucket, 1)
    # Force bucket to a string in order to reify the fields. This validates
    # that the fields are accessible.
    str(bucket)

Prompt:
Use an explicit test here

import pytest

from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS

@pytest.mark.parametrize('divisor', (
    2,
    3,
    4,
    5,
    6,
    10,
    100,
))
def test_divisible(divisor):
    assert NUM_BUCKETS % divisor == 0

def test_at_least_three_buckets_per_percent():
    assert NUM_BUCKETS / 100 >= 3

def test_can_get_empty_bucket_from_old_format():
    session = Session({'buckets/1': []})
    bucket = session.get(Bucket, 1)
    assert not bucket.needs_constraints()


# -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# Copyright 2018 initOS GmbH
#   (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

{
    'name': 'Stock Inventory Chatter',
    'version': '8.0.1.0.0',
    'author': "Eficent, "
              "initOS GmbH, "
              "Odoo Community Association (OCA)",
    "website": "https://github.com/OCA/stock-logistics-warehouse",
    'category': 'Warehouse',
    'summary': "Log changes being done in Inventory Adjustments",
    'depends': ['stock'],
    "data": [
        'data/stock_data.xml',
        'views/stock_inventory_view.xml',
    ],
    'license': 'AGPL-3',
    'installable': True,
    'application': False,
}

Change of the module version

Change of the module version

Response:
<INSERT> Copyright 2018 initOS GmbH
# <INSERT_END> <REPLACE_OLD> '9.0.1.0.0',
 <REPLACE_NEW> '8.0.1.0.0',
 <REPLACE_END> <INSERT> "
              "initOS GmbH, <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
# Copyright 2018 initOS GmbH
#   (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

{
    'name': 'Stock Inventory Chatter',
    'version': '8.0.1.0.0',
    'author': "Eficent, "
              "initOS GmbH, "
              "Odoo Community Association (OCA)",
    "website": "https://github.com/OCA/stock-logistics-warehouse",
    'category': 'Warehouse',
    'summary': "Log changes being done in Inventory Adjustments",
    'depends': ['stock'],
    "data": [
        'data/stock_data.xml',
        'views/stock_inventory_view.xml',
    ],
    'license': 'AGPL-3',
    'installable': True,
    'application': False,
}

Prompt:
Change of the module version

# -*- coding: utf-8 -*-
# Copyright 2017 Eficent Business and IT Consulting Services S.L.
#   (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

{
    'name': 'Stock Inventory Chatter',
    'version': '9.0.1.0.0',
    'author': "Eficent, "
              "Odoo Community Association (OCA)",
    "website": "https://github.com/OCA/stock-logistics-warehouse",
    'category': 'Warehouse',
    'summary': "Log changes being done in Inventory Adjustments",
    'depends': ['stock'],
    "data": [
        'data/stock_data.xml',
        'views/stock_inventory_view.xml',
    ],
    'license': 'AGPL-3',
    'installable': True,
    'application': False,
}


from __future__ import absolute_import

from ds.models import App

from .base import Serializer
from .manager import add

@add(App)
class AppSerializer(Serializer):
    def serialize(self, item, attrs):
        return {
            'id': str(item.id),
            'name': item.name,
            'provider': item.provider,
            'provider_config': item.provider_config,
        }

Add provider information to App

Add provider information to App

Response:
<INSERT>     'provider': item.provider,
            'provider_config': item.provider_config,
        <INSERT_END> <|endoftext|> from __future__ import absolute_import

from ds.models import App

from .base import Serializer
from .manager import add

@add(App)
class AppSerializer(Serializer):
    def serialize(self, item, attrs):
        return {
            'id': str(item.id),
            'name': item.name,
            'provider': item.provider,
            'provider_config': item.provider_config,
        }

Prompt:
Add provider information to App

from __future__ import absolute_import

from ds.models import App

from .base import Serializer
from .manager import add

@add(App)
class AppSerializer(Serializer):
    def serialize(self, item, attrs):
        return {
            'id': str(item.id),
            'name': item.name,
        }


# -*- coding: utf-8 -*-
import os
from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except:
        return ''

setup(
    name='todoist-python',
    version='7.0.9',
    packages=['todoist', 'todoist.managers'],
    author='Doist Team',
    author_email='info@todoist.com',
    license='BSD',
    description='todoist-python - The official Todoist Python API library',
    long_description = read('README.md'),
    install_requires=[
        'requests',
    ],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
    ),
)

Update the PyPI version to 7.0.9.

Update the PyPI version to 7.0.9.

Response:
<REPLACE_OLD> version='7.0.8',
 <REPLACE_NEW> version='7.0.9',
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import os
from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except:
        return ''

setup(
    name='todoist-python',
    version='7.0.9',
    packages=['todoist', 'todoist.managers'],
    author='Doist Team',
    author_email='info@todoist.com',
    license='BSD',
    description='todoist-python - The official Todoist Python API library',
    long_description = read('README.md'),
    install_requires=[
        'requests',
    ],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
    ),
)

Prompt:
Update the PyPI version to 7.0.9.

# -*- coding: utf-8 -*-
import os
from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except:
        return ''

setup(
    name='todoist-python',
    version='7.0.8',
    packages=['todoist', 'todoist.managers'],
    author='Doist Team',
    author_email='info@todoist.com',
    license='BSD',
    description='todoist-python - The official Todoist Python API library',
    long_description = read('README.md'),
    install_requires=[
        'requests',
    ],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
    ),
)


import unittest
import os, sys

sys.path.append(os.path.join(os.path.dirname(__file__), "..\\"))

from app import create_app, db
from app.utils import get_or_create
from app.models import User

class TestUtils(unittest.TestCase):
    def setUp(self):
        self.app = create_app("testing")
        self.app_ctx = self.app.app_context()
        self.app_ctx.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_ctx.pop()

    def test_get_or_create(self):
        user1, created1 = get_or_create(User, name="foo", social_id="bar")
        db.session.add(user1)
        db.session.commit()
        user2, created2 = get_or_create(User, name="foo", social_id="bar")
        assert created1
        assert not created2
        assert user1 == user2

Add test case for get_or_create util

Add test case for get_or_create util

Response:
<INSERT> import unittest
import os, sys

sys.path.append(os.path.join(os.path.dirname(__file__), "..\\"))

from app import create_app, db
from app.utils import get_or_create
from app.models import User

class TestUtils(unittest.TestCase):
 <INSERT_END> <INSERT>   def setUp(self):
        self.app = create_app("testing")
        self.app_ctx = self.app.app_context()
        self.app_ctx.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_ctx.pop()

    def test_get_or_create(self):
        user1, created1 = get_or_create(User, name="foo", social_id="bar")
        db.session.add(user1)
        db.session.commit()
        user2, created2 = get_or_create(User, name="foo", social_id="bar")
        assert created1
        assert not created2
        assert user1 == user2 <INSERT_END> <|endoftext|> import unittest
import os, sys

sys.path.append(os.path.join(os.path.dirname(__file__), "..\\"))

from app import create_app, db
from app.utils import get_or_create
from app.models import User

class TestUtils(unittest.TestCase):
    def setUp(self):
        self.app = create_app("testing")
        self.app_ctx = self.app.app_context()
        self.app_ctx.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_ctx.pop()

    def test_get_or_create(self):
        user1, created1 = get_or_create(User, name="foo", social_id="bar")
        db.session.add(user1)
        db.session.commit()
        user2, created2 = get_or_create(User, name="foo", social_id="bar")
        assert created1
        assert not created2
        assert user1 == user2

Prompt: Add test case for get_or_create util


from .blueprint import root_blueprint as root_route
from ...core.node import node

# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize

from flask import request, Response
import json

@root_route.route("/pysyft", methods=["POST"])
def root_route():
    data = request.get_data()
    obj_msg = _deserialize(blob=data, from_bytes=True)
    if isinstance(obj_msg, SignedImmediateSyftMessageWithReply):
        reply = node.recv_immediate_msg_with_reply(msg=obj_msg)
        r = Response(response=reply.serialize(to_bytes=True), status=200)
        r.headers["Content-Type"] = "application/octet-stream"
        return r
    elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply):
        node.recv_immediate_msg_without_reply(msg=obj_msg)
    else:
        node.recv_eventual_msg_without_reply(msg=obj_msg)
    return ""

Response:
<REPLACE_OLD> json_msg <REPLACE_NEW> data <REPLACE_END> <REPLACE_OLD> request.get_json()
 <REPLACE_NEW> request.get_data()
 <REPLACE_END> <REPLACE_OLD> _deserialize(blob=json_msg, from_json=True)
 <REPLACE_NEW> _deserialize(blob=data, from_bytes=True)
 <REPLACE_END> <INSERT> r = Response(response=reply.serialize(to_bytes=True), status=200)
        r.headers["Content-Type"] = "application/octet-stream"
        <INSERT_END> <REPLACE_OLD> reply.json()
 <REPLACE_NEW> r
 <REPLACE_END> <|endoftext|> from .blueprint import root_blueprint as root_route
from ...core.node import node

# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize

from flask import request, Response
import json

@root_route.route("/pysyft", methods=["POST"])
def root_route():
    data = request.get_data()
    obj_msg = _deserialize(blob=data, from_bytes=True)
    if isinstance(obj_msg, SignedImmediateSyftMessageWithReply):
        reply = node.recv_immediate_msg_with_reply(msg=obj_msg)
        r = Response(response=reply.serialize(to_bytes=True), status=200)
        r.headers["Content-Type"] = "application/octet-stream"
        return r
    elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply):
        node.recv_immediate_msg_without_reply(msg=obj_msg)
    else:
        node.recv_eventual_msg_without_reply(msg=obj_msg)
    return ""

Prompt:
Update /users/login endpoint to return serialized metadata

from .blueprint import root_blueprint as root_route
from ...core.node import node

# syft absolute
from syft.core.common.message import SignedImmediateSyftMessageWithReply
from syft.core.common.message import SignedImmediateSyftMessageWithoutReply
from syft.core.common.serde.deserialize import _deserialize

from flask import request, Response
import json

@root_route.route("/pysyft", methods=["POST"])
def root_route():
    json_msg = request.get_json()
    obj_msg = _deserialize(blob=json_msg, from_json=True)
    if isinstance(obj_msg, SignedImmediateSyftMessageWithReply):
        reply = node.recv_immediate_msg_with_reply(msg=obj_msg)
        return reply.json()
    elif isinstance(obj_msg, SignedImmediateSyftMessageWithoutReply):
        node.recv_immediate_msg_without_reply(msg=obj_msg)
    else:
        node.recv_eventual_msg_without_reply(msg=obj_msg)
    return ""


from ..utils import *

##
# Minions

# Murloc Knight
class AT_076:
	inspire = Summon(CONTROLLER, RandomMurloc())

# Eadric the Pure
class AT_081:
	play = Buff(ENEMY_MINIONS, "AT_081e")

##
# Spells

# Seal of Champions
class AT_074:
	play = Buff(TARGET, "AT_074e2")

##
# Secrets

# Competitive Spirit
class AT_073:
	events = OWN_TURN_BEGIN.on(
		Buff(FRIENDLY_MINIONS, "AT_073e"), Reveal(SELF)
	)

Fix Eadric the Pure's target selection

Fix Eadric the Pure's target selection

Response:
<REPLACE_OLD> AT_076:
    inspire <REPLACE_NEW> AT_076:
	inspire <REPLACE_END> <REPLACE_OLD> AT_081:
    play <REPLACE_NEW> AT_081:
	play <REPLACE_END> <REPLACE_OLD> Buff(ALL_MINIONS, <REPLACE_NEW> Buff(ENEMY_MINIONS, <REPLACE_END> <REPLACE_OLD> AT_074:
    play <REPLACE_NEW> AT_074:
	play <REPLACE_END> <REPLACE_OLD> AT_073:
    events <REPLACE_NEW> AT_073:
	events <REPLACE_END> <REPLACE_OLD> OWN_TURN_BEGIN.on(
        Buff(FRIENDLY_MINIONS, <REPLACE_NEW> OWN_TURN_BEGIN.on(
		Buff(FRIENDLY_MINIONS, <REPLACE_END> <REPLACE_OLD> Reveal(SELF)
    )
 <REPLACE_NEW> Reveal(SELF)
	)
 <REPLACE_END> <|endoftext|> from ..utils import *

##
# Minions

# Murloc Knight
class AT_076:
	inspire = Summon(CONTROLLER, RandomMurloc())

# Eadric the Pure
class AT_081:
	play = Buff(ENEMY_MINIONS, "AT_081e")

##
# Spells

# Seal of Champions
class AT_074:
	play = Buff(TARGET, "AT_074e2")

##
# Secrets

# Competitive Spirit
class AT_073:
	events = OWN_TURN_BEGIN.on(
		Buff(FRIENDLY_MINIONS, "AT_073e"), Reveal(SELF)
	)

Prompt:
Fix Eadric the Pure's target selection

from ..utils import *

##
# Minions

# Murloc Knight
class AT_076:
    inspire = Summon(CONTROLLER, RandomMurloc())

# Eadric the Pure
class AT_081:
    play = Buff(ALL_MINIONS, "AT_081e")

##
# Spells

# Seal of Champions
class AT_074:
    play = Buff(TARGET, "AT_074e2")

##
# Secrets

# Competitive Spirit
class AT_073:
    events = OWN_TURN_BEGIN.on(
        Buff(FRIENDLY_MINIONS, "AT_073e"), Reveal(SELF)
    )


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

"""Copy data from the given zip file to the project."""

import argparse
import fnmatch
import os
import time
import zipfile

__author__ = 'fyabc'

DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
DataFilePattern = '*/resources/*'

def main(args=None):
    parser = argparse.ArgumentParser(description='Copy data from data zip file into this project.')
    parser.add_argument('file', help='path to data zip file')
    args = parser.parse_args(args)

    time_start = time.time()
    n_files = 0

    with zipfile.ZipFile(args.file) as zip_file:
        rc_names = fnmatch.filter((name for name in zip_file.namelist() if not name.endswith('/')), DataFilePattern)
        for name in rc_names:
            print('Copying file {} to {} ... '.format(name, os.path.join(DataDir, name)), end='')
            zip_file.extract(name, path=DataDir)
            n_files += 1
            print('done')

    print('Copy {} files in {:.6f}s.'.format(n_files, time.time() - time_start))

if __name__ == '__main__':
    main()

Add a script to copy data files conveniently.

Response:
<INSERT> #! /usr/bin/python
# -*- coding: utf-8 -*-

"""Copy data from the given zip file to the project."""

import argparse
import fnmatch
import os
import time
import zipfile

__author__ = 'fyabc'

DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
DataFilePattern = '*/resources/*'

def main(args=None):
 <INSERT_END> <INSERT>   parser = argparse.ArgumentParser(description='Copy data from data zip file into this project.')
    parser.add_argument('file', help='path to data zip file')
    args = parser.parse_args(args)

    time_start = time.time()
    n_files = 0

    with zipfile.ZipFile(args.file) as zip_file:
        rc_names = fnmatch.filter((name for name in zip_file.namelist() if not name.endswith('/')), DataFilePattern)
        for name in rc_names:
            print('Copying file {} to {} ... '.format(name, os.path.join(DataDir, name)), end='')
            zip_file.extract(name, path=DataDir)
            n_files += 1
            print('done')

    print('Copy {} files in {:.6f}s.'.format(n_files, time.time() - time_start))

if __name__ == '__main__':
    main()
 <INSERT_END> <|endoftext|> #! /usr/bin/python
# -*- coding: utf-8 -*-

"""Copy data from the given zip file to the project."""

import argparse
import fnmatch
import os
import time
import zipfile

__author__ = 'fyabc'

DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
DataFilePattern = '*/resources/*'

def main(args=None):
    parser = argparse.ArgumentParser(description='Copy data from data zip file into this project.')
    parser.add_argument('file', help='path to data zip file')
    args = parser.parse_args(args)

    time_start = time.time()
    n_files = 0

    with zipfile.ZipFile(args.file) as zip_file:
        rc_names = fnmatch.filter((name for name in zip_file.namelist() if not name.endswith('/')), DataFilePattern)
        for name in rc_names:
            print('Copying file {} to {} ... '.format(name, os.path.join(DataDir, name)), end='')
            zip_file.extract(name, path=DataDir)
            n_files += 1
            print('done')

    print('Copy {} files in {:.6f}s.'.format(n_files, time.time() - time_start))

if __name__ == '__main__':
    main()

Prompt: Add a script to copy data files conveniently.


import pymongo

DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
                                              DEFAULT_MONGODB_PORT,
                                              DEFAULT_MONGODB_NAME)

class MongoDB(object):
    """Simple wrapper to get pymongo real objects from the settings uri"""

    def __init__(self, db_uri=DEFAULT_MONGODB_URI,
                 connection_factory=pymongo.MongoClient):
        self.db_uri = db_uri
        self.connection = connection_factory(
            host=self.db_uri,
            tz_aware=True)

        if self.db_uri.path:
            self.database_name = self.db_uri.path[1:]
        else:
            self.database_name = DEFAULT_MONGODB_NAME

    def get_connection(self):
        return self.connection

    def get_database(self):
        database = self.connection[self.database_name]
        if self.db_uri.username and self.db_uri.password:
            database.authenticate(self.db_uri.username, self.db_uri.password)

        return database

def get_db(request):
    return request.registry.settings['mongodb'].get_database()

Response:
<REPLACE_OLD> pymongo

from eduid_signup.compat import urlparse

DEFAULT_MONGODB_HOST <REPLACE_NEW> pymongo

DEFAULT_MONGODB_HOST <REPLACE_END> <REPLACE_OLD> connection_factory=pymongo.Connection):
 <REPLACE_NEW> connection_factory=pymongo.MongoClient):
 <REPLACE_END> <REPLACE_OLD> urlparse.urlparse(db_uri)
 <REPLACE_NEW> db_uri
 <REPLACE_END> <REPLACE_OLD> host=self.db_uri.hostname or DEFAULT_MONGODB_HOST,
            port=self.db_uri.port or DEFAULT_MONGODB_PORT,
 <REPLACE_NEW> host=self.db_uri,
 <REPLACE_END> <|endoftext|> import pymongo

DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
                                              DEFAULT_MONGODB_PORT,
                                              DEFAULT_MONGODB_NAME)

class MongoDB(object):
    """Simple wrapper to get pymongo real objects from the settings uri"""

    def __init__(self, db_uri=DEFAULT_MONGODB_URI,
                 connection_factory=pymongo.MongoClient):
        self.db_uri = db_uri
        self.connection = connection_factory(
            host=self.db_uri,
            tz_aware=True)

        if self.db_uri.path:
            self.database_name = self.db_uri.path[1:]
        else:
            self.database_name = DEFAULT_MONGODB_NAME

    def get_connection(self):
        return self.connection

    def get_database(self):
        database = self.connection[self.database_name]
        if self.db_uri.username and self.db_uri.password:
            database.authenticate(self.db_uri.username, self.db_uri.password)

        return database

def get_db(request):
    return request.registry.settings['mongodb'].get_database()

Prompt:
Allow Mongo connections to Mongo Replicaset Cluster

import pymongo

from eduid_signup.compat import urlparse

DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
                                              DEFAULT_MONGODB_PORT,
                                              DEFAULT_MONGODB_NAME)

class MongoDB(object):
    """Simple wrapper to get pymongo real objects from the settings uri"""

    def __init__(self, db_uri=DEFAULT_MONGODB_URI,
                 connection_factory=pymongo.Connection):
        self.db_uri = urlparse.urlparse(db_uri)
        self.connection = connection_factory(
            host=self.db_uri.hostname or DEFAULT_MONGODB_HOST,
            port=self.db_uri.port or DEFAULT_MONGODB_PORT,
            tz_aware=True)

        if self.db_uri.path:
            self.database_name = self.db_uri.path[1:]
        else:
            self.database_name = DEFAULT_MONGODB_NAME

    def get_connection(self):
        return self.connection

    def get_database(self):
        database = self.connection[self.database_name]
        if self.db_uri.username and self.db_uri.password:
            database.authenticate(self.db_uri.username, self.db_uri.password)

        return database

def get_db(request):
    return request.registry.settings['mongodb'].get_database()


#!/usr/bin/env python

from distutils.core import setup

setup(name='straight.plugin',
      version='1.1.1',
      description='A simple namespaced plugin facility',
      author='Calvin Spealman',
      author_email='ironfroggy@gmail.com',
      url='https://github.com/ironfroggy/straight.plugin',
      packages=['straight', 'straight.plugin'],
     )

Mark version 1.1.1 with license.

Mark version 1.1.1 with license.

Response:
<REPLACE_OLD> version='1.0',
 <REPLACE_NEW> version='1.1.1',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from distutils.core import setup

setup(name='straight.plugin',
      version='1.1.1',
      description='A simple namespaced plugin facility',
      author='Calvin Spealman',
      author_email='ironfroggy@gmail.com',
      url='https://github.com/ironfroggy/straight.plugin',
      packages=['straight', 'straight.plugin'],
     )

Prompt:
Mark version 1.1.1 with license.

#!/usr/bin/env python

from distutils.core import setup

setup(name='straight.plugin',
      version='1.0',
      description='A simple namespaced plugin facility',
      author='Calvin Spealman',
      author_email='ironfroggy@gmail.com',
      url='https://github.com/ironfroggy/straight.plugin',
      packages=['straight', 'straight.plugin'],
     )


class Asset:
    """
    This is an ooni-probe asset. It is a python
    iterator object, allowing it to be efficiently looped.
    To create your own custom asset your should subclass this
    and override the next_asset method and the len method for
    computing the length of the asset.
    """
    def __init__(self, file=None, *args, **argv):
        self.fh = None
        if file:
            self.name = file
            self.fh = open(file, 'r')
        self.eof = False

    def __iter__(self):
        return self

    def len(self):
        """
        Returns the length of the asset
        """
        for i, l in enumerate(self.fh):
            pass
        # rewind the file
        self.fh.seek(0)
        return i + 1

    def parse_line(self, line):
        """
        Override this method if you need line
        by line parsing of an Asset.
        """
        return line.replace('\n','')

    def next_asset(self):
        """
        Return the next asset.
        """
        # XXX this is really written with my feet.
        #     clean me up please...
        line = self.fh.readline()
        if line:
            parsed_line = self.parse_line(line)
            if parsed_line:
                return parsed_line
        else:
            self.fh.seek(0)
            raise StopIteration

    def next(self):
        try:
            return self.next_asset()
        except:
            raise StopIteration

Response:
<INSERT> parse_line(self, line):
        """
        Override this method if you need line
        by line parsing of an Asset.
        """
        return line.replace('\n','')

    def <INSERT_END> <INSERT> parsed_line = self.parse_line(line)
            if parsed_line:
                <INSERT_END> <REPLACE_OLD> line.replace('\n','')
 <REPLACE_NEW> parsed_line
 <REPLACE_END> <|endoftext|> class Asset:
    """
    This is an ooni-probe asset. It is a python
    iterator object, allowing it to be efficiently looped.
    To create your own custom asset your should subclass this
    and override the next_asset method and the len method for
    computing the length of the asset.
    """
    def __init__(self, file=None, *args, **argv):
        self.fh = None
        if file:
            self.name = file
            self.fh = open(file, 'r')
        self.eof = False

    def __iter__(self):
        return self

    def len(self):
        """
        Returns the length of the asset
        """
        for i, l in enumerate(self.fh):
            pass
        # rewind the file
        self.fh.seek(0)
        return i + 1

    def parse_line(self, line):
        """
        Override this method if you need line
        by line parsing of an Asset.
        """
        return line.replace('\n','')

    def next_asset(self):
        """
        Return the next asset.
        """
        # XXX this is really written with my feet.
        #     clean me up please...
        line = self.fh.readline()
        if line:
            parsed_line = self.parse_line(line)
            if parsed_line:
                return parsed_line
        else:
            self.fh.seek(0)
            raise StopIteration

    def next(self):
        try:
            return self.next_asset()
        except:
            raise StopIteration

Prompt:
Add a method for line by line asset parsing

class Asset:
    """
    This is an ooni-probe asset. It is a python
    iterator object, allowing it to be efficiently looped.
    To create your own custom asset your should subclass this
    and override the next_asset method and the len method for
    computing the length of the asset.
    """
    def __init__(self, file=None, *args, **argv):
        self.fh = None
        if file:
            self.name = file
            self.fh = open(file, 'r')
        self.eof = False

    def __iter__(self):
        return self

    def len(self):
        """
        Returns the length of the asset
        """
        for i, l in enumerate(self.fh):
            pass
        # rewind the file
        self.fh.seek(0)
        return i + 1

    def next_asset(self):
        """
        Return the next asset.
        """
        # XXX this is really written with my feet.
        #     clean me up please...
        line = self.fh.readline()
        if line:
            return line.replace('\n','')
        else:
            self.fh.seek(0)
            raise StopIteration

    def next(self):
        try:
            return self.next_asset()
        except:
            raise StopIteration


import logging
import luigi
import sciluigi as sl
import os
import time
import unittest

log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)

class IntParamTask(sl.Task):
    an_int_param = luigi.IntParameter()

    def out_int_val(self):
        return sl.TargetInfo(self, '/tmp/intparamtask_intval_%d.txt' % self.an_int_param)

    def run(self):
        with self.out_int_val().open('w') as outfile:
            outfile.write('%d' % self.an_int_param)

class NonStringParamWF(sl.WorkflowTask):
    def workflow(self):
        intparam_task = self.new_task('intparam_task', IntParamTask,
                an_int_param = 123)
        return intparam_task

class TestNonStringParameterValues(unittest.TestCase):
    def setUp(self):
        self.w = luigi.worker.Worker()
        self.nsp_wf = NonStringParamWF(instance_name='nonstring_param_wf')
        self.w.add(self.nsp_wf)

    def test_intparam_gets_set(self):
        self.assertEquals(self.nsp_wf._tasks['intparam_task'].an_int_param, 123)

    def test_intparam_gets_set(self):
        self.w.run()
        with self.nsp_wf.workflow().out_int_val().open() as infile:
            val = infile.read()
            self.assertEquals(val, '123')

    def tearDown(self):
        pass

Add test for non-string (integer) parameter value

Response:
<REPLACE_OLD>  <REPLACE_NEW> import logging
import luigi
import sciluigi as sl
import os
import time
import unittest

log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)

class IntParamTask(sl.Task):
    an_int_param = luigi.IntParameter()

    def out_int_val(self):
        return sl.TargetInfo(self, '/tmp/intparamtask_intval_%d.txt' % self.an_int_param)

    def run(self):
        with self.out_int_val().open('w') as outfile:
            outfile.write('%d' % self.an_int_param)

class NonStringParamWF(sl.WorkflowTask):
    def workflow(self):
        intparam_task = self.new_task('intparam_task', IntParamTask,
                an_int_param = 123)
        return intparam_task

class TestNonStringParameterValues(unittest.TestCase):
    def setUp(self):
        self.w = luigi.worker.Worker()
        self.nsp_wf = NonStringParamWF(instance_name='nonstring_param_wf')
        self.w.add(self.nsp_wf)

    def test_intparam_gets_set(self):
        self.assertEquals(self.nsp_wf._tasks['intparam_task'].an_int_param, 123)

    def test_intparam_gets_set(self):
        self.w.run()
        with self.nsp_wf.workflow().out_int_val().open() as infile:
            val = infile.read()
            self.assertEquals(val, '123')

    def tearDown(self):
        pass
 <REPLACE_END> <|endoftext|> import logging
import luigi
import sciluigi as sl
import os
import time
import unittest

log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)

class IntParamTask(sl.Task):
    an_int_param = luigi.IntParameter()

    def out_int_val(self):
        return sl.TargetInfo(self, '/tmp/intparamtask_intval_%d.txt' % self.an_int_param)

    def run(self):
        with self.out_int_val().open('w') as outfile:
            outfile.write('%d' % self.an_int_param)

class NonStringParamWF(sl.WorkflowTask):
    def workflow(self):
        intparam_task = self.new_task('intparam_task', IntParamTask,
                an_int_param = 123)
        return intparam_task

class TestNonStringParameterValues(unittest.TestCase):
    def setUp(self):
        self.w = luigi.worker.Worker()
        self.nsp_wf = NonStringParamWF(instance_name='nonstring_param_wf')
        self.w.add(self.nsp_wf)

    def test_intparam_gets_set(self):
        self.assertEquals(self.nsp_wf._tasks['intparam_task'].an_int_param, 123)

    def test_intparam_gets_set(self):
        self.w.run()
        with self.nsp_wf.workflow().out_int_val().open() as infile:
            val = infile.read()
            self.assertEquals(val, '123')

    def tearDown(self):
        pass

Prompt: Add test for non-string (integer) parameter value


class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits[len(digits)-1] += 1
        if digits[len(digits)-1] < 10:
        	return digits
        for i in xrange(len(digits)-1,0,-1):
        	if digits[i] == 10:
        		digits[i] = 0
        		digits[i-1] += 1
        	else:
        		break
        if digits[0] == 10:
        	digits[0] = 0
        	digits = [1] + digits
        return digits

digits = [0,9,7,9]
print Solution().plusOne(digits)

Add solution for 66 Plus One.

Add solution for 66 Plus One.

Response:
<INSERT> class Solution(object):
 <INSERT_END> <INSERT>   def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits[len(digits)-1] += 1
        if digits[len(digits)-1] < 10:
        	return digits
        for i in xrange(len(digits)-1,0,-1):
        	if digits[i] == 10:
        		digits[i] = 0
        		digits[i-1] += 1
        	else:
        		break
        if digits[0] == 10:
        	digits[0] = 0
        	digits = [1] + digits
        return digits

digits = [0,9,7,9]
print Solution().plusOne(digits)
 <INSERT_END> <|endoftext|> class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits[len(digits)-1] += 1
        if digits[len(digits)-1] < 10:
        	return digits
        for i in xrange(len(digits)-1,0,-1):
        	if digits[i] == 10:
        		digits[i] = 0
        		digits[i-1] += 1
        	else:
        		break
        if digits[0] == 10:
        	digits[0] = 0
        	digits = [1] + digits
        return digits

digits = [0,9,7,9]
print Solution().plusOne(digits)

Prompt: Add solution for 66 Plus One.


# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models

class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    @api.multi
    def _post_add_create(self):
        """ Overrides behaviour when the attachment is created through the controller
        """
        super(IrAttachment, self)._post_add_create()
        for record in self:
            record.register_as_main_attachment(force=False)

    def register_as_main_attachment(self, force=True):
        """ Registers this attachment as the main one of the model it is
        attached to.
        """
        self.ensure_one()
        related_record = self.env[self.res_model].browse(self.res_id)
        # message_main_attachment_id field can be empty, that's why we compare to False;
        # we are just checking that it exists on the model before writing it
        if related_record and hasattr(related_record, 'message_main_attachment_id'):
            if force or not related_record.message_main_attachment_id:
                related_record.message_main_attachment_id = self

Response:
<DELETE> @api.multi
    def unlink(self):
        self.remove_as_main_attachment()
        super(IrAttachment, self).unlink()

    @api.multi
    def remove_as_main_attachment(self):
        for attachment in self:
            related_record = self.env[attachment.res_model].browse(attachment.res_id)
            if related_record and hasattr(related_record, 'message_main_attachment_id'):
                if related_record.message_main_attachment_id == attachment:
                    related_record.message_main_attachment_id = False

    <DELETE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models

class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    @api.multi
    def _post_add_create(self):
        """ Overrides behaviour when the attachment is created through the controller
        """
        super(IrAttachment, self)._post_add_create()
        for record in self:
            record.register_as_main_attachment(force=False)

    def register_as_main_attachment(self, force=True):
        """ Registers this attachment as the main one of the model it is
        attached to.
        """
        self.ensure_one()
        related_record = self.env[self.res_model].browse(self.res_id)
        # message_main_attachment_id field can be empty, that's why we compare to False;
        # we are just checking that it exists on the model before writing it
        if related_record and hasattr(related_record, 'message_main_attachment_id'):
            if force or not related_record.message_main_attachment_id:
                related_record.message_main_attachment_id = self

Prompt:
Revert "[FIX] mail: remove attachment as main at unlink"

This reverts commit abc45b1
Since by default the ondelete attribute of a many2one is `set null`,
this was completely unnecessary to begin with.

Bug caused by this commit:
Unlink a record that has some attachments.
The unlink first removes the record, then its related attachments.
It calls remove_as_main_attachment, which reads the attachment res_model and
res_id. This triggers a check that the related record can be read.
However the related record has already been removed, an exception is raised.
It is thus impossible to unlink a record.

Closes #32563

closes odoo/odoo#32572

Signed-off-by: Raphael Collet (rco) <fcee45b878db1f337818c5c606c1542797080a40@openerp.com>
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models

class IrAttachment(models.Model):
    _inherit = 'ir.attachment'

    @api.multi
    def _post_add_create(self):
        """ Overrides behaviour when the attachment is created through the controller
        """
        super(IrAttachment, self)._post_add_create()
        for record in self:
            record.register_as_main_attachment(force=False)

    @api.multi
    def unlink(self):
        self.remove_as_main_attachment()
        super(IrAttachment, self).unlink()

    @api.multi
    def remove_as_main_attachment(self):
        for attachment in self:
            related_record = self.env[attachment.res_model].browse(attachment.res_id)
            if related_record and hasattr(related_record, 'message_main_attachment_id'):
                if related_record.message_main_attachment_id == attachment:
                    related_record.message_main_attachment_id = False

    def register_as_main_attachment(self, force=True):
        """ Registers this attachment as the main one of the model it is
        attached to.
        """
        self.ensure_one()
        related_record = self.env[self.res_model].browse(self.res_id)
        # message_main_attachment_id field can be empty, that's why we compare to False;
        # we are just checking that it exists on the model before writing it
        if related_record and hasattr(related_record, 'message_main_attachment_id'):
            if force or not related_record.message_main_attachment_id:
                related_record.message_main_attachment_id = self


# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-19 10:35
from __future__ import unicode_literals

from django.db import migrations
import froide.publicbody.models

class Migration(migrations.Migration):

    dependencies = [
        ('publicbody', '0020_foilaw_requires_signature'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProposedPublicBody',
            fields=[
            ],
            options={
                'verbose_name': 'Proposed Public Body',
                'verbose_name_plural': 'Proposed Public Bodies',
                'proxy': True,
                'indexes': [],
            },
            bases=('publicbody.publicbody',),
            managers=[
                ('objects', froide.publicbody.models.ProposedPublicBodyManager()),
            ],
        ),
    ]

Add proposed publicbody proxy model migration

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-19 10:35
from __future__ import unicode_literals

from django.db import migrations
import froide.publicbody.models

class Migration(migrations.Migration):

    dependencies = [
        ('publicbody', '0020_foilaw_requires_signature'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProposedPublicBody',
            fields=[
            ],
            options={
                'verbose_name': 'Proposed Public Body',
                'verbose_name_plural': 'Proposed Public Bodies',
                'proxy': True,
                'indexes': [],
            },
            bases=('publicbody.publicbody',),
            managers=[
                ('objects', froide.publicbody.models.ProposedPublicBodyManager()),
            ],
        ),
    ]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-19 10:35
from __future__ import unicode_literals

from django.db import migrations
import froide.publicbody.models

class Migration(migrations.Migration):

    dependencies = [
        ('publicbody', '0020_foilaw_requires_signature'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProposedPublicBody',
            fields=[
            ],
            options={
                'verbose_name': 'Proposed Public Body',
                'verbose_name_plural': 'Proposed Public Bodies',
                'proxy': True,
                'indexes': [],
            },
            bases=('publicbody.publicbody',),
            managers=[
                ('objects', froide.publicbody.models.ProposedPublicBodyManager()),
            ],
        ),
    ]

Prompt: Add proposed publicbody proxy model migration


import os, sys
from django.conf import settings

# -- Setup Django configuration appropriately

TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
settings.SITE_ID = 1

# The CSRF middleware prevents the Django test client from working, so
# disable it.
settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES)
try:
    settings.MIDDLEWARE_CLASSES.remove(
        'django.contrib.csrf.middleware.CsrfMiddleware')
except IndexError:
    pass

# -- Test cases
from test_functional import *
from test_docstring import *
from test_toctreecache import *

# -- Allow Django test command to find the script tests
test_dir = os.path.join(os.path.dirname(__file__), '..', '..',
                        'scripts', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *

Response:
<REPLACE_OLD> 'pull-test.sh')

# <REPLACE_NEW> 'pull-test.sh')
settings.SITE_ID = 1

# <REPLACE_END> <|endoftext|> import os, sys
from django.conf import settings

# -- Setup Django configuration appropriately

TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
settings.SITE_ID = 1

# The CSRF middleware prevents the Django test client from working, so
# disable it.
settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES)
try:
    settings.MIDDLEWARE_CLASSES.remove(
        'django.contrib.csrf.middleware.CsrfMiddleware')
except IndexError:
    pass

# -- Test cases
from test_functional import *
from test_docstring import *
from test_toctreecache import *

# -- Allow Django test command to find the script tests
test_dir = os.path.join(os.path.dirname(__file__), '..', '..',
                        'scripts', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *

Prompt:
Set SITE_ID=1 in tests (corresponds to that in the test fixtures)
import os, sys
from django.conf import settings

# -- Setup Django configuration appropriately

TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')

# The CSRF middleware prevents the Django test client from working, so
# disable it.
settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES)
try:
    settings.MIDDLEWARE_CLASSES.remove(
        'django.contrib.csrf.middleware.CsrfMiddleware')
except IndexError:
    pass

# -- Test cases
from test_functional import *
from test_docstring import *
from test_toctreecache import *

# -- Allow Django test command to find the script tests
test_dir = os.path.join(os.path.dirname(__file__), '..', '..',
                        'scripts', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *


#!/usr/bin/env python3
import actionlib
import rospy
from humanoid_league_msgs.msg import PlayAnimationGoal, PlayAnimationAction, GameState

class CheeringBehaviour:
    def __init__(self):
        rospy.init_node('cheering_behvaiour')

        self.opponent_goals = 0
        self.animation_running = False

        rospy.Subscriber('/gamestate', GameState, self.gamestate_callback, queue_size=10)
        self.animation_client = actionlib.SimpleActionClient('animation', PlayAnimationAction)

        rospy.spin()

    def gamestate_callback(self, msg: GameState):
        if msg.rivalScore > self.opponent_goals and not self.animation_running:
            goal = PlayAnimationGoal()
            goal.animation = 'cheering'  # TODO
            goal.hcm = False
            self.animation_client.send_goal(goal, done_cb=self.animation_done)
            self.animation_running = True

    def animation_done(self, arg1, arg2):
        self.animation_running = False

if __name__ == '__main__':
    CheeringBehaviour()

Add simple behaviour to cheer when the opponent scores a goal

Response:
<INSERT> #!/usr/bin/env python3
import actionlib
import rospy
from humanoid_league_msgs.msg import PlayAnimationGoal, PlayAnimationAction, GameState

class CheeringBehaviour:
 <INSERT_END> <INSERT>   def __init__(self):
        rospy.init_node('cheering_behvaiour')

        self.opponent_goals = 0
        self.animation_running = False

        rospy.Subscriber('/gamestate', GameState, self.gamestate_callback, queue_size=10)
        self.animation_client = actionlib.SimpleActionClient('animation', PlayAnimationAction)

        rospy.spin()

    def gamestate_callback(self, msg: GameState):
        if msg.rivalScore > self.opponent_goals and not self.animation_running:
            goal = PlayAnimationGoal()
            goal.animation = 'cheering'  # TODO
            goal.hcm = False
            self.animation_client.send_goal(goal, done_cb=self.animation_done)
            self.animation_running = True

    def animation_done(self, arg1, arg2):
        self.animation_running = False

if __name__ == '__main__':
    CheeringBehaviour()
 <INSERT_END> <|endoftext|> #!/usr/bin/env python3
import actionlib
import rospy
from humanoid_league_msgs.msg import PlayAnimationGoal, PlayAnimationAction, GameState

class CheeringBehaviour:
    def __init__(self):
        rospy.init_node('cheering_behvaiour')

        self.opponent_goals = 0
        self.animation_running = False

        rospy.Subscriber('/gamestate', GameState, self.gamestate_callback, queue_size=10)
        self.animation_client = actionlib.SimpleActionClient('animation', PlayAnimationAction)

        rospy.spin()

    def gamestate_callback(self, msg: GameState):
        if msg.rivalScore > self.opponent_goals and not self.animation_running:
            goal = PlayAnimationGoal()
            goal.animation = 'cheering'  # TODO
            goal.hcm = False
            self.animation_client.send_goal(goal, done_cb=self.animation_done)
            self.animation_running = True

    def animation_done(self, arg1, arg2):
        self.animation_running = False

if __name__ == '__main__':
    CheeringBehaviour()

Prompt: Add simple behaviour to cheer when the opponent scores a goal


from kafka.tools.assigner.exceptions import ProgrammingException

def split_partitions_into_batches(partitions, batch_size=10, use_class=None):
    # Currently, this is a very simplistic implementation that just breaks the list of partitions down
    # into even sized chunks. While it could be implemented as a generator, it's not so that it can
    # split the list into more efficient batches.
    if use_class is None:
        raise ProgrammingException("split_partitions_into_batches called with no use_class")

    batches = [use_class(partitions[i:i + batch_size]) for i in range(0, len(partitions), batch_size)]
    return batches

Response:
<REPLACE_OLD> xrange(0, <REPLACE_NEW> range(0, <REPLACE_END> <|endoftext|> from kafka.tools.assigner.exceptions import ProgrammingException

def split_partitions_into_batches(partitions, batch_size=10, use_class=None):
    # Currently, this is a very simplistic implementation that just breaks the list of partitions down
    # into even sized chunks. While it could be implemented as a generator, it's not so that it can
    # split the list into more efficient batches.
    if use_class is None:
        raise ProgrammingException("split_partitions_into_batches called with no use_class")

    batches = [use_class(partitions[i:i + batch_size]) for i in range(0, len(partitions), batch_size)]
    return batches

Prompt:
Remove used of xrange to support python 3

from kafka.tools.assigner.exceptions import ProgrammingException

def split_partitions_into_batches(partitions, batch_size=10, use_class=None):
    # Currently, this is a very simplistic implementation that just breaks the list of partitions down
    # into even sized chunks. While it could be implemented as a generator, it's not so that it can
    # split the list into more efficient batches.
    if use_class is None:
        raise ProgrammingException("split_partitions_into_batches called with no use_class")

    batches = [use_class(partitions[i:i + batch_size]) for i in xrange(0, len(partitions), batch_size)]
    return batches


import jinja2

from django.conf import settings
from django_jinja import library
from jinja2.ext import Extension
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import (
    routablepageurl as dj_routablepageurl
)

from wapps.utils import get_image_url

@library.global_function
def menu():
    return Page.objects.live().in_menu().filter(depth__lte=3)

@library.global_function
@jinja2.contextfunction
def is_site_root(context, page):
    if 'request' not in context or not context['request'].site or not page:
        return False
    site = context['request'].site
    return site.root_page.pk == page.pk

@library.global_function
def image_url(image, specs):
    return get_image_url(image, specs)

@library.global_function
@jinja2.contextfunction
def routablepageurl(context, page, name, *args, **kwargs):
    return dj_routablepageurl(context, page, name, *args, **kwargs)

@library.extension
class WagtailSettings(Extension):
    def __init__(self, environment):
        super(WagtailSettings, self).__init__(environment)
        environment.globals['WAGTAIL_SITE_NAME'] = getattr(settings, 'WAGTAIL_SITE_NAME', None)

Fix is_site_root when no page

Fix is_site_root when no page

Response:
<REPLACE_OLD> context['request'].site:
 <REPLACE_NEW> context['request'].site or not page:
 <REPLACE_END> <|endoftext|> import jinja2

from django.conf import settings
from django_jinja import library
from jinja2.ext import Extension
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import (
    routablepageurl as dj_routablepageurl
)

from wapps.utils import get_image_url

@library.global_function
def menu():
    return Page.objects.live().in_menu().filter(depth__lte=3)

@library.global_function
@jinja2.contextfunction
def is_site_root(context, page):
    if 'request' not in context or not context['request'].site or not page:
        return False
    site = context['request'].site
    return site.root_page.pk == page.pk

@library.global_function
def image_url(image, specs):
    return get_image_url(image, specs)

@library.global_function
@jinja2.contextfunction
def routablepageurl(context, page, name, *args, **kwargs):
    return dj_routablepageurl(context, page, name, *args, **kwargs)

@library.extension
class WagtailSettings(Extension):
    def __init__(self, environment):
        super(WagtailSettings, self).__init__(environment)
        environment.globals['WAGTAIL_SITE_NAME'] = getattr(settings, 'WAGTAIL_SITE_NAME', None)

Prompt:
Fix is_site_root when no page

import jinja2

from django.conf import settings
from django_jinja import library
from jinja2.ext import Extension
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import (
    routablepageurl as dj_routablepageurl
)

from wapps.utils import get_image_url

@library.global_function
def menu():
    return Page.objects.live().in_menu().filter(depth__lte=3)

@library.global_function
@jinja2.contextfunction
def is_site_root(context, page):
    if 'request' not in context or not context['request'].site:
        return False
    site = context['request'].site
    return site.root_page.pk == page.pk

@library.global_function
def image_url(image, specs):
    return get_image_url(image, specs)

@library.global_function
@jinja2.contextfunction
def routablepageurl(context, page, name, *args, **kwargs):
    return dj_routablepageurl(context, page, name, *args, **kwargs)

@library.extension
class WagtailSettings(Extension):
    def __init__(self, environment):
        super(WagtailSettings, self).__init__(environment)
        environment.globals['WAGTAIL_SITE_NAME'] = getattr(settings, 'WAGTAIL_SITE_NAME', None)


# coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.

import os
import sys
from openquake.risklib.scientific import (
    VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix

__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]

# the version is managed by packager.sh with a sed
__version__ = '0.6.0'
__version__ += git_suffix(__file__)

path = search_module('openquake.commonlib.general')
if path:
    sys.exit('Found an obsolete version of commonlib; '
             'please remove %s and/or fix your PYTHONPATH'
             % os.path.dirname(path))

Response:
<REPLACE_OLD> '0.5.1'
__version__ <REPLACE_NEW> '0.6.0'
__version__ <REPLACE_END> <|endoftext|> # coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.

import os
import sys
from openquake.risklib.scientific import (
    VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix

__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]

# the version is managed by packager.sh with a sed
__version__ = '0.6.0'
__version__ += git_suffix(__file__)

path = search_module('openquake.commonlib.general')
if path:
    sys.exit('Found an obsolete version of commonlib; '
             'please remove %s and/or fix your PYTHONPATH'
             % os.path.dirname(path))

Prompt:
Upgrade release number to 0.6.0 (oq-engine 1.3.0)

# coding=utf-8
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake Risklib is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# OpenQuake Risklib is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with OpenQuake Risklib. If not, see
# <http://www.gnu.org/licenses/>.

import os
import sys
from openquake.risklib.scientific import (
    VulnerabilityFunction, DegenerateDistribution, classical)
from openquake.baselib.general import search_module
from openquake.hazardlib.general import git_suffix

__all__ = ["VulnerabilityFunction", "DegenerateDistribution", "classical"]

# the version is managed by packager.sh with a sed
__version__ = '0.5.1'
__version__ += git_suffix(__file__)

path = search_module('openquake.commonlib.general')
if path:
    sys.exit('Found an obsolete version of commonlib; '
             'please remove %s and/or fix your PYTHONPATH'
             % os.path.dirname(path))


import sys
from setuptools import setup

if sys.version_info < (2, 6):
    raise Exception('Wiggelen requires Python 2.6 or higher.')

# Todo: How does this play with pip freeze requirement files?
requires = ['nose']

# Python 2.6 does not include the argparse module.
try:
    import argparse
except ImportError:
    requires.append('argparse')

with open('README.rst') as readme:
    long_description = readme.read()

import wiggelen as distmeta

setup(
    name='wiggelen',
    version=distmeta.__version__,
    description='Working with wiggle tracks in Python',
    long_description=long_description,
    author=distmeta.__author__,
    author_email=distmeta.__contact__,
    url=distmeta.__homepage__,
    license='MIT License',
    platforms=['any'],
    packages=['wiggelen'],
    requires=requires,
    entry_points = {
        'console_scripts': ['wiggelen = wiggelen.commands:main']
        },
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering',
        ],
    keywords='bioinformatics'
)

Response:
<REPLACE_OLD> requires.append('argparse')

import <REPLACE_NEW> requires.append('argparse')

with open('README.rst') as readme:
    long_description = readme.read()

import <REPLACE_END> <REPLACE_OLD> long_description=distmeta.__doc__,
 <REPLACE_NEW> long_description=long_description,
 <REPLACE_END> <|endoftext|> import sys
from setuptools import setup

if sys.version_info < (2, 6):
    raise Exception('Wiggelen requires Python 2.6 or higher.')

# Todo: How does this play with pip freeze requirement files?
requires = ['nose']

# Python 2.6 does not include the argparse module.
try:
    import argparse
except ImportError:
    requires.append('argparse')

with open('README.rst') as readme:
    long_description = readme.read()

import wiggelen as distmeta

setup(
    name='wiggelen',
    version=distmeta.__version__,
    description='Working with wiggle tracks in Python',
    long_description=long_description,
    author=distmeta.__author__,
    author_email=distmeta.__contact__,
    url=distmeta.__homepage__,
    license='MIT License',
    platforms=['any'],
    packages=['wiggelen'],
    requires=requires,
    entry_points = {
        'console_scripts': ['wiggelen = wiggelen.commands:main']
        },
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering',
        ],
    keywords='bioinformatics'
)

Prompt:
Use README.rst as long description for PyPi

import sys
from setuptools import setup

if sys.version_info < (2, 6):
    raise Exception('Wiggelen requires Python 2.6 or higher.')

# Todo: How does this play with pip freeze requirement files?
requires = ['nose']

# Python 2.6 does not include the argparse module.
try:
    import argparse
except ImportError:
    requires.append('argparse')

import wiggelen as distmeta

setup(
    name='wiggelen',
    version=distmeta.__version__,
    description='Working with wiggle tracks in Python',
    long_description=distmeta.__doc__,
    author=distmeta.__author__,
    author_email=distmeta.__contact__,
    url=distmeta.__homepage__,
    license='MIT License',
    platforms=['any'],
    packages=['wiggelen'],
    requires=requires,
    entry_points = {
        'console_scripts': ['wiggelen = wiggelen.commands:main']
        },
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering',
        ],
    keywords='bioinformatics'
)


import os
import re
import sys
import optparse

MARKER_START_FUNCS = "// EMSCRIPTEN_START_FUNCS"
MARKER_END_FUNCS = "// EMSCRIPTEN_END_FUNCS"

FUNCTION_CODE_RE = re.compile(
  r"function (?P<name>[a-zA-Z0-9_]+)(?P<defn>.*?)((?=function)|(?=$))"
)

def analyze_code_size(fileobj, opts):
    funcs = {}
    name_re = None
    if opts.grep is not None:
      name_re = re.compile(opts.grep, re.I)
    # Split out and analyze the code for each individual function.
    # XXX TODO: read incrementally to reduce memory usage.
    data = fileobj.read()
    pre_code, data = data.split(MARKER_START_FUNCS, 1)
    data, post_code = data.split(MARKER_END_FUNCS, 1)
    for match in FUNCTION_CODE_RE.finditer(data):
        name = match.group("name")
        defn = match.group("defn")
        if name_re and not name_re.search(name):
            continue
        funcs[name] = FunctionMetrics(name, defn)
    # Print summary metrics.
    total = 0
    funcs_by_size = ((f.size, f.name) for f in funcs.itervalues())
    for (size, name) in sorted(funcs_by_size, reverse=True):
        print size, name, human_readable(size)
        total += size
    print "Total size:", total, human_readable(total)

class FunctionMetrics(object):

    def __init__(self, name, defn):
        self.name = name
        self.defn = defn
        self.size = len(defn)

def human_readable(size):
    units = ((1024*1024, "M"), (1024, "k"))
    for (scale, unit) in units:
        scale = float(scale)
        if size / scale > 0.1:
            return "(%.2f%s)" % (size / scale, unit)
    return ""

def main(args=None):
    usage = "usage: %prog [options] file"
    descr = "Analyze code size and complexity for emscripten-compiled output"
    parser = optparse.OptionParser(usage=usage, description=descr)
    parser.add_option("-g", "--grep", metavar="REGEXP",
                      help="only analyze functions matching this regexp")

    opts, args = parser.parse_args(args)
    with open(args[0], "r") as infile:
        analyze_code_size(infile, opts)
    return 0

if __name__ == "__main__":
    try:
        exitcode = main()
    except KeyboardInterrupt:
        exitcode = 1
    sys.exit(exitcode)

Add simple function-size analysis tool.

Add simple function-size analysis tool.

Response:
<REPLACE_OLD>  <REPLACE_NEW>
import os
import re
import sys
import optparse

MARKER_START_FUNCS = "// EMSCRIPTEN_START_FUNCS"
MARKER_END_FUNCS = "// EMSCRIPTEN_END_FUNCS"

FUNCTION_CODE_RE = re.compile(
  r"function (?P<name>[a-zA-Z0-9_]+)(?P<defn>.*?)((?=function)|(?=$))"
)

def analyze_code_size(fileobj, opts):
    funcs = {}
    name_re = None
    if opts.grep is not None:
      name_re = re.compile(opts.grep, re.I)
    # Split out and analyze the code for each individual function.
    # XXX TODO: read incrementally to reduce memory usage.
    data = fileobj.read()
    pre_code, data = data.split(MARKER_START_FUNCS, 1)
    data, post_code = data.split(MARKER_END_FUNCS, 1)
    for match in FUNCTION_CODE_RE.finditer(data):
        name = match.group("name")
        defn = match.group("defn")
        if name_re and not name_re.search(name):
            continue
        funcs[name] = FunctionMetrics(name, defn)
    # Print summary metrics.
    total = 0
    funcs_by_size = ((f.size, f.name) for f in funcs.itervalues())
    for (size, name) in sorted(funcs_by_size, reverse=True):
        print size, name, human_readable(size)
        total += size
    print "Total size:", total, human_readable(total)

class FunctionMetrics(object):

    def __init__(self, name, defn):
        self.name = name
        self.defn = defn
        self.size = len(defn)

def human_readable(size):
    units = ((1024*1024, "M"), (1024, "k"))
    for (scale, unit) in units:
        scale = float(scale)
        if size / scale > 0.1:
            return "(%.2f%s)" % (size / scale, unit)
    return ""

def main(args=None):
    usage = "usage: %prog [options] file"
    descr = "Analyze code size and complexity for emscripten-compiled output"
    parser = optparse.OptionParser(usage=usage, description=descr)
    parser.add_option("-g", "--grep", metavar="REGEXP",
                      help="only analyze functions matching this regexp")

    opts, args = parser.parse_args(args)
    with open(args[0], "r") as infile:
        analyze_code_size(infile, opts)
    return 0

if __name__ == "__main__":
    try:
        exitcode = main()
    except KeyboardInterrupt:
        exitcode = 1
    sys.exit(exitcode)
 <REPLACE_END> <|endoftext|>
import os
import re
import sys
import optparse

MARKER_START_FUNCS = "// EMSCRIPTEN_START_FUNCS"
MARKER_END_FUNCS = "// EMSCRIPTEN_END_FUNCS"

FUNCTION_CODE_RE = re.compile(
  r"function (?P<name>[a-zA-Z0-9_]+)(?P<defn>.*?)((?=function)|(?=$))"
)

def analyze_code_size(fileobj, opts):
    funcs = {}
    name_re = None
    if opts.grep is not None:
      name_re = re.compile(opts.grep, re.I)
    # Split out and analyze the code for each individual function.
    # XXX TODO: read incrementally to reduce memory usage.
    data = fileobj.read()
    pre_code, data = data.split(MARKER_START_FUNCS, 1)
    data, post_code = data.split(MARKER_END_FUNCS, 1)
    for match in FUNCTION_CODE_RE.finditer(data):
        name = match.group("name")
        defn = match.group("defn")
        if name_re and not name_re.search(name):
            continue
        funcs[name] = FunctionMetrics(name, defn)
    # Print summary metrics.
    total = 0
    funcs_by_size = ((f.size, f.name) for f in funcs.itervalues())
    for (size, name) in sorted(funcs_by_size, reverse=True):
        print size, name, human_readable(size)
        total += size
    print "Total size:", total, human_readable(total)

class FunctionMetrics(object):

    def __init__(self, name, defn):
        self.name = name
        self.defn = defn
        self.size = len(defn)

def human_readable(size):
    units = ((1024*1024, "M"), (1024, "k"))
    for (scale, unit) in units:
        scale = float(scale)
        if size / scale > 0.1:
            return "(%.2f%s)" % (size / scale, unit)
    return ""

def main(args=None):
    usage = "usage: %prog [options] file"
    descr = "Analyze code size and complexity for emscripten-compiled output"
    parser = optparse.OptionParser(usage=usage, description=descr)
    parser.add_option("-g", "--grep", metavar="REGEXP",
                      help="only analyze functions matching this regexp")

    opts, args = parser.parse_args(args)
    with open(args[0], "r") as infile:
        analyze_code_size(infile, opts)
    return 0

if __name__ == "__main__":
    try:
        exitcode = main()
    except KeyboardInterrupt:
        exitcode = 1
    sys.exit(exitcode)

Prompt: Add simple function-size analysis tool.


#!/usr/bin/python

from config import INTERFACES
from built_in_classes import RootHTBClass
from .upload import Interactive, TCPACK, SSH, HTTP, Default

def apply_qos():
    public_if = INTERFACES["public_if"]
    root_class = RootHTBClass(
        interface=public_if["name"],
        rate=public_if["speed"],
        burst=public_if["speed"]/8,
        qdisc_prefix_id="1:",
        default=1500
    )
    root_class.add_child(Interactive())
    root_class.add_child(TCPACK())
    root_class.add_child(SSH())
    root_class.add_child(HTTP())
    root_class.add_child(Default())

    root_class.apply_qos()

Enable all rules in pythonic_rules

Response:
<DELETE> # <DELETE_END> <DELETE> # <DELETE_END> <DELETE> # <DELETE_END> <DELETE> # <DELETE_END> <|endoftext|> #!/usr/bin/python

from config import INTERFACES
from built_in_classes import RootHTBClass
from .upload import Interactive, TCPACK, SSH, HTTP, Default

def apply_qos():
    public_if = INTERFACES["public_if"]
    root_class = RootHTBClass(
        interface=public_if["name"],
        rate=public_if["speed"],
        burst=public_if["speed"]/8,
        qdisc_prefix_id="1:",
        default=1500
    )
    root_class.add_child(Interactive())
    root_class.add_child(TCPACK())
    root_class.add_child(SSH())
    root_class.add_child(HTTP())
    root_class.add_child(Default())

    root_class.apply_qos()

Prompt:
Enable all rules in pythonic_rules

Has been disabled to avoid errors until the new design was nos finished.

#!/usr/bin/python

from config import INTERFACES
from built_in_classes import RootHTBClass
from .upload import Interactive, TCPACK, SSH, HTTP, Default

def apply_qos():
    public_if = INTERFACES["public_if"]
    root_class = RootHTBClass(
        interface=public_if["name"],
        rate=public_if["speed"],
        burst=public_if["speed"]/8,
        qdisc_prefix_id="1:",
        default=1500
    )
    # root_class.add_child(Interactive())
    # root_class.add_child(TCPACK())
    # root_class.add_child(SSH())
    # root_class.add_child(HTTP())
    root_class.add_child(Default())

    root_class.apply_qos()


from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django import forms
from models import ExcelImportTask
from django.forms import ModelForm

class ExcelFormatTranslateForm(forms.Form):
    # title = forms.CharField(max_length=50)
    import_file = forms.FileField(
        label=_('File to import')
    )
    header_row_numbered_from_1 = forms.IntegerField()
    spreadsheet_numbered_from_1 = forms.IntegerField()
    class_name = forms.CharField()
    is_create_app_now = forms.BooleanField(required=False)

class ExcelImportTaskForm(ModelForm):
    content = forms.ModelChoiceField(queryset=ContentType.objects.order_by('model'))

    class Meta:
        model = ExcelImportTask
        fields = ['excel_file', 'content', "header_row_numbered_from_1", "spreadsheet_numbered_from_1"]

    is_import_now = forms.BooleanField(required=False)

Sort content for data import.

Sort content for data import.

Response:
<INSERT> django.contrib.contenttypes.models import ContentType
from <INSERT_END> <INSERT> content = forms.ModelChoiceField(queryset=ContentType.objects.order_by('model'))

    <INSERT_END> <REPLACE_OLD> "spreadsheet_numbered_from_1"]
 <REPLACE_NEW> "spreadsheet_numbered_from_1"]

 <REPLACE_END> <REPLACE_OLD> forms.BooleanField(required=False)

 <REPLACE_NEW> forms.BooleanField(required=False)
 <REPLACE_END> <|endoftext|> from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django import forms
from models import ExcelImportTask
from django.forms import ModelForm

class ExcelFormatTranslateForm(forms.Form):
    # title = forms.CharField(max_length=50)
    import_file = forms.FileField(
        label=_('File to import')
    )
    header_row_numbered_from_1 = forms.IntegerField()
    spreadsheet_numbered_from_1 = forms.IntegerField()
    class_name = forms.CharField()
    is_create_app_now = forms.BooleanField(required=False)

class ExcelImportTaskForm(ModelForm):
    content = forms.ModelChoiceField(queryset=ContentType.objects.order_by('model'))

    class Meta:
        model = ExcelImportTask
        fields = ['excel_file', 'content', "header_row_numbered_from_1", "spreadsheet_numbered_from_1"]

    is_import_now = forms.BooleanField(required=False)

Prompt:
Sort content for data import.

from django.utils.translation import ugettext_lazy as _
from django import forms
from models import ExcelImportTask
from django.forms import ModelForm

class ExcelFormatTranslateForm(forms.Form):
    # title = forms.CharField(max_length=50)
    import_file = forms.FileField(
        label=_('File to import')
    )
    header_row_numbered_from_1 = forms.IntegerField()
    spreadsheet_numbered_from_1 = forms.IntegerField()
    class_name = forms.CharField()
    is_create_app_now = forms.BooleanField(required=False)

class ExcelImportTaskForm(ModelForm):
    class Meta:
        model = ExcelImportTask
        fields = ['excel_file', 'content', "header_row_numbered_from_1", "spreadsheet_numbered_from_1"]
    is_import_now = forms.BooleanField(required=False)


from django.conf.urls import url

from .views import MessageCreateView, ThreadDetailView, ThreadListView

urlpatterns = [
    url(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
        name='thread-detail'),
    url(r'^(?P<pk>\d+)/new/$', MessageCreateView.as_view(),
        name='new-message'),
    url(r'^$', ThreadListView.as_view())
]

Use `@` in message thread

Use `@` in message thread

Response:
<REPLACE_OLD> url(r'^(?P<recipient>[a-zA-Z0-9_]+)/$', <REPLACE_NEW> url(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', <REPLACE_END> <|endoftext|> from django.conf.urls import url

from .views import MessageCreateView, ThreadDetailView, ThreadListView

urlpatterns = [
    url(r'^@(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
        name='thread-detail'),
    url(r'^(?P<pk>\d+)/new/$', MessageCreateView.as_view(),
        name='new-message'),
    url(r'^$', ThreadListView.as_view())
]

Prompt:
Use `@` in message thread

from django.conf.urls import url

from .views import MessageCreateView, ThreadDetailView, ThreadListView

urlpatterns = [
    url(r'^(?P<recipient>[a-zA-Z0-9_]+)/$', ThreadDetailView.as_view(),
        name='thread-detail'),
    url(r'^(?P<pk>\d+)/new/$', MessageCreateView.as_view(),
        name='new-message'),
    url(r'^$', ThreadListView.as_view())
]


# test list slices, getting values

x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
print(x[::c])
print(x[:b])
print(x[:b:])
print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
print(x[a::c])
print(x[a:b])
print(x[a:b:])
print(x[a:b:c])

# these should not raise IndexError
print([][1:])
print([][-1:])

try:
    [][::0]
except ValueError:
    print('ValueError')

Response:
<REPLACE_OLD> slices; only 2 argument version supported by Micro Python at the moment
x <REPLACE_NEW> list slices, getting values

x <REPLACE_END> <REPLACE_OLD> 3
print(x[:])
print(x[::])
#print(x[::c])
print(x[:b])
print(x[:b:])
#print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
#print(x[a::c])
print(x[a:b])
print(x[a:b:])
#print(x[a:b:c])

# <REPLACE_NEW> 3
print(x[:])
print(x[::])
print(x[::c])
print(x[:b])
print(x[:b:])
print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
print(x[a::c])
print(x[a:b])
print(x[a:b:])
print(x[a:b:c])

# <REPLACE_END> <REPLACE_OLD> IndexError
print([][1:])
print([][-1:])
 <REPLACE_NEW> IndexError
print([][1:])
print([][-1:])

try:
    [][::0]
except ValueError:
    print('ValueError')
 <REPLACE_END> <|endoftext|> # test list slices, getting values

x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
print(x[::c])
print(x[:b])
print(x[:b:])
print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
print(x[a::c])
print(x[a:b])
print(x[a:b:])
print(x[a:b:c])

# these should not raise IndexError
print([][1:])
print([][-1:])

try:
    [][::0]
except ValueError:
    print('ValueError')

Prompt:
tests/basics: Enable tests for list slice getting with 3rd arg.

Also add a test to check case when 3rd arg is 0.

# test slices; only 2 argument version supported by Micro Python at the moment
x = list(range(10))
a = 2
b = 4
c = 3
print(x[:])
print(x[::])
#print(x[::c])
print(x[:b])
print(x[:b:])
#print(x[:b:c])
print(x[a])
print(x[a:])
print(x[a::])
#print(x[a::c])
print(x[a:b])
print(x[a:b:])
#print(x[a:b:c])

# these should not raise IndexError
print([][1:])
print([][-1:])