import logging

l = logging.getLogger('angr.states')

class PathGenerator(object):
    def __init__(self, project):
        self._project = project

    def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
        '''
        blank_point - Returns a start path, representing a clean start of symbolic execution.
        '''
        s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
        return Path(self._project, s, jumpkind=jumpkind)

    def entry_point(self, state=None, *args, **kwargs):
        '''
        entry_point - Returns a path reflecting the processor when execution
                      reaches the binary's entry point.
        '''
        s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
        return Path(self._project, s)

from .path import Path

Response:
<INSERT> jumpkind='Ijk_Boring', <INSERT_END> <REPLACE_OLD> s)

 <REPLACE_NEW> s, jumpkind=jumpkind)

 <REPLACE_END> <|endoftext|> import logging

l = logging.getLogger('angr.states')

class PathGenerator(object):
    def __init__(self, project):
        self._project = project

    def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs):
        '''
        blank_point - Returns a start path, representing a clean start of symbolic execution.
        '''
        s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
        return Path(self._project, s, jumpkind=jumpkind)

    def entry_point(self, state=None, *args, **kwargs):
        '''
        entry_point - Returns a path reflecting the processor when execution
                      reaches the binary's entry point.
        '''
        s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
        return Path(self._project, s)

from .path import Path

Prompt:
Allow specifying jumpkind with creating a Path via PathGenerator.blank_path()

import logging

l = logging.getLogger('angr.states')

class PathGenerator(object):
    def __init__(self, project):
        self._project = project

    def blank_path(self, state=None, *args, **kwargs):
        '''
        blank_point - Returns a start path, representing a clean start of symbolic execution.
        '''
        s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
        return Path(self._project, s)

    def entry_point(self, state=None, *args, **kwargs):
        '''
        entry_point - Returns a path reflecting the processor when execution
                      reaches the binary's entry point.
        '''
        s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
        return Path(self._project, s)

from .path import Path


# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

from .views import LocalitiesAPI, LocalityAPI

urlpatterns = patterns(
    '',
    url(
        r'^localities$', LocalitiesAPI.as_view(),
        name='api_localities'
    ),
    url(
        r'^locality/(?P<uuid>\w{32})$', LocalityAPI.as_view(),
        name='api_locality'
    )
)

Fix spelling for api/locality/:uuid URL

Response:
<REPLACE_OLD> r'^localitiy/(?P<uuid>\w{32})$', <REPLACE_NEW> r'^locality/(?P<uuid>\w{32})$', <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

from .views import LocalitiesAPI, LocalityAPI

urlpatterns = patterns(
    '',
    url(
        r'^localities$', LocalitiesAPI.as_view(),
        name='api_localities'
    ),
    url(
        r'^locality/(?P<uuid>\w{32})$', LocalityAPI.as_view(),
        name='api_locality'
    )
)

Prompt:
Fix spelling for api/locality/:uuid URL

Closes #121

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url

from .views import LocalitiesAPI, LocalityAPI

urlpatterns = patterns(
    '',
    url(
        r'^localities$', LocalitiesAPI.as_view(),
        name='api_localities'
    ),
    url(
        r'^localitiy/(?P<uuid>\w{32})$', LocalityAPI.as_view(),
        name='api_locality'
    )
)


import unittest, os

import svn.core

class SubversionCoreTestCase(unittest.TestCase):
  """Test cases for the basic SWIG Subversion core"""

  def test_SubversionException(self):
    self.assertEqual(svn.core.SubversionException().args, ())
    self.assertEqual(svn.core.SubversionException('error message').args,
                     ('error message',))
    self.assertEqual(svn.core.SubversionException('error message', 1).args,
                     ('error message', 1))
    self.assertEqual(svn.core.SubversionException('error message', 1).apr_err,
                     1)
    self.assertEqual(svn.core.SubversionException('error message', 1).message,
                     'error message')

  def test_mime_type_is_binary(self):
    self.assertEqual(0, svn.core.svn_mime_type_is_binary("text/plain"))
    self.assertEqual(1, svn.core.svn_mime_type_is_binary("image/png"))

  def test_mime_type_validate(self):
    self.assertRaises(svn.core.SubversionException,
            svn.core.svn_mime_type_validate, "this\nis\ninvalid\n")
    svn.core.svn_mime_type_validate("unknown/but-valid; charset=utf8")

def suite():
    return unittest.makeSuite(SubversionCoreTestCase, 'test')

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())

Response:
<REPLACE_OLD> 1))

 <REPLACE_NEW> 1))
    self.assertEqual(svn.core.SubversionException('error message', 1).apr_err,
                     1)
    self.assertEqual(svn.core.SubversionException('error message', 1).message,
                     'error message')

 <REPLACE_END> <|endoftext|> import unittest, os

import svn.core

class SubversionCoreTestCase(unittest.TestCase):
  """Test cases for the basic SWIG Subversion core"""

  def test_SubversionException(self):
    self.assertEqual(svn.core.SubversionException().args, ())
    self.assertEqual(svn.core.SubversionException('error message').args,
                     ('error message',))
    self.assertEqual(svn.core.SubversionException('error message', 1).args,
                     ('error message', 1))
    self.assertEqual(svn.core.SubversionException('error message', 1).apr_err,
                     1)
    self.assertEqual(svn.core.SubversionException('error message', 1).message,
                     'error message')

  def test_mime_type_is_binary(self):
    self.assertEqual(0, svn.core.svn_mime_type_is_binary("text/plain"))
    self.assertEqual(1, svn.core.svn_mime_type_is_binary("image/png"))

  def test_mime_type_validate(self):
    self.assertRaises(svn.core.SubversionException,
            svn.core.svn_mime_type_validate, "this\nis\ninvalid\n")
    svn.core.svn_mime_type_validate("unknown/but-valid; charset=utf8")

def suite():
    return unittest.makeSuite(SubversionCoreTestCase, 'test')

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())

Prompt:
Add a regression test for the bug fixed in r28485.

* subversion/bindings/swig/python/tests/core.py
  (SubversionCoreTestCase.test_SubversionException): Test explicit
    exception fields.

git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@868579 13f79535-47bb-0310-9956-ffa450edef68

import unittest, os

import svn.core

class SubversionCoreTestCase(unittest.TestCase):
  """Test cases for the basic SWIG Subversion core"""

  def test_SubversionException(self):
    self.assertEqual(svn.core.SubversionException().args, ())
    self.assertEqual(svn.core.SubversionException('error message').args,
                     ('error message',))
    self.assertEqual(svn.core.SubversionException('error message', 1).args,
                     ('error message', 1))

  def test_mime_type_is_binary(self):
    self.assertEqual(0, svn.core.svn_mime_type_is_binary("text/plain"))
    self.assertEqual(1, svn.core.svn_mime_type_is_binary("image/png"))

  def test_mime_type_validate(self):
    self.assertRaises(svn.core.SubversionException,
            svn.core.svn_mime_type_validate, "this\nis\ninvalid\n")
    svn.core.svn_mime_type_validate("unknown/but-valid; charset=utf8")

def suite():
    return unittest.makeSuite(SubversionCoreTestCase, 'test')

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())


import sys
if sys.version_info < (2, 7):
    print sys.stderr, "{}: need Python 2.7 or later.".format(sys.argv[0])
    print sys.stderror, "Your python is {}".format(sys.version)
    sys.exit(1)

from setuptools import setup

setup(
    name = "python-json-logger",
    version = "0.0.1",
    url = "http://github.com/madzak/python-json-logger",
    license = "BSD",
    description = "A python library adding a json log formatter",
    author = "Zakaria Zajac",
    author_email = "zak@madzak.com",
    package_dir = {'': 'src'},
    packages = [''],
    test_suite = "tests.tests",
    install_requires = ['setuptools'],
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: System :: Logging',
    ]
)

Response:
<REPLACE_OLD> 1 <REPLACE_NEW> 3 <REPLACE_END> <REPLACE_OLD> 'Operation <REPLACE_NEW> 'Operating <REPLACE_END> <INSERT> System :: <INSERT_END> <|endoftext|> import sys
if sys.version_info < (2, 7):
    print sys.stderr, "{}: need Python 2.7 or later.".format(sys.argv[0])
    print sys.stderror, "Your python is {}".format(sys.version)
    sys.exit(1)

from setuptools import setup

setup(
    name = "python-json-logger",
    version = "0.0.1",
    url = "http://github.com/madzak/python-json-logger",
    license = "BSD",
    description = "A python library adding a json log formatter",
    author = "Zakaria Zajac",
    author_email = "zak@madzak.com",
    package_dir = {'': 'src'},
    packages = [''],
    test_suite = "tests.tests",
    install_requires = ['setuptools'],
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: System :: Logging',
    ]
)

Prompt:
Use trove classifiers from official list

(aligned with https://pypi.python.org/pypi?%3Aaction=list_classifiers)

import sys
if sys.version_info < (2, 7):
    print sys.stderr, "{}: need Python 2.7 or later.".format(sys.argv[0])
    print sys.stderror, "Your python is {}".format(sys.version)
    sys.exit(1)

from setuptools import setup

setup(
    name = "python-json-logger",
    version = "0.0.1",
    url = "http://github.com/madzak/python-json-logger",
    license = "BSD",
    description = "A python library adding a json log formatter",
    author = "Zakaria Zajac",
    author_email = "zak@madzak.com",
    package_dir = {'': 'src'},
    packages = [''],
    test_suite = "tests.tests",
    install_requires = ['setuptools'],
    classifiers = [
        'Development Status :: 1 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operation System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Logging',
    ]
)


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

import re
import uuid
import itertools as it

from abc import ABCMeta, abstractmethod

import numpy as np

class BaseReader(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self):
        pass

    @abstractmethod
    def _to_raw_pyfrm(self):
        pass

    def _optimize(self, mesh):
        # Sort interior interfaces
        for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
            mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]

    def to_pyfrm(self):
        mesh = self._to_raw_pyfrm()

        # Perform some simple optimizations on the mesh
        self._optimize(mesh)

        # Add metadata
        mesh['mesh_uuid'] = str(uuid.uuid4())

        return mesh

Response:
<REPLACE_OLD> uuid

from <REPLACE_NEW> re
import uuid
import itertools as it

from <REPLACE_END> <REPLACE_OLD> abstractmethod

class <REPLACE_NEW> abstractmethod

import numpy as np

class <REPLACE_END> <INSERT> _optimize(self, mesh):
        # Sort interior interfaces
        for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
            mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]

    def <INSERT_END> <INSERT>        # Perform some simple optimizations on the mesh
        self._optimize(mesh)

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

import re
import uuid
import itertools as it

from abc import ABCMeta, abstractmethod

import numpy as np

class BaseReader(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self):
        pass

    @abstractmethod
    def _to_raw_pyfrm(self):
        pass

    def _optimize(self, mesh):
        # Sort interior interfaces
        for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh):
            mesh[f] = mesh[f][:,np.argsort(mesh[f][0])]

    def to_pyfrm(self):
        mesh = self._to_raw_pyfrm()

        # Perform some simple optimizations on the mesh
        self._optimize(mesh)

        # Add metadata
        mesh['mesh_uuid'] = str(uuid.uuid4())

        return mesh

Prompt:
Add some simple optimizations into the mesh reader classes.

This yields a ~1.5% performance improvement.

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

import uuid

from abc import ABCMeta, abstractmethod

class BaseReader(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self):
        pass

    @abstractmethod
    def _to_raw_pyfrm(self):
        pass

    def to_pyfrm(self):
        mesh = self._to_raw_pyfrm()

        # Add metadata
        mesh['mesh_uuid'] = str(uuid.uuid4())

        return mesh


# coding=utf8
"""
ping.py - Sopel Ping Module
Author: Sean B. Palmer, inamidst.com
About: http://sopel.chat
"""
from __future__ import unicode_literals

import random
from sopel.module import rule, priority, thread

@rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$')
def hello(bot, trigger):
    greeting = random.choice(('Hi', 'Hey', 'Hello'))
    punctuation = random.choice(('', '!'))
    bot.say(greeting + ' ' + trigger.nick + punctuation)

@rule(r'(?i)(Fuck|Screw) you,? $nickname[ \t]*$')
def rude(bot, trigger):
    bot.say('Watch your mouth, ' + trigger.nick + ', or I\'ll tell your mother!')

@rule('$nickname!')
@priority('high')
@thread(False)
def interjection(bot, trigger):
    bot.say(trigger.nick + '!')

Response:
<DELETE>    if trigger.owner:
        greeting = random.choice(('Fuck off,', 'Screw you,', 'Go away'))
    else:
     <DELETE_END> <|endoftext|> # coding=utf8
"""
ping.py - Sopel Ping Module
Author: Sean B. Palmer, inamidst.com
About: http://sopel.chat
"""
from __future__ import unicode_literals

import random
from sopel.module import rule, priority, thread

@rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$')
def hello(bot, trigger):
    greeting = random.choice(('Hi', 'Hey', 'Hello'))
    punctuation = random.choice(('', '!'))
    bot.say(greeting + ' ' + trigger.nick + punctuation)

@rule(r'(?i)(Fuck|Screw) you,? $nickname[ \t]*$')
def rude(bot, trigger):
    bot.say('Watch your mouth, ' + trigger.nick + ', or I\'ll tell your mother!')

@rule('$nickname!')
@priority('high')
@thread(False)
def interjection(bot, trigger):
    bot.say(trigger.nick + '!')

Prompt:
Stop Sopel from relying rudely to the bot's owner.

# coding=utf8
"""
ping.py - Sopel Ping Module
Author: Sean B. Palmer, inamidst.com
About: http://sopel.chat
"""
from __future__ import unicode_literals

import random
from sopel.module import rule, priority, thread

@rule(r'(?i)(hi|hello|hey),? $nickname[ \t]*$')
def hello(bot, trigger):
    if trigger.owner:
        greeting = random.choice(('Fuck off,', 'Screw you,', 'Go away'))
    else:
        greeting = random.choice(('Hi', 'Hey', 'Hello'))
    punctuation = random.choice(('', '!'))
    bot.say(greeting + ' ' + trigger.nick + punctuation)

@rule(r'(?i)(Fuck|Screw) you,? $nickname[ \t]*$')
def rude(bot, trigger):
    bot.say('Watch your mouth, ' + trigger.nick + ', or I\'ll tell your mother!')

@rule('$nickname!')
@priority('high')
@thread(False)
def interjection(bot, trigger):
    bot.say(trigger.nick + '!')


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

class TestStartCondor(osgunittest.OSGTestCase):

    def test_01_start_condor(self):
        core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
        core.state['condor.started-service'] = False
        core.state['condor.running-service'] = False

        core.skip_ok_unless_installed('condor')
        if os.path.exists(core.config['condor.lockfile']):
            core.state['condor.running-service'] = True
            self.skip_ok('already running')

        command = ('service', 'condor', 'start')
        stdout, _, fail = core.check_system(command, 'Start Condor')
        self.assert_(stdout.find('error') == -1, fail)
        self.assert_(os.path.exists(core.config['condor.lockfile']),
                     'Condor run lock file missing')
        core.state['condor.started-service'] = True
        core.state['condor.running-service'] = True

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

 <REPLACE_NEW> TestStartCondor(osgunittest.OSGTestCase):

 <REPLACE_END> <REPLACE_OLD> if core.missing_rpm('condor'):
            return
 <REPLACE_NEW> core.skip_ok_unless_installed('condor')
 <REPLACE_END> <REPLACE_OLD> core.skip('apparently <REPLACE_NEW> self.skip_ok('already <REPLACE_END> <REPLACE_OLD> return

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

class TestStartCondor(osgunittest.OSGTestCase):

    def test_01_start_condor(self):
        core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
        core.state['condor.started-service'] = False
        core.state['condor.running-service'] = False

        core.skip_ok_unless_installed('condor')
        if os.path.exists(core.config['condor.lockfile']):
            core.state['condor.running-service'] = True
            self.skip_ok('already running')

        command = ('service', 'condor', 'start')
        stdout, _, fail = core.check_system(command, 'Start Condor')
        self.assert_(stdout.find('error') == -1, fail)
        self.assert_(os.path.exists(core.config['condor.lockfile']),
                     'Condor run lock file missing')
        core.state['condor.started-service'] = True
        core.state['condor.running-service'] = True

Prompt:
Update 10_condor to use OkSkip functionality

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

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

class TestStartCondor(unittest.TestCase):

    def test_01_start_condor(self):
        core.config['condor.lockfile'] = '/var/lock/subsys/condor_master'
        core.state['condor.started-service'] = False
        core.state['condor.running-service'] = False

        if core.missing_rpm('condor'):
            return
        if os.path.exists(core.config['condor.lockfile']):
            core.state['condor.running-service'] = True
            core.skip('apparently running')
            return

        command = ('service', 'condor', 'start')
        stdout, _, fail = core.check_system(command, 'Start Condor')
        self.assert_(stdout.find('error') == -1, fail)
        self.assert_(os.path.exists(core.config['condor.lockfile']),
                     'Condor run lock file missing')
        core.state['condor.started-service'] = True
        core.state['condor.running-service'] = True


# License under the MIT License - see LICENSE

import boto.ec2
import os
import time

def launch(key_name, region='us-west-2', image_id='ami-5189a661',
           instance_type='t2.micro', security_groups='launch-wizard-1',
           user_data=None, initial_check=True):
    '''
    '''

    if not isinstance(security_groups, list):
        security_groups = [security_groups]

    ec2 = boto.ec2.connect_to_region(region)

    reserve = ec2.run_instances(image_id, key_name=key_name,
                                instance_type=instance_type,
                                security_groups=security_groups,
                                user_data=user_data)

    inst = reserve.instances[0]

    while inst.state == u'pending':
        time.sleep(10)
        inst.update()

    # Wait for the status checks first
    status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    if initial_check:
        check_stat = "Status:initializing"

        while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
            time.sleep(10)
            status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    return inst

    # ec2.get_instance_attribute('i-336b69f6', 'instanceType')

Make the initialization wait optional

Make the initialization wait optional

Response:
<REPLACE_OLD> user_data=None):
 <REPLACE_NEW> user_data=None, initial_check=True):
 <REPLACE_END> <INSERT> if initial_check:
        <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> # License under the MIT License - see LICENSE

import boto.ec2
import os
import time

def launch(key_name, region='us-west-2', image_id='ami-5189a661',
           instance_type='t2.micro', security_groups='launch-wizard-1',
           user_data=None, initial_check=True):
    '''
    '''

    if not isinstance(security_groups, list):
        security_groups = [security_groups]

    ec2 = boto.ec2.connect_to_region(region)

    reserve = ec2.run_instances(image_id, key_name=key_name,
                                instance_type=instance_type,
                                security_groups=security_groups,
                                user_data=user_data)

    inst = reserve.instances[0]

    while inst.state == u'pending':
        time.sleep(10)
        inst.update()

    # Wait for the status checks first
    status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    if initial_check:
        check_stat = "Status:initializing"

        while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
            time.sleep(10)
            status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    return inst

    # ec2.get_instance_attribute('i-336b69f6', 'instanceType')

Prompt:
Make the initialization wait optional

# License under the MIT License - see LICENSE

import boto.ec2
import os
import time

def launch(key_name, region='us-west-2', image_id='ami-5189a661',
           instance_type='t2.micro', security_groups='launch-wizard-1',
           user_data=None):
    '''
    '''

    if not isinstance(security_groups, list):
        security_groups = [security_groups]

    ec2 = boto.ec2.connect_to_region(region)

    reserve = ec2.run_instances(image_id, key_name=key_name,
                                instance_type=instance_type,
                                security_groups=security_groups,
                                user_data=user_data)

    inst = reserve.instances[0]

    while inst.state == u'pending':
        time.sleep(10)
        inst.update()

    # Wait for the status checks first
    status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    check_stat = "Status:initializing"

    while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
        time.sleep(10)
        status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]

    return inst

    # ec2.get_instance_attribute('i-336b69f6', 'instanceType')


Create mapping of characters to percentage values

Response:
<INSERT> char_map = {
 <INSERT_END> <INSERT>   'a': 3,
    'b': 6,
    'c': 9,
    'd': 12,
    'e': 15,
    'f': 18,
    'g': 21,
    'h': 24,
    'i': 27,
    'j': 30,
    'k': 33,
    'l': 36,
    'm': 39,
    'n': 42,
    'o': 45,
    'p': 48,
    'q': 51,
    'r': 54,
    's': 57,
    't': 60,
    'u': 63,
    'v': 66,
    'w': 69,
    'x': 72,
    'y': 75,
    'z': 78,
    ' ': 81,
    '.': 84,
    '!': 87,
    '?': 90,
    'EOC': 93,  # End of Character value
    'EOF': 96  # End of String value
}
 <INSERT_END> <|endoftext|> char_map = {
    'a': 3,
    'b': 6,
    'c': 9,
    'd': 12,
    'e': 15,
    'f': 18,
    'g': 21,
    'h': 24,
    'i': 27,
    'j': 30,
    'k': 33,
    'l': 36,
    'm': 39,
    'n': 42,
    'o': 45,
    'p': 48,
    'q': 51,
    'r': 54,
    's': 57,
    't': 60,
    'u': 63,
    'v': 66,
    'w': 69,
    'x': 72,
    'y': 75,
    'z': 78,
    ' ': 81,
    '.': 84,
    '!': 87,
    '?': 90,
    'EOC': 93,  # End of Character value
    'EOF': 96  # End of String value
}

Prompt: Create mapping of characters to percentage values


import subprocess
import os

PYVER = "2.5"

# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])

# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)

# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)

Add top script to generate binaries from scratch.

git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@5553 94b884b6-d6fd-0310-90d3-974f1d3f35e1

Response:
<REPLACE_OLD>  <REPLACE_NEW> import subprocess
import os

PYVER = "2.5"

# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])

# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)

# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
 <REPLACE_END> <|endoftext|> import subprocess
import os

PYVER = "2.5"

# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])

# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)

# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)

Prompt:
Add top script to generate binaries from scratch.

git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@5553 94b884b6-d6fd-0310-90d3-974f1d3f35e1


#!/usr/bin/env python
"""Listing of VTEC events for a WFO and year"""
import cgi
import sys
import json

def report(wfo, year):
    """Generate a report of VTEC ETNs used for a WFO and year

    Args:
      wfo (str): 3 character WFO identifier
      year (int): year to run for
    """
    import psycopg2
    pgconn = psycopg2.connect(database='postgis', host='iemdb', user='nobody')
    cursor = pgconn.cursor()

    table = "warnings_%s" % (year,)
    cursor.execute("""
    SELECT distinct phenomena, significance, eventid,
    issue at time zone 'UTC' as utc_issue,
    init_expire at time zone 'UTC' as utc_expire from
    """+table+""" WHERE wfo = %s
    ORDER by phenomena ASC, significance ASC, utc_issue ASC
    """, (wfo,))
    print '%s report for %s' % (wfo, year)
    lastrow = [None]*5
    for row in cursor:
        if row[0] != lastrow[0] or row[1] != lastrow[1]:
            print '%2s %1s %-4s %20s %20s' % ('.', '.', '.', '.', '.')
        if (row[0] == lastrow[0] and row[1] == lastrow[1] and
            row[2] == lastrow[2] and
            (row[3] == lastrow[3] or row[4] == lastrow[4])):
            pass
        else:
            print '%2s %1s %-4s %20s %20s' % (row[0], row[1], row[2], row[3], row[4])
        lastrow = row

def main():
    """Main()"""
    form = cgi.FieldStorage()
    wfo = form.getfirst("wfo", "MPX")
    year = int(form.getfirst("year", 2015))
    sys.stdout.write("Content-type: text/plain\n\n")
    report(wfo, year)

if __name__ == '__main__':
    main()

Add quick hack of a VTEC listing, will make JSON when time permits

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
"""Listing of VTEC events for a WFO and year"""
import cgi
import sys
import json

def report(wfo, year):
    """Generate a report of VTEC ETNs used for a WFO and year

    Args:
      wfo (str): 3 character WFO identifier
      year (int): year to run for
    """
    import psycopg2
    pgconn = psycopg2.connect(database='postgis', host='iemdb', user='nobody')
    cursor = pgconn.cursor()

    table = "warnings_%s" % (year,)
    cursor.execute("""
    SELECT distinct phenomena, significance, eventid,
    issue at time zone 'UTC' as utc_issue,
    init_expire at time zone 'UTC' as utc_expire from
    """+table+""" WHERE wfo = %s
    ORDER by phenomena ASC, significance ASC, utc_issue ASC
    """, (wfo,))
    print '%s report for %s' % (wfo, year)
    lastrow = [None]*5
    for row in cursor:
        if row[0] != lastrow[0] or row[1] != lastrow[1]:
            print '%2s %1s %-4s %20s %20s' % ('.', '.', '.', '.', '.')
        if (row[0] == lastrow[0] and row[1] == lastrow[1] and
            row[2] == lastrow[2] and
            (row[3] == lastrow[3] or row[4] == lastrow[4])):
            pass
        else:
            print '%2s %1s %-4s %20s %20s' % (row[0], row[1], row[2], row[3], row[4])
        lastrow = row

def main():
    """Main()"""
    form = cgi.FieldStorage()
    wfo = form.getfirst("wfo", "MPX")
    year = int(form.getfirst("year", 2015))
    sys.stdout.write("Content-type: text/plain\n\n")
    report(wfo, year)

if __name__ == '__main__':
    main() <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""Listing of VTEC events for a WFO and year"""
import cgi
import sys
import json

def report(wfo, year):
    """Generate a report of VTEC ETNs used for a WFO and year

    Args:
      wfo (str): 3 character WFO identifier
      year (int): year to run for
    """
    import psycopg2
    pgconn = psycopg2.connect(database='postgis', host='iemdb', user='nobody')
    cursor = pgconn.cursor()

    table = "warnings_%s" % (year,)
    cursor.execute("""
    SELECT distinct phenomena, significance, eventid,
    issue at time zone 'UTC' as utc_issue,
    init_expire at time zone 'UTC' as utc_expire from
    """+table+""" WHERE wfo = %s
    ORDER by phenomena ASC, significance ASC, utc_issue ASC
    """, (wfo,))
    print '%s report for %s' % (wfo, year)
    lastrow = [None]*5
    for row in cursor:
        if row[0] != lastrow[0] or row[1] != lastrow[1]:
            print '%2s %1s %-4s %20s %20s' % ('.', '.', '.', '.', '.')
        if (row[0] == lastrow[0] and row[1] == lastrow[1] and
            row[2] == lastrow[2] and
            (row[3] == lastrow[3] or row[4] == lastrow[4])):
            pass
        else:
            print '%2s %1s %-4s %20s %20s' % (row[0], row[1], row[2], row[3], row[4])
        lastrow = row

def main():
    """Main()"""
    form = cgi.FieldStorage()
    wfo = form.getfirst("wfo", "MPX")
    year = int(form.getfirst("year", 2015))
    sys.stdout.write("Content-type: text/plain\n\n")
    report(wfo, year)

if __name__ == '__main__':
    main()

Prompt: Add quick hack of a VTEC listing, will make JSON when time permits


from __future__ import division
import numpy as np
import pandas as pd
import urllib2

# __author__ = 'mattmcd'

class LseReader:

    def __init__(self):
        dataLoc = '/home/mattmcd/Work/Data/'
        ftseFile =  dataLoc + 'FTSE100.csv'

        self.ftse100 = pd.read_csv( ftseFile )
        self.prefixURL = 'https://www.google.com/finance/getprices?'

    def read_history(self, ticker, interval=300, period=10):
        """Read intraday history for selected ticker on LSE"""
        txt = urllib2.urlopen(self.prefixURL +
                              'q={Ticker}&x=LON&i={Interval}&p={Period}d&f=d,o,h,l,c,v'.format(
            Ticker=ticker, Interval=interval, Period=period)).read()
        return txt

Read prices from Google Finance

Read prices from Google Finance

Response:
<INSERT> from __future__ import division
import numpy as np
import pandas as pd
import urllib2

# __author__ = 'mattmcd'

class LseReader:

 <INSERT_END> <INSERT>   def __init__(self):
        dataLoc = '/home/mattmcd/Work/Data/'
        ftseFile =  dataLoc + 'FTSE100.csv'

        self.ftse100 = pd.read_csv( ftseFile )
        self.prefixURL = 'https://www.google.com/finance/getprices?'

    def read_history(self, ticker, interval=300, period=10):
        """Read intraday history for selected ticker on LSE"""
        txt = urllib2.urlopen(self.prefixURL +
                              'q={Ticker}&x=LON&i={Interval}&p={Period}d&f=d,o,h,l,c,v'.format(
            Ticker=ticker, Interval=interval, Period=period)).read()
        return txt
 <INSERT_END> <|endoftext|> from __future__ import division
import numpy as np
import pandas as pd
import urllib2

# __author__ = 'mattmcd'

class LseReader:

    def __init__(self):
        dataLoc = '/home/mattmcd/Work/Data/'
        ftseFile =  dataLoc + 'FTSE100.csv'

        self.ftse100 = pd.read_csv( ftseFile )
        self.prefixURL = 'https://www.google.com/finance/getprices?'

    def read_history(self, ticker, interval=300, period=10):
        """Read intraday history for selected ticker on LSE"""
        txt = urllib2.urlopen(self.prefixURL +
                              'q={Ticker}&x=LON&i={Interval}&p={Period}d&f=d,o,h,l,c,v'.format(
            Ticker=ticker, Interval=interval, Period=period)).read()
        return txt

Prompt: Read prices from Google Finance


"""CVMFS Servcice."""
import os
import re
import cherrypy
import html
from natsort import natsorted

VERSION_RE = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$")

@cherrypy.popargs('appid')
class CVMFSAppVersions(object):
    """
    CVMFS App Version checking service.

    CVMFS Service to get the list of versions available
    on CVMFS for a given app.
    """

    def __init__(self, cvmfs_root, valid_apps):
        """Initialise."""
        self.cvmfs_root = cvmfs_root
        self.valid_apps = valid_apps

    @cherrypy.expose
    def index(self, appid=None):
        """Return the index page."""
        print "IN CVMFSAppVersion: appid=(%s)" % appid
        if appid not in self.valid_apps:
            print "Invalid app type %s" % appid
            return ''
        html_ = html.HTML()
        _, dirs, _ = os.walk(os.path.join(self.cvmfs_root, appid)).next()
        for dir_ in natsorted(dirs):
            for version in VERSION_RE.findall(dir_):
                html_.option(version)
        return str(html_)

Change the re const name to uppercase.

Change the re const name to uppercase.

Response:
<REPLACE_OLD> natsorted

version_re <REPLACE_NEW> natsorted

VERSION_RE <REPLACE_END> <REPLACE_OLD> version_re.findall(dir_):
 <REPLACE_NEW> VERSION_RE.findall(dir_):
 <REPLACE_END> <|endoftext|> """CVMFS Servcice."""
import os
import re
import cherrypy
import html
from natsort import natsorted

VERSION_RE = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$")

@cherrypy.popargs('appid')
class CVMFSAppVersions(object):
    """
    CVMFS App Version checking service.

    CVMFS Service to get the list of versions available
    on CVMFS for a given app.
    """

    def __init__(self, cvmfs_root, valid_apps):
        """Initialise."""
        self.cvmfs_root = cvmfs_root
        self.valid_apps = valid_apps

    @cherrypy.expose
    def index(self, appid=None):
        """Return the index page."""
        print "IN CVMFSAppVersion: appid=(%s)" % appid
        if appid not in self.valid_apps:
            print "Invalid app type %s" % appid
            return ''
        html_ = html.HTML()
        _, dirs, _ = os.walk(os.path.join(self.cvmfs_root, appid)).next()
        for dir_ in natsorted(dirs):
            for version in VERSION_RE.findall(dir_):
                html_.option(version)
        return str(html_)

Prompt:
Change the re const name to uppercase.

"""CVMFS Servcice."""
import os
import re
import cherrypy
import html
from natsort import natsorted

version_re = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$")

@cherrypy.popargs('appid')
class CVMFSAppVersions(object):
    """
    CVMFS App Version checking service.

    CVMFS Service to get the list of versions available
    on CVMFS for a given app.
    """

    def __init__(self, cvmfs_root, valid_apps):
        """Initialise."""
        self.cvmfs_root = cvmfs_root
        self.valid_apps = valid_apps

    @cherrypy.expose
    def index(self, appid=None):
        """Return the index page."""
        print "IN CVMFSAppVersion: appid=(%s)" % appid
        if appid not in self.valid_apps:
            print "Invalid app type %s" % appid
            return ''
        html_ = html.HTML()
        _, dirs, _ = os.walk(os.path.join(self.cvmfs_root, appid)).next()
        for dir_ in natsorted(dirs):
            for version in version_re.findall(dir_):
                html_.option(version)
        return str(html_)


# Do this first so that we bail early with a useful message if the user didn't
# specify [ipy3] or [ipy4].
try:
    import IPython  # noqa
except ImportError:
    raise ImportError(
        "No IPython installation found.\n"
        "To install pgcontents with the latest Jupyter Notebook"
        " run 'pip install pgcontents[ipy4]b'.\n"
        "To install with the legacy IPython Notebook"
        " run 'pip install pgcontents[ipy3]'.\n"
    )

from .checkpoints import PostgresCheckpoints
from .pgmanager import PostgresContentsManager

__all__ = [
    'PostgresCheckpoints',
    'PostgresContentsManager',
]

Add warning if IPython isn't installed.

Response:
<REPLACE_OLD> from <REPLACE_NEW> # Do this first so that we bail early with a useful message if the user didn't
# specify [ipy3] or [ipy4].
try:
    import IPython  # noqa
except ImportError:
    raise ImportError(
        "No IPython installation found.\n"
        "To install pgcontents with the latest Jupyter Notebook"
        " run 'pip install pgcontents[ipy4]b'.\n"
        "To install with the legacy IPython Notebook"
        " run 'pip install pgcontents[ipy3]'.\n"
    )

from <REPLACE_END> <|endoftext|> # Do this first so that we bail early with a useful message if the user didn't
# specify [ipy3] or [ipy4].
try:
    import IPython  # noqa
except ImportError:
    raise ImportError(
        "No IPython installation found.\n"
        "To install pgcontents with the latest Jupyter Notebook"
        " run 'pip install pgcontents[ipy4]b'.\n"
        "To install with the legacy IPython Notebook"
        " run 'pip install pgcontents[ipy3]'.\n"
    )

from .checkpoints import PostgresCheckpoints
from .pgmanager import PostgresContentsManager

__all__ = [
    'PostgresCheckpoints',
    'PostgresContentsManager',
]

Prompt:
DOC: Add warning if IPython isn't installed.

from .checkpoints import PostgresCheckpoints
from .pgmanager import PostgresContentsManager

__all__ = [
    'PostgresCheckpoints',
    'PostgresContentsManager',
]


from spack import *

class Mbedtls(Package):
    """
    mbed TLS (formerly known as PolarSSL) makes it trivially easy for developers to include cryptographic and SSL/TLS capabilities in their (embedded) products, facilitating this functionality with a minimal coding footprint.
    """
    homepage = "https://tls.mbed.org"
    url      = "https://github.com/ARMmbed/mbedtls/archive/mbedtls-2.2.1.tar.gz"

    version('2.2.1' , '73a38f96898d6d03e32f55dd9f9a67be')
    version('2.2.0' , 'eaf4586c1ef93ae872e606b6c1203942')
    version('2.1.4' , '40cdf67b6c6d92c9cbcfd552d39ea3ae')
    version('2.1.3' , '7eb4cf1dfa68578a2c8dbd0b6fa752dd')
    version('1.3.16', '4144d7320c691f721aeb9e67a1bc38e0')

    def install(self, spec, prefix):
        cmake('.', *std_cmake_args)

        make()
        make("install")

Support mbedtls, an alternative SSL library

Response:
<INSERT> from spack import *

class Mbedtls(Package):
 <INSERT_END> <INSERT>   """
    mbed TLS (formerly known as PolarSSL) makes it trivially easy for developers to include cryptographic and SSL/TLS capabilities in their (embedded) products, facilitating this functionality with a minimal coding footprint.
    """
    homepage = "https://tls.mbed.org"
    url      = "https://github.com/ARMmbed/mbedtls/archive/mbedtls-2.2.1.tar.gz"

    version('2.2.1' , '73a38f96898d6d03e32f55dd9f9a67be')
    version('2.2.0' , 'eaf4586c1ef93ae872e606b6c1203942')
    version('2.1.4' , '40cdf67b6c6d92c9cbcfd552d39ea3ae')
    version('2.1.3' , '7eb4cf1dfa68578a2c8dbd0b6fa752dd')
    version('1.3.16', '4144d7320c691f721aeb9e67a1bc38e0')

    def install(self, spec, prefix):
        cmake('.', *std_cmake_args)

        make()
        make("install")
 <INSERT_END> <|endoftext|> from spack import *

class Mbedtls(Package):
    """
    mbed TLS (formerly known as PolarSSL) makes it trivially easy for developers to include cryptographic and SSL/TLS capabilities in their (embedded) products, facilitating this functionality with a minimal coding footprint.
    """
    homepage = "https://tls.mbed.org"
    url      = "https://github.com/ARMmbed/mbedtls/archive/mbedtls-2.2.1.tar.gz"

    version('2.2.1' , '73a38f96898d6d03e32f55dd9f9a67be')
    version('2.2.0' , 'eaf4586c1ef93ae872e606b6c1203942')
    version('2.1.4' , '40cdf67b6c6d92c9cbcfd552d39ea3ae')
    version('2.1.3' , '7eb4cf1dfa68578a2c8dbd0b6fa752dd')
    version('1.3.16', '4144d7320c691f721aeb9e67a1bc38e0')

    def install(self, spec, prefix):
        cmake('.', *std_cmake_args)

        make()
        make("install")

Prompt: Support mbedtls, an alternative SSL library


import asyncio
import sys

# Use the selector event loop on windows. Do this in tornado/test/__init__.py
# instead of runtests.py so it happens no matter how the test is run (such as
# through editor integrations).
if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())  # type: ignore

Use selector event loop on windows.

test: Use selector event loop on windows.

This gets most of the tests working again on windows with py38.

Response:
<INSERT> import asyncio
import sys

# Use the selector event loop on windows. Do this in tornado/test/__init__.py
# instead of runtests.py so it happens no matter how the test is run (such as
# through editor integrations).
if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
 <INSERT_END> <INSERT>   asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())  # type: ignore
 <INSERT_END> <|endoftext|> import asyncio
import sys

# Use the selector event loop on windows. Do this in tornado/test/__init__.py
# instead of runtests.py so it happens no matter how the test is run (such as
# through editor integrations).
if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())  # type: ignore

Prompt:
test: Use selector event loop on windows.

This gets most of the tests working again on windows with py38.


import sys

def fixFormat(file_name):

    original = open(file_name, 'r')
    fixed_copy = open("fixed_" + file_name, 'w')

    for line in original:
        line = line.replace('<', '<')
        line = line.replace('>', '>')
        line = line.replace(""", '"')
        fixed_copy.write(line)

    original.close()
    fixed_copy.close()

file_name = sys.argv[1]
fixFormat(file_name)

Add core functionality for formatter

Add core functionality for formatter

Response:
<INSERT> import sys

def fixFormat(file_name):

 <INSERT_END> <INSERT>   original = open(file_name, 'r')
    fixed_copy = open("fixed_" + file_name, 'w')

    for line in original:
        line = line.replace('<', '<')
        line = line.replace('>', '>')
        line = line.replace(""", '"')
        fixed_copy.write(line)

    original.close()
    fixed_copy.close()

file_name = sys.argv[1]
fixFormat(file_name)
 <INSERT_END> <|endoftext|> import sys

def fixFormat(file_name):

    original = open(file_name, 'r')
    fixed_copy = open("fixed_" + file_name, 'w')

    for line in original:
        line = line.replace('<', '<')
        line = line.replace('>', '>')
        line = line.replace(""", '"')
        fixed_copy.write(line)

    original.close()
    fixed_copy.close()

file_name = sys.argv[1]
fixFormat(file_name)

Prompt: Add core functionality for formatter


from django.contrib.auth.models import Permission
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from cardbox.card_model import Card
from cardbox.deck_model import Deck
from guardian.shortcuts import assign_perm, get_users_with_perms
from guardian.models    import UserObjectPermission
from memorize.models import Practice
from django.contrib.auth.models import User

@receiver(post_save, sender=UserObjectPermission)
def create_practice_objects_for_new_viewers(sender, **kwargs):
    if kwargs['instance'].permission_id == Permission.objects.get(codename="view_deck").id:
        for card in Card.objects.filter(deck=kwargs['instance'].object_pk):
            Practice(item=card, user=User.objects.get(id = kwargs['instance'].user_id)).save()

@receiver(pre_delete, sender=UserObjectPermission)
def delete_practice_objects_for_removed_viewers(sender, **kwargs):
    if kwargs['instance'].permission_id == Permission.objects.get(codename="view_deck").id:
        for card in Card.objects.filter(deck=kwargs['instance'].object_pk):
            Practice.objects.get(object_id=card.ID, user=User.objects.get(id = kwargs['instance'].user_id)).delete()

@receiver(post_save, sender=Card)
def create_practice_objects_for_new_card(sender,update_fields, **kwargs):
    """Creates practice objects for all users with permission to view the card.

    """
    perm_users = get_users_with_perms(kwargs['instance'].deck)
    for user in perm_users:
        practice = Practice(item = kwargs['instance'], user = user)
        if Practice.objects.filter(object_id = kwargs['instance'].ID, user=user).count() == 0:
            practice.save()

@receiver(pre_delete, sender=Card)
def delete_practice_objects(sender, **kwargs):
    """Deletes all practice objects for a card once it is deleted.

    """
    Practice.objects.filter(object_id = kwargs['instance'].ID).delete()

Response:
<REPLACE_OLD> django.db import models

# Create your models here.
 <REPLACE_NEW> django.contrib.auth.models import Permission
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from cardbox.card_model import Card
from cardbox.deck_model import Deck
from guardian.shortcuts import assign_perm, get_users_with_perms
from guardian.models    import UserObjectPermission
from memorize.models import Practice
from django.contrib.auth.models import User

@receiver(post_save, sender=UserObjectPermission)
def create_practice_objects_for_new_viewers(sender, **kwargs):
    if kwargs['instance'].permission_id == Permission.objects.get(codename="view_deck").id:
        for card in Card.objects.filter(deck=kwargs['instance'].object_pk):
            Practice(item=card, user=User.objects.get(id = kwargs['instance'].user_id)).save()

@receiver(pre_delete, sender=UserObjectPermission)
def delete_practice_objects_for_removed_viewers(sender, **kwargs):
    if kwargs['instance'].permission_id == Permission.objects.get(codename="view_deck").id:
        for card in Card.objects.filter(deck=kwargs['instance'].object_pk):
            Practice.objects.get(object_id=card.ID, user=User.objects.get(id = kwargs['instance'].user_id)).delete()

@receiver(post_save, sender=Card)
def create_practice_objects_for_new_card(sender,update_fields, **kwargs):
    """Creates practice objects for all users with permission to view the card.

    """
    perm_users = get_users_with_perms(kwargs['instance'].deck)
    for user in perm_users:
        practice = Practice(item = kwargs['instance'], user = user)
        if Practice.objects.filter(object_id = kwargs['instance'].ID, user=user).count() == 0:
            practice.save()

@receiver(pre_delete, sender=Card)
def delete_practice_objects(sender, **kwargs):
    """Deletes all practice objects for a card once it is deleted.

    """
    Practice.objects.filter(object_id = kwargs['instance'].ID).delete()

 <REPLACE_END> <|endoftext|> from django.contrib.auth.models import Permission
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from cardbox.card_model import Card
from cardbox.deck_model import Deck
from guardian.shortcuts import assign_perm, get_users_with_perms
from guardian.models    import UserObjectPermission
from memorize.models import Practice
from django.contrib.auth.models import User

@receiver(post_save, sender=UserObjectPermission)
def create_practice_objects_for_new_viewers(sender, **kwargs):
    if kwargs['instance'].permission_id == Permission.objects.get(codename="view_deck").id:
        for card in Card.objects.filter(deck=kwargs['instance'].object_pk):
            Practice(item=card, user=User.objects.get(id = kwargs['instance'].user_id)).save()

@receiver(pre_delete, sender=UserObjectPermission)
def delete_practice_objects_for_removed_viewers(sender, **kwargs):
    if kwargs['instance'].permission_id == Permission.objects.get(codename="view_deck").id:
        for card in Card.objects.filter(deck=kwargs['instance'].object_pk):
            Practice.objects.get(object_id=card.ID, user=User.objects.get(id = kwargs['instance'].user_id)).delete()

@receiver(post_save, sender=Card)
def create_practice_objects_for_new_card(sender,update_fields, **kwargs):
    """Creates practice objects for all users with permission to view the card.

    """
    perm_users = get_users_with_perms(kwargs['instance'].deck)
    for user in perm_users:
        practice = Practice(item = kwargs['instance'], user = user)
        if Practice.objects.filter(object_id = kwargs['instance'].ID, user=user).count() == 0:
            practice.save()

@receiver(pre_delete, sender=Card)
def delete_practice_objects(sender, **kwargs):
    """Deletes all practice objects for a card once it is deleted.

    """
    Practice.objects.filter(object_id = kwargs['instance'].ID).delete()

Prompt:
Add signal hooks to create practice objects

from django.db import models

# Create your models here.


import os
import unittest

import opensim as osim

test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
                        'tests')

# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)

class TestComponentInterface(unittest.TestCase):
    def test_printComponentsMatching(self):
        model = osim.Model(os.path.join(test_dir,
            "gait10dof18musc_subject01.osim"))
        model.finalizeFromProperties();
        num_matches = model.printComponentsMatching("_r")
        self.assertEquals(num_matches, 126)
    def test_attachGeometry_memory_management(self):
        model = osim.Model()
        model.getGround().attachGeometry(osim.Sphere(1.5))

Response:
<REPLACE_OLD> 98)
 <REPLACE_NEW> 126)
 <REPLACE_END> <|endoftext|> import os
import unittest

import opensim as osim

test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
                        'tests')

# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)

class TestComponentInterface(unittest.TestCase):
    def test_printComponentsMatching(self):
        model = osim.Model(os.path.join(test_dir,
            "gait10dof18musc_subject01.osim"))
        model.finalizeFromProperties();
        num_matches = model.printComponentsMatching("_r")
        self.assertEquals(num_matches, 126)
    def test_attachGeometry_memory_management(self):
        model = osim.Model()
        model.getGround().attachGeometry(osim.Sphere(1.5))

Prompt:
Update the number of components listed in the model.

import os
import unittest

import opensim as osim

test_dir = os.path.join(os.path.dirname(os.path.abspath(osim.__file__)),
                        'tests')

# Silence warning messages if mesh (.vtp) files cannot be found.
osim.Model.setDebugLevel(0)

class TestComponentInterface(unittest.TestCase):
    def test_printComponentsMatching(self):
        model = osim.Model(os.path.join(test_dir,
            "gait10dof18musc_subject01.osim"))
        model.finalizeFromProperties();
        num_matches = model.printComponentsMatching("_r")
        self.assertEquals(num_matches, 98)
    def test_attachGeometry_memory_management(self):
        model = osim.Model()
        model.getGround().attachGeometry(osim.Sphere(1.5))


from .. import ControllerTestCase, url

class TestHomeController(ControllerTestCase):

    def test_index(self):
        response = self.app.get(url(controller='home', action='index'))
        assert 'OpenSpending' in response

    def test_locale(self):
        response = self.app.get(url(controller='home', action='set_locale'))

Fix test for locale route generation.

Fix test for locale route generation.

Response:
<REPLACE_OLD> action='locale'))
 <REPLACE_NEW> action='set_locale'))
 <REPLACE_END> <|endoftext|> from .. import ControllerTestCase, url

class TestHomeController(ControllerTestCase):

    def test_index(self):
        response = self.app.get(url(controller='home', action='index'))
        assert 'OpenSpending' in response

    def test_locale(self):
        response = self.app.get(url(controller='home', action='set_locale'))

Prompt:
Fix test for locale route generation.
from .. import ControllerTestCase, url

class TestHomeController(ControllerTestCase):

    def test_index(self):
        response = self.app.get(url(controller='home', action='index'))
        assert 'OpenSpending' in response

    def test_locale(self):
        response = self.app.get(url(controller='home', action='locale'))


import sys
import sqlparse
from .checks import has_cross_join

def parse_file(filename):
    return open(filename, 'r').readlines()

CHECKS = (
    (has_cross_join, 'query contains cross join'),
)

def check_query(el):
    """
    Run each of the defined checks on a query.
    """
    stmt = sqlparse.parse(el)
    for check in CHECKS:
        if check[0](stmt[0]):
            return False, check[1]
    return True, ''

def main():
    argv = sys.argv
    try:
        queries = parse_file(argv[1])
    except IndexError:
        raise Exception('Filename required')
    failed = False
    for query in queries:
        passed, message = check_query(query)
        if not passed:
            failed = True
            print_message(message, query)
    sys.exit(255 if failed else 0)

def print_message(message, query):
    print "FAILED - %s" % (message)
    print "-----------------------------------------------------------------"
    print
    print "Query:"
    print "%s" % query

Work with plain SQL files

Work with plain SQL files

Response:
<REPLACE_OLD> import json
    with <REPLACE_NEW> return <REPLACE_END> <REPLACE_OLD> 'r') as fh:
        return json.load(fh)

CHECKS <REPLACE_NEW> 'r').readlines()

CHECKS <REPLACE_END> <REPLACE_OLD> query, tests <REPLACE_NEW> query <REPLACE_END> <REPLACE_OLD> queries.iteritems():
 <REPLACE_NEW> queries:
 <REPLACE_END> <DELETE> tests, <DELETE_END> <DELETE> tests, <DELETE_END> <DELETE> print "Test Methods:"
    print "%s" % "\n".join(tests)
    <DELETE_END> <|endoftext|> import sys
import sqlparse
from .checks import has_cross_join

def parse_file(filename):
    return open(filename, 'r').readlines()

CHECKS = (
    (has_cross_join, 'query contains cross join'),
)

def check_query(el):
    """
    Run each of the defined checks on a query.
    """
    stmt = sqlparse.parse(el)
    for check in CHECKS:
        if check[0](stmt[0]):
            return False, check[1]
    return True, ''

def main():
    argv = sys.argv
    try:
        queries = parse_file(argv[1])
    except IndexError:
        raise Exception('Filename required')
    failed = False
    for query in queries:
        passed, message = check_query(query)
        if not passed:
            failed = True
            print_message(message, query)
    sys.exit(255 if failed else 0)

def print_message(message, query):
    print "FAILED - %s" % (message)
    print "-----------------------------------------------------------------"
    print
    print "Query:"
    print "%s" % query

Prompt:
Work with plain SQL files

import sys
import sqlparse
from .checks import has_cross_join

def parse_file(filename):
    import json
    with open(filename, 'r') as fh:
        return json.load(fh)

CHECKS = (
    (has_cross_join, 'query contains cross join'),
)

def check_query(el):
    """
    Run each of the defined checks on a query.
    """
    stmt = sqlparse.parse(el)
    for check in CHECKS:
        if check[0](stmt[0]):
            return False, check[1]
    return True, ''

def main():
    argv = sys.argv
    try:
        queries = parse_file(argv[1])
    except IndexError:
        raise Exception('Filename required')
    failed = False
    for query, tests in queries.iteritems():
        passed, message = check_query(query)
        if not passed:
            failed = True
            print_message(message, tests, query)
    sys.exit(255 if failed else 0)

def print_message(message, tests, query):
    print "FAILED - %s" % (message)
    print "-----------------------------------------------------------------"
    print "Test Methods:"
    print "%s" % "\n".join(tests)
    print
    print "Query:"
    print "%s" % query


import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt

def main():
    tau = pm.rdiscrete_uniform(0, 80)
    print tau

    alpha = 1. / 20.
    lambda_1, lambda_2 = pm.rexponential(alpha, 2)
    print lambda_1, lambda_2

    data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]

    def plot_artificial_sms_dataset():
        tau = pm.rdiscrete_uniform(0, 80)
        alpha = 1. / 20.
        lambda_1, lambda_2 = pm.rexponential(alpha, 2)
        data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
        plt.bar(np.arange(80), data, color="#348ABD")
        plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
        plt.xlim(0, 80)

    plt.title("More example of artificial datasets")
    for i in range(1, 5):
        plt.subplot(4, 1, i)
        plot_artificial_sms_dataset()
    plt.show()

if __name__ == '__main__':
    main()

Response:
<DELETE>    matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
    matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))

 <DELETE_END> <|endoftext|> import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt

def main():
    tau = pm.rdiscrete_uniform(0, 80)
    print tau

    alpha = 1. / 20.
    lambda_1, lambda_2 = pm.rexponential(alpha, 2)
    print lambda_1, lambda_2

    data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]

    def plot_artificial_sms_dataset():
        tau = pm.rdiscrete_uniform(0, 80)
        alpha = 1. / 20.
        lambda_1, lambda_2 = pm.rexponential(alpha, 2)
        data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
        plt.bar(np.arange(80), data, color="#348ABD")
        plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
        plt.xlim(0, 80)

    plt.title("More example of artificial datasets")
    for i in range(1, 5):
        plt.subplot(4, 1, i)
        plot_artificial_sms_dataset()
    plt.show()

if __name__ == '__main__':
    main()

Prompt:
Change of repo name. Update effected paths

import json
import matplotlib
import numpy as np
import pymc as pm
from matplotlib import pyplot as plt

def main():
    matplotlibrc_path = '/home/noel/repo/playground/matplotlibrc.json'
    matplotlib.rcParams.update(json.load(open(matplotlibrc_path)))

    tau = pm.rdiscrete_uniform(0, 80)
    print tau

    alpha = 1. / 20.
    lambda_1, lambda_2 = pm.rexponential(alpha, 2)
    print lambda_1, lambda_2

    data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]

    def plot_artificial_sms_dataset():
        tau = pm.rdiscrete_uniform(0, 80)
        alpha = 1. / 20.
        lambda_1, lambda_2 = pm.rexponential(alpha, 2)
        data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)]
        plt.bar(np.arange(80), data, color="#348ABD")
        plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed")
        plt.xlim(0, 80)

    plt.title("More example of artificial datasets")
    for i in range(1, 5):
        plt.subplot(4, 1, i)
        plot_artificial_sms_dataset()
    plt.show()

if __name__ == '__main__':
    main()


#!/usr/bin/env python
import sys

import fedmsg.config
import fmn.lib.models

config = fedmsg.config.load_config()
uri = config.get('fmn.sqlalchemy.uri')
if not uri:
    raise ValueError("fmn.sqlalchemy.uri must be present")

if '-h' in sys.argv or '--help'in sys.argv:
    print "createdb.py [--with-dev-data]"
    sys.exit(0)

session = fmn.lib.models.init(uri, debug=True, create=True)

if '--with-dev-data' in sys.argv:
    context1 = fmn.lib.models.Context.create(
        session, name="irc", description="Internet Relay Chat",
        detail_name="irc nick", icon="user",
        placeholder="z3r0_c00l",
    )
    context2 = fmn.lib.models.Context.create(
        session, name="email", description="Electronic Mail",
        detail_name="email address", icon="envelope",
        placeholder="jane@fedoraproject.org",
    )
    context3 = fmn.lib.models.Context.create(
        session, name="android", description="Google Cloud Messaging",
        detail_name="registration id", icon="phone",
        placeholder="laksdjfasdlfkj183097falkfj109f"
    )
    context4 = fmn.lib.models.Context.create(
        session, name="desktop", description="fedmsg-notify",
        detail_name="None", icon="console",
        placeholder="There's no need to put a value here"
    )
    session.commit()

Response:
<INSERT> context4 = fmn.lib.models.Context.create(
        session, name="desktop", description="fedmsg-notify",
        detail_name="None", icon="console",
        placeholder="There's no need to put a value here"
    )
    <INSERT_END> <|endoftext|> #!/usr/bin/env python
import sys

import fedmsg.config
import fmn.lib.models

config = fedmsg.config.load_config()
uri = config.get('fmn.sqlalchemy.uri')
if not uri:
    raise ValueError("fmn.sqlalchemy.uri must be present")

if '-h' in sys.argv or '--help'in sys.argv:
    print "createdb.py [--with-dev-data]"
    sys.exit(0)

session = fmn.lib.models.init(uri, debug=True, create=True)

if '--with-dev-data' in sys.argv:
    context1 = fmn.lib.models.Context.create(
        session, name="irc", description="Internet Relay Chat",
        detail_name="irc nick", icon="user",
        placeholder="z3r0_c00l",
    )
    context2 = fmn.lib.models.Context.create(
        session, name="email", description="Electronic Mail",
        detail_name="email address", icon="envelope",
        placeholder="jane@fedoraproject.org",
    )
    context3 = fmn.lib.models.Context.create(
        session, name="android", description="Google Cloud Messaging",
        detail_name="registration id", icon="phone",
        placeholder="laksdjfasdlfkj183097falkfj109f"
    )
    context4 = fmn.lib.models.Context.create(
        session, name="desktop", description="fedmsg-notify",
        detail_name="None", icon="console",
        placeholder="There's no need to put a value here"
    )
    session.commit()

Prompt:
Add the desktop context to the setup script.

#!/usr/bin/env python
import sys

import fedmsg.config
import fmn.lib.models

config = fedmsg.config.load_config()
uri = config.get('fmn.sqlalchemy.uri')
if not uri:
    raise ValueError("fmn.sqlalchemy.uri must be present")

if '-h' in sys.argv or '--help'in sys.argv:
    print "createdb.py [--with-dev-data]"
    sys.exit(0)

session = fmn.lib.models.init(uri, debug=True, create=True)

if '--with-dev-data' in sys.argv:
    context1 = fmn.lib.models.Context.create(
        session, name="irc", description="Internet Relay Chat",
        detail_name="irc nick", icon="user",
        placeholder="z3r0_c00l",
    )
    context2 = fmn.lib.models.Context.create(
        session, name="email", description="Electronic Mail",
        detail_name="email address", icon="envelope",
        placeholder="jane@fedoraproject.org",
    )
    context3 = fmn.lib.models.Context.create(
        session, name="android", description="Google Cloud Messaging",
        detail_name="registration id", icon="phone",
        placeholder="laksdjfasdlfkj183097falkfj109f"
    )
    session.commit()


from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
	"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"

if os.environ.get('HEROKU') == 1:
	app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGODB_URI")

db = MongoEngine(app)
app.register_blueprint(mocks)

if __name__ == '__main__':
	app.run()

Fix up settings for Heroku

Fix up settings for Heroku

Response:
<REPLACE_OLD> os.environ.get('PRODUCTION'):
	app.config["MONGODB_SETTINGS"]["host"] <REPLACE_NEW> os.environ.get('HEROKU') == 1:
	app.config["MONGODB_SETTINGS"]["host"] <REPLACE_END> <REPLACE_OLD> os.environ.get("PROD_MONGODB")

db <REPLACE_NEW> os.environ.get("MONGODB_URI")

db <REPLACE_END> <|endoftext|> from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
	"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"

if os.environ.get('HEROKU') == 1:
	app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("MONGODB_URI")

db = MongoEngine(app)
app.register_blueprint(mocks)

if __name__ == '__main__':
	app.run()

Prompt:
Fix up settings for Heroku

from flask import Flask
from flask.ext.mongoengine import MongoEngine
from views import mocks
import os

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {
	"db": "mox"
}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"

if os.environ.get('PRODUCTION'):
	app.config["MONGODB_SETTINGS"]["host"] = os.environ.get("PROD_MONGODB")

db = MongoEngine(app)
app.register_blueprint(mocks)

if __name__ == '__main__':
	app.run()


import platform
import io

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

RUNNING_IN_HELL = platform.system() == 'Windows'
RUNNING_IN_STEVE_JOBS = platform.system() == 'Darwin'
RUNNING_IN_GANOO_LOONIX = platform.system() == 'Linux'

def Pixmap2StringIO(pixmap):

    byteArray = QByteArray()
    buffer = QBuffer(byteArray)

    buffer.open(QIODevice.WriteOnly)
    pixmap.save(buffer, "PNG")

    strio = io.StringIO(byteArray)
    strio.seek(0)

    return strio

Response:
<REPLACE_OLD> platform

RUNNING_IN_HELL <REPLACE_NEW> platform
import io

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

RUNNING_IN_HELL <REPLACE_END> <REPLACE_OLD> 'Linux' <REPLACE_NEW> 'Linux'

def Pixmap2StringIO(pixmap):

    byteArray = QByteArray()
    buffer = QBuffer(byteArray)

    buffer.open(QIODevice.WriteOnly)
    pixmap.save(buffer, "PNG")

    strio = io.StringIO(byteArray)
    strio.seek(0)

    return strio
 <REPLACE_END> <|endoftext|> import platform
import io

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

RUNNING_IN_HELL = platform.system() == 'Windows'
RUNNING_IN_STEVE_JOBS = platform.system() == 'Darwin'
RUNNING_IN_GANOO_LOONIX = platform.system() == 'Linux'

def Pixmap2StringIO(pixmap):

    byteArray = QByteArray()
    buffer = QBuffer(byteArray)

    buffer.open(QIODevice.WriteOnly)
    pixmap.save(buffer, "PNG")

    strio = io.StringIO(byteArray)
    strio.seek(0)

    return strio

Prompt:
Write Pixmap to a StringIO for uploading.

import platform

RUNNING_IN_HELL = platform.system() == 'Windows'
RUNNING_IN_STEVE_JOBS = platform.system() == 'Darwin'
RUNNING_IN_GANOO_LOONIX = platform.system() == 'Linux'


import subprocess
import time

class PackageData(object):
    def __init__(self, local_file, name, version):
        self.local_file = local_file
        self.name = name
        self.version = version

    def __getattr__(self, name):
        if name in self.__dict__:
            return self.__dict__[name]

        return 'TODO:'

    @property
    def pkg_name(self, name):
        if self.name.lower().find('py') != -1:
            return self.name
        else:
            return 'python-%s'

    @property
    def changelog_date_packager(self):
        packager = subprocess.Popen('rpmdev-packager', stdout = subprocess.PIPE).communicate()[0].strip()
        date_str = time.strftime('%a %b %d %Y', time.gmtime())
        return "%s %s" % (date_str, packager)

class PypiData(PackageData):
    def __init__(self, local_file, name, version, md5, url):
        super(PackageData, self).__init__(local_file, name, version)
        self.md5 = md5
        self.url = url

class LocalData(PackageData):
    def __init__(self, local_file, name, version):
        super(PackageData, self).__init__(local_file, name, version)

Response:
<REPLACE_OLD> class <REPLACE_NEW> import subprocess
import time

class <REPLACE_END> <REPLACE_OLD> 'python-%s'

class <REPLACE_NEW> 'python-%s'

    @property
    def changelog_date_packager(self):
        packager = subprocess.Popen('rpmdev-packager', stdout = subprocess.PIPE).communicate()[0].strip()
        date_str = time.strftime('%a %b %d %Y', time.gmtime())
        return "%s %s" % (date_str, packager)

class <REPLACE_END> <|endoftext|> import subprocess
import time

class PackageData(object):
    def __init__(self, local_file, name, version):
        self.local_file = local_file
        self.name = name
        self.version = version

    def __getattr__(self, name):
        if name in self.__dict__:
            return self.__dict__[name]

        return 'TODO:'

    @property
    def pkg_name(self, name):
        if self.name.lower().find('py') != -1:
            return self.name
        else:
            return 'python-%s'

    @property
    def changelog_date_packager(self):
        packager = subprocess.Popen('rpmdev-packager', stdout = subprocess.PIPE).communicate()[0].strip()
        date_str = time.strftime('%a %b %d %Y', time.gmtime())
        return "%s %s" % (date_str, packager)

class PypiData(PackageData):
    def __init__(self, local_file, name, version, md5, url):
        super(PackageData, self).__init__(local_file, name, version)
        self.md5 = md5
        self.url = url

class LocalData(PackageData):
    def __init__(self, local_file, name, version):
        super(PackageData, self).__init__(local_file, name, version)

Prompt:
Add functionality to construct changelog entries

class PackageData(object):
    def __init__(self, local_file, name, version):
        self.local_file = local_file
        self.name = name
        self.version = version

    def __getattr__(self, name):
        if name in self.__dict__:
            return self.__dict__[name]

        return 'TODO:'

    @property
    def pkg_name(self, name):
        if self.name.lower().find('py') != -1:
            return self.name
        else:
            return 'python-%s'

class PypiData(PackageData):
    def __init__(self, local_file, name, version, md5, url):
        super(PackageData, self).__init__(local_file, name, version)
        self.md5 = md5
        self.url = url

class LocalData(PackageData):
    def __init__(self, local_file, name, version):
        super(PackageData, self).__init__(local_file, name, version)


import sys
import os
from cx_Freeze import setup, Executable

paths = []
paths.extend(sys.path)
paths.append('src')

build_exe_options = {
	'path': paths,
	'packages': ['whacked4'],
	'include_files': ['res', 'cfg', 'docs', 'LICENSE', 'README.md'],
	'optimize': 2,
	'include_msvcr': True
}

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

exe = Executable(
	'src/main.py',
	base=base,
	targetName=os.environ['app_name_lower'] + '.exe',
	icon='res/icon-hatchet.ico'
)

setup(
	name = os.environ['app_title'],
	version = os.environ['app_version_value'],
	description = os.environ['app_description'],
	options = {'build_exe': build_exe_options},
	executables = [exe]
)

Response:
<REPLACE_OLD> []
paths.extend(sys.path)
paths.append('whacked4')

build_exe_options <REPLACE_NEW> []
paths.extend(sys.path)
paths.append('src')

build_exe_options <REPLACE_END> <REPLACE_OLD> {
	'packages': [],
	'path': paths,
	'include_files': <REPLACE_NEW> {
	'path': paths,
	'packages': ['whacked4'],
	'include_files': <REPLACE_END> <REPLACE_OLD> True
}
build_exe_options['path'].append('src')

base <REPLACE_NEW> True
}

base <REPLACE_END> <|endoftext|> import sys
import os
from cx_Freeze import setup, Executable

paths = []
paths.extend(sys.path)
paths.append('src')

build_exe_options = {
	'path': paths,
	'packages': ['whacked4'],
	'include_files': ['res', 'cfg', 'docs', 'LICENSE', 'README.md'],
	'optimize': 2,
	'include_msvcr': True
}

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

exe = Executable(
	'src/main.py',
	base=base,
	targetName=os.environ['app_name_lower'] + '.exe',
	icon='res/icon-hatchet.ico'
)

setup(
	name = os.environ['app_title'],
	version = os.environ['app_version_value'],
	description = os.environ['app_description'],
	options = {'build_exe': build_exe_options},
	executables = [exe]
)

Prompt:
Update distutils script. Release builds still twice the size though...

import sys
import os
from cx_Freeze import setup, Executable

paths = []
paths.extend(sys.path)
paths.append('whacked4')

build_exe_options = {
	'packages': [],
	'path': paths,
	'include_files': ['res', 'cfg', 'docs', 'LICENSE', 'README.md'],
	'optimize': 2,
	'include_msvcr': True
}
build_exe_options['path'].append('src')

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

exe = Executable(
	'src/main.py',
	base=base,
	targetName=os.environ['app_name_lower'] + '.exe',
	icon='res/icon-hatchet.ico'
)

setup(
	name = os.environ['app_title'],
	version = os.environ['app_version_value'],
	description = os.environ['app_description'],
	options = {'build_exe': build_exe_options},
	executables = [exe]
)


from __future__ import absolute_import

import datetime as dt
import feedparser
from types import StringTypes

from comics.aggregator.lxmlparser import LxmlParser

class FeedParser(object):
    def __init__(self, url):
        self.raw_feed = feedparser.parse(url)

    def for_date(self, date):
        return [Entry(e) for e in self.raw_feed.entries
            if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]

    def all(self):
        return [Entry(e) for e in self.raw_feed.entries]

class Entry(object):
    def __init__(self, entry):
        self.raw_entry = entry
        if 'summary' in entry:
            self.summary = self.html(entry.summary)
        if 'content' in entry:
            self.content0 = self.html(entry.content[0].value)

    def __getattr__(self, name):
        return getattr(self.raw_entry, name)

    def html(self, string):
        return LxmlParser(string=string)

    def has_tag(self, tag):
        if ('tags' in self.raw_entry and
                len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
            return True
        return False

Response:
<DELETE> def matches_tag(item):
            return item.term == tag
        <DELETE_END> <REPLACE_OLD> len(filter(matches_tag, self.raw_entry['tags']))):
 <REPLACE_NEW> len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
 <REPLACE_END> <|endoftext|> from __future__ import absolute_import

import datetime as dt
import feedparser
from types import StringTypes

from comics.aggregator.lxmlparser import LxmlParser

class FeedParser(object):
    def __init__(self, url):
        self.raw_feed = feedparser.parse(url)

    def for_date(self, date):
        return [Entry(e) for e in self.raw_feed.entries
            if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]

    def all(self):
        return [Entry(e) for e in self.raw_feed.entries]

class Entry(object):
    def __init__(self, entry):
        self.raw_entry = entry
        if 'summary' in entry:
            self.summary = self.html(entry.summary)
        if 'content' in entry:
            self.content0 = self.html(entry.content[0].value)

    def __getattr__(self, name):
        return getattr(self.raw_entry, name)

    def html(self, string):
        return LxmlParser(string=string)

    def has_tag(self, tag):
        if ('tags' in self.raw_entry and
                len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
            return True
        return False

Prompt:
Replace inner function with lambda in FeedParser.has_tag()

from __future__ import absolute_import

import datetime as dt
import feedparser
from types import StringTypes

from comics.aggregator.lxmlparser import LxmlParser

class FeedParser(object):
    def __init__(self, url):
        self.raw_feed = feedparser.parse(url)

    def for_date(self, date):
        return [Entry(e) for e in self.raw_feed.entries
            if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]

    def all(self):
        return [Entry(e) for e in self.raw_feed.entries]

class Entry(object):
    def __init__(self, entry):
        self.raw_entry = entry
        if 'summary' in entry:
            self.summary = self.html(entry.summary)
        if 'content' in entry:
            self.content0 = self.html(entry.content[0].value)

    def __getattr__(self, name):
        return getattr(self.raw_entry, name)

    def html(self, string):
        return LxmlParser(string=string)

    def has_tag(self, tag):
        def matches_tag(item):
            return item.term == tag
        if ('tags' in self.raw_entry and
                len(filter(matches_tag, self.raw_entry['tags']))):
            return True
        return False


# -*- coding: utf-8 -*-
"""Tests for shellapp module.

Authors
-------
* Bradley Froehle
"""
#-----------------------------------------------------------------------------
#  Copyright (C) 2012  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import unittest

import nose.tools as nt

from IPython.testing import decorators as dec
from IPython.testing import tools as tt

class TestFileToRun(unittest.TestCase, tt.TempFileMixin):
    """Test the behavior of the file_to_run parameter."""

    def test_py_script_file_attribute(self):
        """Test that `__file__` is set when running `ipython file.py`"""
        src = "print(__file__)\n"
        self.mktmp(src)

        if dec.module_not_available('sqlite3'):
            err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
        else:
            err = None
        tt.ipexec_validate(self.fname, self.fname, err)

    def test_ipy_script_file_attribute(self):
        """Test that `__file__` is set when running `ipython file.ipy`"""
        src = "print(__file__)\n"
        self.mktmp(src, ext='.ipy')

        if dec.module_not_available('sqlite3'):
            err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
        else:
            err = None
        tt.ipexec_validate(self.fname, self.fname, err)

    # Ideally we would also test that `__file__` is not set in the
    # interactive namespace after running `ipython -i <file>`.

Add test for `__file__` behavior in `ipython <file>`

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-
"""Tests for shellapp module.

Authors
-------
* Bradley Froehle
"""
#-----------------------------------------------------------------------------
#  Copyright (C) 2012  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import unittest

import nose.tools as nt

from IPython.testing import decorators as dec
from IPython.testing import tools as tt

class TestFileToRun(unittest.TestCase, tt.TempFileMixin):
    """Test the behavior of the file_to_run parameter."""

    def test_py_script_file_attribute(self):
        """Test that `__file__` is set when running `ipython file.py`"""
        src = "print(__file__)\n"
        self.mktmp(src)

        if dec.module_not_available('sqlite3'):
            err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
        else:
            err = None
        tt.ipexec_validate(self.fname, self.fname, err)

    def test_ipy_script_file_attribute(self):
        """Test that `__file__` is set when running `ipython file.ipy`"""
        src = "print(__file__)\n"
        self.mktmp(src, ext='.ipy')

        if dec.module_not_available('sqlite3'):
            err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
        else:
            err = None
        tt.ipexec_validate(self.fname, self.fname, err)

    # Ideally we would also test that `__file__` is not set in the
    # interactive namespace after running `ipython -i <file>`.
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""Tests for shellapp module.

Authors
-------
* Bradley Froehle
"""
#-----------------------------------------------------------------------------
#  Copyright (C) 2012  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import unittest

import nose.tools as nt

from IPython.testing import decorators as dec
from IPython.testing import tools as tt

class TestFileToRun(unittest.TestCase, tt.TempFileMixin):
    """Test the behavior of the file_to_run parameter."""

    def test_py_script_file_attribute(self):
        """Test that `__file__` is set when running `ipython file.py`"""
        src = "print(__file__)\n"
        self.mktmp(src)

        if dec.module_not_available('sqlite3'):
            err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
        else:
            err = None
        tt.ipexec_validate(self.fname, self.fname, err)

    def test_ipy_script_file_attribute(self):
        """Test that `__file__` is set when running `ipython file.ipy`"""
        src = "print(__file__)\n"
        self.mktmp(src, ext='.ipy')

        if dec.module_not_available('sqlite3'):
            err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
        else:
            err = None
        tt.ipexec_validate(self.fname, self.fname, err)

    # Ideally we would also test that `__file__` is not set in the
    # interactive namespace after running `ipython -i <file>`.

Prompt: Add test for `__file__` behavior in `ipython <file>`


from ckan.plugins import toolkit
from ckanext.apply_permissions_for_service import model

def service_permission_application_list(context, data_dict):
    return {'success': True}

def service_permission_application_show(context, data_dict):

    permission_application_id = toolkit.get_or_bust(data_dict, 'id')
    application = model.ApplyPermission.get(permission_application_id).as_dict()
    organization = application.get('organization')
    target_organization = application.get('target_organization')
    membership_organizations = toolkit.get_action('organization_list_for_user')(context, {'permission': 'read'})

    if any(True for x in (org.get('id') for org in membership_organizations)
           if x in (organization['id'], target_organization['id'])):
        return {'success': True}

    return {'success': False,
            "msg": toolkit._("User not authorized to view permission application.")}

def service_permission_settings(context, data_dict):
    return {'success': toolkit.check_access('package_update', context, {'id': data_dict['subsystem_id']})}

def service_permission_application_create(context, data_dict):
    editor_or_admin_orgs = toolkit.get_action('organization_list_for_user')(context, {'permission': 'create_dataset'})
    return {'success': len(editor_or_admin_orgs) > 0}

Use generator instead of list.

Response:
<REPLACE_OLD> [org.get('id') <REPLACE_NEW> (org.get('id') <REPLACE_END> <REPLACE_OLD> membership_organizations]
 <REPLACE_NEW> membership_organizations)
 <REPLACE_END> <|endoftext|> from ckan.plugins import toolkit
from ckanext.apply_permissions_for_service import model

def service_permission_application_list(context, data_dict):
    return {'success': True}

def service_permission_application_show(context, data_dict):

    permission_application_id = toolkit.get_or_bust(data_dict, 'id')
    application = model.ApplyPermission.get(permission_application_id).as_dict()
    organization = application.get('organization')
    target_organization = application.get('target_organization')
    membership_organizations = toolkit.get_action('organization_list_for_user')(context, {'permission': 'read'})

    if any(True for x in (org.get('id') for org in membership_organizations)
           if x in (organization['id'], target_organization['id'])):
        return {'success': True}

    return {'success': False,
            "msg": toolkit._("User not authorized to view permission application.")}

def service_permission_settings(context, data_dict):
    return {'success': toolkit.check_access('package_update', context, {'id': data_dict['subsystem_id']})}

def service_permission_application_create(context, data_dict):
    editor_or_admin_orgs = toolkit.get_action('organization_list_for_user')(context, {'permission': 'create_dataset'})
    return {'success': len(editor_or_admin_orgs) > 0}

Prompt:
Use generator instead of list.

Co-authored-by: Teemu Erkkola <ee6c9b9748887a4d25e9c1c5e0aff697ac55fd56@gofore.com>
from ckan.plugins import toolkit
from ckanext.apply_permissions_for_service import model

def service_permission_application_list(context, data_dict):
    return {'success': True}

def service_permission_application_show(context, data_dict):

    permission_application_id = toolkit.get_or_bust(data_dict, 'id')
    application = model.ApplyPermission.get(permission_application_id).as_dict()
    organization = application.get('organization')
    target_organization = application.get('target_organization')
    membership_organizations = toolkit.get_action('organization_list_for_user')(context, {'permission': 'read'})

    if any(True for x in [org.get('id') for org in membership_organizations]
           if x in (organization['id'], target_organization['id'])):
        return {'success': True}

    return {'success': False,
            "msg": toolkit._("User not authorized to view permission application.")}

def service_permission_settings(context, data_dict):
    return {'success': toolkit.check_access('package_update', context, {'id': data_dict['subsystem_id']})}

def service_permission_application_create(context, data_dict):
    editor_or_admin_orgs = toolkit.get_action('organization_list_for_user')(context, {'permission': 'create_dataset'})
    return {'success': len(editor_or_admin_orgs) > 0}


#!/usr/bin/python3
import sys

import git

r = git.Repo( sys.argv[1] )

def printTree( tree, indent=0 ):
    prefix = ' '*indent
    print( prefix, '-' * 16 )
    print( prefix, 'Tree path %s' % (tree.path,) )
    for blob in tree:
        print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )

    for child in tree.trees:
        printTree( child, indent+4 )

for index, commit in enumerate(r.iter_commits( None )):
    print( '=' * 60 )
    for name in sorted( dir( commit ) ):
        if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
            continue

        print( 'Commit: %s: %r' % (name, getattr( commit, name )) )

    print( '-' * 60 )
    stats = commit.stats

    for name in sorted( dir( stats ) ):
        if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
            continue

        if name == 'files':
            for file in stats.files:
                print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )

        else:
            print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )

    print( '-' * 60 )
    tree = commit.tree

    printTree( tree )

    if index > 1:
        break

Exit the loop early when experimenting.

Exit the loop early when experimenting.

Response:
<REPLACE_OLD> )
 <REPLACE_NEW> )

    if index > 1:
        break
 <REPLACE_END> <|endoftext|> #!/usr/bin/python3
import sys

import git

r = git.Repo( sys.argv[1] )

def printTree( tree, indent=0 ):
    prefix = ' '*indent
    print( prefix, '-' * 16 )
    print( prefix, 'Tree path %s' % (tree.path,) )
    for blob in tree:
        print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )

    for child in tree.trees:
        printTree( child, indent+4 )

for index, commit in enumerate(r.iter_commits( None )):
    print( '=' * 60 )
    for name in sorted( dir( commit ) ):
        if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
            continue

        print( 'Commit: %s: %r' % (name, getattr( commit, name )) )

    print( '-' * 60 )
    stats = commit.stats

    for name in sorted( dir( stats ) ):
        if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
            continue

        if name == 'files':
            for file in stats.files:
                print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )

        else:
            print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )

    print( '-' * 60 )
    tree = commit.tree

    printTree( tree )

    if index > 1:
        break

Prompt:
Exit the loop early when experimenting.
#!/usr/bin/python3
import sys

import git

r = git.Repo( sys.argv[1] )

def printTree( tree, indent=0 ):
    prefix = ' '*indent
    print( prefix, '-' * 16 )
    print( prefix, 'Tree path %s' % (tree.path,) )
    for blob in tree:
        print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )

    for child in tree.trees:
        printTree( child, indent+4 )

for index, commit in enumerate(r.iter_commits( None )):
    print( '=' * 60 )
    for name in sorted( dir( commit ) ):
        if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
            continue

        print( 'Commit: %s: %r' % (name, getattr( commit, name )) )

    print( '-' * 60 )
    stats = commit.stats

    for name in sorted( dir( stats ) ):
        if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
            continue

        if name == 'files':
            for file in stats.files:
                print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )

        else:
            print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )

    print( '-' * 60 )
    tree = commit.tree

    printTree( tree )


#!/usr/bin/env python3
# encoding: utf-8

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

setup(
    name='autoprop',
    version='0.0.0',
    author='Kale Kundert',
    author_email='kale@thekunderts.net',
    long_description=open('README.rst').read(),
    url='https://github.com/kalekundert/autoprop',
    license='MIT',
    py_modules=[
        'autoprop',
    ],
    keywords=[
        'property', 'properties',
        'accessor', 'accessors',
        'getter', 'setter'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries',
    ],
)

Upgrade the development status to beta.

Upgrade the development status to beta.

Response:
<REPLACE_OLD> 2 <REPLACE_NEW> 4 <REPLACE_END> <REPLACE_OLD> Pre-Alpha',
 <REPLACE_NEW> Beta',
 <REPLACE_END> <REPLACE_OLD> 2',
 <REPLACE_NEW> 2.6',
 <REPLACE_END> <REPLACE_OLD> 3',
 <REPLACE_NEW> 3.3',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3
# encoding: utf-8

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

setup(
    name='autoprop',
    version='0.0.0',
    author='Kale Kundert',
    author_email='kale@thekunderts.net',
    long_description=open('README.rst').read(),
    url='https://github.com/kalekundert/autoprop',
    license='MIT',
    py_modules=[
        'autoprop',
    ],
    keywords=[
        'property', 'properties',
        'accessor', 'accessors',
        'getter', 'setter'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 3.3',
        'Topic :: Software Development :: Libraries',
    ],
)

Prompt:
Upgrade the development status to beta.

#!/usr/bin/env python3
# encoding: utf-8

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

setup(
    name='autoprop',
    version='0.0.0',
    author='Kale Kundert',
    author_email='kale@thekunderts.net',
    long_description=open('README.rst').read(),
    url='https://github.com/kalekundert/autoprop',
    license='MIT',
    py_modules=[
        'autoprop',
    ],
    keywords=[
        'property', 'properties',
        'accessor', 'accessors',
        'getter', 'setter'
    ],
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Software Development :: Libraries',
    ],
)