"""
graph_objs
==========

This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the following objects defined here.

The reason for the package graph_objs and the module graph_objs is to provide
a clearer API for users.

"""
from . graph_objs import (
    Data, Annotations, Area, Bar, Box, Contour, Heatmap, Histogram,
    Histogram2d, Histogram2dContour, Scatter, Annotation, AngularAxis,
    ColorBar, Contours, ErrorX, ErrorY, Figure, Font, Layout, Legend,
    Line, Margin, Marker, RadialAxis, Stream, Trace, XAxis, XBins, YAxis,
    YBins
)

Response:
<REPLACE_OLD> here.

"""
from __future__ <REPLACE_NEW> here.

The reason for the package graph_objs and the module graph_objs is to provide
a clearer API for users.

"""
from . graph_objs <REPLACE_END> <REPLACE_OLD> absolute_import

from plotly.graph_objs.graph_objs import *

__all__ = ["Data",
 <REPLACE_NEW> (
 <REPLACE_END> <INSERT> Data, Annotations, Area, Bar, Box, Contour, Heatmap, Histogram,
 <INSERT_END> <INSERT> Histogram2d, Histogram2dContour, Scatter, Annotation, AngularAxis,
 <INSERT_END> <REPLACE_OLD>  "Annotations",
 <REPLACE_NEW> ColorBar, Contours, ErrorX, ErrorY, Figure, Font, Layout, Legend,
 <REPLACE_END> <INSERT> Line, Margin, Marker, RadialAxis, Stream, Trace, XAxis, XBins, YAxis,
 <INSERT_END> <REPLACE_OLD>     "Area",
           "Bar",
           "Box",
           "Contour",
           "Heatmap",
           "Histogram",
           "Histogram2d",
           "Histogram2dContour",
           "Scatter",
           "Annotation",
           "AngularAxis",
           "ColorBar",
           "Contours",
           "ErrorX",
           "ErrorY",
           "Figure",
           "Font",
           "Layout",
           "Legend",
           "Line",
           "Margin",
           "Marker",
           "RadialAxis",
           "Stream",
           "Trace",
           "XAxis",
           "XBins",
           "YAxis",
           "YBins"]
 <REPLACE_NEW> YBins
)
 <REPLACE_END> <|endoftext|> """
graph_objs
==========

This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the following objects defined here.

The reason for the package graph_objs and the module graph_objs is to provide
a clearer API for users.

"""
from . graph_objs import (
    Data, Annotations, Area, Bar, Box, Contour, Heatmap, Histogram,
    Histogram2d, Histogram2dContour, Scatter, Annotation, AngularAxis,
    ColorBar, Contours, ErrorX, ErrorY, Figure, Font, Layout, Legend,
    Line, Margin, Marker, RadialAxis, Stream, Trace, XAxis, XBins, YAxis,
    YBins
)

Prompt:
Remove the `import *`. Explicitly import what we want to expose.

Before __all__ was used to manage these. But it's clearer to
just import what we want users to see.

"""
graph_objs
==========

This package imports definitions for all of Plotly's graph objects. For more
information, run help(Obj) on any of the following objects defined here.

"""
from __future__ import absolute_import

from plotly.graph_objs.graph_objs import *

__all__ = ["Data",
           "Annotations",
           "Area",
           "Bar",
           "Box",
           "Contour",
           "Heatmap",
           "Histogram",
           "Histogram2d",
           "Histogram2dContour",
           "Scatter",
           "Annotation",
           "AngularAxis",
           "ColorBar",
           "Contours",
           "ErrorX",
           "ErrorY",
           "Figure",
           "Font",
           "Layout",
           "Legend",
           "Line",
           "Margin",
           "Marker",
           "RadialAxis",
           "Stream",
           "Trace",
           "XAxis",
           "XBins",
           "YAxis",
           "YBins"]


#!/usr/bin/env python2.7
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####

VOWELS = "aeiouy"
CONSTS = "bcdfghjklmnpqrstvwxz"

def shift(message, shift):
    '''Shift a string by a number to produce a string resembling language.
    It pays attention to whether a letter is a vowel or a consonant, and
    shifts them separately.
    This means a vowel will never become a consonant, and neither vice versa.
    This also means that it will stay looking like a language because there
    will always be about enough vowels to be pronouncable/readable.

    Example:
        "This is a thing!"
        When shifted by 1 becomes:
        "Vjot ot e vjoph!"
        And when shifted by 2:
        "Wkuv uv i wkuqj!"
    '''
    # TODO: Randomize the VOWELS and CONSTS strings.
    new_message = ""
    for char in message:
        lowerchar = char.lower()
        for charlist in (VOWELS, CONSTS):
            if lowerchar in charlist:
                index = list(charlist).index(lowerchar)
                newindex = (index+shift)
                newchar = charlist[newindex % len(charlist)]

                if char.istitle():
                    newchar = newchar.title()

                new_message += newchar
                break
        else:
            new_message += char
    return new_message

if __name__ == "__main__":
    for i in xrange(26):
        print i, shift("This is a thing!", i)

Add a dumb language "translator" function.

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python2.7
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####

VOWELS = "aeiouy"
CONSTS = "bcdfghjklmnpqrstvwxz"

def shift(message, shift):
    '''Shift a string by a number to produce a string resembling language.
    It pays attention to whether a letter is a vowel or a consonant, and
    shifts them separately.
    This means a vowel will never become a consonant, and neither vice versa.
    This also means that it will stay looking like a language because there
    will always be about enough vowels to be pronouncable/readable.

    Example:
        "This is a thing!"
        When shifted by 1 becomes:
        "Vjot ot e vjoph!"
        And when shifted by 2:
        "Wkuv uv i wkuqj!"
    '''
    # TODO: Randomize the VOWELS and CONSTS strings.
    new_message = ""
    for char in message:
        lowerchar = char.lower()
        for charlist in (VOWELS, CONSTS):
            if lowerchar in charlist:
                index = list(charlist).index(lowerchar)
                newindex = (index+shift)
                newchar = charlist[newindex % len(charlist)]

                if char.istitle():
                    newchar = newchar.title()

                new_message += newchar
                break
        else:
            new_message += char
    return new_message

if __name__ == "__main__":
    for i in xrange(26):
        print i, shift("This is a thing!", i)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python2.7
# ##### BEGIN AGPL LICENSE BLOCK #####
# This file is part of SimpleMMO.
#
# Copyright (C) 2012 Charles Nelson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####

VOWELS = "aeiouy"
CONSTS = "bcdfghjklmnpqrstvwxz"

def shift(message, shift):
    '''Shift a string by a number to produce a string resembling language.
    It pays attention to whether a letter is a vowel or a consonant, and
    shifts them separately.
    This means a vowel will never become a consonant, and neither vice versa.
    This also means that it will stay looking like a language because there
    will always be about enough vowels to be pronouncable/readable.

    Example:
        "This is a thing!"
        When shifted by 1 becomes:
        "Vjot ot e vjoph!"
        And when shifted by 2:
        "Wkuv uv i wkuqj!"
    '''
    # TODO: Randomize the VOWELS and CONSTS strings.
    new_message = ""
    for char in message:
        lowerchar = char.lower()
        for charlist in (VOWELS, CONSTS):
            if lowerchar in charlist:
                index = list(charlist).index(lowerchar)
                newindex = (index+shift)
                newchar = charlist[newindex % len(charlist)]

                if char.istitle():
                    newchar = newchar.title()

                new_message += newchar
                break
        else:
            new_message += char
    return new_message

if __name__ == "__main__":
    for i in xrange(26):
        print i, shift("This is a thing!", i)

Prompt: Add a dumb language "translator" function.


#!/usr/bin/env python
"""
Copyright (c) 2019-2020 ARM Limited. All rights reserved.

SPDX-License-Identifier: Apache-2.0

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 pytest

from tools.targets import TARGETS

def test_psa_target_attributes():
    psa_targets = (tar for tar in TARGETS
                   if tar.is_TFM_target)

    for tar in psa_targets:
        msg = "tfm_target_name attribute cannot be empty"
        assert(tar.tfm_target_name != ""), msg
        msg = "tfm_bootloader_supported attribute cannot be empty"
        assert(tar.tfm_bootloader_supported != ""), msg
        msg = "tfm_default_toolchain attribute cannot be empty"
        assert(tar.tfm_default_toolchain != ""), msg
        msg = "tfm_supported_toolchains attribute cannot be empty"
        assert(tar.tfm_supported_toolchains != ""), msg
        msg = "delivery_dir attribute cannot be empty"
        assert(tar.tfm_delivery_dir != ""), msg

Add a script to validate PSA targets

psa: Add a script to validate PSA targets

Add a script to parse `targets.json` to identify PSA targets and ensure
mandatory parameters are configured correctly for all PSA targets.

Signed-off-by: Devaraj Ranganna <53e2fcb007e5c6e2caf46b91114119a655266f64@arm.com>

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
"""
Copyright (c) 2019-2020 ARM Limited. All rights reserved.

SPDX-License-Identifier: Apache-2.0

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 pytest

from tools.targets import TARGETS

def test_psa_target_attributes():
    psa_targets = (tar for tar in TARGETS
                   if tar.is_TFM_target)

    for tar in psa_targets:
        msg = "tfm_target_name attribute cannot be empty"
        assert(tar.tfm_target_name != ""), msg
        msg = "tfm_bootloader_supported attribute cannot be empty"
        assert(tar.tfm_bootloader_supported != ""), msg
        msg = "tfm_default_toolchain attribute cannot be empty"
        assert(tar.tfm_default_toolchain != ""), msg
        msg = "tfm_supported_toolchains attribute cannot be empty"
        assert(tar.tfm_supported_toolchains != ""), msg
        msg = "delivery_dir attribute cannot be empty"
        assert(tar.tfm_delivery_dir != ""), msg

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""
Copyright (c) 2019-2020 ARM Limited. All rights reserved.

SPDX-License-Identifier: Apache-2.0

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 pytest

from tools.targets import TARGETS

def test_psa_target_attributes():
    psa_targets = (tar for tar in TARGETS
                   if tar.is_TFM_target)

    for tar in psa_targets:
        msg = "tfm_target_name attribute cannot be empty"
        assert(tar.tfm_target_name != ""), msg
        msg = "tfm_bootloader_supported attribute cannot be empty"
        assert(tar.tfm_bootloader_supported != ""), msg
        msg = "tfm_default_toolchain attribute cannot be empty"
        assert(tar.tfm_default_toolchain != ""), msg
        msg = "tfm_supported_toolchains attribute cannot be empty"
        assert(tar.tfm_supported_toolchains != ""), msg
        msg = "delivery_dir attribute cannot be empty"
        assert(tar.tfm_delivery_dir != ""), msg

Prompt:
psa: Add a script to validate PSA targets

Add a script to parse `targets.json` to identify PSA targets and ensure
mandatory parameters are configured correctly for all PSA targets.

Signed-off-by: Devaraj Ranganna <53e2fcb007e5c6e2caf46b91114119a655266f64@arm.com>


from mongrel2.config import *

main = Server(
    uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
    access_log="/logs/access.log",
    error_log="/logs/error.log",
    chroot="./",
    default_host="localhost",
    name="test",
    pid_file="/run/mongrel2.pid",
    port=6767,
    hosts = [
        Host(name="localhost",
             routes={ r'/(.*)': Proxy(addr='127.0.0.1', port=8888) })
    ]
)

commit([main], settings={'limits.buffer_size': 4 * 1024})

Add the settings to the authdemo.

Add the settings to the authdemo.

Response:
<REPLACE_OLD> ]
)

commit([main])

 <REPLACE_NEW> ]
)

commit([main], settings={'limits.buffer_size': 4 * 1024})

 <REPLACE_END> <|endoftext|> from mongrel2.config import *

main = Server(
    uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
    access_log="/logs/access.log",
    error_log="/logs/error.log",
    chroot="./",
    default_host="localhost",
    name="test",
    pid_file="/run/mongrel2.pid",
    port=6767,
    hosts = [
        Host(name="localhost",
             routes={ r'/(.*)': Proxy(addr='127.0.0.1', port=8888) })
    ]
)

commit([main], settings={'limits.buffer_size': 4 * 1024})

Prompt:
Add the settings to the authdemo.
from mongrel2.config import *

main = Server(
    uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
    access_log="/logs/access.log",
    error_log="/logs/error.log",
    chroot="./",
    default_host="localhost",
    name="test",
    pid_file="/run/mongrel2.pid",
    port=6767,
    hosts = [
        Host(name="localhost",
             routes={ r'/(.*)': Proxy(addr='127.0.0.1', port=8888) })
    ]
)

commit([main])


"""A top-level namespace package for IATI."""
from .codelists import Code, Codelist  # noqa: F401
from .data import Dataset  # noqa: F401
from .rulesets import Rule, Ruleset  # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique  # noqa: F401
from .schemas import ActivitySchema, OrganisationSchema  # noqa: F401

__import__('pkg_resources').declare_namespace(__name__)

Response:
<REPLACE_OLD> IATI."""
__import__('pkg_resources').declare_namespace(__name__)

from <REPLACE_NEW> IATI."""
from <REPLACE_END> <REPLACE_OLD> F401
 <REPLACE_NEW> F401

__import__('pkg_resources').declare_namespace(__name__)
 <REPLACE_END> <|endoftext|> """A top-level namespace package for IATI."""
from .codelists import Code, Codelist  # noqa: F401
from .data import Dataset  # noqa: F401
from .rulesets import Rule, Ruleset  # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique  # noqa: F401
from .schemas import ActivitySchema, OrganisationSchema  # noqa: F401

__import__('pkg_resources').declare_namespace(__name__)

Prompt:
Fix pylint error after iati.core -> iati

"""A top-level namespace package for IATI."""
__import__('pkg_resources').declare_namespace(__name__)

from .codelists import Code, Codelist  # noqa: F401
from .data import Dataset  # noqa: F401
from .rulesets import Rule, Ruleset  # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleStartsWith, RuleSum, RuleUnique  # noqa: F401
from .schemas import ActivitySchema, OrganisationSchema  # noqa: F401


# -*- coding: utf-8 -*-
"""
    flask_cors
    ~~~~
    Flask-CORS is a simple extension to Flask allowing you to support cross
    origin resource sharing (CORS) using a simple decorator.

    :copyright: (c) 2014 by Cory Dolphin.
    :license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin
from .extension import CORS
from .version import __version__

__all__ = ['CORS', 'cross_origin']

# Set default logging handler to avoid "No handler found" warnings.
import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

# Set initial level to WARN. Users must manually enable logging for
# flask_cors to see our logging.
rootlogger = logging.getLogger(__name__)
rootlogger.addHandler(NullHandler())

if rootlogger.level == logging.NOTSET:
    rootlogger.setLevel(logging.WARN)

Response:
<REPLACE_OLD> pass

logging.getLogger(__name__).addHandler(NullHandler()) <REPLACE_NEW> pass

# Set initial level to WARN. Users must manually enable logging for
# flask_cors to see our logging.
rootlogger = logging.getLogger(__name__)
rootlogger.addHandler(NullHandler())

if rootlogger.level == logging.NOTSET:
    rootlogger.setLevel(logging.WARN) <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
    flask_cors
    ~~~~
    Flask-CORS is a simple extension to Flask allowing you to support cross
    origin resource sharing (CORS) using a simple decorator.

    :copyright: (c) 2014 by Cory Dolphin.
    :license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin
from .extension import CORS
from .version import __version__

__all__ = ['CORS', 'cross_origin']

# Set default logging handler to avoid "No handler found" warnings.
import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

# Set initial level to WARN. Users must manually enable logging for
# flask_cors to see our logging.
rootlogger = logging.getLogger(__name__)
rootlogger.addHandler(NullHandler())

if rootlogger.level == logging.NOTSET:
    rootlogger.setLevel(logging.WARN)

Prompt:
Disable logging for flask_cors by default

# -*- coding: utf-8 -*-
"""
    flask_cors
    ~~~~
    Flask-CORS is a simple extension to Flask allowing you to support cross
    origin resource sharing (CORS) using a simple decorator.

    :copyright: (c) 2014 by Cory Dolphin.
    :license: MIT, see LICENSE for more details.
"""
from .decorator import cross_origin
from .extension import CORS
from .version import __version__

__all__ = ['CORS', 'cross_origin']

# Set default logging handler to avoid "No handler found" warnings.
import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

logging.getLogger(__name__).addHandler(NullHandler())


# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2019-01-05 00:21
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function

import sys
import traceback

from django.core.management import call_command
from django.db import connections, migrations

from corehq.sql_db.operations import HqRunPython, noop_migration_fn
from corehq.sql_db.util import get_db_aliases_for_partitioned_query

BLOBMETAS_NOT_MIGRATED_ERROR = """
Blob metadata needs to be migrated before this environment can be upgraded to
the latest version of CommCareHQ. Instructions for running the migration can be
found at this link:

https://github.com/dimagi/commcare-cloud/blob/master/docs/changelog/0009-blob-metadata-part-2.md

If you are unable to run the management command because it has been deleted,
you will need to checkout an older version of CommCareHQ first:

git checkout acc40116a96a40c64efb8613fb2ba5933122b151
"""

def get_num_attachments():
    """Get the number of attachments that need to be migrated"""
    def count(dbname):
        with connections[dbname].cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql")
            return cursor.fetchone()[0]

    return sum(count(db) for db in get_db_aliases_for_partitioned_query())

def _assert_blobmetas_migrated(apps, schema_editor):
    """Check if migrated. Raises SystemExit if not migrated"""
    num_attachments = get_num_attachments()

    migrated = num_attachments == 0
    if migrated:
        return

    if num_attachments < 10000:
        try:
            call_command(
                "run_sql",
                "simple_move_form_attachments_to_blobmeta",
                yes=True,
            )
            migrated = get_num_attachments() == 0
            if not migrated:
                print("Automatic migration failed")
                migrated = False
        except Exception:
            traceback.print_exc()
    else:
        print("Found %s attachments." % num_attachments)
        print("Too many to migrate automatically.")

    if not migrated:
        print("")
        print(BLOBMETAS_NOT_MIGRATED_ERROR)
        sys.exit(1)

class Migration(migrations.Migration):

    dependencies = [
        ('blobs', '0006_restrict_form_attachments'),
    ]

    operations = [
        HqRunPython(_assert_blobmetas_migrated, noop_migration_fn)
    ]

Add blob metadata migration check

Add blob metadata migration check

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2019-01-05 00:21
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function

import sys
import traceback

from django.core.management import call_command
from django.db import connections, migrations

from corehq.sql_db.operations import HqRunPython, noop_migration_fn
from corehq.sql_db.util import get_db_aliases_for_partitioned_query

BLOBMETAS_NOT_MIGRATED_ERROR = """
Blob metadata needs to be migrated before this environment can be upgraded to
the latest version of CommCareHQ. Instructions for running the migration can be
found at this link:

https://github.com/dimagi/commcare-cloud/blob/master/docs/changelog/0009-blob-metadata-part-2.md

If you are unable to run the management command because it has been deleted,
you will need to checkout an older version of CommCareHQ first:

git checkout acc40116a96a40c64efb8613fb2ba5933122b151
"""

def get_num_attachments():
    """Get the number of attachments that need to be migrated"""
    def count(dbname):
        with connections[dbname].cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql")
            return cursor.fetchone()[0]

    return sum(count(db) for db in get_db_aliases_for_partitioned_query())

def _assert_blobmetas_migrated(apps, schema_editor):
    """Check if migrated. Raises SystemExit if not migrated"""
    num_attachments = get_num_attachments()

    migrated = num_attachments == 0
    if migrated:
        return

    if num_attachments < 10000:
        try:
            call_command(
                "run_sql",
                "simple_move_form_attachments_to_blobmeta",
                yes=True,
            )
            migrated = get_num_attachments() == 0
            if not migrated:
                print("Automatic migration failed")
                migrated = False
        except Exception:
            traceback.print_exc()
    else:
        print("Found %s attachments." % num_attachments)
        print("Too many to migrate automatically.")

    if not migrated:
        print("")
        print(BLOBMETAS_NOT_MIGRATED_ERROR)
        sys.exit(1)

class Migration(migrations.Migration):

    dependencies = [
        ('blobs', '0006_restrict_form_attachments'),
    ]

    operations = [
        HqRunPython(_assert_blobmetas_migrated, noop_migration_fn)
    ]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2019-01-05 00:21
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function

import sys
import traceback

from django.core.management import call_command
from django.db import connections, migrations

from corehq.sql_db.operations import HqRunPython, noop_migration_fn
from corehq.sql_db.util import get_db_aliases_for_partitioned_query

BLOBMETAS_NOT_MIGRATED_ERROR = """
Blob metadata needs to be migrated before this environment can be upgraded to
the latest version of CommCareHQ. Instructions for running the migration can be
found at this link:

https://github.com/dimagi/commcare-cloud/blob/master/docs/changelog/0009-blob-metadata-part-2.md

If you are unable to run the management command because it has been deleted,
you will need to checkout an older version of CommCareHQ first:

git checkout acc40116a96a40c64efb8613fb2ba5933122b151
"""

def get_num_attachments():
    """Get the number of attachments that need to be migrated"""
    def count(dbname):
        with connections[dbname].cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql")
            return cursor.fetchone()[0]

    return sum(count(db) for db in get_db_aliases_for_partitioned_query())

def _assert_blobmetas_migrated(apps, schema_editor):
    """Check if migrated. Raises SystemExit if not migrated"""
    num_attachments = get_num_attachments()

    migrated = num_attachments == 0
    if migrated:
        return

    if num_attachments < 10000:
        try:
            call_command(
                "run_sql",
                "simple_move_form_attachments_to_blobmeta",
                yes=True,
            )
            migrated = get_num_attachments() == 0
            if not migrated:
                print("Automatic migration failed")
                migrated = False
        except Exception:
            traceback.print_exc()
    else:
        print("Found %s attachments." % num_attachments)
        print("Too many to migrate automatically.")

    if not migrated:
        print("")
        print(BLOBMETAS_NOT_MIGRATED_ERROR)
        sys.exit(1)

class Migration(migrations.Migration):

    dependencies = [
        ('blobs', '0006_restrict_form_attachments'),
    ]

    operations = [
        HqRunPython(_assert_blobmetas_migrated, noop_migration_fn)
    ]

Prompt: Add blob metadata migration check


# vim: tabstop=4 shiftwidth=4 softtabstop=4

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

import os

class HostDriver(object):

    def get_all_block_devices(self):
        """Get the list of all block devices seen in /dev/disk/by-path/."""
        files = []
        dir = "/dev/disk/by-path/"
        if os.path.isdir(dir):
            files = os.listdir(dir)
        devices = []
        for file in files:
            devices.append(dir + file)
        return devices

Response:
<INSERT> files = []
        <INSERT_END> <INSERT>        if os.path.isdir(dir):
     <INSERT_END> <|endoftext|> # vim: tabstop=4 shiftwidth=4 softtabstop=4

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

import os

class HostDriver(object):

    def get_all_block_devices(self):
        """Get the list of all block devices seen in /dev/disk/by-path/."""
        files = []
        dir = "/dev/disk/by-path/"
        if os.path.isdir(dir):
            files = os.listdir(dir)
        devices = []
        for file in files:
            devices.append(dir + file)
        return devices

Prompt:
Check if dir exists before calling listdir

Changes along the way to how we clean up and detach after
copying an image to a volume exposed a problem in the cleanup
of the brick/initiator routines.

The clean up in the initiator detach was doing a blind listdir
of /dev/disk/by-path, however due to detach and cleanup being
called upon completion of the image download to the volume if
there are no other devices mapped in this directory the directory
is removed.

The result was that even though the create and copy of the image
was succesful, the HostDriver code called os.lisdir on a directory
that doesn't exist any longer and raises an unhandled exception that
cause the taskflow mechanism to mark the volume as failed.

Change-Id: I488755c1a49a77f42efbb58a7a4eb6f4f084df07
Closes-bug: #1243980

# vim: tabstop=4 shiftwidth=4 softtabstop=4

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

import os

class HostDriver(object):

    def get_all_block_devices(self):
        """Get the list of all block devices seen in /dev/disk/by-path/."""
        dir = "/dev/disk/by-path/"
        files = os.listdir(dir)
        devices = []
        for file in files:
            devices.append(dir + file)
        return devices


from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode

class InvitationKeyAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')

class InvitationUserAdmin(admin.ModelAdmin):
    list_display = ('inviter', 'invitations_remaining')

def invite_user(modeladmin, request, queryset):
    for invitation_request in queryset.all():
        invitation = InvitationKey.objects.create_invitation(request.user)
        invitation.send_to(invitation_request.email)
        invitation_request.invited = True
        invitation_request.save()

invite_user.short_description = "Invite selected invitation requests"

class InvitationRequestAdmin(admin.ModelAdmin):
    list_display = ('email', 'invited')
    actions = [invite_user]

admin.site.register(InvitationKey, InvitationKeyAdmin)
admin.site.register(InvitationUser, InvitationUserAdmin)
admin.site.register(InvitationRequest, InvitationRequestAdmin)
admin.site.register(InvitationCode)

Improve the invite_user action name.

Improve the invite_user action name.

Response:
<REPLACE_OLD> this user"

class <REPLACE_NEW> selected invitation requests"

class <REPLACE_END> <|endoftext|> from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode

class InvitationKeyAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')

class InvitationUserAdmin(admin.ModelAdmin):
    list_display = ('inviter', 'invitations_remaining')

def invite_user(modeladmin, request, queryset):
    for invitation_request in queryset.all():
        invitation = InvitationKey.objects.create_invitation(request.user)
        invitation.send_to(invitation_request.email)
        invitation_request.invited = True
        invitation_request.save()

invite_user.short_description = "Invite selected invitation requests"

class InvitationRequestAdmin(admin.ModelAdmin):
    list_display = ('email', 'invited')
    actions = [invite_user]

admin.site.register(InvitationKey, InvitationKeyAdmin)
admin.site.register(InvitationUser, InvitationUserAdmin)
admin.site.register(InvitationRequest, InvitationRequestAdmin)
admin.site.register(InvitationCode)

Prompt:
Improve the invite_user action name.
from django.contrib import admin
from invitation.models import InvitationKey, InvitationUser, InvitationRequest, InvitationCode

class InvitationKeyAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'from_user', 'date_invited', 'key_expired')

class InvitationUserAdmin(admin.ModelAdmin):
    list_display = ('inviter', 'invitations_remaining')

def invite_user(modeladmin, request, queryset):
    for invitation_request in queryset.all():
        invitation = InvitationKey.objects.create_invitation(request.user)
        invitation.send_to(invitation_request.email)
        invitation_request.invited = True
        invitation_request.save()

invite_user.short_description = "Invite this user"

class InvitationRequestAdmin(admin.ModelAdmin):
    list_display = ('email', 'invited')
    actions = [invite_user]

admin.site.register(InvitationKey, InvitationKeyAdmin)
admin.site.register(InvitationUser, InvitationUserAdmin)
admin.site.register(InvitationRequest, InvitationRequestAdmin)
admin.site.register(InvitationCode)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

def kruskal():
	"""Kruskal's algorithm for minimum spanning tree
	in weighted graph.

    Time complexity for graph G(V, E):
    O(|E|+|V|+|E|log(|V|)) = O(|E|log(|V|^2)) = O(|E|log(|V|)).
	"""
	pass

def main():
	w_graph_d = {
        'a': {'b': 1, 'd': 4, 'e': 3},
        'b': {'a': 1, 'd': 4, 'e': 2},
        'c': {'e': 4, 'f': 5},
        'd': {'a': 4, 'b': 4, 'e': 4},
        'e': {'a': 3, 'b': 2, 'c': 4, 'd': 4, 'f': 7},
        'f': {'c': 5, 'e': 7}
    }
    print('w_graph_d:\n{}'.format(w_graph_d))

    print('Kruskal\'s minimum spanning tree:')
    pass

if __name__ == '__main__':
	main()

Response:
<REPLACE_OLD> in <REPLACE_NEW>
	in <REPLACE_END> <REPLACE_OLD> TBD.
	"""
	pass

def <REPLACE_NEW>
    O(|E|+|V|+|E|log(|V|)) = O(|E|log(|V|^2)) = O(|E|log(|V|)).
	"""
	pass

def <REPLACE_END> <|endoftext|> from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

def kruskal():
	"""Kruskal's algorithm for minimum spanning tree
	in weighted graph.

    Time complexity for graph G(V, E):
    O(|E|+|V|+|E|log(|V|)) = O(|E|log(|V|^2)) = O(|E|log(|V|)).
	"""
	pass

def main():
	w_graph_d = {
        'a': {'b': 1, 'd': 4, 'e': 3},
        'b': {'a': 1, 'd': 4, 'e': 2},
        'c': {'e': 4, 'f': 5},
        'd': {'a': 4, 'b': 4, 'e': 4},
        'e': {'a': 3, 'b': 2, 'c': 4, 'd': 4, 'f': 7},
        'f': {'c': 5, 'e': 7}
    }
    print('w_graph_d:\n{}'.format(w_graph_d))

    print('Kruskal\'s minimum spanning tree:')
    pass

if __name__ == '__main__':
	main()

Prompt:
Revise doc string and add time complexity

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

def kruskal():
	"""Kruskal's algorithm for minimum spanning tree in weighted graph.

    Time complexity for graph G(V, E): TBD.
	"""
	pass

def main():
	w_graph_d = {
        'a': {'b': 1, 'd': 4, 'e': 3},
        'b': {'a': 1, 'd': 4, 'e': 2},
        'c': {'e': 4, 'f': 5},
        'd': {'a': 4, 'b': 4, 'e': 4},
        'e': {'a': 3, 'b': 2, 'c': 4, 'd': 4, 'f': 7},
        'f': {'c': 5, 'e': 7}
    }
    print('w_graph_d:\n{}'.format(w_graph_d))

    print('Kruskal\'s minimum spanning tree:')
    pass

if __name__ == '__main__':
	main()


from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase

from carapace.util import ssh as util

from peloid.app import mud
from peloid.app.shell import gameshell, setupshell

def getGameShellFactory(**namespace):
    game = mud.Game()
    sshRealm = gameshell.TerminalRealm(namespace, game)
    sshPortal = portal.Portal(sshRealm)
    factory = manhole_ssh.ConchFactory(sshPortal)
    factory.privateKeys = {'ssh-rsa': util.getPrivKey()}
    factory.publicKeys = {'ssh-rsa': util.getPubKey()}
    factory.portal.registerChecker(SSHPublicKeyDatabase())
    return factory

def getSetupShellFactory(**namespace):
    #telnetRealm = setupshell.X
    #telnetPortal = portal.Portal(telnetRealm)
    pass

Use the new Game class.

Use the new Game class.

Response:
<INSERT> peloid.app import mud
from <INSERT_END> <REPLACE_OLD> None
 <REPLACE_NEW> mud.Game()
 <REPLACE_END> <|endoftext|> from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase

from carapace.util import ssh as util

from peloid.app import mud
from peloid.app.shell import gameshell, setupshell

def getGameShellFactory(**namespace):
    game = mud.Game()
    sshRealm = gameshell.TerminalRealm(namespace, game)
    sshPortal = portal.Portal(sshRealm)
    factory = manhole_ssh.ConchFactory(sshPortal)
    factory.privateKeys = {'ssh-rsa': util.getPrivKey()}
    factory.publicKeys = {'ssh-rsa': util.getPubKey()}
    factory.portal.registerChecker(SSHPublicKeyDatabase())
    return factory

def getSetupShellFactory(**namespace):
    #telnetRealm = setupshell.X
    #telnetPortal = portal.Portal(telnetRealm)
    pass

Prompt:
Use the new Game class.

from twisted.cred import portal
from twisted.conch import manhole_ssh
from twisted.conch.checkers import SSHPublicKeyDatabase

from carapace.util import ssh as util

from peloid.app.shell import gameshell, setupshell

def getGameShellFactory(**namespace):
    game = None
    sshRealm = gameshell.TerminalRealm(namespace, game)
    sshPortal = portal.Portal(sshRealm)
    factory = manhole_ssh.ConchFactory(sshPortal)
    factory.privateKeys = {'ssh-rsa': util.getPrivKey()}
    factory.publicKeys = {'ssh-rsa': util.getPubKey()}
    factory.portal.registerChecker(SSHPublicKeyDatabase())
    return factory

def getSetupShellFactory(**namespace):
    #telnetRealm = setupshell.X
    #telnetPortal = portal.Portal(telnetRealm)
    pass


import sys

def canAppAccessDatabase():
    """
    Returns True if the apps.py file can access database records.

    There are some circumstances where we don't want the ready function in apps.py
    to touch the database
    """

    # If any of the following management commands are being executed,
    # prevent custom "on load" code from running!
    excluded_commands = [
        'flush',
        'loaddata',
        'dumpdata',
        'makemirations',
        'migrate',
        'check',
        'dbbackup',
        'mediabackup',
        'dbrestore',
        'mediarestore',
        'shell',
        'createsuperuser',
        'wait_for_db',
        'prerender',
        'collectstatic',
        'makemessages',
        'compilemessages',
    ]

    for cmd in excluded_commands:
        if cmd in sys.argv:
            return False

    return True

Allow data operations to run for 'test'

Allow data operations to run for 'test'

Response:
<DELETE>     'test',
    <DELETE_END> <|endoftext|> import sys

def canAppAccessDatabase():
    """
    Returns True if the apps.py file can access database records.

    There are some circumstances where we don't want the ready function in apps.py
    to touch the database
    """

    # If any of the following management commands are being executed,
    # prevent custom "on load" code from running!
    excluded_commands = [
        'flush',
        'loaddata',
        'dumpdata',
        'makemirations',
        'migrate',
        'check',
        'dbbackup',
        'mediabackup',
        'dbrestore',
        'mediarestore',
        'shell',
        'createsuperuser',
        'wait_for_db',
        'prerender',
        'collectstatic',
        'makemessages',
        'compilemessages',
    ]

    for cmd in excluded_commands:
        if cmd in sys.argv:
            return False

    return True

Prompt:
Allow data operations to run for 'test'

import sys

def canAppAccessDatabase():
    """
    Returns True if the apps.py file can access database records.

    There are some circumstances where we don't want the ready function in apps.py
    to touch the database
    """

    # If any of the following management commands are being executed,
    # prevent custom "on load" code from running!
    excluded_commands = [
        'flush',
        'loaddata',
        'dumpdata',
        'makemirations',
        'migrate',
        'check',
        'dbbackup',
        'mediabackup',
        'dbrestore',
        'mediarestore',
        'shell',
        'createsuperuser',
        'wait_for_db',
        'prerender',
        'collectstatic',
        'makemessages',
        'compilemessages',
        'test',
    ]

    for cmd in excluded_commands:
        if cmd in sys.argv:
            return False

    return True


from fluent_pages.adminui import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage

@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
    """
    Plugin binding the FaqPage model as pagetype.
    """
    model = FaqPage
    model_admin = HtmlPageAdmin
    urls = 'fluent_faq.urls'

Response:
<REPLACE_OLD> fluent_pages.admin <REPLACE_NEW> fluent_pages.adminui <REPLACE_END> <|endoftext|> from fluent_pages.adminui import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage

@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
    """
    Plugin binding the FaqPage model as pagetype.
    """
    model = FaqPage
    model_admin = HtmlPageAdmin
    urls = 'fluent_faq.urls'

Prompt:
Prepare Django 1.7 compatibility, use new fluent_pages.adminui module

from fluent_pages.admin import HtmlPageAdmin
from fluent_pages.extensions import page_type_pool, PageTypePlugin
from .models import FaqPage

@page_type_pool.register
class FaqPagePlugin(PageTypePlugin):
    """
    Plugin binding the FaqPage model as pagetype.
    """
    model = FaqPage
    model_admin = HtmlPageAdmin
    urls = 'fluent_faq.urls'


#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball

rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)

numRows = 16
height = ledMatrix.height
width = ledMatrix.width
red = Ball(5, 9, 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)

try:
	print "Press Ctrl + C to stop executing"
	while True:
		nextFrame = ledMatrix.CreateFrameCanvas()
		red.updateValues(1 / 60.0)
		blue.updateValues(1 / 60.0)
		red.drawOnMatrix(nextFrame)
		blue.drawOnMatrix(nextFrame)
		ledMatrix.SwapOnVSync(nextFrame)
		time.sleep(1 / 60.0)
except KeyboardInterrupt:
	print "Exiting\n"
	sys.exit(0)

Add two balls to animation

Add two balls to animation

Response:
<REPLACE_OLD> ledMatrix.width
ball <REPLACE_NEW> ledMatrix.width
red <REPLACE_END> <REPLACE_OLD> 4)

try:
	print <REPLACE_NEW> 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)

try:
	print <REPLACE_END> <REPLACE_OLD> ledMatrix.CreateFrameCanvas()
		ball.updateValues(1 <REPLACE_NEW> ledMatrix.CreateFrameCanvas()
		red.updateValues(1 <REPLACE_END> <REPLACE_OLD> 60.0)
		ball.drawOnMatrix(nextFrame)
		ledMatrix.SwapOnVSync(nextFrame)
		time.sleep(1 <REPLACE_NEW> 60.0)
		blue.updateValues(1 / 60.0)
		red.drawOnMatrix(nextFrame)
		blue.drawOnMatrix(nextFrame)
		ledMatrix.SwapOnVSync(nextFrame)
		time.sleep(1 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball

rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)

numRows = 16
height = ledMatrix.height
width = ledMatrix.width
red = Ball(5, 9, 4)
blue = Ball(6, 9, 2, 2, 0, 0, 255)

try:
	print "Press Ctrl + C to stop executing"
	while True:
		nextFrame = ledMatrix.CreateFrameCanvas()
		red.updateValues(1 / 60.0)
		blue.updateValues(1 / 60.0)
		red.drawOnMatrix(nextFrame)
		blue.drawOnMatrix(nextFrame)
		ledMatrix.SwapOnVSync(nextFrame)
		time.sleep(1 / 60.0)
except KeyboardInterrupt:
	print "Exiting\n"
	sys.exit(0)

Prompt:
Add two balls to animation

#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball

rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)

numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)

try:
	print "Press Ctrl + C to stop executing"
	while True:
		nextFrame = ledMatrix.CreateFrameCanvas()
		ball.updateValues(1 / 60.0)
		ball.drawOnMatrix(nextFrame)
		ledMatrix.SwapOnVSync(nextFrame)
		time.sleep(1 / 60.0)
except KeyboardInterrupt:
	print "Exiting\n"
	sys.exit(0)


import os
from osgtest.library import core, osgunittest
import unittest

class TestStartGridFTP(osgunittest.OSGTestCase):

    def test_01_start_gridftp(self):
        core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid'
        core.state['gridftp.started-server'] = False

        core.skip_ok_unless_installed('globus-gridftp-server-progs')
        self.skip_ok_if(os.path.exists(core.config['gridftp.pid-file']), 'already running')

        command = ('service', 'globus-gridftp-server', 'start')
        stdout, _, fail = core.check_system(command, 'Start GridFTP server')
        self.assert_(stdout.find('FAILED') == -1, fail)
        self.assert_(os.path.exists(core.config['gridftp.pid-file']),
                     'GridFTP server PID file missing')
        core.state['gridftp.started-server'] = True

Response:
<REPLACE_OLD> os
import osgtest.library.core as core
import <REPLACE_NEW> os
from osgtest.library import core, osgunittest
import <REPLACE_END> <REPLACE_OLD> TestStartGridFTP(unittest.TestCase):

 <REPLACE_NEW> TestStartGridFTP(osgunittest.OSGTestCase):

 <REPLACE_END> <REPLACE_OLD> if not core.rpm_is_installed('globus-gridftp-server-progs'):
 <REPLACE_NEW> core.skip_ok_unless_installed('globus-gridftp-server-progs')
 <REPLACE_END> <REPLACE_OLD>     core.skip('not installed')
            return
        if os.path.exists(core.config['gridftp.pid-file']):
            core.skip('apparently running')
            return

 <REPLACE_NEW> self.skip_ok_if(os.path.exists(core.config['gridftp.pid-file']), 'already running')

 <REPLACE_END> <|endoftext|> import os
from osgtest.library import core, osgunittest
import unittest

class TestStartGridFTP(osgunittest.OSGTestCase):

    def test_01_start_gridftp(self):
        core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid'
        core.state['gridftp.started-server'] = False

        core.skip_ok_unless_installed('globus-gridftp-server-progs')
        self.skip_ok_if(os.path.exists(core.config['gridftp.pid-file']), 'already running')

        command = ('service', 'globus-gridftp-server', 'start')
        stdout, _, fail = core.check_system(command, 'Start GridFTP server')
        self.assert_(stdout.find('FAILED') == -1, fail)
        self.assert_(os.path.exists(core.config['gridftp.pid-file']),
                     'GridFTP server PID file missing')
        core.state['gridftp.started-server'] = True

Prompt:
Update 13_gridftp to use OkSkip functionality

git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@16527 4e558342-562e-0410-864c-e07659590f8c

import os
import osgtest.library.core as core
import unittest

class TestStartGridFTP(unittest.TestCase):

    def test_01_start_gridftp(self):
        core.config['gridftp.pid-file'] = '/var/run/globus-gridftp-server.pid'
        core.state['gridftp.started-server'] = False

        if not core.rpm_is_installed('globus-gridftp-server-progs'):
            core.skip('not installed')
            return
        if os.path.exists(core.config['gridftp.pid-file']):
            core.skip('apparently running')
            return

        command = ('service', 'globus-gridftp-server', 'start')
        stdout, _, fail = core.check_system(command, 'Start GridFTP server')
        self.assert_(stdout.find('FAILED') == -1, fail)
        self.assert_(os.path.exists(core.config['gridftp.pid-file']),
                     'GridFTP server PID file missing')
        core.state['gridftp.started-server'] = True


# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.

import detail.util
import os
import sys

def get(arch, vs_version):
  vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
  vs_path = os.getenv(vs_path_env)
  if not vs_path:
    sys.exit(
        'Environment variable {} is empty, '
        'looks like Visual Studio {} is not installed'.format(
            vs_path_env, vs_version
        )
    )

  if vs_version == '15':
    vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC', 'Auxiliary', 'Build')
  else:
    vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC')

  if not os.path.isdir(vcvarsall_dir):
    sys.exit(
        'Directory `{}` not exists '
        '({} environment variable)'.format(vcvarsall_dir, vs_path_env)
    )
  vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat')
  if not os.path.isfile(vcvarsall_path):
    sys.exit(
        'File vcvarsall.bat not found in directory '
        '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env)
    )
  return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])

Response:
<REPLACE_OLD> )
 <REPLACE_NEW> )

  if vs_version == '15':
   <REPLACE_END> <REPLACE_OLD> 'VC')
 <REPLACE_NEW> 'VC', 'Auxiliary', 'Build')
  else:
    vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC')

 <REPLACE_END> <|endoftext|> # Copyright (c) 2014, Ruslan Baratov
# All rights reserved.

import detail.util
import os
import sys

def get(arch, vs_version):
  vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
  vs_path = os.getenv(vs_path_env)
  if not vs_path:
    sys.exit(
        'Environment variable {} is empty, '
        'looks like Visual Studio {} is not installed'.format(
            vs_path_env, vs_version
        )
    )

  if vs_version == '15':
    vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC', 'Auxiliary', 'Build')
  else:
    vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC')

  if not os.path.isdir(vcvarsall_dir):
    sys.exit(
        'Directory `{}` not exists '
        '({} environment variable)'.format(vcvarsall_dir, vs_path_env)
    )
  vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat')
  if not os.path.isfile(vcvarsall_path):
    sys.exit(
        'File vcvarsall.bat not found in directory '
        '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env)
    )
  return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])

Prompt:
polly.py: Fix vcvarsall_dir for Visual Studio 2017

[skip ci]

# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.

import detail.util
import os
import sys

def get(arch, vs_version):
  vs_path_env = 'VS{}0COMNTOOLS'.format(vs_version)
  vs_path = os.getenv(vs_path_env)
  if not vs_path:
    sys.exit(
        'Environment variable {} is empty, '
        'looks like Visual Studio {} is not installed'.format(
            vs_path_env, vs_version
        )
    )
  vcvarsall_dir = os.path.join(vs_path, '..', '..', 'VC')
  if not os.path.isdir(vcvarsall_dir):
    sys.exit(
        'Directory `{}` not exists '
        '({} environment variable)'.format(vcvarsall_dir, vs_path_env)
    )
  vcvarsall_path = os.path.join(vcvarsall_dir, 'vcvarsall.bat')
  if not os.path.isfile(vcvarsall_path):
    sys.exit(
        'File vcvarsall.bat not found in directory '
        '`{}` ({} environment variable)'.format(vcvarsall_dir, vs_path_env)
    )
  return detail.util.get_environment_from_batch_command([vcvarsall_path, arch])


import torch
import torch.nn as nn
import torch.nn.functional as F

class DenseBinaryCrossEntropy(nn.Module):
    """ BCE using one-hot from dense targets w/ label smoothing
    NOTE for experiments comparing CE to BCE /w label smoothing, may remove
    """
    def __init__(self, smoothing=0.1):
        super(DenseBinaryCrossEntropy, self).__init__()
        assert 0. <= smoothing < 1.0
        self.smoothing = smoothing
        self.bce = nn.BCEWithLogitsLoss()

    def forward(self, x, target):
        num_classes = x.shape[-1]
        off_value = self.smoothing / num_classes
        on_value = 1. - self.smoothing + off_value
        target = target.long().view(-1, 1)
        target = torch.full(
            (target.size()[0], num_classes), off_value, device=x.device, dtype=x.dtype).scatter_(1, target, on_value)
        return self.bce(x, target)

Add a BCE loss impl that converts dense targets to sparse /w smoothing as an alternate to CE w/ smoothing. For training experiments.

Response:
<INSERT> import torch
import torch.nn as nn
import torch.nn.functional as F

class DenseBinaryCrossEntropy(nn.Module):
 <INSERT_END> <INSERT>   """ BCE using one-hot from dense targets w/ label smoothing
    NOTE for experiments comparing CE to BCE /w label smoothing, may remove
    """
    def __init__(self, smoothing=0.1):
        super(DenseBinaryCrossEntropy, self).__init__()
        assert 0. <= smoothing < 1.0
        self.smoothing = smoothing
        self.bce = nn.BCEWithLogitsLoss()

    def forward(self, x, target):
        num_classes = x.shape[-1]
        off_value = self.smoothing / num_classes
        on_value = 1. - self.smoothing + off_value
        target = target.long().view(-1, 1)
        target = torch.full(
            (target.size()[0], num_classes), off_value, device=x.device, dtype=x.dtype).scatter_(1, target, on_value)
        return self.bce(x, target)
 <INSERT_END> <|endoftext|> import torch
import torch.nn as nn
import torch.nn.functional as F

class DenseBinaryCrossEntropy(nn.Module):
    """ BCE using one-hot from dense targets w/ label smoothing
    NOTE for experiments comparing CE to BCE /w label smoothing, may remove
    """
    def __init__(self, smoothing=0.1):
        super(DenseBinaryCrossEntropy, self).__init__()
        assert 0. <= smoothing < 1.0
        self.smoothing = smoothing
        self.bce = nn.BCEWithLogitsLoss()

    def forward(self, x, target):
        num_classes = x.shape[-1]
        off_value = self.smoothing / num_classes
        on_value = 1. - self.smoothing + off_value
        target = target.long().view(-1, 1)
        target = torch.full(
            (target.size()[0], num_classes), off_value, device=x.device, dtype=x.dtype).scatter_(1, target, on_value)
        return self.bce(x, target)

Prompt: Add a BCE loss impl that converts dense targets to sparse /w smoothing as an alternate to CE w/ smoothing. For training experiments.


# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import migrations, models
from corehq.sql_db.operations import RawSQLMigration
from custom.icds_reports.utils.migrations import get_view_migrations

migrator = RawSQLMigration(('custom', 'icds_reports', 'migrations', 'sql_templates'))

class Migration(migrations.Migration):

    dependencies = [
        ('icds_reports', '0069_valid_visits'),
    ]

    operations = [
    ]
    operations.extend(get_view_migrations())

Remove adding field to View model

Remove adding field to View model

Response:
<DELETE>     migrations.AddField(
            model_name='CcsRecordMonthlyView',
            name='open_in_month',
            field=models.SmallIntegerField(blank=True, null=True),
        ),
    <DELETE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import migrations, models
from corehq.sql_db.operations import RawSQLMigration
from custom.icds_reports.utils.migrations import get_view_migrations

migrator = RawSQLMigration(('custom', 'icds_reports', 'migrations', 'sql_templates'))

class Migration(migrations.Migration):

    dependencies = [
        ('icds_reports', '0069_valid_visits'),
    ]

    operations = [
    ]
    operations.extend(get_view_migrations())

Prompt:
Remove adding field to View model

# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 14:35
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import migrations, models
from corehq.sql_db.operations import RawSQLMigration
from custom.icds_reports.utils.migrations import get_view_migrations

migrator = RawSQLMigration(('custom', 'icds_reports', 'migrations', 'sql_templates'))

class Migration(migrations.Migration):

    dependencies = [
        ('icds_reports', '0069_valid_visits'),
    ]

    operations = [
        migrations.AddField(
            model_name='CcsRecordMonthlyView',
            name='open_in_month',
            field=models.SmallIntegerField(blank=True, null=True),
        ),
    ]
    operations.extend(get_view_migrations())


import pandas as pd
import numpy as np
import operator
from sys import argv
import os

def extract( file_name ):
    with open(file_name) as f:
        for i,line in enumerate(f,1):
            if "SCN" in line:
                return i
def main(lta_name):
    os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
    dictionary = {}
    #lta_file = str(argv[1])
    skipped_rows = extract('lta_file.txt')-1

    header = pd.read_csv('lta_file.txt',skiprows=skipped_rows,delimiter=r"\s+")
    flux = list(set(header["OBJECT"]))
    #print flux

    header['Nrecs'] = header['Nrecs'].astype(float)

    for i in flux :
        temp = header.loc[header.OBJECT==i,'Nrecs'].values
        temp = np.mean(temp)
        dictionary[i]=temp
    #print dictionary

    source = max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
    return source

Insert main body of code into function

Insert main body of code into function

Response:
<DELETE>     <DELETE_END> <DELETE>         <DELETE_END> <DELETE>             <DELETE_END> <INSERT> return i
def main(lta_name):
 <INSERT_END> <INSERT> os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
 <INSERT_END> <INSERT> dictionary = {}
 <INSERT_END> <INSERT> #lta_file = str(argv[1])
 <INSERT_END> <INSERT> skipped_rows = extract('lta_file.txt')-1

 <INSERT_END> <INSERT> header = pd.read_csv('lta_file.txt',skiprows=skipped_rows,delimiter=r"\s+")
 <INSERT_END> <REPLACE_OLD> return i

os.system('ltahdr -i'+ argv[1]+ '> lta_file.txt')
dictionary <REPLACE_NEW>   flux <REPLACE_END> <REPLACE_OLD> {}
#lta_file <REPLACE_NEW> list(set(header["OBJECT"]))
    #print flux

    header['Nrecs'] <REPLACE_END> <REPLACE_OLD> str(argv[1])
skipped_rows = extract('lta_file.txt')-1

header = pd.read_csv('lta_file.txt',skiprows=skipped_rows,delimiter=r"\s+")
flux = list(set(header["OBJECT"]))
print flux

header['Nrecs'] = header['Nrecs'].astype(float)

for <REPLACE_NEW> header['Nrecs'].astype(float)

    for <REPLACE_END> <REPLACE_OLD> dictionary[i]=temp
print dictionary

source <REPLACE_NEW> dictionary[i]=temp
    #print dictionary

    source <REPLACE_END> <REPLACE_OLD> max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
print source

 <REPLACE_NEW> max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
    return source
 <REPLACE_END> <|endoftext|> import pandas as pd
import numpy as np
import operator
from sys import argv
import os

def extract( file_name ):
    with open(file_name) as f:
        for i,line in enumerate(f,1):
            if "SCN" in line:
                return i
def main(lta_name):
    os.system('ltahdr -i'+ lta_name + '> lta_file.txt')
    dictionary = {}
    #lta_file = str(argv[1])
    skipped_rows = extract('lta_file.txt')-1

    header = pd.read_csv('lta_file.txt',skiprows=skipped_rows,delimiter=r"\s+")
    flux = list(set(header["OBJECT"]))
    #print flux

    header['Nrecs'] = header['Nrecs'].astype(float)

    for i in flux :
        temp = header.loc[header.OBJECT==i,'Nrecs'].values
        temp = np.mean(temp)
        dictionary[i]=temp
    #print dictionary

    source = max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
    return source

Prompt:
Insert main body of code into function

import pandas as pd
import numpy as np
import operator
from sys import argv
import os

def extract( file_name ):
        with open(file_name) as f:
                for i,line in enumerate(f,1):
                        if "SCN" in line:
                                return i

os.system('ltahdr -i'+ argv[1]+ '> lta_file.txt')
dictionary = {}
#lta_file = str(argv[1])
skipped_rows = extract('lta_file.txt')-1

header = pd.read_csv('lta_file.txt',skiprows=skipped_rows,delimiter=r"\s+")
flux = list(set(header["OBJECT"]))
print flux

header['Nrecs'] = header['Nrecs'].astype(float)

for i in flux :
        temp = header.loc[header.OBJECT==i,'Nrecs'].values
        temp = np.mean(temp)
        dictionary[i]=temp
print dictionary

source = max(dictionary.iteritems(),key=operator.itemgetter(1))[0]
print source


# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
from pylab import *
import types
from skimage import io, data

# 读取图片,灰度化，并转为数组
im0 = Image.open("test.jpeg").convert('L')
im = array(im0)

# print(type(im[1, 1]))

x = y = 0
m = im.shape[0]
n = im.shape[1]
h = range(m - 2)
k = range(n - 2)
matrix = np.array([[255 for i in range(n)] for i in range(m)])
limit = 255

gray()

# 将图像处理成“点图”
for x in h[::2]:
    for y in k[::2]:
        im[x + 1, y + 1] = (int(im[x, y]) + int(im[x, y + 2]) + int(
            im[x + 1, y + 1]) + int(im[x + 2, y]) + int(im[x + 2, y + 2])) / 5
        im[x, y] = 255

# 在“点图”中连线

imshow(im)
# imshow(matrix)
#io.imsave('dot.jpg', matrix)

# im0.save("test.jpg")

show()

Convert a image to many lines.

Convert a image to many lines.

Response:
<INSERT> # -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
from pylab import *
import types
from skimage import io, data

# 读取图片,灰度化，并转为数组
im0 = Image.open("test.jpeg").convert('L')
im = array(im0)

# print(type(im[1, 1]))

x = y = 0
m = im.shape[0]
n = im.shape[1]
h = range(m - 2)
k = range(n - 2)
matrix = np.array([[255 for i in range(n)] for i in range(m)])
limit = 255

gray()

# 将图像处理成“点图”
for x in h[::2]:
 <INSERT_END> <INSERT>   for y in k[::2]:
        im[x + 1, y + 1] = (int(im[x, y]) + int(im[x, y + 2]) + int(
            im[x + 1, y + 1]) + int(im[x + 2, y]) + int(im[x + 2, y + 2])) / 5
        im[x, y] = 255

# 在“点图”中连线

imshow(im)
# imshow(matrix)
#io.imsave('dot.jpg', matrix)

# im0.save("test.jpg")

show()
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
from pylab import *
import types
from skimage import io, data

# 读取图片,灰度化，并转为数组
im0 = Image.open("test.jpeg").convert('L')
im = array(im0)

# print(type(im[1, 1]))

x = y = 0
m = im.shape[0]
n = im.shape[1]
h = range(m - 2)
k = range(n - 2)
matrix = np.array([[255 for i in range(n)] for i in range(m)])
limit = 255

gray()

# 将图像处理成“点图”
for x in h[::2]:
    for y in k[::2]:
        im[x + 1, y + 1] = (int(im[x, y]) + int(im[x, y + 2]) + int(
            im[x + 1, y + 1]) + int(im[x + 2, y]) + int(im[x + 2, y + 2])) / 5
        im[x, y] = 255

# 在“点图”中连线

imshow(im)
# imshow(matrix)
#io.imsave('dot.jpg', matrix)

# im0.save("test.jpg")

show()

Prompt: Convert a image to many lines.


# cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import os

from cerbero.commands import Command, register_command
from cerbero.ide.common import PkgConfig
from cerbero.ide.vs.pkgconfig2vsprops import PkgConfig2VSProps, CommonVSProps
from cerbero.utils import _, N_, ArgparseArgument
from cerbero.utils import messages as m

DEFAULT_PREFIX_MACRO = 'CERBERO_SDK_ROOT'

class GenVSProps(Command):
    doc = N_('Generate Visual Studio property sheets to use the SDK from VS')
    name = 'genvsprops'

    def __init__(self):
        Command.__init__(self,
            [ArgparseArgument('-o', '--output_dir', default='.',
                help=_('output directory where .vsprops files will be saved')),
            ])

    def run(self, config, args):
        if not os.path.exists(args.output_dir):
            os.makedirs(args.output_dir)

        for pc in PkgConfig.list_all():
            m.action('Created %s.vsprops' % pc)
            p2v = PkgConfig2VSProps(pc, config.prefix, '$(%s)' %
                    DEFAULT_PREFIX_MACRO, False)
            p2v.create(args.output_dir)
            m.action('Created %s.vsprops' % pc)

        common = CommonVSProps(config.prefix, DEFAULT_PREFIX_MACRO)
        common.create(args.output_dir)
        m.message('Property sheets files were sucessfully created in %s' %
                  os.path.abspath(args.output_dir))

register_command(GenVSProps)

Add command to create VS property sheets for all pkgconfig pacakges

Response:
<REPLACE_OLD>  <REPLACE_NEW> # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import os

from cerbero.commands import Command, register_command
from cerbero.ide.common import PkgConfig
from cerbero.ide.vs.pkgconfig2vsprops import PkgConfig2VSProps, CommonVSProps
from cerbero.utils import _, N_, ArgparseArgument
from cerbero.utils import messages as m

DEFAULT_PREFIX_MACRO = 'CERBERO_SDK_ROOT'

class GenVSProps(Command):
    doc = N_('Generate Visual Studio property sheets to use the SDK from VS')
    name = 'genvsprops'

    def __init__(self):
        Command.__init__(self,
            [ArgparseArgument('-o', '--output_dir', default='.',
                help=_('output directory where .vsprops files will be saved')),
            ])

    def run(self, config, args):
        if not os.path.exists(args.output_dir):
            os.makedirs(args.output_dir)

        for pc in PkgConfig.list_all():
            m.action('Created %s.vsprops' % pc)
            p2v = PkgConfig2VSProps(pc, config.prefix, '$(%s)' %
                    DEFAULT_PREFIX_MACRO, False)
            p2v.create(args.output_dir)
            m.action('Created %s.vsprops' % pc)

        common = CommonVSProps(config.prefix, DEFAULT_PREFIX_MACRO)
        common.create(args.output_dir)
        m.message('Property sheets files were sucessfully created in %s' %
                  os.path.abspath(args.output_dir))

register_command(GenVSProps)
 <REPLACE_END> <|endoftext|> # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import os

from cerbero.commands import Command, register_command
from cerbero.ide.common import PkgConfig
from cerbero.ide.vs.pkgconfig2vsprops import PkgConfig2VSProps, CommonVSProps
from cerbero.utils import _, N_, ArgparseArgument
from cerbero.utils import messages as m

DEFAULT_PREFIX_MACRO = 'CERBERO_SDK_ROOT'

class GenVSProps(Command):
    doc = N_('Generate Visual Studio property sheets to use the SDK from VS')
    name = 'genvsprops'

    def __init__(self):
        Command.__init__(self,
            [ArgparseArgument('-o', '--output_dir', default='.',
                help=_('output directory where .vsprops files will be saved')),
            ])

    def run(self, config, args):
        if not os.path.exists(args.output_dir):
            os.makedirs(args.output_dir)

        for pc in PkgConfig.list_all():
            m.action('Created %s.vsprops' % pc)
            p2v = PkgConfig2VSProps(pc, config.prefix, '$(%s)' %
                    DEFAULT_PREFIX_MACRO, False)
            p2v.create(args.output_dir)
            m.action('Created %s.vsprops' % pc)

        common = CommonVSProps(config.prefix, DEFAULT_PREFIX_MACRO)
        common.create(args.output_dir)
        m.message('Property sheets files were sucessfully created in %s' %
                  os.path.abspath(args.output_dir))

register_command(GenVSProps)

Prompt: Add command to create VS property sheets for all pkgconfig pacakges


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

from chess.chess import Chess
import unittest

class TestBuildChess(unittest.TestCase):
    """
    `TestBuildChess()` class is unit-testing the class
    Chess().
    """

    # ///////////////////////////////////////////////////
    def setUp(self):
        params = [4, 4]
        pieces = {'King': 2, 'Queen': 1, 'Bishop': 1, 'Rook': 1, 'Knight': 1}
        params.append(pieces)
        self.chess = Chess(params)

    # ///////////////////////////////////////////////////
    def test_build_chess(self):
        """Tests validity of build chessboard"""
        self.assertEqual(self.chess.pieces_types == ['K', 'K', 'Q'], True)
        self.assertEqual(self.chess.number_pieces == 6, True)

    def test_solution_only_kings(self):
        params = [5, 5]
        pieces = {'King': 2, 'Queen': 0, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)
        self.chess.run_game()
        self.assertEqual(self.chess.solutions == 228, True)

    def test_solution_only_queens(self):
        params = [5, 5]
        pieces = {'King': 0, 'Queen': 2, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)
        self.chess.run_game()
        self.assertEqual(self.chess.solutions == 140, True)

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

Response:
<REPLACE_OLD> app.chess.chess <REPLACE_NEW> chess.chess <REPLACE_END> <REPLACE_OLD> unittest

class <REPLACE_NEW> unittest

class <REPLACE_END> <REPLACE_OLD> 0, <REPLACE_NEW> 1, <REPLACE_END> <REPLACE_OLD> 0, <REPLACE_NEW> 1, <REPLACE_END> <REPLACE_OLD> 0}
 <REPLACE_NEW> 1}
 <REPLACE_END> <REPLACE_OLD> test_solve(self):
 <REPLACE_NEW> test_build_chess(self):
 <REPLACE_END> <REPLACE_OLD> solution"""
 <REPLACE_NEW> build chessboard"""
 <REPLACE_END> <REPLACE_OLD> 3, True)
#       self.assertEqual(self.chess.solutions == 1, <REPLACE_NEW> 6, <REPLACE_END> <DELETE>  <DELETE_END> <REPLACE_OLD>

if <REPLACE_NEW>
    def test_solution_only_queens(self):
        params = [5, 5]
        pieces = {'King': 0, 'Queen': 2, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)
        self.chess.run_game()
        self.assertEqual(self.chess.solutions == 140, True)

if <REPLACE_END> <DELETE>
 <DELETE_END> <|endoftext|> # -*- coding: utf-8 -*-

from chess.chess import Chess
import unittest

class TestBuildChess(unittest.TestCase):
    """
    `TestBuildChess()` class is unit-testing the class
    Chess().
    """

    # ///////////////////////////////////////////////////
    def setUp(self):
        params = [4, 4]
        pieces = {'King': 2, 'Queen': 1, 'Bishop': 1, 'Rook': 1, 'Knight': 1}
        params.append(pieces)
        self.chess = Chess(params)

    # ///////////////////////////////////////////////////
    def test_build_chess(self):
        """Tests validity of build chessboard"""
        self.assertEqual(self.chess.pieces_types == ['K', 'K', 'Q'], True)
        self.assertEqual(self.chess.number_pieces == 6, True)

    def test_solution_only_kings(self):
        params = [5, 5]
        pieces = {'King': 2, 'Queen': 0, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)
        self.chess.run_game()
        self.assertEqual(self.chess.solutions == 228, True)

    def test_solution_only_queens(self):
        params = [5, 5]
        pieces = {'King': 0, 'Queen': 2, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)
        self.chess.run_game()
        self.assertEqual(self.chess.solutions == 140, True)

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

Prompt:
Add a TDD function ( queens on chess board)
# -*- coding: utf-8 -*-

from app.chess.chess import Chess
import unittest

class TestBuildChess(unittest.TestCase):
    """
    `TestBuildChess()` class is unit-testing the class
    Chess().
    """

    # ///////////////////////////////////////////////////
    def setUp(self):
        params = [4, 4]
        pieces = {'King': 2, 'Queen': 1, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)

    # ///////////////////////////////////////////////////
    def test_solve(self):
        """Tests validity of solution"""
        self.assertEqual(self.chess.pieces_types == ['K', 'K', 'Q'], True)
        self.assertEqual(self.chess.number_pieces == 3, True)
#       self.assertEqual(self.chess.solutions == 1, True)

    def test_solution_only_kings(self):
        params = [5, 5]
        pieces = {'King': 2, 'Queen': 0, 'Bishop': 0, 'Rook': 0, 'Knight': 0}
        params.append(pieces)
        self.chess = Chess(params)
        self.chess.run_game()
        self.assertEqual(self.chess.solutions == 228, True)

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


Add missing newline between imports

Add missing newline between imports

Response:
<REPLACE_OLD> _
from <REPLACE_NEW> _

from <REPLACE_END> <|endoftext|> from django import forms
from django.utils.translation import ugettext_lazy as _

from ...setting.models import Setting

class SettingForm(forms.ModelForm):
    class Meta:
        model = Setting
        exclude = []

    def clean_name(self):
        name = self.cleaned_data['name']
        if len(name.split()) > 1:
            raise forms.ValidationError(_("Name cannot contains whitespaces"))
        return name

Prompt:
Add missing newline between imports

from django import forms
from django.utils.translation import ugettext_lazy as _
from ...setting.models import Setting

class SettingForm(forms.ModelForm):
    class Meta:
        model = Setting
        exclude = []

    def clean_name(self):
        name = self.cleaned_data['name']
        if len(name.split()) > 1:
            raise forms.ValidationError(_("Name cannot contains whitespaces"))
        return name


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

import codecs
import pytest

from poyo import parse_string

@pytest.fixture
def string_data():
    with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
        return ymlfile.read()

def test_parse_string(string_data):
    expected = {
        u'default_context': {
            u'greeting': u'こんにちは',
            u'email': u'raphael@hackebrot.de',
            u'docs': True,
            u'gui': False,
            123: 456.789,
            u'someint': 1000000,
            u'foo': u'hallo #welt',
            u'trueish': u'Falseeeeeee',
            u'doc_tools': [u'mkdocs', u'sphinx', None],
        },
        u'zZz': True,
        u'NullValue': None,
        u'Hello World': {
            None: u'This is madness',
            u'gh': u'https://github.com/{0}.git',
        },
        u'Yay #python': u'Cool!'
    }

    assert parse_string(string_data) == expected

Add list to expectation in test

Add list to expectation in test

Response:
<INSERT>     u'doc_tools': [u'mkdocs', u'sphinx', None],
        <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

import codecs
import pytest

from poyo import parse_string

@pytest.fixture
def string_data():
    with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
        return ymlfile.read()

def test_parse_string(string_data):
    expected = {
        u'default_context': {
            u'greeting': u'こんにちは',
            u'email': u'raphael@hackebrot.de',
            u'docs': True,
            u'gui': False,
            123: 456.789,
            u'someint': 1000000,
            u'foo': u'hallo #welt',
            u'trueish': u'Falseeeeeee',
            u'doc_tools': [u'mkdocs', u'sphinx', None],
        },
        u'zZz': True,
        u'NullValue': None,
        u'Hello World': {
            None: u'This is madness',
            u'gh': u'https://github.com/{0}.git',
        },
        u'Yay #python': u'Cool!'
    }

    assert parse_string(string_data) == expected

Prompt:
Add list to expectation in test

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

import codecs
import pytest

from poyo import parse_string

@pytest.fixture
def string_data():
    with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile:
        return ymlfile.read()

def test_parse_string(string_data):
    expected = {
        u'default_context': {
            u'greeting': u'こんにちは',
            u'email': u'raphael@hackebrot.de',
            u'docs': True,
            u'gui': False,
            123: 456.789,
            u'someint': 1000000,
            u'foo': u'hallo #welt',
            u'trueish': u'Falseeeeeee',
        },
        u'zZz': True,
        u'NullValue': None,
        u'Hello World': {
            None: u'This is madness',
            u'gh': u'https://github.com/{0}.git',
        },
        u'Yay #python': u'Cool!'
    }

    assert parse_string(string_data) == expected


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

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin

from .routers import router

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^api/v1/', include(router.urls)),
    url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^admin/', include(admin.site.urls)),
)

def mediafiles_urlpatterns():
    """
    Method for serve media files with runserver.
    """

    _media_url = settings.MEDIA_URL
    if _media_url.startswith('/'):
        _media_url = _media_url[1:]

    from django.views.static import serve
    return patterns('',
        (r'^%s(?P<path>.*)$' % 'media', serve,
            {'document_root': settings.MEDIA_ROOT})
    )

urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()

Set prefix to static url patterm call

Set prefix to static url patterm call

Response:
<REPLACE_OLD> staticfiles_urlpatterns()
urlpatterns <REPLACE_NEW> staticfiles_urlpatterns(prefix="/static/")
urlpatterns <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin

from .routers import router

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^api/v1/', include(router.urls)),
    url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^admin/', include(admin.site.urls)),
)

def mediafiles_urlpatterns():
    """
    Method for serve media files with runserver.
    """

    _media_url = settings.MEDIA_URL
    if _media_url.startswith('/'):
        _media_url = _media_url[1:]

    from django.views.static import serve
    return patterns('',
        (r'^%s(?P<path>.*)$' % 'media', serve,
            {'document_root': settings.MEDIA_ROOT})
    )

urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()

Prompt:
Set prefix to static url patterm call

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

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin

from .routers import router

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^api/v1/', include(router.urls)),
    url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^admin/', include(admin.site.urls)),
)

def mediafiles_urlpatterns():
    """
    Method for serve media files with runserver.
    """

    _media_url = settings.MEDIA_URL
    if _media_url.startswith('/'):
        _media_url = _media_url[1:]

    from django.views.static import serve
    return patterns('',
        (r'^%s(?P<path>.*)$' % 'media', serve,
            {'document_root': settings.MEDIA_ROOT})
    )

urlpatterns += staticfiles_urlpatterns()
urlpatterns += mediafiles_urlpatterns()


# coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -------------------------------------------------------------------------------

import tempfile
import os.path      as op
import logging

from   .config import get_temp_dir

log = logging.getLogger(__name__)

def get_extension(filepath, check_if_exists=False):
    """Return the extension of fpath.

    Parameters
    ----------
    fpath: string
    File name or path

    check_if_exists: bool

    Returns
    -------
    str
    The extension of the file name or path
    """
    if check_if_exists:
        if not op.exists(filepath):
            err = 'File not found: ' + filepath
            log.error(err)
            raise IOError(err)

    try:
        rest, ext = op.splitext(filepath)
    except:
        raise
    else:
        return ext

def add_extension_if_needed(filepath, ext, check_if_exists=False):
    """Add the extension ext to fpath if it doesn't have it.

    Parameters
    ----------
    filepath: str
    File name or path

    ext: str
    File extension

    check_if_exists: bool

    Returns
    -------
    File name or path with extension added, if needed.
    """
    if not filepath.endswith(ext):
        filepath += ext

    if check_if_exists:
        if not op.exists(filepath):
            err = 'File not found: ' + filepath
            log.error(err)
            raise IOError(err)

    return filepath

def remove_ext(filepath):
    """Removes the extension of the file.

    Parameters
    ----------
    filepath: str
        File path or name

    Returns
    -------
    str
        File path or name without extension
    """
    return filepath[:filepath.rindex(get_extension(filepath))]

def get_tempfile(suffix='.txt'):
    """
    Parameters
    ----------

    Returns
    -------
    """
    return tempfile.NamedTemporaryFile(suffix=suffix, dir=get_temp_dir())

Add helpers to manage file names

Add helpers to manage file names

Response:
<REPLACE_OLD>  <REPLACE_NEW> # coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -------------------------------------------------------------------------------

import tempfile
import os.path      as op
import logging

from   .config import get_temp_dir

log = logging.getLogger(__name__)

def get_extension(filepath, check_if_exists=False):
    """Return the extension of fpath.

    Parameters
    ----------
    fpath: string
    File name or path

    check_if_exists: bool

    Returns
    -------
    str
    The extension of the file name or path
    """
    if check_if_exists:
        if not op.exists(filepath):
            err = 'File not found: ' + filepath
            log.error(err)
            raise IOError(err)

    try:
        rest, ext = op.splitext(filepath)
    except:
        raise
    else:
        return ext

def add_extension_if_needed(filepath, ext, check_if_exists=False):
    """Add the extension ext to fpath if it doesn't have it.

    Parameters
    ----------
    filepath: str
    File name or path

    ext: str
    File extension

    check_if_exists: bool

    Returns
    -------
    File name or path with extension added, if needed.
    """
    if not filepath.endswith(ext):
        filepath += ext

    if check_if_exists:
        if not op.exists(filepath):
            err = 'File not found: ' + filepath
            log.error(err)
            raise IOError(err)

    return filepath

def remove_ext(filepath):
    """Removes the extension of the file.

    Parameters
    ----------
    filepath: str
        File path or name

    Returns
    -------
    str
        File path or name without extension
    """
    return filepath[:filepath.rindex(get_extension(filepath))]

def get_tempfile(suffix='.txt'):
    """
    Parameters
    ----------

    Returns
    -------
    """
    return tempfile.NamedTemporaryFile(suffix=suffix, dir=get_temp_dir())
 <REPLACE_END> <|endoftext|> # coding=utf-8
# -------------------------------------------------------------------------------
# Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
# Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
# Universidad del Pais Vasco UPV/EHU
#
# 2015, Alexandre Manhaes Savio
# Use this at your own risk!
# -------------------------------------------------------------------------------

import tempfile
import os.path      as op
import logging

from   .config import get_temp_dir

log = logging.getLogger(__name__)

def get_extension(filepath, check_if_exists=False):
    """Return the extension of fpath.

    Parameters
    ----------
    fpath: string
    File name or path

    check_if_exists: bool

    Returns
    -------
    str
    The extension of the file name or path
    """
    if check_if_exists:
        if not op.exists(filepath):
            err = 'File not found: ' + filepath
            log.error(err)
            raise IOError(err)

    try:
        rest, ext = op.splitext(filepath)
    except:
        raise
    else:
        return ext

def add_extension_if_needed(filepath, ext, check_if_exists=False):
    """Add the extension ext to fpath if it doesn't have it.

    Parameters
    ----------
    filepath: str
    File name or path

    ext: str
    File extension

    check_if_exists: bool

    Returns
    -------
    File name or path with extension added, if needed.
    """
    if not filepath.endswith(ext):
        filepath += ext

    if check_if_exists:
        if not op.exists(filepath):
            err = 'File not found: ' + filepath
            log.error(err)
            raise IOError(err)

    return filepath

def remove_ext(filepath):
    """Removes the extension of the file.

    Parameters
    ----------
    filepath: str
        File path or name

    Returns
    -------
    str
        File path or name without extension
    """
    return filepath[:filepath.rindex(get_extension(filepath))]

def get_tempfile(suffix='.txt'):
    """
    Parameters
    ----------

    Returns
    -------
    """
    return tempfile.NamedTemporaryFile(suffix=suffix, dir=get_temp_dir())

Prompt: Add helpers to manage file names


from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir

# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this as an example, make sure to either
#       1) create a local `user_opts.py`, or
#       2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value
#          (i.e., user_opts['swan']['username'] -> 'your_username')
from .user_opts import user_opts

config = Config(
    executors=[
        ThreadPoolExecutor(
            label='local_threads_globus',
            storage_access=[GlobusScheme(
                endpoint_uuid=user_opts['globus']['endpoint'],
                endpoint_path=user_opts['globus']['path']
            )[,
            working_dir=user_opts['globus']['path']
        )
    ],
    run_dir=get_rundir()
)

Fix storage_access in the test config

Fix storage_access in the test config

Response:
<REPLACE_OLD> storage_access=GlobusScheme(
 <REPLACE_NEW> storage_access=[GlobusScheme(
 <REPLACE_END> <REPLACE_OLD> ),
 <REPLACE_NEW> )[,
 <REPLACE_END> <|endoftext|> from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir

# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this as an example, make sure to either
#       1) create a local `user_opts.py`, or
#       2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value
#          (i.e., user_opts['swan']['username'] -> 'your_username')
from .user_opts import user_opts

config = Config(
    executors=[
        ThreadPoolExecutor(
            label='local_threads_globus',
            storage_access=[GlobusScheme(
                endpoint_uuid=user_opts['globus']['endpoint'],
                endpoint_path=user_opts['globus']['path']
            )[,
            working_dir=user_opts['globus']['path']
        )
    ],
    run_dir=get_rundir()
)

Prompt:
Fix storage_access in the test config

from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir

# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this as an example, make sure to either
#       1) create a local `user_opts.py`, or
#       2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value
#          (i.e., user_opts['swan']['username'] -> 'your_username')
from .user_opts import user_opts

config = Config(
    executors=[
        ThreadPoolExecutor(
            label='local_threads_globus',
            storage_access=GlobusScheme(
                endpoint_uuid=user_opts['globus']['endpoint'],
                endpoint_path=user_opts['globus']['path']
            ),
            working_dir=user_opts['globus']['path']
        )
    ],
    run_dir=get_rundir()
)


"""
Test that debug symbols have the correct order as specified by the order file.
"""

import os, time
import re
import unittest
import lldb
import lldbtest

class TestClassTypes(lldbtest.TestBase):

    mydir = "order"

    def test_order(self):
        """Test debug symbols follow the correct order by the order file."""
        res = self.res
        exe = os.path.join(os.getcwd(), "a.out")
        self.ci.HandleCommand("file " + exe, res)
        self.assertTrue(res.Succeeded())

        # Test that the debug symbols have Function f3 before Function f1.
        self.ci.HandleCommand("image dump symtab a.out", res)
        self.assertTrue(res.Succeeded())
        output = res.GetOutput()
        mo_f3 = re.search("Function +.+f3", output)
        mo_f1 = re.search("Function +.+f1", output)

        # Match objects for f3 and f1 must exist and f3 must come before f1.
        self.assertTrue(mo_f3 and mo_f1 and mo_f3.start() < mo_f1.start())

        self.ci.HandleCommand("run", res)
        self.assertTrue(res.Succeeded())

if __name__ == '__main__':
    lldb.SBDebugger.Initialize()
    unittest.main()
    lldb.SBDebugger.Terminate()

Test that debug symbols have the correct order as specified by the order file.

git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@107844 91177308-0d34-0410-b5e6-96231b3b80d8

Response:
<REPLACE_OLD>  <REPLACE_NEW> """
Test that debug symbols have the correct order as specified by the order file.
"""

import os, time
import re
import unittest
import lldb
import lldbtest

class TestClassTypes(lldbtest.TestBase):

    mydir = "order"

    def test_order(self):
        """Test debug symbols follow the correct order by the order file."""
        res = self.res
        exe = os.path.join(os.getcwd(), "a.out")
        self.ci.HandleCommand("file " + exe, res)
        self.assertTrue(res.Succeeded())

        # Test that the debug symbols have Function f3 before Function f1.
        self.ci.HandleCommand("image dump symtab a.out", res)
        self.assertTrue(res.Succeeded())
        output = res.GetOutput()
        mo_f3 = re.search("Function +.+f3", output)
        mo_f1 = re.search("Function +.+f1", output)

        # Match objects for f3 and f1 must exist and f3 must come before f1.
        self.assertTrue(mo_f3 and mo_f1 and mo_f3.start() < mo_f1.start())

        self.ci.HandleCommand("run", res)
        self.assertTrue(res.Succeeded())

if __name__ == '__main__':
    lldb.SBDebugger.Initialize()
    unittest.main()
    lldb.SBDebugger.Terminate()
 <REPLACE_END> <|endoftext|> """
Test that debug symbols have the correct order as specified by the order file.
"""

import os, time
import re
import unittest
import lldb
import lldbtest

class TestClassTypes(lldbtest.TestBase):

    mydir = "order"

    def test_order(self):
        """Test debug symbols follow the correct order by the order file."""
        res = self.res
        exe = os.path.join(os.getcwd(), "a.out")
        self.ci.HandleCommand("file " + exe, res)
        self.assertTrue(res.Succeeded())

        # Test that the debug symbols have Function f3 before Function f1.
        self.ci.HandleCommand("image dump symtab a.out", res)
        self.assertTrue(res.Succeeded())
        output = res.GetOutput()
        mo_f3 = re.search("Function +.+f3", output)
        mo_f1 = re.search("Function +.+f1", output)

        # Match objects for f3 and f1 must exist and f3 must come before f1.
        self.assertTrue(mo_f3 and mo_f1 and mo_f3.start() < mo_f1.start())

        self.ci.HandleCommand("run", res)
        self.assertTrue(res.Succeeded())

if __name__ == '__main__':
    lldb.SBDebugger.Initialize()
    unittest.main()
    lldb.SBDebugger.Terminate()

Prompt:
Test that debug symbols have the correct order as specified by the order file.

git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@107844 91177308-0d34-0410-b5e6-96231b3b80d8