from __future__ import absolute_import

from django.db import models

class Pet(models.Model):
    name = models.CharField(max_length=30)

class Film(models.Model):
    reporters = models.ManyToManyField('Reporter',
                                       related_name='films')

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
    pets = models.ManyToManyField('self')

    def __str__(self):              # __unicode__ on Python 2
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, related_name='articles')
    lang = models.CharField(max_length=2, help_text='Language', choices=[
        ('es', 'Spanish'),
        ('en', 'English')
    ], default='es')

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

    class Meta:
        ordering = ('headline',)

Response:
<REPLACE_OLD> related_name='articles')

 <REPLACE_NEW> related_name='articles')
    lang = models.CharField(max_length=2, help_text='Language', choices=[
        ('es', 'Spanish'),
        ('en', 'English')
    ], default='es')

 <REPLACE_END> <|endoftext|> from __future__ import absolute_import

from django.db import models

class Pet(models.Model):
    name = models.CharField(max_length=30)

class Film(models.Model):
    reporters = models.ManyToManyField('Reporter',
                                       related_name='films')

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
    pets = models.ManyToManyField('self')

    def __str__(self):              # __unicode__ on Python 2
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, related_name='articles')
    lang = models.CharField(max_length=2, help_text='Language', choices=[
        ('es', 'Spanish'),
        ('en', 'English')
    ], default='es')

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

    class Meta:
        ordering = ('headline',)

Prompt:
Improve Django field conversion real-life tests

from __future__ import absolute_import

from django.db import models

class Pet(models.Model):
    name = models.CharField(max_length=30)

class Film(models.Model):
    reporters = models.ManyToManyField('Reporter',
                                       related_name='films')

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
    pets = models.ManyToManyField('self')

    def __str__(self):              # __unicode__ on Python 2
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, related_name='articles')

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

    class Meta:
        ordering = ('headline',)


# Copyright 2012 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

from ctypes import byref, POINTER, cast
import sys
sys.path.insert(0, '..')

from pgi.gitypes import *

gi_init()

repo = GIRepository.get_default()

error = POINTER(GError)()
repo.require("GLib", "2.0", GIRepositoryLoadFlags.LAZY, byref(error))
check_gerror(error)

base_info = repo.find_by_name("GLib", "warn_message")
if not base_info:
    raise Exception

function_info = cast(base_info, GIFunctionInfoPtr)

in_args_type = GIArgument * 5
in_args = in_args_type(GIArgument(v_string="GITYPES"),
                       GIArgument(v_string=__file__),
                       GIArgument(v_uint=42),
                       GIArgument(v_string="main"),
                       GIArgument(v_string="hello world"),
)
retval = GIArgument()

error = POINTER(GError)()
function_info.invoke(in_args, 5, None, 0, byref(retval), byref(error))
check_gerror(error)

base_info.unref()

Add back the old gir example

Add back the old gir example

Response:
<INSERT> # Copyright 2012 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

from ctypes import byref, POINTER, cast
import sys
sys.path.insert(0, '..')

from pgi.gitypes import *

gi_init()

repo = GIRepository.get_default()

error = POINTER(GError)()
repo.require("GLib", "2.0", GIRepositoryLoadFlags.LAZY, byref(error))
check_gerror(error)

base_info = repo.find_by_name("GLib", "warn_message")
if not base_info:
 <INSERT_END> <INSERT>   raise Exception

function_info = cast(base_info, GIFunctionInfoPtr)

in_args_type = GIArgument * 5
in_args = in_args_type(GIArgument(v_string="GITYPES"),
                       GIArgument(v_string=__file__),
                       GIArgument(v_uint=42),
                       GIArgument(v_string="main"),
                       GIArgument(v_string="hello world"),
)
retval = GIArgument()

error = POINTER(GError)()
function_info.invoke(in_args, 5, None, 0, byref(retval), byref(error))
check_gerror(error)

base_info.unref()
 <INSERT_END> <|endoftext|> # Copyright 2012 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

from ctypes import byref, POINTER, cast
import sys
sys.path.insert(0, '..')

from pgi.gitypes import *

gi_init()

repo = GIRepository.get_default()

error = POINTER(GError)()
repo.require("GLib", "2.0", GIRepositoryLoadFlags.LAZY, byref(error))
check_gerror(error)

base_info = repo.find_by_name("GLib", "warn_message")
if not base_info:
    raise Exception

function_info = cast(base_info, GIFunctionInfoPtr)

in_args_type = GIArgument * 5
in_args = in_args_type(GIArgument(v_string="GITYPES"),
                       GIArgument(v_string=__file__),
                       GIArgument(v_uint=42),
                       GIArgument(v_string="main"),
                       GIArgument(v_string="hello world"),
)
retval = GIArgument()

error = POINTER(GError)()
function_info.invoke(in_args, 5, None, 0, byref(retval), byref(error))
check_gerror(error)

base_info.unref()

Prompt: Add back the old gir example


from django.core import mail

from bluebottle.events.messages import EventClosedOwnerMessage
from bluebottle.events.tests.factories import EventFactory
from bluebottle.notifications.effects import NotificationEffect
from bluebottle.test.factory_models.accounts import BlueBottleUserFactory
from bluebottle.test.utils import BluebottleTestCase

class NotificationEffectsTestCase(BluebottleTestCase):

    def test_notification_effect(self):
        user = BlueBottleUserFactory.create(
            email='faal@haas.nl'
        )
        event = EventFactory.create(
            title='Bound to fail',
            owner=user
        )
        subject = 'Your event "Bound to fail" has been closed'
        effect = NotificationEffect(EventClosedOwnerMessage)(event)
        self.assertEqual(unicode(effect), 'Message {} to faal@haas.nl'.format(subject))
        effect.execute()
        self.assertEqual(mail.outbox[0].subject, subject)

Add effect test for notifications

Add effect test for notifications

Response:
<INSERT> from django.core import mail

from bluebottle.events.messages import EventClosedOwnerMessage
from bluebottle.events.tests.factories import EventFactory
from bluebottle.notifications.effects import NotificationEffect
from bluebottle.test.factory_models.accounts import BlueBottleUserFactory
from bluebottle.test.utils import BluebottleTestCase

class NotificationEffectsTestCase(BluebottleTestCase):

 <INSERT_END> <INSERT>   def test_notification_effect(self):
        user = BlueBottleUserFactory.create(
            email='faal@haas.nl'
        )
        event = EventFactory.create(
            title='Bound to fail',
            owner=user
        )
        subject = 'Your event "Bound to fail" has been closed'
        effect = NotificationEffect(EventClosedOwnerMessage)(event)
        self.assertEqual(unicode(effect), 'Message {} to faal@haas.nl'.format(subject))
        effect.execute()
        self.assertEqual(mail.outbox[0].subject, subject)
 <INSERT_END> <|endoftext|> from django.core import mail

from bluebottle.events.messages import EventClosedOwnerMessage
from bluebottle.events.tests.factories import EventFactory
from bluebottle.notifications.effects import NotificationEffect
from bluebottle.test.factory_models.accounts import BlueBottleUserFactory
from bluebottle.test.utils import BluebottleTestCase

class NotificationEffectsTestCase(BluebottleTestCase):

    def test_notification_effect(self):
        user = BlueBottleUserFactory.create(
            email='faal@haas.nl'
        )
        event = EventFactory.create(
            title='Bound to fail',
            owner=user
        )
        subject = 'Your event "Bound to fail" has been closed'
        effect = NotificationEffect(EventClosedOwnerMessage)(event)
        self.assertEqual(unicode(effect), 'Message {} to faal@haas.nl'.format(subject))
        effect.execute()
        self.assertEqual(mail.outbox[0].subject, subject)

Prompt: Add effect test for notifications


# stdlib
from typing import Any
from typing import Optional

# third party
from nacl.signing import VerifyKey

# relative
from ... import UID
from ....abstract.node import AbstractNode
from .simple_messages import NodeRunnableMessageWithReply

class DoesObjectExistMessage(NodeRunnableMessageWithReply):

    __attr_allowlist__ = ["obj_id"]

    def __init__(self, obj_id: UID):
        self.obj_id = obj_id

    def run(self, node: AbstractNode, verify_key: Optional[VerifyKey] = None) -> Any:

        try:
            storable_object = node.store[self.obj_id]  # type: ignore
            return True
        except Exception as e:
            return False

Add new message which checks whether an object exists

Response:
<INSERT> # stdlib
from typing import Any
from typing import Optional

# third party
from nacl.signing import VerifyKey

# relative
from ... import UID
from ....abstract.node import AbstractNode
from .simple_messages import NodeRunnableMessageWithReply

class DoesObjectExistMessage(NodeRunnableMessageWithReply):

 <INSERT_END> <INSERT>   __attr_allowlist__ = ["obj_id"]

    def __init__(self, obj_id: UID):
        self.obj_id = obj_id

    def run(self, node: AbstractNode, verify_key: Optional[VerifyKey] = None) -> Any:

        try:
            storable_object = node.store[self.obj_id]  # type: ignore
            return True
        except Exception as e:
            return False
 <INSERT_END> <|endoftext|> # stdlib
from typing import Any
from typing import Optional

# third party
from nacl.signing import VerifyKey

# relative
from ... import UID
from ....abstract.node import AbstractNode
from .simple_messages import NodeRunnableMessageWithReply

class DoesObjectExistMessage(NodeRunnableMessageWithReply):

    __attr_allowlist__ = ["obj_id"]

    def __init__(self, obj_id: UID):
        self.obj_id = obj_id

    def run(self, node: AbstractNode, verify_key: Optional[VerifyKey] = None) -> Any:

        try:
            storable_object = node.store[self.obj_id]  # type: ignore
            return True
        except Exception as e:
            return False

Prompt: Add new message which checks whether an object exists


import logging
import jinja2
import datetime as dt

from muffin_debugtoolbar.panels import DebugPanel
from muffin_debugtoolbar.utils import LoggingTrackingHandler

LOGGER = logging.getLogger('peewee')

class PeeweeDebugPanel(DebugPanel):

    name = 'Peewee queries'
    template = jinja2.Template("""

                    Time
                    Query

                {% for record in records %}

                        {{ record['time'] }}
                        {{ record['message'] }}

                {% endfor %}

    """)

    def __init__(self, app, request=None):
        super(PeeweeDebugPanel, self).__init__(app, request)
        LOGGER.setLevel(logging.DEBUG)
        self.handler = LoggingTrackingHandler()

    def wrap_handler(self, handler, context_switcher):
        context_switcher.add_context_in(lambda: LOGGER.addHandler(self.handler))
        context_switcher.add_context_out(lambda: LOGGER.removeHandler(self.handler))

    @property
    def nav_title(self):
        """ Get a navigation title. """
        return "%s (%s)" % (self.title, len(self.handler.records))

    @property
    def has_content(self):
        return self.handler.records

    def render_vars(self):
        return {
            'records': [
                {
                    'message': record.getMessage(),
                    'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'),
                } for record in self.handler.records
            ]
        }

Add debugpanel for Muffin Debugtoolbar

Add debugpanel for Muffin Debugtoolbar

Response:
<REPLACE_OLD>  <REPLACE_NEW> import logging
import jinja2
import datetime as dt

from muffin_debugtoolbar.panels import DebugPanel
from muffin_debugtoolbar.utils import LoggingTrackingHandler

LOGGER = logging.getLogger('peewee')

class PeeweeDebugPanel(DebugPanel):

    name = 'Peewee queries'
    template = jinja2.Template("""
        <table class="table table-striped table-condensed">
            <thead>
                <tr>
                    <th>Time</th>
                    <th>Query</th>
                </tr>
            </thead>
            <tbody>
                {% for record in records %}
                    <tr>
                        <td>{{ record['time'] }}</td>
                        <td>{{ record['message'] }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    """)

    def __init__(self, app, request=None):
        super(PeeweeDebugPanel, self).__init__(app, request)
        LOGGER.setLevel(logging.DEBUG)
        self.handler = LoggingTrackingHandler()

    def wrap_handler(self, handler, context_switcher):
        context_switcher.add_context_in(lambda: LOGGER.addHandler(self.handler))
        context_switcher.add_context_out(lambda: LOGGER.removeHandler(self.handler))

    @property
    def nav_title(self):
        """ Get a navigation title. """
        return "%s (%s)" % (self.title, len(self.handler.records))

    @property
    def has_content(self):
        return self.handler.records

    def render_vars(self):
        return {
            'records': [
                {
                    'message': record.getMessage(),
                    'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'),
                } for record in self.handler.records
            ]
        }
 <REPLACE_END> <|endoftext|> import logging
import jinja2
import datetime as dt

from muffin_debugtoolbar.panels import DebugPanel
from muffin_debugtoolbar.utils import LoggingTrackingHandler

LOGGER = logging.getLogger('peewee')

class PeeweeDebugPanel(DebugPanel):

    name = 'Peewee queries'
    template = jinja2.Template("""
        <table class="table table-striped table-condensed">
            <thead>
                <tr>
                    <th>Time</th>
                    <th>Query</th>
                </tr>
            </thead>
            <tbody>
                {% for record in records %}
                    <tr>
                        <td>{{ record['time'] }}</td>
                        <td>{{ record['message'] }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    """)

    def __init__(self, app, request=None):
        super(PeeweeDebugPanel, self).__init__(app, request)
        LOGGER.setLevel(logging.DEBUG)
        self.handler = LoggingTrackingHandler()

    def wrap_handler(self, handler, context_switcher):
        context_switcher.add_context_in(lambda: LOGGER.addHandler(self.handler))
        context_switcher.add_context_out(lambda: LOGGER.removeHandler(self.handler))

    @property
    def nav_title(self):
        """ Get a navigation title. """
        return "%s (%s)" % (self.title, len(self.handler.records))

    @property
    def has_content(self):
        return self.handler.records

    def render_vars(self):
        return {
            'records': [
                {
                    'message': record.getMessage(),
                    'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'),
                } for record in self.handler.records
            ]
        }

Prompt: Add debugpanel for Muffin Debugtoolbar


#!/usr/bin/env python
#
# transform-sql.py -- create a header file with the appropriate SQL variables
# from an SQL file
#

import os
import re
import sys

def usage_and_exit(msg):
  if msg:
    sys.stderr.write("%s\n\n" % msg)
  sys.stderr.write("usage: %s [sqlite_file]\n" % \
    os.path.basename(sys.argv[0]))
  sys.stderr.flush()
  sys.exit(1)

def main(input_filename, output_filename):
  input = open(input_filename, "r")
  output = open(output_filename, "w")

  var_name = os.path.basename(input_filename).replace('.', '_')
  var_name = var_name.replace('-', '_')

  output.write('static const char * const %s[] = { NULL,\n' % var_name)

  in_comment = False
  for line in input:
    line = line.replace('\n', '')
    line = line.replace('"', '\\"')

    if line:
      output.write('  "' + line + '"\n')
    else:
      output.write('  APR_EOL_STR\n')

  output.write('  };')

  input.close()
  output.close()

if __name__ == '__main__':
  if len(sys.argv) < 2:
    usage_and_exit("Incorrect number of arguments")
  main(sys.argv[1], sys.argv[1] + ".h")

Add a helper script which will transform a file full of SQL commands into a
header file suitable for inclusion in a standard C file and use with the
Subversion SQLite APIs.  The goal here is that we can maintain our SQL schema
directly as such, and let this script do the appropriate transformation as
part of autogen.sh.

* build/transform-sql.py:
  New.

Response:
<INSERT> #!/usr/bin/env python
#
# transform-sql.py -- create a header file with the appropriate SQL variables
# from an SQL file
#

import os
import re
import sys

def usage_and_exit(msg):
 <INSERT_END> <INSERT> if msg:
    sys.stderr.write("%s\n\n" % msg)
  sys.stderr.write("usage: %s [sqlite_file]\n" % \
    os.path.basename(sys.argv[0]))
  sys.stderr.flush()
  sys.exit(1)

def main(input_filename, output_filename):
  input = open(input_filename, "r")
  output = open(output_filename, "w")

  var_name = os.path.basename(input_filename).replace('.', '_')
  var_name = var_name.replace('-', '_')

  output.write('static const char * const %s[] = { NULL,\n' % var_name)

  in_comment = False
  for line in input:
    line = line.replace('\n', '')
    line = line.replace('"', '\\"')

    if line:
      output.write('  "' + line + '"\n')
    else:
      output.write('  APR_EOL_STR\n')

  output.write('  };')

  input.close()
  output.close()

if __name__ == '__main__':
  if len(sys.argv) < 2:
    usage_and_exit("Incorrect number of arguments")
  main(sys.argv[1], sys.argv[1] + ".h")
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
#
# transform-sql.py -- create a header file with the appropriate SQL variables
# from an SQL file
#

import os
import re
import sys

def usage_and_exit(msg):
  if msg:
    sys.stderr.write("%s\n\n" % msg)
  sys.stderr.write("usage: %s [sqlite_file]\n" % \
    os.path.basename(sys.argv[0]))
  sys.stderr.flush()
  sys.exit(1)

def main(input_filename, output_filename):
  input = open(input_filename, "r")
  output = open(output_filename, "w")

  var_name = os.path.basename(input_filename).replace('.', '_')
  var_name = var_name.replace('-', '_')

  output.write('static const char * const %s[] = { NULL,\n' % var_name)

  in_comment = False
  for line in input:
    line = line.replace('\n', '')
    line = line.replace('"', '\\"')

    if line:
      output.write('  "' + line + '"\n')
    else:
      output.write('  APR_EOL_STR\n')

  output.write('  };')

  input.close()
  output.close()

if __name__ == '__main__':
  if len(sys.argv) < 2:
    usage_and_exit("Incorrect number of arguments")
  main(sys.argv[1], sys.argv[1] + ".h")

Prompt:
Add a helper script which will transform a file full of SQL commands into a
header file suitable for inclusion in a standard C file and use with the
Subversion SQLite APIs.  The goal here is that we can maintain our SQL schema
directly as such, and let this script do the appropriate transformation as
part of autogen.sh.

* build/transform-sql.py:
  New.


#!/usr/bin/env python
# encoding=utf8

from flexbe_core import EventState, Logger
import json

class Wonderland_Objects_In_A_Room(EventState):
	'''
	Return all objects in a room

	># json_text        string  json to read

	#> names            int[]   array containing all names of objects in the room
	#> ids              id[]    array containing all IDs of objects in the room

	<= done             return when the room contain at least one object
	<= empty            return when the room is empty
	<= error            return when error reading data
	'''

	def __init__(self):
		# See example_state.py for basic explanations.
		super(Wonderland_Objects_In_A_Room, self).__init__(outcomes=['done', 'empty', 'error'],
		                                             input_keys=['json_text'],
		                                             output_keys=['ids', 'names'])

	def execute(self, userdata):
		# parse parameter json data
		datas = json.loads(userdata.json_text)

		# read if there is data
		if not datas:
			# continue to Zero
			return 'empty'

		names = []
		ids = []

		for data in datas:
			# try to read data
			if 'id' not in data:
				return 'error'

			# try to read data
			if 'name' not in data:
				return 'error'

			# write return datas
			names += [data['name']]
			ids += [data['id']]

		userdata.names=names
		userdata.ids=ids
		print str(names)[1:-1]
		print str(ids)[1:-1]

		# continue to Done
		return 'done'

Add a state listing all entities in a room

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# encoding=utf8

from flexbe_core import EventState, Logger
import json

class Wonderland_Objects_In_A_Room(EventState):
	'''
	Return all objects in a room

	># json_text        string  json to read

	#> names            int[]   array containing all names of objects in the room
	#> ids              id[]    array containing all IDs of objects in the room

	<= done             return when the room contain at least one object
	<= empty            return when the room is empty
	<= error            return when error reading data
	'''

	def __init__(self):
		# See example_state.py for basic explanations.
		super(Wonderland_Objects_In_A_Room, self).__init__(outcomes=['done', 'empty', 'error'],
		                                             input_keys=['json_text'],
		                                             output_keys=['ids', 'names'])

	def execute(self, userdata):
		# parse parameter json data
		datas = json.loads(userdata.json_text)

		# read if there is data
		if not datas:
			# continue to Zero
			return 'empty'

		names = []
		ids = []

		for data in datas:
			# try to read data
			if 'id' not in data:
				return 'error'

			# try to read data
			if 'name' not in data:
				return 'error'

			# write return datas
			names += [data['name']]
			ids += [data['id']]

		userdata.names=names
		userdata.ids=ids
		print str(names)[1:-1]
		print str(ids)[1:-1]

		# continue to Done
		return 'done' <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# encoding=utf8

from flexbe_core import EventState, Logger
import json

class Wonderland_Objects_In_A_Room(EventState):
	'''
	Return all objects in a room

	># json_text        string  json to read

	#> names            int[]   array containing all names of objects in the room
	#> ids              id[]    array containing all IDs of objects in the room

	<= done             return when the room contain at least one object
	<= empty            return when the room is empty
	<= error            return when error reading data
	'''

	def __init__(self):
		# See example_state.py for basic explanations.
		super(Wonderland_Objects_In_A_Room, self).__init__(outcomes=['done', 'empty', 'error'],
		                                             input_keys=['json_text'],
		                                             output_keys=['ids', 'names'])

	def execute(self, userdata):
		# parse parameter json data
		datas = json.loads(userdata.json_text)

		# read if there is data
		if not datas:
			# continue to Zero
			return 'empty'

		names = []
		ids = []

		for data in datas:
			# try to read data
			if 'id' not in data:
				return 'error'

			# try to read data
			if 'name' not in data:
				return 'error'

			# write return datas
			names += [data['name']]
			ids += [data['id']]

		userdata.names=names
		userdata.ids=ids
		print str(names)[1:-1]
		print str(ids)[1:-1]

		# continue to Done
		return 'done'

Prompt: Add a state listing all entities in a room


import os.path

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

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")

with open(README_FILE) as f:
    long_description = f.read()

setup(
    name="xutils",
    version="1.2.0",
    description="A Fragmentary Python Library, no any third-part dependencies.",
    long_description=long_description,
    author="xgfone",
    author_email="xgfone@126.com",
    maintainer="xgfone",
    maintainer_email="xgfone@126.com",
    url="https://github.com/xgfone/xutils",
    packages=["xutils"],

    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
    ],
)

Set the version to 1.2.0

Set the version to 1.2.0

Response:
<REPLACE_OLD> version="1.1.0",
 <REPLACE_NEW> version="1.2.0",
 <REPLACE_END> <|endoftext|> import os.path

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

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")

with open(README_FILE) as f:
    long_description = f.read()

setup(
    name="xutils",
    version="1.2.0",
    description="A Fragmentary Python Library, no any third-part dependencies.",
    long_description=long_description,
    author="xgfone",
    author_email="xgfone@126.com",
    maintainer="xgfone",
    maintainer_email="xgfone@126.com",
    url="https://github.com/xgfone/xutils",
    packages=["xutils"],

    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
    ],
)

Prompt:
Set the version to 1.2.0

import os.path

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

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")

with open(README_FILE) as f:
    long_description = f.read()

setup(
    name="xutils",
    version="1.1.0",
    description="A Fragmentary Python Library, no any third-part dependencies.",
    long_description=long_description,
    author="xgfone",
    author_email="xgfone@126.com",
    maintainer="xgfone",
    maintainer_email="xgfone@126.com",
    url="https://github.com/xgfone/xutils",
    packages=["xutils"],

    classifiers=[
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
    ],
)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('genealogio', '0003_auto_20150220_0733'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='family',
            options={'ordering': ('name',), 'verbose_name': 'Familie', 'verbose_name_plural': 'Familien'},
        ),
    ]

Add ordering by family name to Family model.

Response:
<INSERT> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('genealogio', '0003_auto_20150220_0733'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='family',
            options={'ordering': ('name',), 'verbose_name': 'Familie', 'verbose_name_plural': 'Familien'},
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('genealogio', '0003_auto_20150220_0733'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='family',
            options={'ordering': ('name',), 'verbose_name': 'Familie', 'verbose_name_plural': 'Familien'},
        ),
    ]

Prompt: Add ordering by family name to Family model.


import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings')

app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend='redis')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

app.conf.beat_schedule = {
    'process-deadlines': {
        'task': 'lims.projects.tasks.process_deadlines',
        'schedule': crontab(minute=0, hour='*/3'),
    }
}

Response:
<REPLACE_OLD> broker='redis://localhost', <REPLACE_NEW> broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), <REPLACE_END> <|endoftext|> import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings')

app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend='redis')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

app.conf.beat_schedule = {
    'process-deadlines': {
        'task': 'lims.projects.tasks.process_deadlines',
        'schedule': crontab(minute=0, hour='*/3'),
    }
}

Prompt:
Extend time period at which deadline processing happens

import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings')

app = Celery('lims', broker='redis://localhost', backend='redis')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

app.conf.beat_schedule = {
    'process-deadlines': {
        'task': 'lims.projects.tasks.process_deadlines',
        'schedule': crontab(minute=0, hour='*/3'),
    }
}


import pytest

from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val

def pytestmark(func):
    pytest.mark.django_db(func)
    pytest.mark.usefixtures('test_table')(func)

@pytest.fixture(scope='module')
def test_table():
    # NOTE: We wrap that into transaction because in other case django will gobble it up
    #       into single transaction with first test and then rollback everything happily on
    #       that tests end.
    do_sql('''
        begin;

        create table test (
            id int primary key,
            tag int not null
        );
        insert into test values (1, 10), (2, 20);

        commit;
    ''')

def test_fetch_val():
    assert fetch_val('select min(id) from test') == 1

def test_fetch_col():
    assert fetch_col('select tag from test order by tag') == [10, 20]

def test_fetch_row():
    assert fetch_row('select * from test where id = 2') == (2, 20)

def test_fetch_all():
    assert fetch_all('select * from test order by id') == [(1, 10), (2, 20)]

Response:
<INSERT> # NOTE: We wrap that into transaction because in other case django will gobble it up
    #       into single transaction with first test and then rollback everything happily on
    #       that tests end.
    <INSERT_END> <REPLACE_OLD> begin;
 <REPLACE_NEW> begin;

 <REPLACE_END> <REPLACE_OLD> );

 <REPLACE_NEW> );
 <REPLACE_END> <REPLACE_OLD> 20);
 <REPLACE_NEW> 20);

 <REPLACE_END> <|endoftext|> import pytest

from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val

def pytestmark(func):
    pytest.mark.django_db(func)
    pytest.mark.usefixtures('test_table')(func)

@pytest.fixture(scope='module')
def test_table():
    # NOTE: We wrap that into transaction because in other case django will gobble it up
    #       into single transaction with first test and then rollback everything happily on
    #       that tests end.
    do_sql('''
        begin;

        create table test (
            id int primary key,
            tag int not null
        );
        insert into test values (1, 10), (2, 20);

        commit;
    ''')

def test_fetch_val():
    assert fetch_val('select min(id) from test') == 1

def test_fetch_col():
    assert fetch_col('select tag from test order by tag') == [10, 20]

def test_fetch_row():
    assert fetch_row('select * from test where id = 2') == (2, 20)

def test_fetch_all():
    assert fetch_all('select * from test order by id') == [(1, 10), (2, 20)]

Prompt:
Add NOTE regarding transaction to db tests setup

import pytest

from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val

def pytestmark(func):
    pytest.mark.django_db(func)
    pytest.mark.usefixtures('test_table')(func)

@pytest.fixture(scope='module')
def test_table():
    do_sql('''
        begin;
        create table test (
            id int primary key,
            tag int not null
        );

        insert into test values (1, 10), (2, 20);
        commit;
    ''')

def test_fetch_val():
    assert fetch_val('select min(id) from test') == 1

def test_fetch_col():
    assert fetch_col('select tag from test order by tag') == [10, 20]

def test_fetch_row():
    assert fetch_row('select * from test where id = 2') == (2, 20)

def test_fetch_all():
    assert fetch_all('select * from test order by id') == [(1, 10), (2, 20)]


# 'physics' is a tentative name for this subpackage.  Another
# possibility is 'plasma'.  The organization is to be decided by v0.1.

from .parameters import (Alfven_speed,
                         ion_sound_speed,
                         electron_thermal_speed,
                         ion_thermal_speed,
                         electron_gyrofrequency,
                         ion_gyrofrequency,
                         electron_gyroradius,
                         ion_gyroradius,
                         electron_plasma_frequency,
                         ion_plasma_frequency,
                         Debye_length,
                         Debye_number,
                         ion_inertial_length,
                         electron_inertial_length,
                         magnetic_pressure,
                         magnetic_energy_density,
                         )

Response:
<REPLACE_OLD> from <REPLACE_NEW> # 'physics' is a tentative name for this subpackage.  Another
# possibility is 'plasma'.  The organization is to be decided by v0.1.

from <REPLACE_END> <|endoftext|> # 'physics' is a tentative name for this subpackage.  Another
# possibility is 'plasma'.  The organization is to be decided by v0.1.

from .parameters import (Alfven_speed,
                         ion_sound_speed,
                         electron_thermal_speed,
                         ion_thermal_speed,
                         electron_gyrofrequency,
                         ion_gyrofrequency,
                         electron_gyroradius,
                         ion_gyroradius,
                         electron_plasma_frequency,
                         ion_plasma_frequency,
                         Debye_length,
                         Debye_number,
                         ion_inertial_length,
                         electron_inertial_length,
                         magnetic_pressure,
                         magnetic_energy_density,
                         )

Prompt:
Comment that physics is a tentative subpackage name

from .parameters import (Alfven_speed,
                         ion_sound_speed,
                         electron_thermal_speed,
                         ion_thermal_speed,
                         electron_gyrofrequency,
                         ion_gyrofrequency,
                         electron_gyroradius,
                         ion_gyroradius,
                         electron_plasma_frequency,
                         ion_plasma_frequency,
                         Debye_length,
                         Debye_number,
                         ion_inertial_length,
                         electron_inertial_length,
                         magnetic_pressure,
                         magnetic_energy_density,
                         )


"""A more or less complete user-defined wrapper around dictionary objects."""

import riscos

class _Environ:
    def __init__(self, initial = None):
        pass
    def __repr__(self):
        return repr(riscos.getenvdict())
    def __cmp__(self, dict):
        if isinstance(dict, UserDict):
            return cmp(riscos.getenvdict(), dict)
    def __len__(self):
        return len(riscos.getenvdict())
    def __getitem__(self, key):
        ret = riscos.getenv(key)
        if ret<>None:
            return ret
        else:
            raise KeyError
    def __setitem__(self, key, item):
        riscos.putenv(key, item)
    def __delitem__(self, key):
        riscos.delenv(key)
    def clear(self):
        # too dangerous on RISC OS
        pass
    def copy(self):
        return riscos.getenvdict()
    def keys(self): return riscos.getenvdict().keys()
    def items(self): return riscos.getenvdict().items()
    def values(self): return riscos.getenvdict().values()
    def has_key(self, key):
        value = riscos.getenv(key)
        return value<>None
    def update(self, dict):
        for k, v in dict.items():
            riscos.putenv(k, v)
    def get(self, key, failobj=None):
        value = riscos.getenv(key)
        if value<>None:
            return value
        else:
            return failobj

Response:
<REPLACE_OLD> riscos.setenv(key, <REPLACE_NEW> riscos.putenv(key, <REPLACE_END> <|endoftext|> """A more or less complete user-defined wrapper around dictionary objects."""

import riscos

class _Environ:
    def __init__(self, initial = None):
        pass
    def __repr__(self):
        return repr(riscos.getenvdict())
    def __cmp__(self, dict):
        if isinstance(dict, UserDict):
            return cmp(riscos.getenvdict(), dict)
    def __len__(self):
        return len(riscos.getenvdict())
    def __getitem__(self, key):
        ret = riscos.getenv(key)
        if ret<>None:
            return ret
        else:
            raise KeyError
    def __setitem__(self, key, item):
        riscos.putenv(key, item)
    def __delitem__(self, key):
        riscos.delenv(key)
    def clear(self):
        # too dangerous on RISC OS
        pass
    def copy(self):
        return riscos.getenvdict()
    def keys(self): return riscos.getenvdict().keys()
    def items(self): return riscos.getenvdict().items()
    def values(self): return riscos.getenvdict().values()
    def has_key(self, key):
        value = riscos.getenv(key)
        return value<>None
    def update(self, dict):
        for k, v in dict.items():
            riscos.putenv(k, v)
    def get(self, key, failobj=None):
        value = riscos.getenv(key)
        if value<>None:
            return value
        else:
            return failobj

Prompt:
Replace setenv with putenv. Reported by Dietmar Schwertberger.

"""A more or less complete user-defined wrapper around dictionary objects."""

import riscos

class _Environ:
    def __init__(self, initial = None):
        pass
    def __repr__(self):
        return repr(riscos.getenvdict())
    def __cmp__(self, dict):
        if isinstance(dict, UserDict):
            return cmp(riscos.getenvdict(), dict)
    def __len__(self):
        return len(riscos.getenvdict())
    def __getitem__(self, key):
        ret = riscos.getenv(key)
        if ret<>None:
            return ret
        else:
            raise KeyError
    def __setitem__(self, key, item):
        riscos.setenv(key, item)
    def __delitem__(self, key):
        riscos.delenv(key)
    def clear(self):
        # too dangerous on RISC OS
        pass
    def copy(self):
        return riscos.getenvdict()
    def keys(self): return riscos.getenvdict().keys()
    def items(self): return riscos.getenvdict().items()
    def values(self): return riscos.getenvdict().values()
    def has_key(self, key):
        value = riscos.getenv(key)
        return value<>None
    def update(self, dict):
        for k, v in dict.items():
            riscos.putenv(k, v)
    def get(self, key, failobj=None):
        value = riscos.getenv(key)
        if value<>None:
            return value
        else:
            return failobj


#!/usr/bin/env python3

from setuptools import setup
from ipyrmd import __version__

with open("README.md") as f:
    long_desc = f.read()

setup(name="ipyrmd",
      version=__version__,
      description="Convert between IPython/Jupyter notebooks and RMarkdown",
      long_description=long_desc,
      author="Gordon Ball",
      author_email="gordon@chronitis.net",
      url="https://github.com/chronitis/ipyrmd",
      packages=["ipyrmd"],
      license="MIT",
      install_requires=["nbformat", "pyyaml"],
      scripts=["scripts/ipyrmd"],
      keywords="ipython jupyter irkernel rmarkdown ipynb",
      classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Environment :: Console",
        "Framework :: IPython",
        "Topic :: Scientific/Engineering",
        "Topic :: Utilities"
      ])

Response:
<REPLACE_OLD> __version__

setup(name="ipyrmd",
 <REPLACE_NEW> __version__

with open("README.md") as f:
    long_desc = f.read()

setup(name="ipyrmd",
 <REPLACE_END> <INSERT> long_description=long_desc,
      <INSERT_END> <|endoftext|> #!/usr/bin/env python3

from setuptools import setup
from ipyrmd import __version__

with open("README.md") as f:
    long_desc = f.read()

setup(name="ipyrmd",
      version=__version__,
      description="Convert between IPython/Jupyter notebooks and RMarkdown",
      long_description=long_desc,
      author="Gordon Ball",
      author_email="gordon@chronitis.net",
      url="https://github.com/chronitis/ipyrmd",
      packages=["ipyrmd"],
      license="MIT",
      install_requires=["nbformat", "pyyaml"],
      scripts=["scripts/ipyrmd"],
      keywords="ipython jupyter irkernel rmarkdown ipynb",
      classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Environment :: Console",
        "Framework :: IPython",
        "Topic :: Scientific/Engineering",
        "Topic :: Utilities"
      ])

Prompt:
Use contents of README as long_description

#!/usr/bin/env python3

from setuptools import setup
from ipyrmd import __version__

setup(name="ipyrmd",
      version=__version__,
      description="Convert between IPython/Jupyter notebooks and RMarkdown",
      author="Gordon Ball",
      author_email="gordon@chronitis.net",
      url="https://github.com/chronitis/ipyrmd",
      packages=["ipyrmd"],
      license="MIT",
      install_requires=["nbformat", "pyyaml"],
      scripts=["scripts/ipyrmd"],
      keywords="ipython jupyter irkernel rmarkdown ipynb",
      classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Environment :: Console",
        "Framework :: IPython",
        "Topic :: Scientific/Engineering",
        "Topic :: Utilities"
      ])


#!/usr/bin/python

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

"""Makes sure that the app/ code is cpplint clean."""

INCLUDE_CPP_FILES_ONLY = (
  r'.*\.cc$', r'.*\.h$'
)

EXCLUDE = (
  # Autogenerated window resources files are off limits
  r'.*resource.h$',
)

def CheckChangeOnUpload(input_api, output_api):
  results = []
  black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
  sources = lambda x: input_api.FilterSourceFile(
    x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
  results.extend(input_api.canned_checks.CheckChangeLintsClean(
      input_api, output_api, sources))
  return results

def GetPreferredTrySlaves():
  return ['win', 'linux', 'linux_view', 'linux_chromeos', 'mac']

Response:
<REPLACE_OLD> results
 <REPLACE_NEW> results

def GetPreferredTrySlaves():
  return ['win', 'linux', 'linux_view', 'linux_chromeos', 'mac']
 <REPLACE_END> <|endoftext|> #!/usr/bin/python

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

"""Makes sure that the app/ code is cpplint clean."""

INCLUDE_CPP_FILES_ONLY = (
  r'.*\.cc$', r'.*\.h$'
)

EXCLUDE = (
  # Autogenerated window resources files are off limits
  r'.*resource.h$',
)

def CheckChangeOnUpload(input_api, output_api):
  results = []
  black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
  sources = lambda x: input_api.FilterSourceFile(
    x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
  results.extend(input_api.canned_checks.CheckChangeLintsClean(
      input_api, output_api, sources))
  return results

def GetPreferredTrySlaves():
  return ['win', 'linux', 'linux_view', 'linux_chromeos', 'mac']

Prompt:
Make all changes to app/ run on all trybot platforms, not just the big three.
Anyone who's changing a header here may break the chromeos build.

BUG=none
TEST=none

Review URL: http://codereview.chromium.org/2838027

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51000 0039d316-1c4b-4281-b951-d872f2087c98

#!/usr/bin/python

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

"""Makes sure that the app/ code is cpplint clean."""

INCLUDE_CPP_FILES_ONLY = (
  r'.*\.cc$', r'.*\.h$'
)

EXCLUDE = (
  # Autogenerated window resources files are off limits
  r'.*resource.h$',
)

def CheckChangeOnUpload(input_api, output_api):
  results = []
  black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
  sources = lambda x: input_api.FilterSourceFile(
    x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
  results.extend(input_api.canned_checks.CheckChangeLintsClean(
      input_api, output_api, sources))
  return results


# coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig

def test_autoconfig_env():
    config = AutoConfig()
    path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project')
    with patch.object(config, '_caller_path', return_value=path):
        assert 'ENV' == config('KEY')

def test_autoconfig_ini():
    config = AutoConfig()
    path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project')
    with patch.object(config, '_caller_path', return_value=path):
        assert 'INI' == config('KEY')

def test_autoconfig_none():
    config = AutoConfig()
    with patch('os.path.exists', return_value=False):
        with patch.object(config, '_caller_path', return_value="/"):
            with pytest.raises(RuntimeError):
                config('KEY')

Replace cwd with current module's path

Replace cwd with current module's path

Response:
<REPLACE_OLD> os.path.join(os.getcwd(), <REPLACE_NEW> os.path.join(os.path.dirname(__file__), <REPLACE_END> <REPLACE_OLD> os.path.join(os.getcwd(), <REPLACE_NEW> os.path.join(os.path.dirname(__file__), <REPLACE_END> <|endoftext|> # coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig

def test_autoconfig_env():
    config = AutoConfig()
    path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project')
    with patch.object(config, '_caller_path', return_value=path):
        assert 'ENV' == config('KEY')

def test_autoconfig_ini():
    config = AutoConfig()
    path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project')
    with patch.object(config, '_caller_path', return_value=path):
        assert 'INI' == config('KEY')

def test_autoconfig_none():
    config = AutoConfig()
    with patch('os.path.exists', return_value=False):
        with patch.object(config, '_caller_path', return_value="/"):
            with pytest.raises(RuntimeError):
                config('KEY')

Prompt:
Replace cwd with current module's path
# coding: utf-8
import os
import pytest
from mock import patch
from decouple import AutoConfig

def test_autoconfig_env():
    config = AutoConfig()
    path = os.path.join(os.getcwd(), 'autoconfig', 'env', 'project')
    with patch.object(config, '_caller_path', return_value=path):
        assert 'ENV' == config('KEY')

def test_autoconfig_ini():
    config = AutoConfig()
    path = os.path.join(os.getcwd(), 'autoconfig', 'ini', 'project')
    with patch.object(config, '_caller_path', return_value=path):
        assert 'INI' == config('KEY')

def test_autoconfig_none():
    config = AutoConfig()
    with patch('os.path.exists', return_value=False):
        with patch.object(config, '_caller_path', return_value="/"):
            with pytest.raises(RuntimeError):
                config('KEY')


import openface
import numpy as np
import os
import cv2
import pickle

id_name = ["Alec", "Greg", "Phong", "Emil"]

def classify(aligned_face, net, clf, le):
    rep = net.forward(aligned_face)
    predictions = clf.predict_proba(rep.reshape((1, len(rep)))).ravel()
    maxI = np.argmax(predictions)
    person = le.inverse_transform(maxI)
    confidence = predictions[maxI]
    print("Predict {} with {:.2f} confidence.".format(person, confidence))
    return person

# path to the face alignment model
dLib_predictor = "../../resource/shaqpe_predictor_68_face_landmarks.dat"
# construct the face alignment model
align = openface.AlignDlib(dLib_predictor)
# path to deep neural network for feature representation
network_model = "../../resource/nn4.small2.v1.t7"
# construct the network for feature represenation
net = openface.TorchNeuralNet(network_model, 96)

classifier_model = "../../resource/svm.pkl"

with open(classifier_model, 'r') as f:
    (le, clf) = pickle.load(f)
    print("Successfully loaded SVM model")
    video = cv2.VideoCapture(0)
    if video is None:
        exit()

    while True:
        # grab image
        ret, cameraFrame = video.read()
        if not ret:
            exit()
        try:
            bbs = align.getAllFaceBoundingBoxes(cameraFrame)
            print("Found {} face".format(len(bbs)))
            for bb2 in bbs:
                alignedFace = align.align(96, cameraFrame, bb2,
                                            landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)
                id = classify(alignedFace, net, clf, le)
                person_name = id_name[id]
                print(person_name)

                rectColor = (0,255, 0)
                textColor = (255, 0, 0)
                face_top_left = (bb2.left(), bb2.top())
                face_bottom_right = (bb2.right(), bb2.bottom())
                cv2.rectangle(cameraFrame, face_top_left, face_bottom_right, rectColor)
                cv2.putText(cameraFrame, person_name, face_top_left,
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=textColor, thickness=2)

            cv2.imshow('FaceRecognizer', cameraFrame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        except:
            cv2.imshow('FaceRecognize', cameraFrame)
            continue

Use the model to classify face in local camera.

Response:
<REPLACE_OLD>  <REPLACE_NEW> import openface
import numpy as np
import os
import cv2
import pickle

id_name = ["Alec", "Greg", "Phong", "Emil"]

def classify(aligned_face, net, clf, le):
    rep = net.forward(aligned_face)
    predictions = clf.predict_proba(rep.reshape((1, len(rep)))).ravel()
    maxI = np.argmax(predictions)
    person = le.inverse_transform(maxI)
    confidence = predictions[maxI]
    print("Predict {} with {:.2f} confidence.".format(person, confidence))
    return person

# path to the face alignment model
dLib_predictor = "../../resource/shaqpe_predictor_68_face_landmarks.dat"
# construct the face alignment model
align = openface.AlignDlib(dLib_predictor)
# path to deep neural network for feature representation
network_model = "../../resource/nn4.small2.v1.t7"
# construct the network for feature represenation
net = openface.TorchNeuralNet(network_model, 96)

classifier_model = "../../resource/svm.pkl"

with open(classifier_model, 'r') as f:
    (le, clf) = pickle.load(f)
    print("Successfully loaded SVM model")
    video = cv2.VideoCapture(0)
    if video is None:
        exit()

    while True:
        # grab image
        ret, cameraFrame = video.read()
        if not ret:
            exit()
        try:
            bbs = align.getAllFaceBoundingBoxes(cameraFrame)
            print("Found {} face".format(len(bbs)))
            for bb2 in bbs:
                alignedFace = align.align(96, cameraFrame, bb2,
                                            landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)
                id = classify(alignedFace, net, clf, le)
                person_name = id_name[id]
                print(person_name)

                rectColor = (0,255, 0)
                textColor = (255, 0, 0)
                face_top_left = (bb2.left(), bb2.top())
                face_bottom_right = (bb2.right(), bb2.bottom())
                cv2.rectangle(cameraFrame, face_top_left, face_bottom_right, rectColor)
                cv2.putText(cameraFrame, person_name, face_top_left,
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=textColor, thickness=2)

            cv2.imshow('FaceRecognizer', cameraFrame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        except:
            cv2.imshow('FaceRecognize', cameraFrame)
            continue
 <REPLACE_END> <|endoftext|> import openface
import numpy as np
import os
import cv2
import pickle

id_name = ["Alec", "Greg", "Phong", "Emil"]

def classify(aligned_face, net, clf, le):
    rep = net.forward(aligned_face)
    predictions = clf.predict_proba(rep.reshape((1, len(rep)))).ravel()
    maxI = np.argmax(predictions)
    person = le.inverse_transform(maxI)
    confidence = predictions[maxI]
    print("Predict {} with {:.2f} confidence.".format(person, confidence))
    return person

# path to the face alignment model
dLib_predictor = "../../resource/shaqpe_predictor_68_face_landmarks.dat"
# construct the face alignment model
align = openface.AlignDlib(dLib_predictor)
# path to deep neural network for feature representation
network_model = "../../resource/nn4.small2.v1.t7"
# construct the network for feature represenation
net = openface.TorchNeuralNet(network_model, 96)

classifier_model = "../../resource/svm.pkl"

with open(classifier_model, 'r') as f:
    (le, clf) = pickle.load(f)
    print("Successfully loaded SVM model")
    video = cv2.VideoCapture(0)
    if video is None:
        exit()

    while True:
        # grab image
        ret, cameraFrame = video.read()
        if not ret:
            exit()
        try:
            bbs = align.getAllFaceBoundingBoxes(cameraFrame)
            print("Found {} face".format(len(bbs)))
            for bb2 in bbs:
                alignedFace = align.align(96, cameraFrame, bb2,
                                            landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)
                id = classify(alignedFace, net, clf, le)
                person_name = id_name[id]
                print(person_name)

                rectColor = (0,255, 0)
                textColor = (255, 0, 0)
                face_top_left = (bb2.left(), bb2.top())
                face_bottom_right = (bb2.right(), bb2.bottom())
                cv2.rectangle(cameraFrame, face_top_left, face_bottom_right, rectColor)
                cv2.putText(cameraFrame, person_name, face_top_left,
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1, color=textColor, thickness=2)

            cv2.imshow('FaceRecognizer', cameraFrame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        except:
            cv2.imshow('FaceRecognize', cameraFrame)
            continue

Prompt: Use the model to classify face in local camera.


# Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
    name="rc build",
    builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
    reason=FixedParameter(name="reason", default=""),
    branch=FixedParameter(name="branch", default=""),
    repository=FixedParameter(name="repository", default=""),
    project=FixedParameter(name="project", default="Packaging"),
    properties=[
    ]
)
c['schedulers'].append(rc_scheduler)

Add ppc64le tarball rc force builder

Add ppc64le tarball rc force builder

Response:
<REPLACE_OLD> "package_tarballarm"],
 <REPLACE_NEW> "package_tarballarm", "package_tarballppc64le"],
 <REPLACE_END> <|endoftext|> # Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
    name="rc build",
    builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm", "package_tarballppc64le"],
    reason=FixedParameter(name="reason", default=""),
    branch=FixedParameter(name="branch", default=""),
    repository=FixedParameter(name="repository", default=""),
    project=FixedParameter(name="project", default="Packaging"),
    properties=[
    ]
)
c['schedulers'].append(rc_scheduler)

Prompt:
Add ppc64le tarball rc force builder

# Add a manual scheduler for building release candidates
rc_scheduler = ForceScheduler(
    name="rc build",
    builderNames=["package_osx10.9-x64", "package_win6.2-x64", "package_win6.2-x86", "package_tarball64", "package_tarball32", "package_tarballarm"],
    reason=FixedParameter(name="reason", default=""),
    branch=FixedParameter(name="branch", default=""),
    repository=FixedParameter(name="repository", default=""),
    project=FixedParameter(name="project", default="Packaging"),
    properties=[
    ]
)
c['schedulers'].append(rc_scheduler)


#!/usr/bin/env python
import sys
from os.path import dirname, abspath

from django.conf import settings

if not settings.configured:
    settings.configure(
        DATABASE_ENGINE='django.db.backends.postgresql_psycopg2',
        DATABASE_NAME='bitfield_test',
        INSTALLED_APPS=[
            'django.contrib.contenttypes',
            'bitfield',
            'bitfield.tests',
        ],
        ROOT_URLCONF='',
        DEBUG=False,
    )

from django.test.simple import run_tests

def runtests(*test_args):
    if not test_args:
        test_args = ['bitfield']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests(*sys.argv[1:])

Response:
<REPLACE_OLD> 'django.contrib.contettypes',
 <REPLACE_NEW> 'django.contrib.contenttypes',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
import sys
from os.path import dirname, abspath

from django.conf import settings

if not settings.configured:
    settings.configure(
        DATABASE_ENGINE='django.db.backends.postgresql_psycopg2',
        DATABASE_NAME='bitfield_test',
        INSTALLED_APPS=[
            'django.contrib.contenttypes',
            'bitfield',
            'bitfield.tests',
        ],
        ROOT_URLCONF='',
        DEBUG=False,
    )

from django.test.simple import run_tests

def runtests(*test_args):
    if not test_args:
        test_args = ['bitfield']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests(*sys.argv[1:])

Prompt:
Test suite requires me to spell contenttypes correctly

#!/usr/bin/env python
import sys
from os.path import dirname, abspath

from django.conf import settings

if not settings.configured:
    settings.configure(
        DATABASE_ENGINE='django.db.backends.postgresql_psycopg2',
        DATABASE_NAME='bitfield_test',
        INSTALLED_APPS=[
            'django.contrib.contettypes',
            'bitfield',
            'bitfield.tests',
        ],
        ROOT_URLCONF='',
        DEBUG=False,
    )

from django.test.simple import run_tests

def runtests(*test_args):
    if not test_args:
        test_args = ['bitfield']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests(*sys.argv[1:])


import logging

from openspending.lib import cubes
from openspending import migration, model, mongo

log = logging.getLogger(__name__)

def up():
    group_args = ({'dataset':1}, {}, {'num': 0},
                  'function (x, acc) { acc.num += 1 }')

    before = mongo.db.dimension.group(*group_args)
    dims = model.dimension.find({'type': {'$nin': ['entity', 'classifier']}})
    for d in dims:
        log.info("Removing dimension: %s", d)
        model.dimension.remove({'_id': d['_id']})
    after = mongo.db.dimension.group(*group_args)

    for bf, af in zip(before, after):
        if int(bf['num']) != int(af['num']):
            log.warn("Number of dimensions for dimension '%s' "
                     "changed. Recomputing cubes.", bf['dataset'])
            ds = model.dataset.find_one({'name': bf['dataset']})
            cubes.Cube.update_all_cubes(ds)

def down():
    raise migration.IrreversibleMigrationError("Can't add back dimension "
                                               "fields that we dropped!")

Add migration to remove non-{entity,classifier} dimensions from the database, and to recompute cubes if necessary

Response:
<REPLACE_OLD>  <REPLACE_NEW> import logging

from openspending.lib import cubes
from openspending import migration, model, mongo

log = logging.getLogger(__name__)

def up():
    group_args = ({'dataset':1}, {}, {'num': 0},
                  'function (x, acc) { acc.num += 1 }')

    before = mongo.db.dimension.group(*group_args)
    dims = model.dimension.find({'type': {'$nin': ['entity', 'classifier']}})
    for d in dims:
        log.info("Removing dimension: %s", d)
        model.dimension.remove({'_id': d['_id']})
    after = mongo.db.dimension.group(*group_args)

    for bf, af in zip(before, after):
        if int(bf['num']) != int(af['num']):
            log.warn("Number of dimensions for dimension '%s' "
                     "changed. Recomputing cubes.", bf['dataset'])
            ds = model.dataset.find_one({'name': bf['dataset']})
            cubes.Cube.update_all_cubes(ds)

def down():
    raise migration.IrreversibleMigrationError("Can't add back dimension "
                                               "fields that we dropped!") <REPLACE_END> <|endoftext|> import logging

from openspending.lib import cubes
from openspending import migration, model, mongo

log = logging.getLogger(__name__)

def up():
    group_args = ({'dataset':1}, {}, {'num': 0},
                  'function (x, acc) { acc.num += 1 }')

    before = mongo.db.dimension.group(*group_args)
    dims = model.dimension.find({'type': {'$nin': ['entity', 'classifier']}})
    for d in dims:
        log.info("Removing dimension: %s", d)
        model.dimension.remove({'_id': d['_id']})
    after = mongo.db.dimension.group(*group_args)

    for bf, af in zip(before, after):
        if int(bf['num']) != int(af['num']):
            log.warn("Number of dimensions for dimension '%s' "
                     "changed. Recomputing cubes.", bf['dataset'])
            ds = model.dataset.find_one({'name': bf['dataset']})
            cubes.Cube.update_all_cubes(ds)

def down():
    raise migration.IrreversibleMigrationError("Can't add back dimension "
                                               "fields that we dropped!")

Prompt: Add migration to remove non-{entity,classifier} dimensions from the database, and to recompute cubes if necessary


######
#  Check ExId (GUID) by Email through JDBC
#
#  Author:        Christoph Stoettner
#  Mail:          christoph.stoettner@stoeps.de
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-04
#
#  License:       Apache 2.0
#
#  Check ExId of a User in all Connections Applications

import ibmcnx.functions

cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"

# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
    dbname = db.split('(')
    n = 0
    for i in dbname:
        if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
            dblist.append(str(db).replace('"',''))
        n += 1

dblist.sort()

for db in dblist:
      #t1 = ibmcnx.functions.getDSId( db )
      print db
#      AdminConfig.show( t1 )
#      print '\n\n'
#      AdminConfig.showall( t1 )
#      AdminConfig.showAttribute(t1,'statementCacheSize' )
#      AdminConfig.showAttribute(t1,'[statementCacheSize]' )

Response:
<REPLACE_OLD> db <REPLACE_NEW> dbname <REPLACE_END> <REPLACE_OLD> db:
 <REPLACE_NEW> dbname:
 <REPLACE_END> <REPLACE_OLD> dblist.append(str(i).replace('"',''))
 <REPLACE_NEW> dblist.append(str(db).replace('"',''))
 <REPLACE_END> <REPLACE_OLD> t1 <REPLACE_NEW> #t1 <REPLACE_END> <REPLACE_OLD> t1
# <REPLACE_NEW> db
# <REPLACE_END> <|endoftext|> ######
#  Check ExId (GUID) by Email through JDBC
#
#  Author:        Christoph Stoettner
#  Mail:          christoph.stoettner@stoeps.de
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-04
#
#  License:       Apache 2.0
#
#  Check ExId of a User in all Connections Applications

import ibmcnx.functions

cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"

# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
    dbname = db.split('(')
    n = 0
    for i in dbname:
        if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
            dblist.append(str(db).replace('"',''))
        n += 1

dblist.sort()

for db in dblist:
      #t1 = ibmcnx.functions.getDSId( db )
      print db
#      AdminConfig.show( t1 )
#      print '\n\n'
#      AdminConfig.showall( t1 )
#      AdminConfig.showAttribute(t1,'statementCacheSize' )
#      AdminConfig.showAttribute(t1,'[statementCacheSize]' )

Prompt:
8: Create documentation of DataSource Settings

Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
######
#  Check ExId (GUID) by Email through JDBC
#
#  Author:        Christoph Stoettner
#  Mail:          christoph.stoettner@stoeps.de
#  Documentation: http://scripting101.stoeps.de
#
#  Version:       2.0
#  Date:          2014-06-04
#
#  License:       Apache 2.0
#
#  Check ExId of a User in all Connections Applications

import ibmcnx.functions

cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"

# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
    db = db.split('(')
    n = 0
    for i in db:
        if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
            dblist.append(str(i).replace('"',''))
        n += 1

dblist.sort()

for db in dblist:
      t1 = ibmcnx.functions.getDSId( db )
      print t1
#      AdminConfig.show( t1 )
#      print '\n\n'
#      AdminConfig.showall( t1 )
#      AdminConfig.showAttribute(t1,'statementCacheSize' )
#      AdminConfig.showAttribute(t1,'[statementCacheSize]' )


### -*- coding: utf-8 -*-
###
### © 2012 Krux Digital, Inc.
### Author: Paul Lathrop <paul@krux.com>
###

from setuptools import setup, find_packages

setup(name='pysecurity-groups',
      version="1.0.0",
      description='Library for working with EC2 security groups in bulk.',
      author='Paul Lathrop',
      author_email='paul@krux.com',
      url='https://github.com/krux/pysecurity-groups',
      packages=find_packages(),
      install_requires=['boto', 'argparse', 'IPy'],
      entry_points={'console_scripts':
                    ['security-groups = pysecurity_groups.cli:main'] },
      )

Update release version to 1.0.0

Update release version to 1.0.0

Response:
<REPLACE_OLD> version="0.0.1",
 <REPLACE_NEW> version="1.0.0",
 <REPLACE_END> <|endoftext|> ### -*- coding: utf-8 -*-
###
### © 2012 Krux Digital, Inc.
### Author: Paul Lathrop <paul@krux.com>
###

from setuptools import setup, find_packages

setup(name='pysecurity-groups',
      version="1.0.0",
      description='Library for working with EC2 security groups in bulk.',
      author='Paul Lathrop',
      author_email='paul@krux.com',
      url='https://github.com/krux/pysecurity-groups',
      packages=find_packages(),
      install_requires=['boto', 'argparse', 'IPy'],
      entry_points={'console_scripts':
                    ['security-groups = pysecurity_groups.cli:main'] },
      )

Prompt:
Update release version to 1.0.0

### -*- coding: utf-8 -*-
###
### © 2012 Krux Digital, Inc.
### Author: Paul Lathrop <paul@krux.com>
###

from setuptools import setup, find_packages

setup(name='pysecurity-groups',
      version="0.0.1",
      description='Library for working with EC2 security groups in bulk.',
      author='Paul Lathrop',
      author_email='paul@krux.com',
      url='https://github.com/krux/pysecurity-groups',
      packages=find_packages(),
      install_requires=['boto', 'argparse', 'IPy'],
      entry_points={'console_scripts':
                    ['security-groups = pysecurity_groups.cli:main'] },
      )


__version__ = '2.0.0'

def get_account(using=None):
    from django.conf import settings
    accounts = settings.SMSGATEWAY_ACCOUNTS
    if using is not None:
        return accounts[using]
    else:
        return accounts[accounts['__default__']]

def send(to, msg, signature, using=None, reliable=False):
    """
    Send an SMS message immediately.

    *   'to' is a semicolon separated list of phone numbers with an international
        prefix (+32... etc).
    *   'msg' is the message itself as a unicode object (max 160 characters).
    *   'signature' is where the message comes from. Depends on the backend in use.
    *   'using' is an optional parameter where you can specify a specific account
        to send messages from.
    """
    from smsgateway.backends import get_backend
    from smsgateway.sms import SMSRequest
    account_dict = get_account(using)
    backend = get_backend(account_dict['backend'])
    sms_request = SMSRequest(to, msg, signature, reliable=reliable)
    return backend.send(sms_request, account_dict)

def send_queued(to, msg, signature, using=None, reliable=False, priority=None):
    """
    Place SMS message in queue to be sent.
    """
    from smsgateway.models import QueuedSMS
    queued_sms = QueuedSMS(
        to=to,
        content=msg,
        signature=signature,
        using=using if using is not None else '__none__',
        reliable=reliable
    )
    if priority is not None:
        queued_sms.priority = priority
    queued_sms.save()

Add priority option to send_queued

Add priority option to send_queued

Response:
<REPLACE_OLD> reliable=False):
 <REPLACE_NEW> reliable=False, priority=None):
 <REPLACE_END> <REPLACE_OLD> QueuedSMS.objects.create(
 <REPLACE_NEW> queued_sms = QueuedSMS(
 <REPLACE_END> <INSERT>    if priority is not None:
        queued_sms.priority = priority
    queued_sms.save()
 <INSERT_END> <|endoftext|> __version__ = '2.0.0'

def get_account(using=None):
    from django.conf import settings
    accounts = settings.SMSGATEWAY_ACCOUNTS
    if using is not None:
        return accounts[using]
    else:
        return accounts[accounts['__default__']]

def send(to, msg, signature, using=None, reliable=False):
    """
    Send an SMS message immediately.

    *   'to' is a semicolon separated list of phone numbers with an international
        prefix (+32... etc).
    *   'msg' is the message itself as a unicode object (max 160 characters).
    *   'signature' is where the message comes from. Depends on the backend in use.
    *   'using' is an optional parameter where you can specify a specific account
        to send messages from.
    """
    from smsgateway.backends import get_backend
    from smsgateway.sms import SMSRequest
    account_dict = get_account(using)
    backend = get_backend(account_dict['backend'])
    sms_request = SMSRequest(to, msg, signature, reliable=reliable)
    return backend.send(sms_request, account_dict)

def send_queued(to, msg, signature, using=None, reliable=False, priority=None):
    """
    Place SMS message in queue to be sent.
    """
    from smsgateway.models import QueuedSMS
    queued_sms = QueuedSMS(
        to=to,
        content=msg,
        signature=signature,
        using=using if using is not None else '__none__',
        reliable=reliable
    )
    if priority is not None:
        queued_sms.priority = priority
    queued_sms.save()

Prompt:
Add priority option to send_queued

__version__ = '2.0.0'

def get_account(using=None):
    from django.conf import settings
    accounts = settings.SMSGATEWAY_ACCOUNTS
    if using is not None:
        return accounts[using]
    else:
        return accounts[accounts['__default__']]

def send(to, msg, signature, using=None, reliable=False):
    """
    Send an SMS message immediately.

    *   'to' is a semicolon separated list of phone numbers with an international
        prefix (+32... etc).
    *   'msg' is the message itself as a unicode object (max 160 characters).
    *   'signature' is where the message comes from. Depends on the backend in use.
    *   'using' is an optional parameter where you can specify a specific account
        to send messages from.
    """
    from smsgateway.backends import get_backend
    from smsgateway.sms import SMSRequest
    account_dict = get_account(using)
    backend = get_backend(account_dict['backend'])
    sms_request = SMSRequest(to, msg, signature, reliable=reliable)
    return backend.send(sms_request, account_dict)

def send_queued(to, msg, signature, using=None, reliable=False):
    """
    Place SMS message in queue to be sent.
    """
    from smsgateway.models import QueuedSMS
    QueuedSMS.objects.create(
        to=to,
        content=msg,
        signature=signature,
        using=using if using is not None else '__none__',
        reliable=reliable
    )


#!/usr/bin/env python

import argparse

from githublist.parser import main as get_data
from githublist.serve import serve_content

parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
                    choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
                    help='File output format.')

def main():
    args = parser.parse_args()
    user = args.user
    format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format

    for u in user:
        print('Preparing data for {}...'.format(u))
        d = get_data(u)
        for f in format_:
            if f is not None:
                print(' Writing {}...'.format(f), end='')
                serve_content(d, u, f)
                print(' Done!')
            else:
                serve_content(d, u, f)
    print('Complete!')
    return None

if __name__ == '__main__':
    main()

Response:
<INSERT> nargs='+', <INSERT_END> <INSERT> nargs='+',
                    <INSERT_END> <REPLACE_OLD> 'tbl.txt'],
 <REPLACE_NEW> 'tbl.txt', 'all'],
 <REPLACE_END> <REPLACE_OLD> user, <REPLACE_NEW> user = args.user
    <REPLACE_END> <REPLACE_OLD> args.user, <REPLACE_NEW> ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else <REPLACE_END> <INSERT> for u in user:
        print('Preparing data for {}...'.format(u))
        d = get_data(u)
        for f in format_:
            if f is not None:
                print(' Writing {}...'.format(f), end='')
                serve_content(d, u, f)
                print(' Done!')
            else:
                serve_content(d, u, f)
    print('Complete!')
    <INSERT_END> <REPLACE_OLD> serve_content(get_data(user), user, format_)

if <REPLACE_NEW> None

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

import argparse

from githublist.parser import main as get_data
from githublist.serve import serve_content

parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f', '--format', nargs='+',
                    choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt', 'all'],
                    help='File output format.')

def main():
    args = parser.parse_args()
    user = args.user
    format_ = ['json', 'csv', 'md', 'raw.txt', 'tbl.txt'] if 'all' in args.format else args.format

    for u in user:
        print('Preparing data for {}...'.format(u))
        d = get_data(u)
        for f in format_:
            if f is not None:
                print(' Writing {}...'.format(f), end='')
                serve_content(d, u, f)
                print(' Done!')
            else:
                serve_content(d, u, f)
    print('Complete!')
    return None

if __name__ == '__main__':
    main()

Prompt:
Add support for multiple users, format types

#!/usr/bin/env python

import argparse

from githublist.parser import main as get_data
from githublist.serve import serve_content

parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--format', choices=['json', 'csv', 'md', 'raw.txt', 'tbl.txt'],
                    help='File output format.')

def main():
    args = parser.parse_args()
    user, format_ = args.user, args.format

    return serve_content(get_data(user), user, format_)

if __name__ == '__main__':
    main()


import sys
import bsddb3
from xclib.utf8 import utf8, unutf8

def perform(args):
    domain_db = bsddb3.hashopen(args.domain_db, 'c', 0o600)
    if args.get:
        print(unutf8(domain_db[utf8(args.get)], 'illegal'))
    elif args.put:
        domain_db[utf8(args.put[0])] = args.put[1]
    elif args.delete:
        del domain_db[utf8(args.delete)]
    elif args.unload:
        for k in list(domain_db.keys()):
            print('%s\t%s' % (unutf8(k, 'illegal'), unutf8(domain_db[k], 'illegal')))
        # Should work according to documentation, but doesn't
        # for k, v in DOMAIN_DB.iteritems():
        #     print k, '\t', v
    elif args.load:
        for line in sys.stdin:
            k, v = line.rstrip('\r\n').split('\t', 1)
            domain_db[utf8(k)] = v
    domain_db.close()

# vim: tabstop=8 softtabstop=0 expandtab shiftwidth=4

Allow dumping illegal utf-8 contents

Allow dumping illegal utf-8 contents

Response:
<REPLACE_OLD> print(unutf8(domain_db[utf8(args.get)]))
 <REPLACE_NEW> print(unutf8(domain_db[utf8(args.get)], 'illegal'))
 <REPLACE_END> <REPLACE_OLD> (unutf8(k), unutf8(domain_db[k])))
 <REPLACE_NEW> (unutf8(k, 'illegal'), unutf8(domain_db[k], 'illegal')))
 <REPLACE_END> <|endoftext|> import sys
import bsddb3
from xclib.utf8 import utf8, unutf8

def perform(args):
    domain_db = bsddb3.hashopen(args.domain_db, 'c', 0o600)
    if args.get:
        print(unutf8(domain_db[utf8(args.get)], 'illegal'))
    elif args.put:
        domain_db[utf8(args.put[0])] = args.put[1]
    elif args.delete:
        del domain_db[utf8(args.delete)]
    elif args.unload:
        for k in list(domain_db.keys()):
            print('%s\t%s' % (unutf8(k, 'illegal'), unutf8(domain_db[k], 'illegal')))
        # Should work according to documentation, but doesn't
        # for k, v in DOMAIN_DB.iteritems():
        #     print k, '\t', v
    elif args.load:
        for line in sys.stdin:
            k, v = line.rstrip('\r\n').split('\t', 1)
            domain_db[utf8(k)] = v
    domain_db.close()

# vim: tabstop=8 softtabstop=0 expandtab shiftwidth=4

Prompt:
Allow dumping illegal utf-8 contents

import sys
import bsddb3
from xclib.utf8 import utf8, unutf8

def perform(args):
    domain_db = bsddb3.hashopen(args.domain_db, 'c', 0o600)
    if args.get:
        print(unutf8(domain_db[utf8(args.get)]))
    elif args.put:
        domain_db[utf8(args.put[0])] = args.put[1]
    elif args.delete:
        del domain_db[utf8(args.delete)]
    elif args.unload:
        for k in list(domain_db.keys()):
            print('%s\t%s' % (unutf8(k), unutf8(domain_db[k])))
        # Should work according to documentation, but doesn't
        # for k, v in DOMAIN_DB.iteritems():
        #     print k, '\t', v
    elif args.load:
        for line in sys.stdin:
            k, v = line.rstrip('\r\n').split('\t', 1)
            domain_db[utf8(k)] = v
    domain_db.close()

# vim: tabstop=8 softtabstop=0 expandtab shiftwidth=4


from setuptools import setup, find_packages
import sys

install_reqs = [
    "decorator>=3.3.2"
]
test_reqs = [
     "Pillow>=2.5.0"
]

if sys.version_info[0] == 2:
    # simplejson is not python3 compatible
    install_reqs.append("simplejson>=2.0.9")

if [sys.version_info[0], sys.version_info[1]] < [2, 7]:
    install_reqs.append("argparse>=1.2")

setup(
    name = "dogapi",
    version = "1.9.1",
    packages = find_packages("src"),
    package_dir = {'':'src'},
    author = "Datadog, Inc.",
    author_email = "packages@datadoghq.com",
    description = "Python bindings to Datadog's API and a user-facing command line tool.",
    license = "BSD",
    keywords = "datadog data",
    url = "http://www.datadoghq.com",
    install_requires = install_reqs,
    tests_require = test_reqs,
    entry_points = {
        'console_scripts': [
            'dog = dogshell:main',
            'dogwrap = dogshell.wrap:main',
        ],
    },
)

Move Pillow to tests requirements

Move Pillow to tests requirements

Response:
<REPLACE_OLD> sys

reqs <REPLACE_NEW> sys

install_reqs <REPLACE_END> <REPLACE_OLD> "decorator>=3.3.2",
 <REPLACE_NEW> "decorator>=3.3.2"
]
test_reqs = [
 <REPLACE_END> <REPLACE_OLD> "Pillow>=2.5.0"
]
if <REPLACE_NEW>  "Pillow>=2.5.0"
]

if <REPLACE_END> <REPLACE_OLD> reqs.append("simplejson>=2.0.9")

if <REPLACE_NEW> install_reqs.append("simplejson>=2.0.9")

if <REPLACE_END> <REPLACE_OLD> reqs.append("argparse>=1.2")

setup(
 <REPLACE_NEW> install_reqs.append("argparse>=1.2")

setup(
 <REPLACE_END> <REPLACE_OLD> reqs,
 <REPLACE_NEW> install_reqs,
 <REPLACE_END> <REPLACE_OLD> entry_points={
 <REPLACE_NEW> tests_require = test_reqs,
    entry_points = {
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
import sys

install_reqs = [
    "decorator>=3.3.2"
]
test_reqs = [
     "Pillow>=2.5.0"
]

if sys.version_info[0] == 2:
    # simplejson is not python3 compatible
    install_reqs.append("simplejson>=2.0.9")

if [sys.version_info[0], sys.version_info[1]] < [2, 7]:
    install_reqs.append("argparse>=1.2")

setup(
    name = "dogapi",
    version = "1.9.1",
    packages = find_packages("src"),
    package_dir = {'':'src'},
    author = "Datadog, Inc.",
    author_email = "packages@datadoghq.com",
    description = "Python bindings to Datadog's API and a user-facing command line tool.",
    license = "BSD",
    keywords = "datadog data",
    url = "http://www.datadoghq.com",
    install_requires = install_reqs,
    tests_require = test_reqs,
    entry_points = {
        'console_scripts': [
            'dog = dogshell:main',
            'dogwrap = dogshell.wrap:main',
        ],
    },
)

Prompt:
Move Pillow to tests requirements

from setuptools import setup, find_packages
import sys

reqs = [
    "decorator>=3.3.2",
    "Pillow>=2.5.0"
]
if sys.version_info[0] == 2:
    # simplejson is not python3 compatible
    reqs.append("simplejson>=2.0.9")

if [sys.version_info[0], sys.version_info[1]] < [2, 7]:
    reqs.append("argparse>=1.2")

setup(
    name = "dogapi",
    version = "1.9.1",
    packages = find_packages("src"),
    package_dir = {'':'src'},
    author = "Datadog, Inc.",
    author_email = "packages@datadoghq.com",
    description = "Python bindings to Datadog's API and a user-facing command line tool.",
    license = "BSD",
    keywords = "datadog data",
    url = "http://www.datadoghq.com",
    install_requires = reqs,
    entry_points={
        'console_scripts': [
            'dog = dogshell:main',
            'dogwrap = dogshell.wrap:main',
        ],
    },
)


#!/usr/bin/env python3

import i3ipc

# make connection to i3 ipc
i3 = i3ipc.Connection()

# check if workspaces are all in order
def workspaces_ordered(i3conn):
    last_workspace_number = 0
    for i in sorted(i3conn.get_workspaces(), key=lambda x: x['num']):
        if i['num'] != last_workspace_number+1:
            return False
        last_workspace_number += 1
    return True

# find all the workspaces that are out of order and
# the least possible valid workspace number that is unassigned
def find_disordered(i3conn):
    last_workspace_number = 0
    disordered = []
    least_number = None
    for i in sorted(i3conn.get_workspaces(), key=lambda x: x['num']):
        if i['num'] != last_workspace_number+1:
            disordered.append(i['num'])
            if least_number is None:
                least_number = last_workspace_number + 1
        last_workspace_number += 1
    return (disordered, least_number)

# renumber all the workspaces that appear out of order from the others
def fix_ordering(i3conn):
    if workspaces_ordered(i3conn):
        return
    else:
        workspaces = i3conn.get_tree().workspaces()
        disordered_workspaces,least_number = find_disordered(i3conn)
        containers = list(filter(lambda x: x.num in disordered_workspaces, workspaces))
        for c in containers:
            for i in c.leaves():
                i.command("move container to workspace %s" % least_number)
            least_number += 1
    return

# callback for when workspace focus changes
def on_workspace_focus(i3conn, e):
    fix_ordering(i3conn)

if __name__ == '__main__':
    i3.on('workspace::focus', on_workspace_focus)
    i3.main()

Add script that makes sure workspace numbers are always in consecutive order by moving windows on out of order workspaces to the appropriate workspace

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python3

import i3ipc

# make connection to i3 ipc
i3 = i3ipc.Connection()

# check if workspaces are all in order
def workspaces_ordered(i3conn):
    last_workspace_number = 0
    for i in sorted(i3conn.get_workspaces(), key=lambda x: x['num']):
        if i['num'] != last_workspace_number+1:
            return False
        last_workspace_number += 1
    return True

# find all the workspaces that are out of order and
# the least possible valid workspace number that is unassigned
def find_disordered(i3conn):
    last_workspace_number = 0
    disordered = []
    least_number = None
    for i in sorted(i3conn.get_workspaces(), key=lambda x: x['num']):
        if i['num'] != last_workspace_number+1:
            disordered.append(i['num'])
            if least_number is None:
                least_number = last_workspace_number + 1
        last_workspace_number += 1
    return (disordered, least_number)

# renumber all the workspaces that appear out of order from the others
def fix_ordering(i3conn):
    if workspaces_ordered(i3conn):
        return
    else:
        workspaces = i3conn.get_tree().workspaces()
        disordered_workspaces,least_number = find_disordered(i3conn)
        containers = list(filter(lambda x: x.num in disordered_workspaces, workspaces))
        for c in containers:
            for i in c.leaves():
                i.command("move container to workspace %s" % least_number)
            least_number += 1
    return

# callback for when workspace focus changes
def on_workspace_focus(i3conn, e):
    fix_ordering(i3conn)

if __name__ == '__main__':
    i3.on('workspace::focus', on_workspace_focus)
    i3.main()

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

import i3ipc

# make connection to i3 ipc
i3 = i3ipc.Connection()

# check if workspaces are all in order
def workspaces_ordered(i3conn):
    last_workspace_number = 0
    for i in sorted(i3conn.get_workspaces(), key=lambda x: x['num']):
        if i['num'] != last_workspace_number+1:
            return False
        last_workspace_number += 1
    return True

# find all the workspaces that are out of order and
# the least possible valid workspace number that is unassigned
def find_disordered(i3conn):
    last_workspace_number = 0
    disordered = []
    least_number = None
    for i in sorted(i3conn.get_workspaces(), key=lambda x: x['num']):
        if i['num'] != last_workspace_number+1:
            disordered.append(i['num'])
            if least_number is None:
                least_number = last_workspace_number + 1
        last_workspace_number += 1
    return (disordered, least_number)

# renumber all the workspaces that appear out of order from the others
def fix_ordering(i3conn):
    if workspaces_ordered(i3conn):
        return
    else:
        workspaces = i3conn.get_tree().workspaces()
        disordered_workspaces,least_number = find_disordered(i3conn)
        containers = list(filter(lambda x: x.num in disordered_workspaces, workspaces))
        for c in containers:
            for i in c.leaves():
                i.command("move container to workspace %s" % least_number)
            least_number += 1
    return

# callback for when workspace focus changes
def on_workspace_focus(i3conn, e):
    fix_ordering(i3conn)

if __name__ == '__main__':
    i3.on('workspace::focus', on_workspace_focus)
    i3.main()

Prompt:
Add script that makes sure workspace numbers are always in consecutive
order by moving windows on out of order workspaces to the appropriate
workspace


import os

"""
Loader settings:
we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the
same id_sample based on the hash of the file name
"""

inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat'
keyFormatClass = 'org.apache.hadoop.io.LongWritable'
valueFormatClass = 'org.apache.hadoop.io.Text'
defaultCombineSize = 64

# configuration of the Hadoop loader used by spark
conf = {"textinputformat.record.delimiter": "\n",
        "mapreduce.input.fileinputformat.input.dir.recursive": "true",
        "mapred.max.split.size": str(defaultCombineSize*1024*1024)
        }

"""
    Generation of the index of the pandas dataframe.
    This can be done in different ways:
    - hashing the complete file name
    - using directly the file as index (this is visually appealing :) )
"""

def generateHashKey(filename):
    return hash(filename)

def generateNameKey(filename):
    filename = os.path.basename(filename)
    if filename.endswith(".meta"):
        return filename[:-5]
    else:
        return filename

Use only the base file name for key

Response:
<REPLACE_OLD> """
Loader <REPLACE_NEW> import os

"""
Loader <REPLACE_END> <REPLACE_OLD> }

def <REPLACE_NEW> }

"""
    Generation of the index of the pandas dataframe.
    This can be done in different ways:
    - hashing the complete file name
    - using directly the file as index (this is visually appealing :) )
"""

def <REPLACE_END> <INSERT>    filename = os.path.basename(filename)
 <INSERT_END> <|endoftext|> import os

"""
Loader settings:
we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the
same id_sample based on the hash of the file name
"""

inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat'
keyFormatClass = 'org.apache.hadoop.io.LongWritable'
valueFormatClass = 'org.apache.hadoop.io.Text'
defaultCombineSize = 64

# configuration of the Hadoop loader used by spark
conf = {"textinputformat.record.delimiter": "\n",
        "mapreduce.input.fileinputformat.input.dir.recursive": "true",
        "mapred.max.split.size": str(defaultCombineSize*1024*1024)
        }

"""
    Generation of the index of the pandas dataframe.
    This can be done in different ways:
    - hashing the complete file name
    - using directly the file as index (this is visually appealing :) )
"""

def generateHashKey(filename):
    return hash(filename)

def generateNameKey(filename):
    filename = os.path.basename(filename)
    if filename.endswith(".meta"):
        return filename[:-5]
    else:
        return filename

Prompt:
Use only the base file name for key

Former-commit-id: 3acbf9e93d3d501013e2a1b6aa9631bdcc663c66 [formerly eea949727d3693aa032033d84dcca3790d9072dd] [formerly ca065bc9f78b1416903179418d64b3273d437987]
Former-commit-id: 58c1d18e8960ad3236a34b8080b18ccff5684eaa
Former-commit-id: 6501068cea164df37ec055c3fb8baf8c89fc7823
"""
Loader settings:
we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the
same id_sample based on the hash of the file name
"""

inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat'
keyFormatClass = 'org.apache.hadoop.io.LongWritable'
valueFormatClass = 'org.apache.hadoop.io.Text'
defaultCombineSize = 64

# configuration of the Hadoop loader used by spark
conf = {"textinputformat.record.delimiter": "\n",
        "mapreduce.input.fileinputformat.input.dir.recursive": "true",
        "mapred.max.split.size": str(defaultCombineSize*1024*1024)
        }

def generateHashKey(filename):
    return hash(filename)

def generateNameKey(filename):
    if filename.endswith(".meta"):
        return filename[:-5]
    else:
        return filename


def prime_factors(n):
    factors = []
    factor = 2
    while n != 1:
        while n % factor == 0:
            factors += [factor]
            n //= factor
        factor += 1
    return factors

Response:
<REPLACE_OLD> import sieve

def <REPLACE_NEW> def <REPLACE_END> <DELETE>    primes = sieve.sieve(n)
 <DELETE_END> <REPLACE_OLD> for p in primes:
 <REPLACE_NEW> factor = 2
    while n != 1:
 <REPLACE_END> <REPLACE_OLD> p <REPLACE_NEW> factor <REPLACE_END> <REPLACE_OLD> [p]
 <REPLACE_NEW> [factor]
 <REPLACE_END> <REPLACE_OLD> p
 <REPLACE_NEW> factor
        factor += 1
 <REPLACE_END> <|endoftext|> def prime_factors(n):
    factors = []
    factor = 2
    while n != 1:
        while n % factor == 0:
            factors += [factor]
            n //= factor
        factor += 1
    return factors

Prompt:
Fix memory issues by just trying every number

import sieve

def prime_factors(n):
    primes = sieve.sieve(n)
    factors = []
    for p in primes:
        while n % p == 0:
            factors += [p]
            n //= p
    return factors


import unittest

class ExampleTest(unittest.TestCase):
    def test_example(self):
        self.assertEqual(1, 1)

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

Fix typo in method name

Fix typo in method name

Response:
<REPLACE_OLD> test_xample(self):
 <REPLACE_NEW> test_example(self):
 <REPLACE_END> <|endoftext|> import unittest

class ExampleTest(unittest.TestCase):
    def test_example(self):
        self.assertEqual(1, 1)

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

Prompt:
Fix typo in method name
import unittest

class ExampleTest(unittest.TestCase):
    def test_xample(self):
        self.assertEqual(1, 1)

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