#!/usr/bin/env python
#   -*- encoding: UTF-8 -*-

# This file is part of Addison Arches.
#
# Addison Arches 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.
#
# Addison Arches 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 Addison Arches.  If not, see <http://www.gnu.org/licenses/>.

from turberfield.dialogue.types import Player

async def default(folder, ensemble:list, log=None, loop=None):
    if log is not None:
        log.debug("No activity during interlude")
    return folder

async def stop(folder, ensemble:list, log=None, loop=None):
    if log is not None:
        log.debug("Interlude stops dialogue")
    for entity in ensemble[:]:
        if not isinstance(entity, Player):
            ensemble.remove(entity)
    return None

Response:
<REPLACE_OLD> <http://www.gnu.org/licenses/>.

async <REPLACE_NEW> <http://www.gnu.org/licenses/>.

from turberfield.dialogue.types import Player

async <REPLACE_END> <REPLACE_OLD> ensemble, <REPLACE_NEW> ensemble:list, <REPLACE_END> <REPLACE_OLD> ensemble, <REPLACE_NEW> ensemble:list, <REPLACE_END> <INSERT> for entity in ensemble[:]:
        if not isinstance(entity, Player):
            ensemble.remove(entity)
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
#   -*- encoding: UTF-8 -*-

# This file is part of Addison Arches.
#
# Addison Arches 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.
#
# Addison Arches 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 Addison Arches.  If not, see <http://www.gnu.org/licenses/>.

from turberfield.dialogue.types import Player

async def default(folder, ensemble:list, log=None, loop=None):
    if log is not None:
        log.debug("No activity during interlude")
    return folder

async def stop(folder, ensemble:list, log=None, loop=None):
    if log is not None:
        log.debug("Interlude stops dialogue")
    for entity in ensemble[:]:
        if not isinstance(entity, Player):
            ensemble.remove(entity)
    return None

Prompt:
Stop interlude removes non-player characters.

#!/usr/bin/env python
#   -*- encoding: UTF-8 -*-

# This file is part of Addison Arches.
#
# Addison Arches 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.
#
# Addison Arches 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 Addison Arches.  If not, see <http://www.gnu.org/licenses/>.

async def default(folder, ensemble, log=None, loop=None):
    if log is not None:
        log.debug("No activity during interlude")
    return folder

async def stop(folder, ensemble, log=None, loop=None):
    if log is not None:
        log.debug("Interlude stops dialogue")
    return None


from . import uuid

def task_crud(self, shotgun, trigger_poll=lambda: None):

    shot_name = uuid(8)
    shot = shotgun.create('Shot', {'code': shot_name})

    name = uuid(8)
    task = shotgun.create('Task', {'content': name, 'entity': shot})
    trigger_poll()

    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'])
    self.assertSameEntity(task, x)

    # entity field
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['entity'])
    self.assertSameEntity(shot, x['entity'])

    # return through entity field
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['entity.Shot.code'])
    self.assertEqual(shot_name, x['entity.Shot.code'])

    # Updates
    name += '-2'
    shotgun.update('Task', task['id'], {'content': name})
    trigger_poll()
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'])
    self.assertEqual(x['content'], name)

    # Delete
    shotgun.delete('Task', task['id'])
    trigger_poll()
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'])
    self.assertIs(x, None)
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'], retired_only=True)
    self.assertSameEntity(task, x)

Add entity link to basic crud tests

Add entity link to basic crud tests

Response:
<INSERT> shot_name = uuid(8)
    shot = shotgun.create('Shot', {'code': shot_name})

    <INSERT_END> <REPLACE_OLD> a <REPLACE_NEW> task <REPLACE_END> <REPLACE_OLD> name})
 <REPLACE_NEW> name, 'entity': shot})
 <REPLACE_END> <REPLACE_OLD> trigger_poll()
 <REPLACE_NEW> trigger_poll()

 <REPLACE_END> <REPLACE_OLD> b <REPLACE_NEW> x <REPLACE_END> <REPLACE_OLD> a['id'])], <REPLACE_NEW> task['id'])], <REPLACE_END> <REPLACE_OLD> self.assertSameEntity(a, b)

 <REPLACE_NEW> self.assertSameEntity(task, x)

    # entity field
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['entity'])
    self.assertSameEntity(shot, x['entity'])

    # return through entity field
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['entity.Shot.code'])
    self.assertEqual(shot_name, x['entity.Shot.code'])

    # Updates
 <REPLACE_END> <REPLACE_OLD> a['id'], <REPLACE_NEW> task['id'], <REPLACE_END> <REPLACE_OLD> c <REPLACE_NEW> x <REPLACE_END> <REPLACE_OLD> a['id'])], <REPLACE_NEW> task['id'])], <REPLACE_END> <REPLACE_OLD> self.assertEqual(c['content'], <REPLACE_NEW> self.assertEqual(x['content'], <REPLACE_END> <INSERT> # Delete
    <INSERT_END> <REPLACE_OLD> a['id'])
 <REPLACE_NEW> task['id'])
 <REPLACE_END> <REPLACE_OLD> d <REPLACE_NEW> x <REPLACE_END> <REPLACE_OLD> a['id'])], <REPLACE_NEW> task['id'])], <REPLACE_END> <REPLACE_OLD> self.assertIs(d, <REPLACE_NEW> self.assertIs(x, <REPLACE_END> <INSERT>    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'], retired_only=True)
    self.assertSameEntity(task, x)
 <INSERT_END> <|endoftext|> from . import uuid

def task_crud(self, shotgun, trigger_poll=lambda: None):

    shot_name = uuid(8)
    shot = shotgun.create('Shot', {'code': shot_name})

    name = uuid(8)
    task = shotgun.create('Task', {'content': name, 'entity': shot})
    trigger_poll()

    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'])
    self.assertSameEntity(task, x)

    # entity field
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['entity'])
    self.assertSameEntity(shot, x['entity'])

    # return through entity field
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['entity.Shot.code'])
    self.assertEqual(shot_name, x['entity.Shot.code'])

    # Updates
    name += '-2'
    shotgun.update('Task', task['id'], {'content': name})
    trigger_poll()
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'])
    self.assertEqual(x['content'], name)

    # Delete
    shotgun.delete('Task', task['id'])
    trigger_poll()
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'])
    self.assertIs(x, None)
    x = self.cached.find_one('Task', [('id', 'is', task['id'])], ['content'], retired_only=True)
    self.assertSameEntity(task, x)

Prompt:
Add entity link to basic crud tests

from . import uuid

def task_crud(self, shotgun, trigger_poll=lambda: None):

    name = uuid(8)
    a = shotgun.create('Task', {'content': name})
    trigger_poll()
    b = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content'])
    self.assertSameEntity(a, b)

    name += '-2'
    shotgun.update('Task', a['id'], {'content': name})
    trigger_poll()
    c = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content'])
    self.assertEqual(c['content'], name)

    shotgun.delete('Task', a['id'])
    trigger_poll()
    d = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content'])
    self.assertIs(d, None)


DEFAULT_URL = 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip'  # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'

Fix URL to current MD dataset on S3

Fix URL to current MD dataset on S3

Response:
<REPLACE_OLD> "https://s3-us-west-2.amazonaws.com/openpolicingdata/Maryland-Traffic-Stop-Data-2013.zip" <REPLACE_NEW> 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip' <REPLACE_END> <|endoftext|> DEFAULT_URL = 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip'  # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'

Prompt:
Fix URL to current MD dataset on S3

DEFAULT_URL = "https://s3-us-west-2.amazonaws.com/openpolicingdata/Maryland-Traffic-Stop-Data-2013.zip"  # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'


import marshmallow

class StorySchema(marshmallow.Schema):
    id = marshmallow.fields.Int(dump_only=True)
    title = marshmallow.fields.Str(required=True)
    created = marshmallow.fields.DateTime(dump_only=True)
    event_time = marshmallow.fields.DateTime(allow_none=True)
    location = marshmallow.fields.Str(allow_none=True)
    section = marshmallow.fields.Str(allow_none=True)

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'stories' if many else 'story'
        return {key: data}

class PersonSchema(marshmallow.Schema):
    id = marshmallow.fields.Int(dump_only=True)
    name = marshmallow.fields.Str(required=True)

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'people' if many else 'person'
        return {key: data}

class AddStoryPersonSchema(marshmallow.Schema):
    id = marshmallow.fields.Int()

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'story_people' if many else 'story_person'
        return {key: data}

Response:
<REPLACE_OLD> marshmallow.fields.Str()
 <REPLACE_NEW> marshmallow.fields.Str(allow_none=True)
 <REPLACE_END> <REPLACE_OLD> marshmallow.fields.Str()

 <REPLACE_NEW> marshmallow.fields.Str(allow_none=True)

 <REPLACE_END> <|endoftext|> import marshmallow

class StorySchema(marshmallow.Schema):
    id = marshmallow.fields.Int(dump_only=True)
    title = marshmallow.fields.Str(required=True)
    created = marshmallow.fields.DateTime(dump_only=True)
    event_time = marshmallow.fields.DateTime(allow_none=True)
    location = marshmallow.fields.Str(allow_none=True)
    section = marshmallow.fields.Str(allow_none=True)

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'stories' if many else 'story'
        return {key: data}

class PersonSchema(marshmallow.Schema):
    id = marshmallow.fields.Int(dump_only=True)
    name = marshmallow.fields.Str(required=True)

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'people' if many else 'person'
        return {key: data}

class AddStoryPersonSchema(marshmallow.Schema):
    id = marshmallow.fields.Int()

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'story_people' if many else 'story_person'
        return {key: data}

Prompt:
Allow story location and section to be null

import marshmallow

class StorySchema(marshmallow.Schema):
    id = marshmallow.fields.Int(dump_only=True)
    title = marshmallow.fields.Str(required=True)
    created = marshmallow.fields.DateTime(dump_only=True)
    event_time = marshmallow.fields.DateTime(allow_none=True)
    location = marshmallow.fields.Str()
    section = marshmallow.fields.Str()

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'stories' if many else 'story'
        return {key: data}

class PersonSchema(marshmallow.Schema):
    id = marshmallow.fields.Int(dump_only=True)
    name = marshmallow.fields.Str(required=True)

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'people' if many else 'person'
        return {key: data}

class AddStoryPersonSchema(marshmallow.Schema):
    id = marshmallow.fields.Int()

    @marshmallow.post_dump(pass_many=True)
    def wrap(self, data, many):
        key = 'story_people' if many else 'story_person'
        return {key: data}


# -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': 'Campos Checkin',
    'description': """
        CampOS Check In functionality""",
    'version': '8.0.1.0.0',
    'license': 'AGPL-3',
    'author': 'Stein & Gabelgaard ApS',
    'website': 'www.steingabelgaard.dk',
    'depends': [
        'campos_jobber_final',
        'campos_transportation',
        'campos_crewnet',
        'web_ir_actions_act_window_message',
        #'web_tree_dynamic_colored_field',
    ],
    'data': [
        'wizards/campos_checkin_wiz.xml',
        'security/campos_checkin.xml',
        'views/campos_event_participant.xml',
        'views/campos_mat_report.xml',
        'wizards/campos_checkin_grp_wiz.xml',
        'views/event_registration.xml',
    ],
    'demo': [
    ],
}

Fix order for menu ref

Fix order for menu ref

Response:
<DELETE> 'wizards/campos_checkin_grp_wiz.xml',
        'views/event_registration.xml',
        <DELETE_END> <INSERT>     'wizards/campos_checkin_grp_wiz.xml',
        'views/event_registration.xml',
    <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': 'Campos Checkin',
    'description': """
        CampOS Check In functionality""",
    'version': '8.0.1.0.0',
    'license': 'AGPL-3',
    'author': 'Stein & Gabelgaard ApS',
    'website': 'www.steingabelgaard.dk',
    'depends': [
        'campos_jobber_final',
        'campos_transportation',
        'campos_crewnet',
        'web_ir_actions_act_window_message',
        #'web_tree_dynamic_colored_field',
    ],
    'data': [
        'wizards/campos_checkin_wiz.xml',
        'security/campos_checkin.xml',
        'views/campos_event_participant.xml',
        'views/campos_mat_report.xml',
        'wizards/campos_checkin_grp_wiz.xml',
        'views/event_registration.xml',
    ],
    'demo': [
    ],
}

Prompt:
Fix order for menu ref
# -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

{
    'name': 'Campos Checkin',
    'description': """
        CampOS Check In functionality""",
    'version': '8.0.1.0.0',
    'license': 'AGPL-3',
    'author': 'Stein & Gabelgaard ApS',
    'website': 'www.steingabelgaard.dk',
    'depends': [
        'campos_jobber_final',
        'campos_transportation',
        'campos_crewnet',
        'web_ir_actions_act_window_message',
        #'web_tree_dynamic_colored_field',
    ],
    'data': [
        'wizards/campos_checkin_grp_wiz.xml',
        'views/event_registration.xml',
        'wizards/campos_checkin_wiz.xml',
        'security/campos_checkin.xml',
        'views/campos_event_participant.xml',
        'views/campos_mat_report.xml',
    ],
    'demo': [
    ],
}


from .base import Base

class List(Base):
    current = None

    def __init__(self, result, object_type):
        Base.__init__(self, result)
        self.object_type = object_type

    def get_object_name(self):
        return self.object_type.__name__.lower() + 's'

    def __iter__(self):
        """Implement iterator logic."""
        self.current = None
        return self

    def __next__(self):
        """Implement iterator logic."""
        if self.current is None:
            self.current = 0
        else:
            self.current += 1
        try:
            item = self['_embedded'][self.get_object_name()][self.current]
            return self.object_type(item)
        except IndexError:
            raise StopIteration

    next = __next__  # support python2 iterator interface

    @property
    def count(self):
        if 'count' not in self:
            return None
        return int(self['count'])

    def get_offset(self):
        if 'offset' not in self:
            return None
        return self['offset']

Response:
<INSERT> next = __next__  # support python2 iterator interface

    <INSERT_END> <|endoftext|> from .base import Base

class List(Base):
    current = None

    def __init__(self, result, object_type):
        Base.__init__(self, result)
        self.object_type = object_type

    def get_object_name(self):
        return self.object_type.__name__.lower() + 's'

    def __iter__(self):
        """Implement iterator logic."""
        self.current = None
        return self

    def __next__(self):
        """Implement iterator logic."""
        if self.current is None:
            self.current = 0
        else:
            self.current += 1
        try:
            item = self['_embedded'][self.get_object_name()][self.current]
            return self.object_type(item)
        except IndexError:
            raise StopIteration

    next = __next__  # support python2 iterator interface

    @property
    def count(self):
        if 'count' not in self:
            return None
        return int(self['count'])

    def get_offset(self):
        if 'offset' not in self:
            return None
        return self['offset']

Prompt:
Add proxy method for python2 iterator support

from .base import Base

class List(Base):
    current = None

    def __init__(self, result, object_type):
        Base.__init__(self, result)
        self.object_type = object_type

    def get_object_name(self):
        return self.object_type.__name__.lower() + 's'

    def __iter__(self):
        """Implement iterator logic."""
        self.current = None
        return self

    def __next__(self):
        """Implement iterator logic."""
        if self.current is None:
            self.current = 0
        else:
            self.current += 1
        try:
            item = self['_embedded'][self.get_object_name()][self.current]
            return self.object_type(item)
        except IndexError:
            raise StopIteration

    @property
    def count(self):
        if 'count' not in self:
            return None
        return int(self['count'])

    def get_offset(self):
        if 'offset' not in self:
            return None
        return self['offset']


import sys

def import_attribute(import_path, exception_handler=None):
    try:
        from importlib import import_module
    except ImportError:
        from django.utils.importlib import import_module
    module_name, object_name = import_path.rsplit('.', 1)
    try:
        module = import_module(module_name)
    except:  # pragma: no cover
        if callable(exception_handler):
            exctype, excvalue, tb = sys.exc_info()
            return exception_handler(import_path, exctype, excvalue, tb)
        else:
            raise
    try:
        return getattr(module, object_name)
    except:  # pragma: no cover
        if callable(exception_handler):
            exctype, excvalue, tb = sys.exc_info()
            return exception_handler(import_path, exctype, excvalue, tb)
        else:
            raise

Response:
<INSERT> try:
        from importlib import import_module
    except ImportError:
        <INSERT_END> <|endoftext|> import sys

def import_attribute(import_path, exception_handler=None):
    try:
        from importlib import import_module
    except ImportError:
        from django.utils.importlib import import_module
    module_name, object_name = import_path.rsplit('.', 1)
    try:
        module = import_module(module_name)
    except:  # pragma: no cover
        if callable(exception_handler):
            exctype, excvalue, tb = sys.exc_info()
            return exception_handler(import_path, exctype, excvalue, tb)
        else:
            raise
    try:
        return getattr(module, object_name)
    except:  # pragma: no cover
        if callable(exception_handler):
            exctype, excvalue, tb = sys.exc_info()
            return exception_handler(import_path, exctype, excvalue, tb)
        else:
            raise

Prompt:
Use import_module from standard library if exists

Django 1.8+ drops `django.utils.importlib`. I imagine because that is because an older version of Python (either 2.5 and/or 2.6) is being dropped. I haven't checked older versions but `importlib` exists in Python 2.7.
import sys

def import_attribute(import_path, exception_handler=None):
    from django.utils.importlib import import_module
    module_name, object_name = import_path.rsplit('.', 1)
    try:
        module = import_module(module_name)
    except:  # pragma: no cover
        if callable(exception_handler):
            exctype, excvalue, tb = sys.exc_info()
            return exception_handler(import_path, exctype, excvalue, tb)
        else:
            raise
    try:
        return getattr(module, object_name)
    except:  # pragma: no cover
        if callable(exception_handler):
            exctype, excvalue, tb = sys.exc_info()
            return exception_handler(import_path, exctype, excvalue, tb)
        else:
            raise


# -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>

from dotenv import load_dotenv, get_key, set_key, unset_key

def load_envs(path):
    import os
    path, _ = os.path.split(path)
    if path == '/':
        # bail out when you reach top of the FS
        load_dotenv(os.path.join(path, '.env'))
        return
    # load higher envs first
    # closer-to-base environments need higher precedence.
    load_envs(path)
    load_dotenv(os.path.join(path, '.env'))

Response:
<REPLACE_OLD> <sb@ryansb.com>

import dotenv
 <REPLACE_NEW> <sb@ryansb.com>

from dotenv import load_dotenv, get_key, set_key, unset_key

def load_envs(path):
    import os
    path, _ = os.path.split(path)
    if path == '/':
        # bail out when you reach top of the FS
        load_dotenv(os.path.join(path, '.env'))
        return
    # load higher envs first
    # closer-to-base environments need higher precedence.
    load_envs(path)
    load_dotenv(os.path.join(path, '.env'))
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>

from dotenv import load_dotenv, get_key, set_key, unset_key

def load_envs(path):
    import os
    path, _ = os.path.split(path)
    if path == '/':
        # bail out when you reach top of the FS
        load_dotenv(os.path.join(path, '.env'))
        return
    # load higher envs first
    # closer-to-base environments need higher precedence.
    load_envs(path)
    load_dotenv(os.path.join(path, '.env'))

Prompt:
Add `load_envs` to take a base path and recurse up, looking for .envs

# -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>

import dotenv


import re

class ArtifactAnnotator:

    excluded_types = set(['heading', 'code'])

    def linkify_artifacts(marked_tree, artifacts):
        big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)

        for artifact in artifacts:
            link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
            for token in artifact['tokens']:
                reg = ArtifactAnnotator._token_reg(token)
                repl = r'[\1]%s' % link
                big_string = reg.sub(repl, big_string)

        ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string)
        return marked_tree

    def _token_reg(token):
        reg = r'(\b%s)' % token
        return re.compile(reg, re.IGNORECASE)

    def _marked_tree_to_big_string(marked_tree):
        strings = []
        for item in marked_tree:
            if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types:
                strings.append(item['text'])
        big_string = u'\u1394'.join(strings)
        return big_string

    def _big_string_to_marked_tree(marked_tree, big_string):
        strings = big_string.split(u'\u1394')
        i = 0
        for item in marked_tree:
            if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types
                item['text'] = strings[i]
                i = i + 1

Improve annotating of code segements

Response:
<REPLACE_OLD> ArtifactAnnotator:
 <REPLACE_NEW> ArtifactAnnotator:

    excluded_types = set(['heading', 'code'])

 <REPLACE_END> <REPLACE_OLD> != 'heading' and item[
                    'type'] != 'code':
 <REPLACE_NEW> not in ArtifactAnnotator.excluded_types:
 <REPLACE_END> <REPLACE_OLD> != 'heading' and item[
                    'type'] != 'code':
 <REPLACE_NEW> not in ArtifactAnnotator.excluded_types
 <REPLACE_END> <|endoftext|> import re

class ArtifactAnnotator:

    excluded_types = set(['heading', 'code'])

    def linkify_artifacts(marked_tree, artifacts):
        big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)

        for artifact in artifacts:
            link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
            for token in artifact['tokens']:
                reg = ArtifactAnnotator._token_reg(token)
                repl = r'[\1]%s' % link
                big_string = reg.sub(repl, big_string)

        ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string)
        return marked_tree

    def _token_reg(token):
        reg = r'(\b%s)' % token
        return re.compile(reg, re.IGNORECASE)

    def _marked_tree_to_big_string(marked_tree):
        strings = []
        for item in marked_tree:
            if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types:
                strings.append(item['text'])
        big_string = u'\u1394'.join(strings)
        return big_string

    def _big_string_to_marked_tree(marked_tree, big_string):
        strings = big_string.split(u'\u1394')
        i = 0
        for item in marked_tree:
            if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types
                item['text'] = strings[i]
                i = i + 1

Prompt:
feat: Improve annotating of code segements

import re

class ArtifactAnnotator:
    def linkify_artifacts(marked_tree, artifacts):
        big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)

        for artifact in artifacts:
            link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
            for token in artifact['tokens']:
                reg = ArtifactAnnotator._token_reg(token)
                repl = r'[\1]%s' % link
                big_string = reg.sub(repl, big_string)

        ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string)
        return marked_tree

    def _token_reg(token):
        reg = r'(\b%s)' % token
        return re.compile(reg, re.IGNORECASE)

    def _marked_tree_to_big_string(marked_tree):
        strings = []
        for item in marked_tree:
            if 'text' in item and item['type'] != 'heading' and item[
                    'type'] != 'code':
                strings.append(item['text'])
        big_string = u'\u1394'.join(strings)
        return big_string

    def _big_string_to_marked_tree(marked_tree, big_string):
        strings = big_string.split(u'\u1394')
        i = 0
        for item in marked_tree:
            if 'text' in item and item['type'] != 'heading' and item[
                    'type'] != 'code':
                item['text'] = strings[i]
                i = i + 1


from pathlib import Path

extensions = [
    'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = (
    Path(__file__).parent.parent / 'cairocffi' / 'VERSION').read_text().strip()
version = '.'.join(release.split('.')[:2])
exclude_patterns = ['_build']
autodoc_member_order = 'bysource'
autodoc_default_flags = ['members']
intersphinx_mapping = {
    'http://docs.python.org/': None,
    'http://cairographics.org/documentation/pycairo/2/': None}

Fix the VERSION path for doc

Fix the VERSION path for doc

Response:
<REPLACE_OLD> (Path(__file__).parent <REPLACE_NEW> (
    Path(__file__).parent.parent <REPLACE_END> <|endoftext|> from pathlib import Path

extensions = [
    'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = (
    Path(__file__).parent.parent / 'cairocffi' / 'VERSION').read_text().strip()
version = '.'.join(release.split('.')[:2])
exclude_patterns = ['_build']
autodoc_member_order = 'bysource'
autodoc_default_flags = ['members']
intersphinx_mapping = {
    'http://docs.python.org/': None,
    'http://cairographics.org/documentation/pycairo/2/': None}

Prompt:
Fix the VERSION path for doc

from pathlib import Path

extensions = [
    'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = (Path(__file__).parent / 'cairocffi' / 'VERSION').read_text().strip()
version = '.'.join(release.split('.')[:2])
exclude_patterns = ['_build']
autodoc_member_order = 'bysource'
autodoc_default_flags = ['members']
intersphinx_mapping = {
    'http://docs.python.org/': None,
    'http://cairographics.org/documentation/pycairo/2/': None}


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

"""
Tests for koji_sign module.
"""

import unittest

import os
import sys

# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")

DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))

from releng_sop.common import Environment  # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign  # noqa: E402

RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")

class TestRPMSignClass(unittest.TestCase):
    """
    Tests related to RPMSign classes.
    """

    longMessage = True

    def test_get_rpmsign_class(self):
        """Test if a RPMSign class can be properly loaded based on env settings."""
        env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
        cls = get_rpmsign_class(env)
        self.assertEqual(cls, LocalRPMSign)

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

Response:
<REPLACE_OLD> sys

DIR <REPLACE_NEW> sys

# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")

DIR <REPLACE_END> <|endoftext|> #!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Tests for koji_sign module.
"""

import unittest

import os
import sys

# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")

DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))

from releng_sop.common import Environment  # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign  # noqa: E402

RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")

class TestRPMSignClass(unittest.TestCase):
    """
    Tests related to RPMSign classes.
    """

    longMessage = True

    def test_get_rpmsign_class(self):
        """Test if a RPMSign class can be properly loaded based on env settings."""
        env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
        cls = get_rpmsign_class(env)
        self.assertEqual(cls, LocalRPMSign)

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

Prompt:
Fix failing tests by injecting an empty koji module.

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

"""
Tests for koji_sign module.
"""

import unittest

import os
import sys

DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))

from releng_sop.common import Environment  # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign  # noqa: E402

RELEASES_DIR = os.path.join(DIR, "releases")
ENVIRONMENTS_DIR = os.path.join(DIR, "environments")

class TestRPMSignClass(unittest.TestCase):
    """
    Tests related to RPMSign classes.
    """

    longMessage = True

    def test_get_rpmsign_class(self):
        """Test if a RPMSign class can be properly loaded based on env settings."""
        env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR])
        cls = get_rpmsign_class(env)
        self.assertEqual(cls, LocalRPMSign)

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


import dumper.utils

def invalidate_paths(paths):
    '''
    Invalidate all pages for a certain path.
    '''
    for path in paths:
        for key in all_cache_keys_from_path(path):
            dumper.utils.cache.delete(key)

def all_cache_keys_from_path(path):
    '''
    Each path can actually have multiple cached entries, varying based on different HTTP
    methods. So a GET request will have a different cached response from a HEAD request.

    In order to invalidate a path, we must first know all the different cache keys that the
    path might have been cached at. This returns those keys
    '''
    return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]

Response:
<INSERT> '''
    Each path can actually have multiple cached entries, varying based on different HTTP
    methods. So a GET request will have a different cached response from a HEAD request.

    In order to invalidate a path, we must first know all the different cache keys that the
    path might have been cached at. This returns those keys
    '''
    <INSERT_END> <|endoftext|> import dumper.utils

def invalidate_paths(paths):
    '''
    Invalidate all pages for a certain path.
    '''
    for path in paths:
        for key in all_cache_keys_from_path(path):
            dumper.utils.cache.delete(key)

def all_cache_keys_from_path(path):
    '''
    Each path can actually have multiple cached entries, varying based on different HTTP
    methods. So a GET request will have a different cached response from a HEAD request.

    In order to invalidate a path, we must first know all the different cache keys that the
    path might have been cached at. This returns those keys
    '''
    return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]

Prompt:
Comment concerning differences in keys per path
import dumper.utils

def invalidate_paths(paths):
    '''
    Invalidate all pages for a certain path.
    '''
    for path in paths:
        for key in all_cache_keys_from_path(path):
            dumper.utils.cache.delete(key)

def all_cache_keys_from_path(path):
    return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]


import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', 'img.jpg')

Change save path to local path

Change save path to local path

Response:
<REPLACE_OLD> '/home/pi/img/img.jpg') <REPLACE_NEW> 'img.jpg') <REPLACE_END> <|endoftext|> import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', 'img.jpg')

Prompt:
Change save path to local path

import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', '/home/pi/img/img.jpg')


import unittest

from werkzeug.datastructures import MultiDict

from cla_public.app import create_app
from cla_public.apps.contact.forms import ContactForm

def submit(**kwargs):
    return ContactForm(MultiDict(kwargs), csrf_enabled=False)

class NotesTest(unittest.TestCase):

    def setUp(self):
        app = create_app('config/testing.py')
        app.test_request_context().push()

    def validate_notes(self, notes):
        form = submit(
            extra_notes=notes)
        form.validate()
        return u'Your notes must be 4000 characters or less' not in \
            form.extra_notes.errors

    def test_notes_max_length(self):
        longest_allowed = 'x' * 4000
        self.assertTrue(self.validate_notes(longest_allowed))

        too_long = longest_allowed + 'x'
        self.assertFalse(self.validate_notes(too_long))

Add python test for notes length validation

Response:
<INSERT> import unittest

from werkzeug.datastructures import MultiDict

from cla_public.app import create_app
from cla_public.apps.contact.forms import ContactForm

def submit(**kwargs):
 <INSERT_END> <INSERT>   return ContactForm(MultiDict(kwargs), csrf_enabled=False)

class NotesTest(unittest.TestCase):

    def setUp(self):
        app = create_app('config/testing.py')
        app.test_request_context().push()

    def validate_notes(self, notes):
        form = submit(
            extra_notes=notes)
        form.validate()
        return u'Your notes must be 4000 characters or less' not in \
            form.extra_notes.errors

    def test_notes_max_length(self):
        longest_allowed = 'x' * 4000
        self.assertTrue(self.validate_notes(longest_allowed))

        too_long = longest_allowed + 'x'
        self.assertFalse(self.validate_notes(too_long))
 <INSERT_END> <|endoftext|> import unittest

from werkzeug.datastructures import MultiDict

from cla_public.app import create_app
from cla_public.apps.contact.forms import ContactForm

def submit(**kwargs):
    return ContactForm(MultiDict(kwargs), csrf_enabled=False)

class NotesTest(unittest.TestCase):

    def setUp(self):
        app = create_app('config/testing.py')
        app.test_request_context().push()

    def validate_notes(self, notes):
        form = submit(
            extra_notes=notes)
        form.validate()
        return u'Your notes must be 4000 characters or less' not in \
            form.extra_notes.errors

    def test_notes_max_length(self):
        longest_allowed = 'x' * 4000
        self.assertTrue(self.validate_notes(longest_allowed))

        too_long = longest_allowed + 'x'
        self.assertFalse(self.validate_notes(too_long))

Prompt: Add python test for notes length validation


#! /usr/bin/env python

from tools import check_cmd

def run_cyclus(cyclus, cwd, sim_files):
    """Runs cyclus with various inputs and creates output databases
       """

    for sim_input, sim_output in sim_files:
        holdsrtn = [1]  # needed because nose does not send() to test generator
        cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
        check_cmd(cmd, cwd, holdsrtn)
        rtn = holdsrtn[0]
        if rtn != 0:
            return  # don"t execute further commands

Response:
<REPLACE_OLD> zip(sim_files):
 <REPLACE_NEW> sim_files:
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python

from tools import check_cmd

def run_cyclus(cyclus, cwd, sim_files):
    """Runs cyclus with various inputs and creates output databases
       """

    for sim_input, sim_output in sim_files:
        holdsrtn = [1]  # needed because nose does not send() to test generator
        cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
        check_cmd(cmd, cwd, holdsrtn)
        rtn = holdsrtn[0]
        if rtn != 0:
            return  # don"t execute further commands

Prompt:
Correct zip() error in run_cyclus function

#! /usr/bin/env python

from tools import check_cmd

def run_cyclus(cyclus, cwd, sim_files):
    """Runs cyclus with various inputs and creates output databases
       """

    for sim_input, sim_output in zip(sim_files):
        holdsrtn = [1]  # needed because nose does not send() to test generator
        cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
        check_cmd(cmd, cwd, holdsrtn)
        rtn = holdsrtn[0]
        if rtn != 0:
            return  # don"t execute further commands


import discord
from stickord.registry import Command

@Command(['tellen', 'tel'])
async def counting(cont, mesg, client, *args, **kwargs):
    count, auth, when = (0, discord.User, None)
    if cont:
        try:
            num = int(cont[0])
            if num != count + 1:
                return f'Whoops, you done goof! you should have entered "{cnt+1}" but you entered "{num}"'
            else if mesg.author.id == auth.id:
                return f'You can\'t submit a number twice in a row! Shame on you {mesg.author.mention}!'
            else:
                #save num
                await client.add_reaction(mesg, '\U0001f44c')
        except ValueError:
            return 'Entered number was not valid.'

Add framework for counting command

Add framework for counting command

Response:
<REPLACE_OLD>  <REPLACE_NEW> import discord
from stickord.registry import Command

@Command(['tellen', 'tel'])
async def counting(cont, mesg, client, *args, **kwargs):
    count, auth, when = (0, discord.User, None)
    if cont:
        try:
            num = int(cont[0])
            if num != count + 1:
                return f'Whoops, you done goof! you should have entered "{cnt+1}" but you entered "{num}"'
            else if mesg.author.id == auth.id:
                return f'You can\'t submit a number twice in a row! Shame on you {mesg.author.mention}!'
            else:
                #save num
                await client.add_reaction(mesg, '\U0001f44c')
        except ValueError:
            return 'Entered number was not valid.'

 <REPLACE_END> <|endoftext|> import discord
from stickord.registry import Command

@Command(['tellen', 'tel'])
async def counting(cont, mesg, client, *args, **kwargs):
    count, auth, when = (0, discord.User, None)
    if cont:
        try:
            num = int(cont[0])
            if num != count + 1:
                return f'Whoops, you done goof! you should have entered "{cnt+1}" but you entered "{num}"'
            else if mesg.author.id == auth.id:
                return f'You can\'t submit a number twice in a row! Shame on you {mesg.author.mention}!'
            else:
                #save num
                await client.add_reaction(mesg, '\U0001f44c')
        except ValueError:
            return 'Entered number was not valid.'

Prompt: Add framework for counting command


"""
Export course metadata for all courses
"""

from django.core.management.base import BaseCommand

from xmodule.modulestore.django import modulestore

from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task

class Command(BaseCommand):
    """
    Export course metadata for all courses
    """
    help = 'Export course metadata for all courses'

    def handle(self, *args, **options):
        """
        Execute the command
        """
        export_course_metadata_for_all_courses()

def export_course_metadata_for_all_courses():
    """
    Export course metadata for all courses
    """
    courses = modulestore().get_course_summaries()
    for course in courses:
        export_course_metadata_task.delay(str(course.id))

Response:
<DELETE> module_store = modulestore()
    <DELETE_END> <REPLACE_OLD> module_store.get_courses()
 <REPLACE_NEW> modulestore().get_course_summaries()
 <REPLACE_END> <|endoftext|> """
Export course metadata for all courses
"""

from django.core.management.base import BaseCommand

from xmodule.modulestore.django import modulestore

from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task

class Command(BaseCommand):
    """
    Export course metadata for all courses
    """
    help = 'Export course metadata for all courses'

    def handle(self, *args, **options):
        """
        Execute the command
        """
        export_course_metadata_for_all_courses()

def export_course_metadata_for_all_courses():
    """
    Export course metadata for all courses
    """
    courses = modulestore().get_course_summaries()
    for course in courses:
        export_course_metadata_task.delay(str(course.id))

Prompt:
Change how we get course ids to avoid memory issues

"""
Export course metadata for all courses
"""

from django.core.management.base import BaseCommand

from xmodule.modulestore.django import modulestore

from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task

class Command(BaseCommand):
    """
    Export course metadata for all courses
    """
    help = 'Export course metadata for all courses'

    def handle(self, *args, **options):
        """
        Execute the command
        """
        export_course_metadata_for_all_courses()

def export_course_metadata_for_all_courses():
    """
    Export course metadata for all courses
    """
    module_store = modulestore()
    courses = module_store.get_courses()
    for course in courses:
        export_course_metadata_task.delay(str(course.id))


#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

Create file for Nonterminal have method

Create file for Nonterminal have method

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

""" <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

Prompt: Create file for Nonterminal have method


# -*- coding: utf-8 -*-
from django.shortcuts import render

# Create your views here.

from rest_framework import viewsets
from rest_framework import filters

from porchlightapi.models import Repository, ValueDataPoint
from porchlightapi.serializers import RepositorySerializer, ValueDataPointSerializer

class RepositoryViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A REST view of repositories. Provides GET listing of Repositories,
    filtering on name and project, and individual repsositories on id.
    """
    queryset = Repository.objects.all()
    serializer_class = RepositorySerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('name', 'project', 'url')

class ValueDataPointViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A REST view of data points.
    """
    queryset = ValueDataPoint.objects.all()
    serializer_class = ValueDataPointSerializer

Use DRF's built-in search filter

Use DRF's built-in search filter

Response:
<REPLACE_OLD> here.

import django_filters

from <REPLACE_NEW> here.

from <REPLACE_END> <DELETE> RepositoryFilter(django_filters.FilterSet):
    """
    Provide filtering of repository objects based on name or project.
    This is 'icontains' filtering, so a repo with the name "Porchlight"
    will match 'por', 'Por', etc.
    """
    name = django_filters.CharFilter(name="name", lookup_type='icontains')
    project = django_filters.CharFilter(name="project", lookup_type='icontains')
    class Meta:
        model = Repository
        fields = ['name', 'project',]

class <DELETE_END> <REPLACE_OLD> (filters.DjangoFilterBackend,)
 <REPLACE_NEW> (filters.SearchFilter,)
 <REPLACE_END> <REPLACE_OLD> filter_class = RepositoryFilter
    # filter_fields <REPLACE_NEW> search_fields <REPLACE_END> <REPLACE_OLD> 'project')

class <REPLACE_NEW> 'project', 'url')

class <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.shortcuts import render

# Create your views here.

from rest_framework import viewsets
from rest_framework import filters

from porchlightapi.models import Repository, ValueDataPoint
from porchlightapi.serializers import RepositorySerializer, ValueDataPointSerializer

class RepositoryViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A REST view of repositories. Provides GET listing of Repositories,
    filtering on name and project, and individual repsositories on id.
    """
    queryset = Repository.objects.all()
    serializer_class = RepositorySerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ('name', 'project', 'url')

class ValueDataPointViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A REST view of data points.
    """
    queryset = ValueDataPoint.objects.all()
    serializer_class = ValueDataPointSerializer

Prompt:
Use DRF's built-in search filter

# -*- coding: utf-8 -*-
from django.shortcuts import render

# Create your views here.

import django_filters

from rest_framework import viewsets
from rest_framework import filters

from porchlightapi.models import Repository, ValueDataPoint
from porchlightapi.serializers import RepositorySerializer, ValueDataPointSerializer

class RepositoryFilter(django_filters.FilterSet):
    """
    Provide filtering of repository objects based on name or project.
    This is 'icontains' filtering, so a repo with the name "Porchlight"
    will match 'por', 'Por', etc.
    """
    name = django_filters.CharFilter(name="name", lookup_type='icontains')
    project = django_filters.CharFilter(name="project", lookup_type='icontains')
    class Meta:
        model = Repository
        fields = ['name', 'project',]

class RepositoryViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A REST view of repositories. Provides GET listing of Repositories,
    filtering on name and project, and individual repsositories on id.
    """
    queryset = Repository.objects.all()
    serializer_class = RepositorySerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = RepositoryFilter
    # filter_fields = ('name', 'project')

class ValueDataPointViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A REST view of data points.
    """
    queryset = ValueDataPoint.objects.all()
    serializer_class = ValueDataPointSerializer


from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel

class Menu(models.Model):
    slug = models.SlugField(max_length=50)

    class Meta:
        permissions = (
            ('view_menu',
             pgettext_lazy('Permission description', 'Can view menus')),
            ('edit_menu',
             pgettext_lazy('Permission description', 'Can edit menus')))

    def __str__(self):
        return self.slug

class MenuItem(MPTTModel):
    menu = models.ForeignKey(
        Menu, related_name='items', on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    sort_order = models.PositiveIntegerField(editable=False)
    url = models.URLField(max_length=256)
    parent = models.ForeignKey(
        'self', null=True, blank=True, related_name='children',
        on_delete=models.CASCADE)

    objects = models.Manager()
    tree = TreeManager()

    class Meta:
        ordering = ('sort_order',)
        app_label = 'menu'

    def __str__(self):
        return self.name

    def get_ordering_queryset(self):
        return (
            self.menu.items.all() if not self.parent
            else self.parent.children.all())

    def save(self, *args, **kwargs):
        if self.sort_order is None:
            qs = self.get_ordering_queryset()
            existing_max = qs.aggregate(Max('sort_order'))
            existing_max = existing_max.get('sort_order__max')
            self.sort_order = 0 if existing_max is None else existing_max + 1
        super().save(*args, **kwargs)

Save sorting order on MenuItem

Save sorting order on MenuItem

Response:
<INSERT> django.db.models import Max
from <INSERT_END> <REPLACE_OLD> self.name
 <REPLACE_NEW> self.name

    def get_ordering_queryset(self):
        return (
            self.menu.items.all() if not self.parent
            else self.parent.children.all())

    def save(self, *args, **kwargs):
        if self.sort_order is None:
            qs = self.get_ordering_queryset()
            existing_max = qs.aggregate(Max('sort_order'))
            existing_max = existing_max.get('sort_order__max')
            self.sort_order = 0 if existing_max is None else existing_max + 1
        super().save(*args, **kwargs)
 <REPLACE_END> <|endoftext|> from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel

class Menu(models.Model):
    slug = models.SlugField(max_length=50)

    class Meta:
        permissions = (
            ('view_menu',
             pgettext_lazy('Permission description', 'Can view menus')),
            ('edit_menu',
             pgettext_lazy('Permission description', 'Can edit menus')))

    def __str__(self):
        return self.slug

class MenuItem(MPTTModel):
    menu = models.ForeignKey(
        Menu, related_name='items', on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    sort_order = models.PositiveIntegerField(editable=False)
    url = models.URLField(max_length=256)
    parent = models.ForeignKey(
        'self', null=True, blank=True, related_name='children',
        on_delete=models.CASCADE)

    objects = models.Manager()
    tree = TreeManager()

    class Meta:
        ordering = ('sort_order',)
        app_label = 'menu'

    def __str__(self):
        return self.name

    def get_ordering_queryset(self):
        return (
            self.menu.items.all() if not self.parent
            else self.parent.children.all())

    def save(self, *args, **kwargs):
        if self.sort_order is None:
            qs = self.get_ordering_queryset()
            existing_max = qs.aggregate(Max('sort_order'))
            existing_max = existing_max.get('sort_order__max')
            self.sort_order = 0 if existing_max is None else existing_max + 1
        super().save(*args, **kwargs)

Prompt:
Save sorting order on MenuItem

from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel

class Menu(models.Model):
    slug = models.SlugField(max_length=50)

    class Meta:
        permissions = (
            ('view_menu',
             pgettext_lazy('Permission description', 'Can view menus')),
            ('edit_menu',
             pgettext_lazy('Permission description', 'Can edit menus')))

    def __str__(self):
        return self.slug

class MenuItem(MPTTModel):
    menu = models.ForeignKey(
        Menu, related_name='items', on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    sort_order = models.PositiveIntegerField(editable=False)
    url = models.URLField(max_length=256)
    parent = models.ForeignKey(
        'self', null=True, blank=True, related_name='children',
        on_delete=models.CASCADE)

    objects = models.Manager()
    tree = TreeManager()

    class Meta:
        ordering = ('sort_order',)
        app_label = 'menu'

    def __str__(self):
        return self.name


from ..Module import Module
from ..TagData import TagData

class rgp(Module):
    opmap = {
        'infData':      'descend',
    }

    def parse_rgpStatus(self, response, tag):
        status = tag.attrib['s']
        response.set(status, tag.text)

    def render_default(self, request, data):
        ext = self.render_extension(request, 'update')
        request.add_subtag(ext, 'rgp:restore', { 'op': 'request'})

    def render_request(self, request, data):
        return self.render_default(request, data)

    def render_report(self, request, data):
        ext = self.render_extension(request, 'update')
        restore = request.add_subtag(ext, 'rgp:restore', { 'op': 'report'})
        report = request.add_subtag(restore, 'rgp:report')
        request.add_subtag(report, 'rgp:preData', {}, data.get('preData'))
        request.add_subtag(report, 'rgp:postData', {}, data.get('postData'))
        request.add_subtag(report, 'rgp:delTime', {}, data.get('delTime'))
        request.add_subtag(report, 'rgp:resTime', {}, data.get('resTime'))
        request.add_subtag(report, 'rgp:resReason', {}, data.get('resReason', 'Registrant error'))
        request.add_subtag(report, 'rgp:statement', {}, data.get('statement', 'This registrar has not restored the Registered Name in order to assume the rights to use or sell the Registered Name for itself or for any third party'))
        request.add_subtag(report, 'rgp:statement', {}, data.get('statement', 'The information in this report is true to best of this registrar\'s knowledge, and this registrar acknowledges that intentionally supplying false information in this report shall constitute an incurable material breach of the Registry-Registrar Agreement'))

Add RGP request and report

Add RGP request and report

Response:
<INSERT>    def render_request(self, request, data):
        return self.render_default(request, data)

    def render_report(self, request, data):
        ext = self.render_extension(request, 'update')
        restore = request.add_subtag(ext, 'rgp:restore', { 'op': 'report'})
        report = request.add_subtag(restore, 'rgp:report')
        request.add_subtag(report, 'rgp:preData', {}, data.get('preData'))
        request.add_subtag(report, 'rgp:postData', {}, data.get('postData'))
        request.add_subtag(report, 'rgp:delTime', {}, data.get('delTime'))
        request.add_subtag(report, 'rgp:resTime', {}, data.get('resTime'))
        request.add_subtag(report, 'rgp:resReason', {}, data.get('resReason', 'Registrant error'))
        request.add_subtag(report, 'rgp:statement', {}, data.get('statement', 'This registrar has not restored the Registered Name in order to assume the rights to use or sell the Registered Name for itself or for any third party'))
        request.add_subtag(report, 'rgp:statement', {}, data.get('statement', 'The information in this report is true to best of this registrar\'s knowledge, and this registrar acknowledges that intentionally supplying false information in this report shall constitute an incurable material breach of the Registry-Registrar Agreement'))

 <INSERT_END> <|endoftext|> from ..Module import Module
from ..TagData import TagData

class rgp(Module):
    opmap = {
        'infData':      'descend',
    }

    def parse_rgpStatus(self, response, tag):
        status = tag.attrib['s']
        response.set(status, tag.text)

    def render_default(self, request, data):
        ext = self.render_extension(request, 'update')
        request.add_subtag(ext, 'rgp:restore', { 'op': 'request'})

    def render_request(self, request, data):
        return self.render_default(request, data)

    def render_report(self, request, data):
        ext = self.render_extension(request, 'update')
        restore = request.add_subtag(ext, 'rgp:restore', { 'op': 'report'})
        report = request.add_subtag(restore, 'rgp:report')
        request.add_subtag(report, 'rgp:preData', {}, data.get('preData'))
        request.add_subtag(report, 'rgp:postData', {}, data.get('postData'))
        request.add_subtag(report, 'rgp:delTime', {}, data.get('delTime'))
        request.add_subtag(report, 'rgp:resTime', {}, data.get('resTime'))
        request.add_subtag(report, 'rgp:resReason', {}, data.get('resReason', 'Registrant error'))
        request.add_subtag(report, 'rgp:statement', {}, data.get('statement', 'This registrar has not restored the Registered Name in order to assume the rights to use or sell the Registered Name for itself or for any third party'))
        request.add_subtag(report, 'rgp:statement', {}, data.get('statement', 'The information in this report is true to best of this registrar\'s knowledge, and this registrar acknowledges that intentionally supplying false information in this report shall constitute an incurable material breach of the Registry-Registrar Agreement'))

Prompt:
Add RGP request and report

from ..Module import Module
from ..TagData import TagData

class rgp(Module):
    opmap = {
        'infData':      'descend',
    }

    def parse_rgpStatus(self, response, tag):
        status = tag.attrib['s']
        response.set(status, tag.text)

    def render_default(self, request, data):
        ext = self.render_extension(request, 'update')
        request.add_subtag(ext, 'rgp:restore', { 'op': 'request'})


"""
Various parser-related exceptions.
"""
from emds.exceptions import EMDSError

class ParseError(EMDSError):
    """
    Raise this when some unrecoverable error happens while parsing serialized
    market data.
    """
    pass

Make ParseError a child of EMDSError.

Make ParseError a child of EMDSError.

Response:
<REPLACE_OLD> exceptions.
"""

class ParseError(Exception):
 <REPLACE_NEW> exceptions.
"""
from emds.exceptions import EMDSError

class ParseError(EMDSError):
 <REPLACE_END> <|endoftext|> """
Various parser-related exceptions.
"""
from emds.exceptions import EMDSError

class ParseError(EMDSError):
    """
    Raise this when some unrecoverable error happens while parsing serialized
    market data.
    """
    pass

Prompt:
Make ParseError a child of EMDSError.

"""
Various parser-related exceptions.
"""

class ParseError(Exception):
    """
    Raise this when some unrecoverable error happens while parsing serialized
    market data.
    """
    pass


import git
import os

from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render

class SaveContentMixin():

    """Save exam or question content to a git repository and to a database."""

#    object = None
#    request = None
#    template_name = None

    def write_content(self, directory, form, inlines=None):
        try:
            repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH'])
            os.environ['GIT_AUTHOR_NAME'] = 'Numbas'
            os.environ['GIT_AUTHOR_EMAIL'] = 'numbas@ncl.ac.uk'
            path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'],
                                        directory, self.object.filename)
            fh = open(path_to_file, 'w')
            fh.write(self.object.content)
            fh.close()
            repo.index.add([os.path.join(directory, self.object.filename)])
            repo.index.commit('Made some changes to %s' % self.object.name)
        except IOError:
            error = "Could not save file."
            return render(self.request, self.template_name,
                          {'form': form, 'inlines': inlines, 'error': error,
                           'object': self.object})
        self.object = form.save()
        if inlines is not None:
            for formset in inlines:
                formset.save()
        return HttpResponseRedirect(self.get_success_url())

Set the git author name and e-mail

Set the git author name and e-mail

Response:
<INSERT> os.environ['GIT_AUTHOR_NAME'] = 'Numbas'
            os.environ['GIT_AUTHOR_EMAIL'] = 'numbas@ncl.ac.uk'
            <INSERT_END> <|endoftext|> import git
import os

from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render

class SaveContentMixin():

    """Save exam or question content to a git repository and to a database."""

#    object = None
#    request = None
#    template_name = None

    def write_content(self, directory, form, inlines=None):
        try:
            repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH'])
            os.environ['GIT_AUTHOR_NAME'] = 'Numbas'
            os.environ['GIT_AUTHOR_EMAIL'] = 'numbas@ncl.ac.uk'
            path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'],
                                        directory, self.object.filename)
            fh = open(path_to_file, 'w')
            fh.write(self.object.content)
            fh.close()
            repo.index.add([os.path.join(directory, self.object.filename)])
            repo.index.commit('Made some changes to %s' % self.object.name)
        except IOError:
            error = "Could not save file."
            return render(self.request, self.template_name,
                          {'form': form, 'inlines': inlines, 'error': error,
                           'object': self.object})
        self.object = form.save()
        if inlines is not None:
            for formset in inlines:
                formset.save()
        return HttpResponseRedirect(self.get_success_url())

Prompt:
Set the git author name and e-mail

import git
import os

from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render

class SaveContentMixin():

    """Save exam or question content to a git repository and to a database."""

#    object = None
#    request = None
#    template_name = None

    def write_content(self, directory, form, inlines=None):
        try:
            repo = git.Repo(settings.GLOBAL_SETTINGS['REPO_PATH'])
            path_to_file = os.path.join(settings.GLOBAL_SETTINGS['REPO_PATH'],
                                        directory, self.object.filename)
            fh = open(path_to_file, 'w')
            fh.write(self.object.content)
            fh.close()
            repo.index.add([os.path.join(directory, self.object.filename)])
            repo.index.commit('Made some changes to %s' % self.object.name)
        except IOError:
            error = "Could not save file."
            return render(self.request, self.template_name,
                          {'form': form, 'inlines': inlines, 'error': error,
                           'object': self.object})
        self.object = form.save()
        if inlines is not None:
            for formset in inlines:
                formset.save()
        return HttpResponseRedirect(self.get_success_url())


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

from feedback.forms import FeedbackForm

def leave_feedback(request, template_name='feedback/feedback_form.html'):
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        feedback = form.save(commit=False)
        feedback.user = request.user
        feedback.save()
        request.user.message_set.create(message="Your feedback has been saved successfully.")
        return HttpResponseRedirect(request.POST.get('next', request.META.get('HTTP_REFERER', '/')))
    return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))

Allow passing of template_name to view

Allow passing of template_name to view

Response:
<REPLACE_OLD> leave_feedback(request):
 <REPLACE_NEW> leave_feedback(request, template_name='feedback/feedback_form.html'):
 <REPLACE_END> <REPLACE_OLD> render_to_response('feedback/feedback_form.html', <REPLACE_NEW> render_to_response(template_name, <REPLACE_END> <REPLACE_OLD> context_instance=RequestContext(request)) <REPLACE_NEW> context_instance=RequestContext(request))

 <REPLACE_END> <|endoftext|> from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from feedback.forms import FeedbackForm

def leave_feedback(request, template_name='feedback/feedback_form.html'):
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        feedback = form.save(commit=False)
        feedback.user = request.user
        feedback.save()
        request.user.message_set.create(message="Your feedback has been saved successfully.")
        return HttpResponseRedirect(request.POST.get('next', request.META.get('HTTP_REFERER', '/')))
    return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))

Prompt:
Allow passing of template_name to view

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

from feedback.forms import FeedbackForm

def leave_feedback(request):
    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        feedback = form.save(commit=False)
        feedback.user = request.user
        feedback.save()
        request.user.message_set.create(message="Your feedback has been saved successfully.")
        return HttpResponseRedirect(request.POST.get('next', request.META.get('HTTP_REFERER', '/')))
    return render_to_response('feedback/feedback_form.html', {'form': form}, context_instance=RequestContext(request))


from config.experiment_config_lib import ControllerConfig
from sts.control_flow.fuzzer import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.simulation_state import SimulationConfig
from sts.invariant_checker import InvariantChecker
from sts.topology import MeshTopology, BufferedPatchPanel
from sts.happensbefore.hb_logger import HappensBeforeLogger
from sts.control_flow.interactive import Interactive

# Use POX as our controller
start_cmd = ('''./pox.py --verbose --no-cli sts.syncproto.pox_syncer --blocking=False '''
                '''forwarding.l2_learning '''
                '''sts.util.socket_mux.pox_monkeypatcher '''
                '''openflow.of_01 --address=/tmp/sts_socket_pipe''')

controllers = [ControllerConfig(start_cmd, address="/tmp/sts_socket_pipe", cwd="pox", sync="tcp:localhost:18899")]

topology_class = MeshTopology
topology_params = "num_switches=2"

results_dir = "experiments/pox_sync"

simulation_config = SimulationConfig(controller_configs=controllers,
                                     topology_class=topology_class,
                                     topology_params=topology_params,
                                     multiplex_sockets=True,
                                     violation_persistence_threshold=None,
                                     kill_controllers_on_exit=True,
                                     hb_logger_class=HappensBeforeLogger,
                                     hb_logger_params=results_dir)

# Manual, interactive mode
control_flow = Interactive(simulation_config, input_logger=InputLogger())

Add example for using sync protocol in pox

Response:
<REPLACE_OLD>  <REPLACE_NEW> from config.experiment_config_lib import ControllerConfig
from sts.control_flow.fuzzer import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.simulation_state import SimulationConfig
from sts.invariant_checker import InvariantChecker
from sts.topology import MeshTopology, BufferedPatchPanel
from sts.happensbefore.hb_logger import HappensBeforeLogger
from sts.control_flow.interactive import Interactive

# Use POX as our controller
start_cmd = ('''./pox.py --verbose --no-cli sts.syncproto.pox_syncer --blocking=False '''
                '''forwarding.l2_learning '''
                '''sts.util.socket_mux.pox_monkeypatcher '''
                '''openflow.of_01 --address=/tmp/sts_socket_pipe''')

controllers = [ControllerConfig(start_cmd, address="/tmp/sts_socket_pipe", cwd="pox", sync="tcp:localhost:18899")]

topology_class = MeshTopology
topology_params = "num_switches=2"

results_dir = "experiments/pox_sync"

simulation_config = SimulationConfig(controller_configs=controllers,
                                     topology_class=topology_class,
                                     topology_params=topology_params,
                                     multiplex_sockets=True,
                                     violation_persistence_threshold=None,
                                     kill_controllers_on_exit=True,
                                     hb_logger_class=HappensBeforeLogger,
                                     hb_logger_params=results_dir)

# Manual, interactive mode
control_flow = Interactive(simulation_config, input_logger=InputLogger())

 <REPLACE_END> <|endoftext|> from config.experiment_config_lib import ControllerConfig
from sts.control_flow.fuzzer import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.simulation_state import SimulationConfig
from sts.invariant_checker import InvariantChecker
from sts.topology import MeshTopology, BufferedPatchPanel
from sts.happensbefore.hb_logger import HappensBeforeLogger
from sts.control_flow.interactive import Interactive

# Use POX as our controller
start_cmd = ('''./pox.py --verbose --no-cli sts.syncproto.pox_syncer --blocking=False '''
                '''forwarding.l2_learning '''
                '''sts.util.socket_mux.pox_monkeypatcher '''
                '''openflow.of_01 --address=/tmp/sts_socket_pipe''')

controllers = [ControllerConfig(start_cmd, address="/tmp/sts_socket_pipe", cwd="pox", sync="tcp:localhost:18899")]

topology_class = MeshTopology
topology_params = "num_switches=2"

results_dir = "experiments/pox_sync"

simulation_config = SimulationConfig(controller_configs=controllers,
                                     topology_class=topology_class,
                                     topology_params=topology_params,
                                     multiplex_sockets=True,
                                     violation_persistence_threshold=None,
                                     kill_controllers_on_exit=True,
                                     hb_logger_class=HappensBeforeLogger,
                                     hb_logger_params=results_dir)

# Manual, interactive mode
control_flow = Interactive(simulation_config, input_logger=InputLogger())

Prompt: Add example for using sync protocol in pox


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys

def execute_command(target):
    os.chdir(target)
    command = sys.argv[1:]
    try:
        subprocess.check_call(command)
    except Exception as e:
        print "ERROR in %s: %s" % (target, e)

def main():
    base = os.getcwdu() + "/"
    targets = None

    # Get immediate child directories.
    for root, dirs, files in os.walk('.'):
        targets = dirs
        break  # dirty hack so we only get the first level

    # Traverse through the directories.
    for target in sorted(targets, key=lambda s: s.lower()):
        target_full_path = base + target
        print "\nwalker: in %s" % target_full_path
        execute_command(target_full_path)
        os.chdir(base)

if __name__ == '__main__':
    main()

Response:
<REPLACE_OLD> "walker: <REPLACE_NEW> "\nwalker: <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys

def execute_command(target):
    os.chdir(target)
    command = sys.argv[1:]
    try:
        subprocess.check_call(command)
    except Exception as e:
        print "ERROR in %s: %s" % (target, e)

def main():
    base = os.getcwdu() + "/"
    targets = None

    # Get immediate child directories.
    for root, dirs, files in os.walk('.'):
        targets = dirs
        break  # dirty hack so we only get the first level

    # Traverse through the directories.
    for target in sorted(targets, key=lambda s: s.lower()):
        target_full_path = base + target
        print "\nwalker: in %s" % target_full_path
        execute_command(target_full_path)
        os.chdir(base)

if __name__ == '__main__':
    main()

Prompt:
Add a new line before displaying the current dir

This makes it easier for my brain to read.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys

def execute_command(target):
    os.chdir(target)
    command = sys.argv[1:]
    try:
        subprocess.check_call(command)
    except Exception as e:
        print "ERROR in %s: %s" % (target, e)

def main():
    base = os.getcwdu() + "/"
    targets = None

    # Get immediate child directories.
    for root, dirs, files in os.walk('.'):
        targets = dirs
        break  # dirty hack so we only get the first level

    # Traverse through the directories.
    for target in sorted(targets, key=lambda s: s.lower()):
        target_full_path = base + target
        print "walker: in %s" % target_full_path
        execute_command(target_full_path)
        os.chdir(base)

if __name__ == '__main__':
    main()


"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""

class MenuItem:
    """ To store menu item information """

    def __init__(self, txt, target, hidden):
        """ Constructor

        txt - Menu link text
        target - Can be several things
            -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3)
            -- hardcoded URL (absolute URL)
            -- link to sitemap (so equals 'sitemap')
            -- hardcoded URL to file (includes '/files/' in string)
            -- None if normal menu entry for page
        """
        self.txt = txt
        self.target = target
        if self.target:
            self.target = self.target.strip()
        self.hidden = hidden
        self.children = []
        self.children_sort_way = None

    def target_is_url(self):
        return False if self.target is None else self.target.startswith('http')

    def target_is_sitemap(self):
        return self.target == "sitemap"

    def target_is_file(self):
        return False if self.target is None else '/files/' in self.target

    def sort_children(self, sort_way):
        self.children_sort_way = sort_way
        self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))

Response:
<DELETE> target_is_reference(self):
        # If it is not another possibility, it is a reference
        return not self.target_is_sitemap() and \
            not self.target_is_url() and \
            self.target is not None

    def <DELETE_END> <|endoftext|> """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""

class MenuItem:
    """ To store menu item information """

    def __init__(self, txt, target, hidden):
        """ Constructor

        txt - Menu link text
        target - Can be several things
            -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3)
            -- hardcoded URL (absolute URL)
            -- link to sitemap (so equals 'sitemap')
            -- hardcoded URL to file (includes '/files/' in string)
            -- None if normal menu entry for page
        """
        self.txt = txt
        self.target = target
        if self.target:
            self.target = self.target.strip()
        self.hidden = hidden
        self.children = []
        self.children_sort_way = None

    def target_is_url(self):
        return False if self.target is None else self.target.startswith('http')

    def target_is_sitemap(self):
        return self.target == "sitemap"

    def target_is_file(self):
        return False if self.target is None else '/files/' in self.target

    def sort_children(self, sort_way):
        self.children_sort_way = sort_way
        self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))

Prompt:
Remove previously added method because finally not used...

"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""

class MenuItem:
    """ To store menu item information """

    def __init__(self, txt, target, hidden):
        """ Constructor

        txt - Menu link text
        target - Can be several things
            -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3)
            -- hardcoded URL (absolute URL)
            -- link to sitemap (so equals 'sitemap')
            -- hardcoded URL to file (includes '/files/' in string)
            -- None if normal menu entry for page
        """
        self.txt = txt
        self.target = target
        if self.target:
            self.target = self.target.strip()
        self.hidden = hidden
        self.children = []
        self.children_sort_way = None

    def target_is_url(self):
        return False if self.target is None else self.target.startswith('http')

    def target_is_sitemap(self):
        return self.target == "sitemap"

    def target_is_file(self):
        return False if self.target is None else '/files/' in self.target

    def target_is_reference(self):
        # If it is not another possibility, it is a reference
        return not self.target_is_sitemap() and \
            not self.target_is_url() and \
            self.target is not None

    def sort_children(self, sort_way):
        self.children_sort_way = sort_way
        self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))


import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])

class MyTest(unittest.TestCase):
    def test_urllib(self):
        import urllib
        print(urllib.__file__)
        from future import standard_library
        with standard_library.hooks():
            import urllib.response
        print(urllib.__file__)
        print(urllib.response.__file__)

unittest.main()

Add a new little urllib import test

Add a new little urllib import test

Response:
<INSERT> import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])

class MyTest(unittest.TestCase):
 <INSERT_END> <INSERT>   def test_urllib(self):
        import urllib
        print(urllib.__file__)
        from future import standard_library
        with standard_library.hooks():
            import urllib.response
        print(urllib.__file__)
        print(urllib.response.__file__)

unittest.main()
 <INSERT_END> <|endoftext|> import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])

class MyTest(unittest.TestCase):
    def test_urllib(self):
        import urllib
        print(urllib.__file__)
        from future import standard_library
        with standard_library.hooks():
            import urllib.response
        print(urllib.__file__)
        print(urllib.response.__file__)

unittest.main()

Prompt: Add a new little urllib import test


class Docstring:
    """Class for storing docstring information.

    Following headers are used by this class:

    * 'summary' - first line of the docstring
    * 'extended' - blocks of extended description concerning the functionality of the code
    * 'parameters' - parameters of a method
    * 'other parameters' - parameters that are not commonly used
    * 'returns' - returned value of a method
    * 'yields' - generated value of a generator
    * 'raises' - errors raised
    * 'see also' - other related code
    * 'notes' - blocks of other information about the code (e.g. implementation details)
    * 'references' - references used
    * 'examples' - examples of code usage
    * 'attributes' - attributes of a class
    * 'methods' - methods of a class/module

    Attributes
    ----------
    info : dict
        Dictionary of the headers to contents under header.

    Methods
    -------
    __init__(**headers_contents)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    parse_instance(instance)
        Return instance of Docstring that corresponds to provided instance.
    make_google()
        Return corresponding google docstring
    make_numpy()
        Return corresponding numpy docstring

    Example
    -------
    For example, this docstring should be equivalent to

    info = {'Attributes': {'info': {'type': ['dict'],
                           'docs':['Dictionary of the headers to contents under header.']}}}
    info = {'Attributes': {'info': <ParamDocstring object>}}
    """
    pass

class ParamDocstring:
    """Class for storing docstring information on parameters.

    Attributes
    ----------
    name : str
        Name of the parameter.
    types : list of str
        Type of the parameters allowed.
    docs : list of str
        Documentations for the parameter.

    Methods
    -------
    __init__(name, type=None, docs=None)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    """
    pass

class MethodDocstring:
    """Class for storing docstring information on methods.

    Attributes
    ----------
    name : str
        Name of the method.
    call_signature : str
        Call signature of the method.
    docs : list of str
        Documentations for the method.

    Methods
    -------
    __init__(name, call_signature, docs=None)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    """
    pass

Add general framework for coding

Add general framework for coding

using documentation

Response:
<REPLACE_OLD>  <REPLACE_NEW> class Docstring:
    """Class for storing docstring information.

    Following headers are used by this class:

    * 'summary' - first line of the docstring
    * 'extended' - blocks of extended description concerning the functionality of the code
    * 'parameters' - parameters of a method
    * 'other parameters' - parameters that are not commonly used
    * 'returns' - returned value of a method
    * 'yields' - generated value of a generator
    * 'raises' - errors raised
    * 'see also' - other related code
    * 'notes' - blocks of other information about the code (e.g. implementation details)
    * 'references' - references used
    * 'examples' - examples of code usage
    * 'attributes' - attributes of a class
    * 'methods' - methods of a class/module

    Attributes
    ----------
    info : dict
        Dictionary of the headers to contents under header.

    Methods
    -------
    __init__(**headers_contents)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    parse_instance(instance)
        Return instance of Docstring that corresponds to provided instance.
    make_google()
        Return corresponding google docstring
    make_numpy()
        Return corresponding numpy docstring

    Example
    -------
    For example, this docstring should be equivalent to

    info = {'Attributes': {'info': {'type': ['dict'],
                           'docs':['Dictionary of the headers to contents under header.']}}}
    info = {'Attributes': {'info': <ParamDocstring object>}}
    """
    pass

class ParamDocstring:
    """Class for storing docstring information on parameters.

    Attributes
    ----------
    name : str
        Name of the parameter.
    types : list of str
        Type of the parameters allowed.
    docs : list of str
        Documentations for the parameter.

    Methods
    -------
    __init__(name, type=None, docs=None)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    """
    pass

class MethodDocstring:
    """Class for storing docstring information on methods.

    Attributes
    ----------
    name : str
        Name of the method.
    call_signature : str
        Call signature of the method.
    docs : list of str
        Documentations for the method.

    Methods
    -------
    __init__(name, call_signature, docs=None)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    """
    pass
 <REPLACE_END> <|endoftext|> class Docstring:
    """Class for storing docstring information.

    Following headers are used by this class:

    * 'summary' - first line of the docstring
    * 'extended' - blocks of extended description concerning the functionality of the code
    * 'parameters' - parameters of a method
    * 'other parameters' - parameters that are not commonly used
    * 'returns' - returned value of a method
    * 'yields' - generated value of a generator
    * 'raises' - errors raised
    * 'see also' - other related code
    * 'notes' - blocks of other information about the code (e.g. implementation details)
    * 'references' - references used
    * 'examples' - examples of code usage
    * 'attributes' - attributes of a class
    * 'methods' - methods of a class/module

    Attributes
    ----------
    info : dict
        Dictionary of the headers to contents under header.

    Methods
    -------
    __init__(**headers_contents)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    parse_instance(instance)
        Return instance of Docstring that corresponds to provided instance.
    make_google()
        Return corresponding google docstring
    make_numpy()
        Return corresponding numpy docstring

    Example
    -------
    For example, this docstring should be equivalent to

    info = {'Attributes': {'info': {'type': ['dict'],
                           'docs':['Dictionary of the headers to contents under header.']}}}
    info = {'Attributes': {'info': <ParamDocstring object>}}
    """
    pass

class ParamDocstring:
    """Class for storing docstring information on parameters.

    Attributes
    ----------
    name : str
        Name of the parameter.
    types : list of str
        Type of the parameters allowed.
    docs : list of str
        Documentations for the parameter.

    Methods
    -------
    __init__(name, type=None, docs=None)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    """
    pass

class MethodDocstring:
    """Class for storing docstring information on methods.

    Attributes
    ----------
    name : str
        Name of the method.
    call_signature : str
        Call signature of the method.
    docs : list of str
        Documentations for the method.

    Methods
    -------
    __init__(name, call_signature, docs=None)
        Initialize.
    parse_google(docstring)
        Return instance of Docstring that corresponds to given google docstring.
    parse_numpy(docstring)
        Return instance of Docstring that corresponds to given numpy docstring.
    """
    pass

Prompt:
Add general framework for coding

using documentation


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

"""
Interface to Redis-storage.

@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license

Copyright (C) 2015
"""
from .utils import logger

# We will catch all import exceptions in bot.py
from redis import StrictRedis

class Storage:
    def __init__(self, bot):
        """
        Create new storage for bot

        :param bot: Bot object
        :return:
        """
        self.bot = bot

        # Connect to Redis.
        # If we had problems with Redis - just set self.redis to None.
        # Not redis-required modules must work without Redis.
        try:
            self.redis = StrictRedis(host=bot.config.get('SHELDON_REDIS_HOST',
                                                         'localhost'),
                                     port=int(
                                         bot.config.get('SHELDON_REDIS_PORT',
                                                        '6379')
                                     ),
                                     db=int(
                                         bot.config.get('SHELDON_REDIS_DB', '0')
                                     )
                                    )
        except Exception as error:
            logger.error_log_message('Error while connecting Redis:')
            logger.error_log_message(str(error.__traceback__))
            self.redis = None

Fix typo in redis error message

Fix typo in redis error message

Response:
<REPLACE_OLD> connection <REPLACE_NEW> connecting <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

"""
Interface to Redis-storage.

@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license

Copyright (C) 2015
"""
from .utils import logger

# We will catch all import exceptions in bot.py
from redis import StrictRedis

class Storage:
    def __init__(self, bot):
        """
        Create new storage for bot

        :param bot: Bot object
        :return:
        """
        self.bot = bot

        # Connect to Redis.
        # If we had problems with Redis - just set self.redis to None.
        # Not redis-required modules must work without Redis.
        try:
            self.redis = StrictRedis(host=bot.config.get('SHELDON_REDIS_HOST',
                                                         'localhost'),
                                     port=int(
                                         bot.config.get('SHELDON_REDIS_PORT',
                                                        '6379')
                                     ),
                                     db=int(
                                         bot.config.get('SHELDON_REDIS_DB', '0')
                                     )
                                    )
        except Exception as error:
            logger.error_log_message('Error while connecting Redis:')
            logger.error_log_message(str(error.__traceback__))
            self.redis = None

Prompt:
Fix typo in redis error message

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

"""
Interface to Redis-storage.

@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license

Copyright (C) 2015
"""
from .utils import logger

# We will catch all import exceptions in bot.py
from redis import StrictRedis

class Storage:
    def __init__(self, bot):
        """
        Create new storage for bot

        :param bot: Bot object
        :return:
        """
        self.bot = bot

        # Connect to Redis.
        # If we had problems with Redis - just set self.redis to None.
        # Not redis-required modules must work without Redis.
        try:
            self.redis = StrictRedis(host=bot.config.get('SHELDON_REDIS_HOST',
                                                         'localhost'),
                                     port=int(
                                         bot.config.get('SHELDON_REDIS_PORT',
                                                        '6379')
                                     ),
                                     db=int(
                                         bot.config.get('SHELDON_REDIS_DB', '0')
                                     )
                                    )
        except Exception as error:
            logger.error_log_message('Error while connection Redis:')
            logger.error_log_message(str(error.__traceback__))
            self.redis = None