#!/usr/bin/python
#coding=utf8

from Tkinter import *
import sys
from ui import Gui

if __name__ == '__main__':
    Root = Tk()
    App = Gui(Root)
    App.pack(expand='yes',fill='both')
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    Root.overrideredirect(1)
    Root.geometry("%dx%d+0+0" % (w, h))
    Root.focus_set() # <-- move focus to this widget
    Root.bind("<Escape>", lambda e: e.widget.quit())
    Root.title('Mid!Magic')
    Root.mainloop()

Add support for full screen.

Add support for full screen.

Response:
#!/usr/bin/python
#coding=utf8

from Tkinter import *
import sys
from ui import Gui

if __name__ == '__main__':
    Root = Tk()
    App = Gui(Root)
    App.pack(expand='yes',fill='both')
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    Root.overrideredirect(1)
    Root.geometry("%dx%d+0+0" % (w, h))
    Root.focus_set() # <-- move focus to this widget
    Root.bind("<Escape>", lambda e: e.widget.quit())
    Root.title('Mid!Magic')
    Root.mainloop()

Prompt:
Add support for full screen.
#!/usr/bin/python
#coding=utf8

from Tkinter import *
import sys
from ui import Gui

if __name__ == '__main__':
    Root = Tk()
    App = Gui(Root)
    App.pack(expand='yes',fill='both')
    Root.geometry('320x240+10+10')
    Root.title('Mid!Magic')
    Root.mainloop()


from Adafruit_MotorHAT import Adafruit_MotorHAT

class Vehicle:
    def __init__(self, motor_hat=Adafruit_MotorHAT()):
        self.motor_hat = motor_hat
        self.motors = []

    def release(self):
        self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)

    def update_motor(self, index, command, speed):
        with self.motor_hat.getMotor(index) as motor:
            motor.run(command)
            motor.setSpeed(speed)

        motor = {"location": index, "command": command, "speed": speed}
        n = len(self.motors)

        if index < n:
            self.motors[index] = motor
        elif index == n:
            self.motors.append(motor)
        else:
            raise IndexError()

Build vehicle with motor hat.

Build vehicle with motor hat.

Response:
from Adafruit_MotorHAT import Adafruit_MotorHAT

class Vehicle:
    def __init__(self, motor_hat=Adafruit_MotorHAT()):
        self.motor_hat = motor_hat
        self.motors = []

    def release(self):
        self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)

    def update_motor(self, index, command, speed):
        with self.motor_hat.getMotor(index) as motor:
            motor.run(command)
            motor.setSpeed(speed)

        motor = {"location": index, "command": command, "speed": speed}
        n = len(self.motors)

        if index < n:
            self.motors[index] = motor
        elif index == n:
            self.motors.append(motor)
        else:
            raise IndexError()

Prompt:
Build vehicle with motor hat.

from Adafruit_MotorHAT import Adafruit_MotorHAT

class Vehicle:
    def __init__(self, motor_hat=None):
        self.motor_hat = motor_hat
        self.motors = []

    def release(self):
        self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
        self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)

    def update_motor(self, index, command, speed):
        with self.motor_hat.getMotor(index) as motor:
            motor.run(command)
            motor.setSpeed(speed)

        motor = {"location": index, "command": command, "speed": speed}
        n = len(self.motors)

        if index < n:
            self.motors[index] = motor
        elif index == n:
            self.motors.append(motor)
        else:
            raise IndexError()


from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now

today = date.today()
this_year = today.year

class ValidatorTests(TestCase):
    def test_year_to_now(self):
        self.assertRaises(ValidationError, year_to_now, 1899)
        self.assertRaises(ValidationError, year_to_now, '1899')

        self.assertRaises(ValidationError, year_to_now, this_year)
        self.assertRaises(ValidationError, year_to_now, this_year + 3)

        self.assertIsNone(year_to_now(1900))
        self.assertIsNone(year_to_now(this_year - 1))

    def test_calling_year_to_now_with_non_integer_throws_value_error(self):
        self.assertRaises(ValidationError, year_to_now, 'a')
        self.assertRaises(ValidationError, year_to_now, '1900.1')

Response:
from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now

today = date.today()
this_year = today.year

class ValidatorTests(TestCase):
    def test_year_to_now(self):
        self.assertRaises(ValidationError, year_to_now, 1899)
        self.assertRaises(ValidationError, year_to_now, '1899')

        self.assertRaises(ValidationError, year_to_now, this_year)
        self.assertRaises(ValidationError, year_to_now, this_year + 3)

        self.assertIsNone(year_to_now(1900))
        self.assertIsNone(year_to_now(this_year - 1))

    def test_calling_year_to_now_with_non_integer_throws_value_error(self):
        self.assertRaises(ValidationError, year_to_now, 'a')
        self.assertRaises(ValidationError, year_to_now, '1900.1')

Prompt:
Add test for year_to_now with non-integer values
from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now

today = date.today()
this_year = today.year

class ValidatorTests(TestCase):
    def test_year_to_now(self):
        self.assertRaises(ValidationError, year_to_now, 1899)
        self.assertRaises(ValidationError, year_to_now, '1899')

        self.assertRaises(ValidationError, year_to_now, this_year)
        self.assertRaises(ValidationError, year_to_now, this_year + 3)

        self.assertIsNone(year_to_now(1900))
        self.assertIsNone(year_to_now(this_year - 1))


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

# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
#   Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for handling the DataONE Node and NodeList types
"""

def pyxb_to_dict(node_list_pyxb):
  """Return a dict representation of {node_list_pyxb}, keyed on
  the Node identifier (urn:node:*). E.g.:
  {
    u'urn:node:ARCTIC': {
      'base_url': u'https://arcticdata.io/metacat/d1/mn',
      'description': u'The US National Science Foundation...',
      'name': u'Arctic Data Center',
      'ping': None,
      'replicate': 0,
      'state': u'up',
      'synchronize': 1,
      'type': u'mn'
    },
    u'urn:node:BCODMO': {
      'base_url': u'https://www.bco-dmo.org/d1/mn',
      'description': u'Biological and Chemical Oceanography Data...',
      'name': u'Biological and Chemical Oceanography Data...',
      'ping': None,
      'replicate': 0,
      'state': u'up',
      'synchronize': 1,
      'type': u'mn'
    },
  }
  """
  f_dict = {}
  for f_pyxb in sorted(node_list_pyxb.node, key=lambda x: x.identifier.value()):
    f_dict[f_pyxb.identifier.value()] = {
      'name': f_pyxb.name,
      'description': f_pyxb.description,
      'base_url': f_pyxb.baseURL,
      'ping': f_pyxb.ping,
      'replicate': f_pyxb.replicate,
      'synchronize': f_pyxb.synchronize,
      'type': f_pyxb.type,
      'state': f_pyxb.state,
    }
    # TODO:
    # f_pyxb.services
    # f_pyxb.synchronization
    # f_pyxb.subject
    # f_pyxb.contactSubject
    # f_pyxb.nodeReplicationPolicy,

  return f_dict

Add utility module for working with the Node type

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

# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
#   Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for handling the DataONE Node and NodeList types
"""

def pyxb_to_dict(node_list_pyxb):
  """Return a dict representation of {node_list_pyxb}, keyed on
  the Node identifier (urn:node:*). E.g.:
  {
    u'urn:node:ARCTIC': {
      'base_url': u'https://arcticdata.io/metacat/d1/mn',
      'description': u'The US National Science Foundation...',
      'name': u'Arctic Data Center',
      'ping': None,
      'replicate': 0,
      'state': u'up',
      'synchronize': 1,
      'type': u'mn'
    },
    u'urn:node:BCODMO': {
      'base_url': u'https://www.bco-dmo.org/d1/mn',
      'description': u'Biological and Chemical Oceanography Data...',
      'name': u'Biological and Chemical Oceanography Data...',
      'ping': None,
      'replicate': 0,
      'state': u'up',
      'synchronize': 1,
      'type': u'mn'
    },
  }
  """
  f_dict = {}
  for f_pyxb in sorted(node_list_pyxb.node, key=lambda x: x.identifier.value()):
    f_dict[f_pyxb.identifier.value()] = {
      'name': f_pyxb.name,
      'description': f_pyxb.description,
      'base_url': f_pyxb.baseURL,
      'ping': f_pyxb.ping,
      'replicate': f_pyxb.replicate,
      'synchronize': f_pyxb.synchronize,
      'type': f_pyxb.type,
      'state': f_pyxb.state,
    }
    # TODO:
    # f_pyxb.services
    # f_pyxb.synchronization
    # f_pyxb.subject
    # f_pyxb.contactSubject
    # f_pyxb.nodeReplicationPolicy,

  return f_dict

Prompt: Add utility module for working with the Node type


import redis

class Benchmark(object):
    def __init__(self, author, author_url, date_submitted, date_updated,
                 name, summary, tags, title, url):
        self.author = author
        self.author_url = author_url
        self.date_submitted = date_submitted
        self.date_updated = date_updated
        self.name = name
        self.summary = summary
        self.tags = tags
        self.title = title
        self.url = url

    def __repr__(self):
        return '<Benchmark: %s>' % self.name

class BenchmarkDoesNotExist(Exception):
    pass

class BenchmarkAlreadyExists(Exception):
    pass

class McBenchClient(object):
    def __init__(self, redis):
        self.redis = redis

    def get_benchmark_by_id(self, benchmark_id):
        data = self.redis.hgetall('benchmark:%s' % benchmark_id)
        if not data:
            raise BenchmarkDoesNotExist
        return Benchmark(**data)

    def get_benchmark_by_name(self, name):
        benchmark_id = self.redis.get('name:%s:id' % name)
        if benchmark_id is None:
            raise BenchmarkDoesNotExist
        return self.get_benchmark_by_id(benchmark_id)

    def get_all_benchmarks(self):
        return [self.get_benchmark_by_id(key[len('benchmark:'):])
                for key in self.redis.keys('benchmark:*')]

    def insert_benchmark(self, benchmark):
        benchmark_id = self.redis.get('name:%s:id' % benchmark.name)
        if benchmark_id is not None:
            raise BenchmarkAlreadyExists
        benchmark_id = self.redis.incr('global:next_benchmark_id')
        self.redis.set('name:%s:id' % benchmark.name, benchmark_id)
        self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark))

def from_redis_url(redis_url):
    return McBenchClient(redis.from_url(redis_url))

Response:
import redis

class Benchmark(object):
    def __init__(self, author, author_url, date_submitted, date_updated,
                 name, summary, tags, title, url):
        self.author = author
        self.author_url = author_url
        self.date_submitted = date_submitted
        self.date_updated = date_updated
        self.name = name
        self.summary = summary
        self.tags = tags
        self.title = title
        self.url = url

    def __repr__(self):
        return '<Benchmark: %s>' % self.name

class BenchmarkDoesNotExist(Exception):
    pass

class BenchmarkAlreadyExists(Exception):
    pass

class McBenchClient(object):
    def __init__(self, redis):
        self.redis = redis

    def get_benchmark_by_id(self, benchmark_id):
        data = self.redis.hgetall('benchmark:%s' % benchmark_id)
        if not data:
            raise BenchmarkDoesNotExist
        return Benchmark(**data)

    def get_benchmark_by_name(self, name):
        benchmark_id = self.redis.get('name:%s:id' % name)
        if benchmark_id is None:
            raise BenchmarkDoesNotExist
        return self.get_benchmark_by_id(benchmark_id)

    def get_all_benchmarks(self):
        return [self.get_benchmark_by_id(key[len('benchmark:'):])
                for key in self.redis.keys('benchmark:*')]

    def insert_benchmark(self, benchmark):
        benchmark_id = self.redis.get('name:%s:id' % benchmark.name)
        if benchmark_id is not None:
            raise BenchmarkAlreadyExists
        benchmark_id = self.redis.incr('global:next_benchmark_id')
        self.redis.set('name:%s:id' % benchmark.name, benchmark_id)
        self.redis.hmset('benchmark:%s' % benchmark_id, vars(benchmark))

def from_redis_url(redis_url):
    return McBenchClient(redis.from_url(redis_url))

Prompt:
Make Benchmark a class, not a namedtuple.

import collections

import redis

BENCHMARK_FIELDS = [
    'author', 'author_url', 'date_submitted', 'date_updated',
    'name', 'summary', 'tags', 'title', 'url'
]

Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS))

class McBenchClient(object):
    def __init__(self, redis):
        self.redis = redis

    def get_benchmark_by_id(self, benchmark_id):
        return Benchmark(**self.redis.hgetall('benchmark:%s' % benchmark_id))

    def get_benchmark_by_name(self, name):
        benchmark_id = self.redis.get('benchmark:%s:id', name)
        return self.get_benchmark_by_id(benchmark_id)

    def insert_benchmark(self, benchmark):
        benchmark_id = self.redis.incr('global:next_benchmark_id')
        self.redis.set('benchmark:%s:id' % benchmark.name, benchmark_id)
        self.redis.hmset('benchmark:%s' % benchmark_id, benchmark._asdict())

def from_redis_url(redis_url):
    return McBenchClient(redis.from_url(redis_url))


"""
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~

Functions related to traversing the configuration file
"""

from __future__ import print_function
from colorama import init, Fore, Back

init()

def traverse_next(page, next, results):
    """
    Recursive generator to traverse through the next attribute and \
    crawl through the links to be followed
    """
    for link in page.extract_links(next['follow_link']):
        print(Back.YELLOW + Fore.BLUE + "Loading page ", link.url + Back.RESET + Fore.RESET)
        r = results.copy()
        for attribute in next['scraping'].get('data'):
            if attribute['field'] != "":
                print("\nExtracting", attribute['field'], "attribute", sep=' ')
                r[attribute['field']] = link.extract_content(attribute['selector'], attribute['attr'], attribute['default'])
        if not next['scraping'].get('next'):
            yield r
        else:
            for next2 in next['scraping'].get('next'):
                for result in traverse_next(link, next2, r):
                    yield result

Modify stdout logging in crawler run

Modify stdout logging in crawler run

Response:
"""
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~

Functions related to traversing the configuration file
"""

from __future__ import print_function
from colorama import init, Fore, Back

init()

def traverse_next(page, next, results):
    """
    Recursive generator to traverse through the next attribute and \
    crawl through the links to be followed
    """
    for link in page.extract_links(next['follow_link']):
        print(Back.YELLOW + Fore.BLUE + "Loading page ", link.url + Back.RESET + Fore.RESET)
        r = results.copy()
        for attribute in next['scraping'].get('data'):
            if attribute['field'] != "":
                print("\nExtracting", attribute['field'], "attribute", sep=' ')
                r[attribute['field']] = link.extract_content(attribute['selector'], attribute['attr'], attribute['default'])
        if not next['scraping'].get('next'):
            yield r
        else:
            for next2 in next['scraping'].get('next'):
                for result in traverse_next(link, next2, r):
                    yield result

Prompt:
Modify stdout logging in crawler run

"""
scrapple.utils.config
~~~~~~~~~~~~~~~~~~~~~

Functions related to traversing the configuration file
"""

from __future__ import print_function

def traverse_next(page, next, results):
    """
    Recursive generator to traverse through the next attribute and \
    crawl through the links to be followed
    """
    for link in page.extract_links(next['follow_link']):
        print("Loading page", link.url)
        r = results.copy()
        for attribute in next['scraping'].get('data'):
            if attribute['field'] != "":
                print("\nExtracting", attribute['field'], "attribute", sep=' ')
                r[attribute['field']] = link.extract_content(attribute['selector'], attribute['attr'], attribute['default'])
        if not next['scraping'].get('next'):
            yield r
        else:
            for next2 in next['scraping'].get('next'):
                for result in traverse_next(link, next2, r):
                    yield result


#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *

class TestStringQueries(ImpalaTestSuite):

  @classmethod
  def get_workload(cls):
    return 'functional-query'

  def setup_method(self, method):
    self.__cleanup_char_tables()
    self.__create_char_tables()

  def teardown_method(self, method):
    self.__cleanup_char_tables()

  def __cleanup_char_tables(self):
    self.client.execute('drop table if exists functional.test_char_tmp');
    self.client.execute('drop table if exists functional.test_varchar_tmp');

  def __create_char_tables(self):
    self.client.execute(
        'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
    self.client.execute(
        'create table if not exists functional.test_char_tmp (c char(5))')

  @classmethod
  def add_test_dimensions(cls):
    super(TestStringQueries, cls).add_test_dimensions()
    cls.TestMatrix.add_dimension(
      create_exec_option_dimension(disable_codegen_options=[True]))
    cls.TestMatrix.add_constraint(lambda v:\
        v.get_value('table_format').file_format in ['text'] and
        v.get_value('table_format').compression_codec in ['none'])

  def test_varchar(self, vector):
    self.run_test_case('QueryTest/chars', vector)

Fix char test to only run on test/none.

Response:
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *

class TestStringQueries(ImpalaTestSuite):

  @classmethod
  def get_workload(cls):
    return 'functional-query'

  def setup_method(self, method):
    self.__cleanup_char_tables()
    self.__create_char_tables()

  def teardown_method(self, method):
    self.__cleanup_char_tables()

  def __cleanup_char_tables(self):
    self.client.execute('drop table if exists functional.test_char_tmp');
    self.client.execute('drop table if exists functional.test_varchar_tmp');

  def __create_char_tables(self):
    self.client.execute(
        'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
    self.client.execute(
        'create table if not exists functional.test_char_tmp (c char(5))')

  @classmethod
  def add_test_dimensions(cls):
    super(TestStringQueries, cls).add_test_dimensions()
    cls.TestMatrix.add_dimension(
      create_exec_option_dimension(disable_codegen_options=[True]))
    cls.TestMatrix.add_constraint(lambda v:\
        v.get_value('table_format').file_format in ['text'] and
        v.get_value('table_format').compression_codec in ['none'])

  def test_varchar(self, vector):
    self.run_test_case('QueryTest/chars', vector)

Prompt:
Fix char test to only run on test/none.

Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326
Tested-by: jenkins
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>

#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *

class TestStringQueries(ImpalaTestSuite):

  @classmethod
  def get_workload(cls):
    return 'functional-query'

  def setup_method(self, method):
    self.__cleanup_char_tables()
    self.__create_char_tables()

  def teardown_method(self, method):
    self.__cleanup_char_tables()

  def __cleanup_char_tables(self):
    self.client.execute('drop table if exists functional.test_char_tmp');
    self.client.execute('drop table if exists functional.test_varchar_tmp');

  def __create_char_tables(self):
    self.client.execute(
        'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
    self.client.execute(
        'create table if not exists functional.test_char_tmp (c char(5))')

  @classmethod
  def add_test_dimensions(cls):
    super(TestStringQueries, cls).add_test_dimensions()
    cls.TestMatrix.add_dimension(
      create_exec_option_dimension(disable_codegen_options=[True]))
    cls.TestMatrix.add_constraint(lambda v:\
        v.get_value('table_format').file_format in ['text'])

  def test_varchar(self, vector):
    self.run_test_case('QueryTest/chars', vector)


from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.utils.translation import gettext as _
from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView

class SearchView(FacetedSearchView):
    template = 'search/search.htm'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.form_class = FacetedSearchForm
        self.searchqueryset = SearchQuerySet()

    def build_page(self):
        page = self.request.resolver_match.kwargs.get('page') or self.request.GET.get('page') or 1
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                raise Http404(_("Page is not 'last', nor can it be converted to an int."))

        paginator = Paginator(self.results, self.results_per_page)
        try:
            page = paginator.page(page_number)
        except InvalidPage:
            raise Http404(_('Invalid page (%(page_number)s)') % {
                                'page_number': page_number
            })

        return (paginator, page)

    def extra_context(self):
        context = super().extra_context()
        context.update({'is_paginated': bool(self.query)})
        return context

Switch import from ugettext to gettext

Switch import from ugettext to gettext

Response:
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.utils.translation import gettext as _
from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView

class SearchView(FacetedSearchView):
    template = 'search/search.htm'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.form_class = FacetedSearchForm
        self.searchqueryset = SearchQuerySet()

    def build_page(self):
        page = self.request.resolver_match.kwargs.get('page') or self.request.GET.get('page') or 1
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                raise Http404(_("Page is not 'last', nor can it be converted to an int."))

        paginator = Paginator(self.results, self.results_per_page)
        try:
            page = paginator.page(page_number)
        except InvalidPage:
            raise Http404(_('Invalid page (%(page_number)s)') % {
                                'page_number': page_number
            })

        return (paginator, page)

    def extra_context(self):
        context = super().extra_context()
        context.update({'is_paginated': bool(self.query)})
        return context

Prompt:
Switch import from ugettext to gettext

from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.utils.translation import ugettext as _
from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView

class SearchView(FacetedSearchView):
    template = 'search/search.htm'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.form_class = FacetedSearchForm
        self.searchqueryset = SearchQuerySet()

    def build_page(self):
        page = self.request.resolver_match.kwargs.get('page') or self.request.GET.get('page') or 1
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                raise Http404(_("Page is not 'last', nor can it be converted to an int."))

        paginator = Paginator(self.results, self.results_per_page)
        try:
            page = paginator.page(page_number)
        except InvalidPage:
            raise Http404(_('Invalid page (%(page_number)s)') % {
                                'page_number': page_number
            })

        return (paginator, page)

    def extra_context(self):
        context = super().extra_context()
        context.update({'is_paginated': bool(self.query)})
        return context


from flask import jsonify

from . import app
from . import firebase

@app.route("/", methods=["GET"])
def index():
	response = firebase.get("/", None)
	response = response or {}

	return jsonify(response)

Response:
from flask import jsonify

from . import app
from . import firebase

@app.route("/", methods=["GET"])
def index():
	response = firebase.get("/", None)
	response = response or {}

	return jsonify(response)

Prompt:
Remove commented code and unused imports

from flask import request, jsonify, session, g
import numpy as np
from DatasetCreation import ConstructDataset

from . import app
from . import firebase

from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
from sklearn.cross_validation import cross_val_score

@app.route("/", methods=["GET"])
def index():
	response = firebase.get("/", None)
	response = response or {}

	datapoints, labels = ConstructDataset(response)
	print len(datapoints)
	print len(labels)

	#	print datapoints[ labels == True ]
	print datapoints[10]

	#enc = preprocessing.OneHotEncoder()
	#print enc.fit(datapoints)

	#clf = RandomForestClassifier(n_estimators=10, min_samples_split=1)
	#clf = clf.fit(datapoints, labels)

	#scores = cross_val_score(clf, datapoints, labels)
	#scores.mean()

	#clf = DecisionTreeClassifier(max_depth=None, min_samples_split=1, random_state=0)
	#scores = cross_val_score(clf, datapoints, labels)
	#scores.mean()

	return jsonify(response)


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

from subprocess import Popen,PIPE
import shlex
import logging

class ExecProc:

    def __init__(self):
        self.command = None
        self.debug = False

    def setDebug(self,debug):
        self.debug = debug

    def setCommand(self,command):
        if type(command) != str:
            raise ValueError
        self.command = command

    def execute(self):
        if self.command == None:
            raise ValueError
        # Remove Carriage Returns
        command = self.command.strip('\r')
        args = shlex.split(command)
        if self.debug == True:
            logging.info("command=\"%s\"",args)
        p = Popen(args,stdout=PIPE)
        o,e = p.communicate()
        if self.debug == True:
            logging.info("output=\"%s\"",o)
            logging.info(':'.join(x.encode('hex') for x in o))
        return o

Add output of command in hex

Add output of command in hex

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

from subprocess import Popen,PIPE
import shlex
import logging

class ExecProc:

    def __init__(self):
        self.command = None
        self.debug = False

    def setDebug(self,debug):
        self.debug = debug

    def setCommand(self,command):
        if type(command) != str:
            raise ValueError
        self.command = command

    def execute(self):
        if self.command == None:
            raise ValueError
        # Remove Carriage Returns
        command = self.command.strip('\r')
        args = shlex.split(command)
        if self.debug == True:
            logging.info("command=\"%s\"",args)
        p = Popen(args,stdout=PIPE)
        o,e = p.communicate()
        if self.debug == True:
            logging.info("output=\"%s\"",o)
            logging.info(':'.join(x.encode('hex') for x in o))
        return o

Prompt:
Add output of command in hex

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

from subprocess import Popen,PIPE
import shlex
import logging

class ExecProc:

    def __init__(self):
        self.command = None
        self.debug = False

    def setDebug(self,debug):
        self.debug = debug

    def setCommand(self,command):
        if type(command) != str:
            raise ValueError
        self.command = command

    def execute(self):
        if self.command == None:
            raise ValueError
        args = shlex.split(self.command)
        if self.debug == True:
            logging.info("command=\"%s\"",self.command)
        p = Popen(args,stdout=PIPE)
        o,e = p.communicate()
        if self.debug == True:
            logging.info("output=\"%s\"",o)
        return o


from xml.etree import ElementTree
from django.core.management.base import BaseCommand

from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.models import CommCareCase
from dimagi.utils.chunked import chunked
from dimagi.utils.couch.database import iter_docs

from corehq.apps.domain.models import Domain
from corehq.apps.hqcase.utils import submit_case_blocks

def needs_update(case):
    return (case.get('location_id', None) and
            case['owner_id'] != case['location_id'])

def case_block(case):
    return ElementTree.tostring(CaseBlock(
        create=False,
        case_id=case['_id'],
        owner_id=case['location_id'],
    ).as_xml())

def get_cases(domain):
    supply_point_ids = (case['id'] for case in CommCareCase.get_db().view(
        'commtrack/supply_point_by_loc',
        startkey=[domain],
        endkey=[domain, {}],
        reduce=False,
        include_docs=False,
    ).all())
    return iter_docs(CommCareCase.get_db(), supply_point_ids)

def update_supply_points(domain):
    case_blocks = (case_block(c) for c in get_cases(domain) if needs_update(c))
    if case_blocks:
        for chunk in chunked(case_blocks, 100):
            submit_case_blocks(chunk, domain)
            print "updated {} cases on domain {}".format(len(chunk), domain)

class Command(BaseCommand):
    help = ("Make sure all supply point cases have their owner_id set "
            "to the location_id")

    def handle(self, *args, **options):
        all_domains = Domain.get_all_names()
        total = len(all_domains)
        finished = 0
        for domain in all_domains:
            update_supply_points(domain)
            finished += 1
            if finished % 100 == 0:
                print "Processed {} of {} domains".format(finished, total)

Use CaseBlocks to update case owner_ids

Use CaseBlocks to update case owner_ids

Response:
from xml.etree import ElementTree
from django.core.management.base import BaseCommand

from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.models import CommCareCase
from dimagi.utils.chunked import chunked
from dimagi.utils.couch.database import iter_docs

from corehq.apps.domain.models import Domain
from corehq.apps.hqcase.utils import submit_case_blocks

def needs_update(case):
    return (case.get('location_id', None) and
            case['owner_id'] != case['location_id'])

def case_block(case):
    return ElementTree.tostring(CaseBlock(
        create=False,
        case_id=case['_id'],
        owner_id=case['location_id'],
    ).as_xml())

def get_cases(domain):
    supply_point_ids = (case['id'] for case in CommCareCase.get_db().view(
        'commtrack/supply_point_by_loc',
        startkey=[domain],
        endkey=[domain, {}],
        reduce=False,
        include_docs=False,
    ).all())
    return iter_docs(CommCareCase.get_db(), supply_point_ids)

def update_supply_points(domain):
    case_blocks = (case_block(c) for c in get_cases(domain) if needs_update(c))
    if case_blocks:
        for chunk in chunked(case_blocks, 100):
            submit_case_blocks(chunk, domain)
            print "updated {} cases on domain {}".format(len(chunk), domain)

class Command(BaseCommand):
    help = ("Make sure all supply point cases have their owner_id set "
            "to the location_id")

    def handle(self, *args, **options):
        all_domains = Domain.get_all_names()
        total = len(all_domains)
        finished = 0
        for domain in all_domains:
            update_supply_points(domain)
            finished += 1
            if finished % 100 == 0:
                print "Processed {} of {} domains".format(finished, total)

Prompt:
Use CaseBlocks to update case owner_ids

from django.core.management.base import BaseCommand
from casexml.apps.case.models import CommCareCase
from corehq.util.couch import iter_update, DocUpdate

class Command(BaseCommand):
    help = ("Make sure all supply point cases have their owner_id set "
            "to the location_id")

    def handle(self, *args, **options):
        def add_location(case):
            if not case['location_id']:
                return None
            if case['owner_id'] != case['location_id']:
                case['owner_id'] = case['location_id']
                return DocUpdate(case)

        iter_update(
            CommCareCase.get_db(),
            add_location,
            self.get_case_ids(),
            verbose=True
        )

    def get_case_ids(self):
        return (case['id'] for case in CommCareCase.get_db().view(
            'commtrack/supply_point_by_loc',
            reduce=False,
            include_docs=False,
        ).all())


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

#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.

import luna.plugins

_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""

def register(identity, metadata):
	"""
	Registers a new configuration plug-in to track configuration with.

	This expects the metadata to already be verified as configuration's
	metadata.

	:param identity: The identity of the plug-in to register.
	:param metadata: The metadata of a configuration plug-in.
	"""
	if identity in _configurations:
		luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
		return
	_configurations[identity] = metadata["configuration"]["class"]

def unregister(identity):
	"""
	Undoes the registration of a configuration plug-in.

	The configuration plug-in will no longer keep track of any configuration.
	Existing configuration will be stored persistently.

	:param identity: The identity of the plug-in to unregister.
	"""
	if identity not in _configurations:
		luna.plugins.api("logger").warning("Configuration {configuration} is not registered, so I can't unregister it.", configuration=identity)
		return
	del _configurations[identity] #The actual unregistration.

def validate_metadata(metadata):
	raise Exception("Not implemented yet.")

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

#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.

import luna.plugins

_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""

def register(identity, metadata):
	"""
	Registers a new configuration plug-in to track configuration with.

	This expects the metadata to already be verified as configuration's
	metadata.

	:param identity: The identity of the plug-in to register.
	:param metadata: The metadata of a configuration plug-in.
	"""
	if identity in _configurations:
		luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
		return
	_configurations[identity] = metadata["configuration"]["class"]

def unregister(identity):
	"""
	Undoes the registration of a configuration plug-in.

	The configuration plug-in will no longer keep track of any configuration.
	Existing configuration will be stored persistently.

	:param identity: The identity of the plug-in to unregister.
	"""
	if identity not in _configurations:
		luna.plugins.api("logger").warning("Configuration {configuration} is not registered, so I can't unregister it.", configuration=identity)
		return
	del _configurations[identity] #The actual unregistration.

def validate_metadata(metadata):
	raise Exception("Not implemented yet.")

Prompt:
Implement unregistration of configuration plug-ins

Perhaps we should not give a warning, but instead an exception, when registering or unregistering fails?

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

#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.

import luna.plugins

_configurations = {}
"""
The configuration classes that have been registered here so far, keyed by their
identities.
"""

def register(identity, metadata):
	"""
	Registers a new configuration plug-in to track configuration with.

	This expects the metadata to already be verified as configuration's
	metadata.

	:param identity: The identity of the plug-in to register.
	:param metadata: The metadata of a configuration plug-in.
	"""
	if identity in _configurations:
		luna.plugins.api("logger").warning("Configuration {configuration} is already registered.", configuration=identity)
		return
	_configurations[identity] = metadata["configuration"]["class"]

def unregister(identity):
	raise Exception("Not implemented yet.")

def validate_metadata(metadata):
	raise Exception("Not implemented yet.")


import gettext

class Version(object):
    def __init__(self, canonical_version, final):
        self.canonical_version = canonical_version
        self.final = final

    @property
    def pretty_version(self):
        if self.final:
            return self.canonical_version
        else:
            return '%s-dev' % (self.canonical_version,)

_version = Version('1.4.3', False)
__version__ = _version.pretty_version
__canonical_version__ = _version.canonical_version

gettext.install('swift')

Switch trunk to 1.4.3 development

Switch trunk to 1.4.3 development

Response:
import gettext

class Version(object):
    def __init__(self, canonical_version, final):
        self.canonical_version = canonical_version
        self.final = final

    @property
    def pretty_version(self):
        if self.final:
            return self.canonical_version
        else:
            return '%s-dev' % (self.canonical_version,)

_version = Version('1.4.3', False)
__version__ = _version.pretty_version
__canonical_version__ = _version.canonical_version

gettext.install('swift')

Prompt:
Switch trunk to 1.4.3 development
import gettext

class Version(object):
    def __init__(self, canonical_version, final):
        self.canonical_version = canonical_version
        self.final = final

    @property
    def pretty_version(self):
        if self.final:
            return self.canonical_version
        else:
            return '%s-dev' % (self.canonical_version,)

_version = Version('1.4.2', False)
__version__ = _version.pretty_version
__canonical_version__ = _version.canonical_version

gettext.install('swift')


Add a blank line in the end

Add a blank line in the end

Response:
# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4

"""

做为 Apple Store App 独立开发者，你要搞限时促销，为你的应用生成激活码（或者优惠券），
使用 Python 如何生成 200 个激活码（或者优惠券）？

"""

import uuid

def generate_key():
    key_list = []
    for i in range(200):
        uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1()))
        key_list.append(str(uuid_key).replace('-', ''))
    return key_list

if __name__ == '__main__':
    print(generate_key())

Prompt:
Add a blank line in the end

# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4

"""

做为 Apple Store App 独立开发者，你要搞限时促销，为你的应用生成激活码（或者优惠券），
使用 Python 如何生成 200 个激活码（或者优惠券）？

"""

import uuid

def generate_key():
    key_list = []
    for i in range(200):
        uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1()))
        key_list.append(str(uuid_key).replace('-', ''))
    return key_list

if __name__ == '__main__':
    print(generate_key())


from __future__ import absolute_import, print_function, unicode_literals

from collections import Counter
from streamparse.bolt import Bolt

class WordCounter(Bolt):

    AUTO_ACK = True  # automatically acknowledge tuples after process()
    AUTO_ANCHOR = True  # automatically anchor tuples to current tuple
    AUTO_FAIL = True  # automatically fail tuples when exceptions occur

    def initialize(self, conf, ctx):
        self.counts = Counter()

    def process(self, tup):
        word = tup.values[0]
        self.counts[word] += 1
        self.emit([word, self.counts[word]])
        self.log('%s: %d' % (word, self.counts[word]))

Update quickstart project to use AUTO_*

Update quickstart project to use AUTO_*

Response:
from __future__ import absolute_import, print_function, unicode_literals

from collections import Counter
from streamparse.bolt import Bolt

class WordCounter(Bolt):

    AUTO_ACK = True  # automatically acknowledge tuples after process()
    AUTO_ANCHOR = True  # automatically anchor tuples to current tuple
    AUTO_FAIL = True  # automatically fail tuples when exceptions occur

    def initialize(self, conf, ctx):
        self.counts = Counter()

    def process(self, tup):
        word = tup.values[0]
        self.counts[word] += 1
        self.emit([word, self.counts[word]])
        self.log('%s: %d' % (word, self.counts[word]))

Prompt:
Update quickstart project to use AUTO_*

from __future__ import absolute_import, print_function, unicode_literals

from collections import Counter
from streamparse.bolt import Bolt

class WordCounter(Bolt):

    def initialize(self, conf, ctx):
        self.counts = Counter()

    def process(self, tup):
        word = tup.values[0]
        self.counts[word] += 1
        self.emit([word, self.counts[word]])
        self.log('%s: %d' % (word, self.counts[word]))


Response:
import warnings

import django

if django.VERSION < (3, 2):
    from feincms3.applications import *  # noqa

    warnings.warn(
        "Django 3.2 will start autodiscovering app configs inside '.apps' modules."
        " We cannot continue using feincms3.apps because the AppsMixin inside this"
        " module can only be loaded after Django initializes all apps."
        " Please change feincms3.apps to feincms3.applications in your code."
        " This compatibility shim will be removed at some point in the future."
        " Sorry for the inconvenience.",
        DeprecationWarning,
        stacklevel=2,
    )

Prompt:
Remove a no cover pragma having no effect (since the pragma only affects the current line)

# pragma: no cover

import warnings

import django

if django.VERSION < (3, 2):
    from feincms3.applications import *  # noqa

    warnings.warn(
        "Django 3.2 will start autodiscovering app configs inside '.apps' modules."
        " We cannot continue using feincms3.apps because the AppsMixin inside this"
        " module can only be loaded after Django initializes all apps."
        " Please change feincms3.apps to feincms3.applications in your code."
        " This compatibility shim will be removed at some point in the future."
        " Sorry for the inconvenience.",
        DeprecationWarning,
        stacklevel=2,
    )


from twisted.cred import checkers, portal
from twisted.protocols import amp
from zope import interface

class AuthenticationLocator(amp.CommandLocator):
    """
    A base class for responder locators that allow users to authenticate.
    """
    credentialInterfaces = []

    def __init__(self, store):
        """
        Initializes an authentication responder locator.

        :param store: The root store.
        """
        self.store = store

        storeCheckers = store.powerupsFor(checkers.ICredentialsChecker)
        self.portal = portal.Portal(Realm(store), storeCheckers)

    def acquireStore(self, userIdentifier):
        """
        Acquires a user store.
        """

@interface.implementer(portal.IRealm)
class Realm(object):
    """
    A realm that produces box receivers for users.
    """
    def __init__(self, getUserByUid):
        self._getUser = getUserByUid

    def requestAvatar(self, uid, mind, *interfaces):
        """
        Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``.
        """
        if amp.IBoxReceiver not in interfaces:
            raise NotImplementedError()

        return self._getUser(uid).addCallback(_gotUser)

def _gotUser(user):
    """
    Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable
    as the return value for ``requestAvatar``.
    """
    return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None

Response:
from twisted.cred import checkers, portal
from twisted.protocols import amp
from zope import interface

class AuthenticationLocator(amp.CommandLocator):
    """
    A base class for responder locators that allow users to authenticate.
    """
    credentialInterfaces = []

    def __init__(self, store):
        """
        Initializes an authentication responder locator.

        :param store: The root store.
        """
        self.store = store

        storeCheckers = store.powerupsFor(checkers.ICredentialsChecker)
        self.portal = portal.Portal(Realm(store), storeCheckers)

    def acquireStore(self, userIdentifier):
        """
        Acquires a user store.
        """

@interface.implementer(portal.IRealm)
class Realm(object):
    """
    A realm that produces box receivers for users.
    """
    def __init__(self, getUserByUid):
        self._getUser = getUserByUid

    def requestAvatar(self, uid, mind, *interfaces):
        """
        Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``.
        """
        if amp.IBoxReceiver not in interfaces:
            raise NotImplementedError()

        return self._getUser(uid).addCallback(_gotUser)

def _gotUser(user):
    """
    Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable
    as the return value for ``requestAvatar``.
    """
    return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None

Prompt:
Remove get user by id nonsense, now exponent.auth.name

from exponent.auth import common
from twisted.cred import checkers, portal
from twisted.internet import defer
from twisted.protocols import amp
from zope import interface

def _getUserByIdentifier(rootStore, userIdentifier):
    """
    Gets a user by uid.
    """
    user = common.User.findUnique(rootStore, userIdentifier)
    return defer.succeed(user)

class AuthenticationLocator(amp.CommandLocator):
    """
    A base class for responder locators that allow users to authenticate.
    """
    credentialInterfaces = []

    def __init__(self, store):
        """
        Initializes an authentication responder locator.

        :param store: The root store.
        """
        self.store = store

        storeCheckers = store.powerupsFor(checkers.ICredentialsChecker)
        self.portal = portal.Portal(Realm(store), storeCheckers)

    def acquireStore(self, userIdentifier):
        """
        Acquires a user store.
        """

@interface.implementer(portal.IRealm)
class Realm(object):
    """
    A realm that produces box receivers for users.
    """
    def __init__(self, getUserByUid):
        self._getUser = getUserByUid

    def requestAvatar(self, uid, mind, *interfaces):
        """
        Attempts to get a lock on the user, then adapts it to ``IBoxReceiver``.
        """
        if amp.IBoxReceiver not in interfaces:
            raise NotImplementedError()

        return self._getUser(uid).addCallback(_gotUser)

def _gotUser(user):
    """
    Adapts the user to ``IBoxReceiver`` and returns a 3-tuple suitable
    as the return value for ``requestAvatar``.
    """
    return amp.IBoxReceiver, amp.IBoxReceiver(user), lambda: None


""" fedmsg-notifications internal API """

import fmn.lib.models

import logging
log = logging.getLogger(__name__)

def recipients(session, config, message):
    """ The main API function.

    Accepts a fedmsg message as an argument.

    Returns a dict mapping context names to lists of recipients.
    """

    res = {}

    for context in session.query(fmn.lib.models.Context).all():
        res[context.name] = recipients_for_context(
            session, config, context, message)

    return res

def recipients_for_context(session, config, context, message):
    """ Returns the recipients for a given fedmsg message and stated context.

    Context may be either the name of a context or an instance of
    fmn.lib.models.Context.
    """

    if isinstance(context, basestring):
        context = session.query(fmn.lib.models.Context)\
            .filter_by(name=context).one()

    return context.recipients(session, config, message)

def load_filters(root='fmn.filters'):
    """ Load the big list of allowed callable filters. """

    module = __import__(root, fromlist=[root.split('.')[0]])

    filters = {}
    for name in dir(module):
        obj = getattr(module, name)
        if not callable(obj):
            continue
        log.info("Found filter %r %r" % (name, obj))
        filters[name] = obj

    return {root: filters}

Response:
""" fedmsg-notifications internal API """

import fmn.lib.models

import logging
log = logging.getLogger(__name__)

def recipients(session, config, message):
    """ The main API function.

    Accepts a fedmsg message as an argument.

    Returns a dict mapping context names to lists of recipients.
    """

    res = {}

    for context in session.query(fmn.lib.models.Context).all():
        res[context.name] = recipients_for_context(
            session, config, context, message)

    return res

def recipients_for_context(session, config, context, message):
    """ Returns the recipients for a given fedmsg message and stated context.

    Context may be either the name of a context or an instance of
    fmn.lib.models.Context.
    """

    if isinstance(context, basestring):
        context = session.query(fmn.lib.models.Context)\
            .filter_by(name=context).one()

    return context.recipients(session, config, message)

def load_filters(root='fmn.filters'):
    """ Load the big list of allowed callable filters. """

    module = __import__(root, fromlist=[root.split('.')[0]])

    filters = {}
    for name in dir(module):
        obj = getattr(module, name)
        if not callable(obj):
            continue
        log.info("Found filter %r %r" % (name, obj))
        filters[name] = obj

    return {root: filters}

Prompt:
Restructure the valid_paths list into a dict.

""" fedmsg-notifications internal API """

import fmn.lib.models

import logging
log = logging.getLogger(__name__)

def recipients(session, config, message):
    """ The main API function.

    Accepts a fedmsg message as an argument.

    Returns a dict mapping context names to lists of recipients.
    """

    res = {}

    for context in session.query(fmn.lib.models.Context).all():
        res[context.name] = recipients_for_context(
            session, config, context, message)

    return res

def recipients_for_context(session, config, context, message):
    """ Returns the recipients for a given fedmsg message and stated context.

    Context may be either the name of a context or an instance of
    fmn.lib.models.Context.
    """

    if isinstance(context, basestring):
        context = session.query(fmn.lib.models.Context)\
            .filter_by(name=context).one()

    return context.recipients(session, config, message)

def load_filters(root='fmn.filters'):
    """ Load the big list of allowed callable filters. """

    module = __import__(root, fromlist=[root.split('.')[0]])

    filters = []
    for name in dir(module):
        obj = getattr(module, name)
        if not callable(obj):
            continue
        log.info("Found filter %r %r" % (name, obj))
        filters.append(obj)

    return filters


from setuptools import setup

with open('README.md') as file:
    long_description = file.read()

setup(
    name="chalupas-files",
    version="0.1.0",
    author="Antonin Messinger",
    author_email="antonin.messinger@gmail.com",
    description=" Convert any document",
    long_description=long_description,
    license="MIT License",
    url="https://github.com/Antojitos/chalupas",
    download_url="https://github.com/Antojitos/chalupas/archive/0.1.0.tar.gz",
    keywords=["chalupas", "convert", "document"],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Flask',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP',
    ],

    packages=['chalupas'],
    install_requires=[
        'Flask==0.12.3',
        'pypandoc==1.1.3'
    ],

    tests_require=[
        'python-magic==0.4.11',
    ],
    test_suite='tests.main'
)

Response:
from setuptools import setup

with open('README.md') as file:
    long_description = file.read()

setup(
    name="chalupas-files",
    version="0.1.0",
    author="Antonin Messinger",
    author_email="antonin.messinger@gmail.com",
    description=" Convert any document",
    long_description=long_description,
    license="MIT License",
    url="https://github.com/Antojitos/chalupas",
    download_url="https://github.com/Antojitos/chalupas/archive/0.1.0.tar.gz",
    keywords=["chalupas", "convert", "document"],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Flask',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP',
    ],

    packages=['chalupas'],
    install_requires=[
        'Flask==0.12.3',
        'pypandoc==1.1.3'
    ],

    tests_require=[
        'python-magic==0.4.11',
    ],
    test_suite='tests.main'
)

Prompt:
Upgrade to Flask 0.12.3 to fix CVE-2018-1000656

from setuptools import setup

with open('README.md') as file:
    long_description = file.read()

setup(
    name="chalupas-files",
    version="0.1.0",
    author="Antonin Messinger",
    author_email="antonin.messinger@gmail.com",
    description=" Convert any document",
    long_description=long_description,
    license="MIT License",
    url="https://github.com/Antojitos/chalupas",
    download_url="https://github.com/Antojitos/chalupas/archive/0.1.0.tar.gz",
    keywords=["chalupas", "convert", "document"],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Flask',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP',
    ],

    packages=['chalupas'],
    install_requires=[
        'Flask==0.10.1',
        'pypandoc==1.1.3'
    ],

    tests_require=[
        'python-magic==0.4.11',
    ],
    test_suite='tests.main'
)


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:
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:
# 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:
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:
# 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:
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
            ]
        }

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:
#!/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:
#!/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:
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:
# -*- 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:
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:
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:
# '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:
"""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:
#!/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:
#!/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