import collections

from data import anagram_index
from spec.data.fixtures import tries
from spec.mamba import *

with description('anagram_index'):
  with before.all:
    words = collections.OrderedDict(tries.kitchen_sink_data())
    self.subject = anagram_index.AnagramIndex(words)

  with it('instantiates'):
    expect(len(self.subject)).to(be_above(0))

  with it('accepts pre-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('low'))

  with it('accepts anti-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('wlo'))

  with it('returns multiple matches'):
    expect(self.subject['snap']).to(equal(['snap', 'naps']))

Update anagram index spec data source.

Update anagram index spec data source.

Response:
import collections

from data import anagram_index
from spec.data.fixtures import tries
from spec.mamba import *

with description('anagram_index'):
  with before.all:
    words = collections.OrderedDict(tries.kitchen_sink_data())
    self.subject = anagram_index.AnagramIndex(words)

  with it('instantiates'):
    expect(len(self.subject)).to(be_above(0))

  with it('accepts pre-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('low'))

  with it('accepts anti-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('wlo'))

  with it('returns multiple matches'):
    expect(self.subject['snap']).to(equal(['snap', 'naps']))

Prompt:
Update anagram index spec data source.

from data import anagram_index, warehouse
from spec.mamba import *

with description('anagram_index'):
  with before.all:
    self.subject = anagram_index.AnagramIndex(warehouse.get('/words/unigram'))

  with it('instantiates'):
    expect(len(self.subject)).to(be_above(0))

  with it('accepts pre-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('low'))

  with it('accepts anti-sort-jumbled anagrams'):
    expect(self.subject).to(have_key('wlo'))

  with it('returns multiple matches'):
    expect(self.subject['snap']).to(equal(['snap', 'naps']))


from telegram import Updater
import json
import os

def getToken():
    token = []
    if not os.path.exists(file_path):
        token.append(input('Insert Token here: '))
        with open('token.json', 'w') as f:
            json.dump(token, f)
    else:
        with open("token.json") as f:
            token = json.load(f)
    return token[0]

def echo(bot, update):
    '''
    Simple function that echos every received message back to the user.
    '''
    bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)

def main():
    token = getToken()
    print("Starting Bot...")

    # Start the Bot with the token
    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add the echo-Message Handler to the Dispatcher
    dispatcher.addTelegramMessageHandler(echo)

    # Make the bot listen for commands
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Response:
from telegram import Updater
import json
import os

def getToken():
    token = []
    if not os.path.exists(file_path):
        token.append(input('Insert Token here: '))
        with open('token.json', 'w') as f:
            json.dump(token, f)
    else:
        with open("token.json") as f:
            token = json.load(f)
    return token[0]

def echo(bot, update):
    '''
    Simple function that echos every received message back to the user.
    '''
    bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)

def main():
    token = getToken()
    print("Starting Bot...")

    # Start the Bot with the token
    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    # Add the echo-Message Handler to the Dispatcher
    dispatcher.addTelegramMessageHandler(echo)

    # Make the bot listen for commands
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Prompt:
Add simple Echo function and Bot initialisation

from telegram import Updater
import json
import os

def getToken():
    token = []
    if not os.path.exists(file_path):
        token.append(input('Insert Token here: '))
        with open('token.json', 'w') as f:
            json.dump(token, f)
    else:
        with open("token.json") as f:
            token = json.load(f)
    return token[0]

def main():
    token = getToken()
    print(token)

if __name__ == '__main__':
    main()


from setuptools import setup, find_packages

setup(name='lightweight-rest-tester',
      version='1.4.0',
      description='A lightweight REST API testing framework.',
      url='https://github.com/ridibooks/lightweight-rest-tester',
      author='Jeehoon Yoo',
      author_email='jeehoon.yoo@ridi.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      install_requires=[
          'certifi==2017.4.17',
          'chardet==3.0.4',
          'idna==2.5',
          'jsonschema==2.6.0',
          'requests==2.18.1',
          'urllib3==1.21.1',
          'click==6.7',
      ],
      entry_points={
          'console_scripts': [
              'lw_rest_tester = rest_tester.command_line:main'
          ],
      })

Update the version to 1.4.0.

Update the version to 1.4.0.

Response:
from setuptools import setup, find_packages

setup(name='lightweight-rest-tester',
      version='1.4.0',
      description='A lightweight REST API testing framework.',
      url='https://github.com/ridibooks/lightweight-rest-tester',
      author='Jeehoon Yoo',
      author_email='jeehoon.yoo@ridi.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      install_requires=[
          'certifi==2017.4.17',
          'chardet==3.0.4',
          'idna==2.5',
          'jsonschema==2.6.0',
          'requests==2.18.1',
          'urllib3==1.21.1',
          'click==6.7',
      ],
      entry_points={
          'console_scripts': [
              'lw_rest_tester = rest_tester.command_line:main'
          ],
      })

Prompt:
Update the version to 1.4.0.

from setuptools import setup, find_packages

setup(name='lightweight-rest-tester',
      version='1.2.0',
      description='A lightweight REST API testing framework.',
      url='https://github.com/ridibooks/lightweight-rest-tester',
      author='Jeehoon Yoo',
      author_email='jeehoon.yoo@ridi.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      install_requires=[
          'certifi==2017.4.17',
          'chardet==3.0.4',
          'idna==2.5',
          'jsonschema==2.6.0',
          'requests==2.18.1',
          'urllib3==1.21.1',
          'click==6.7',
      ],
      entry_points={
          'console_scripts': [
              'lw_rest_tester = rest_tester.command_line:main'
          ],
      })


import functools

from pkit.slot import get_slot_pool

def acquire(pool_name):
    """Actor's method decorator to auto-acquire a slot before execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                # Unix semaphores are acquired through sem_post and sem_wait
                # syscalls, which can potentially fail.
                slots_pool.acquire()
            except OSError:
                pass

            res = method(self, *args, **kwargs)
            return res
        return wrapper
    return decorator

def release(pool_name):
    """Actors method decorator to auto-release a used slot after execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                res = method(self, *args, **kwargs)
            except Exception:
                raise
            finally:
                try:
                    slots_pool.release()
                except OSError:
                    pass

            return res

        return wrapper
    return decorator

Fix slot release on method exception

Fix slot release on method exception

Response:
import functools

from pkit.slot import get_slot_pool

def acquire(pool_name):
    """Actor's method decorator to auto-acquire a slot before execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                # Unix semaphores are acquired through sem_post and sem_wait
                # syscalls, which can potentially fail.
                slots_pool.acquire()
            except OSError:
                pass

            res = method(self, *args, **kwargs)
            return res
        return wrapper
    return decorator

def release(pool_name):
    """Actors method decorator to auto-release a used slot after execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                res = method(self, *args, **kwargs)
            except Exception:
                raise
            finally:
                try:
                    slots_pool.release()
                except OSError:
                    pass

            return res

        return wrapper
    return decorator

Prompt:
Fix slot release on method exception

import functools

from pkit.slot import get_slot_pool

def acquire(pool_name):
    """Actor's method decorator to auto-acquire a slot before execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)

            try:
                # Unix semaphores are acquired through sem_post and sem_wait
                # syscalls, which can potentially fail.
                slots_pool.acquire()
            except OSError:
                pass

            res = method(self, *args, **kwargs)
            return res
        return wrapper
    return decorator

def release(pool_name):
    """Actors method decorator to auto-release a used slot after execution"""
    def decorator(method):
        @functools.wraps(method)
        def wrapper(self, *args, **kwargs):
            slots_pool = get_slot_pool(pool_name)
            res = method(self, *args, **kwargs)

            try:
                slots_pool.release()
            except OSError:
                pass

            return res

        return wrapper
    return decorator


from .exceptions import ApiError

# -----------------------------------------------------------------------------

class Related(object):
    def __init__(self, item_class=None, **kwargs):
        self._item_class = item_class
        self._resolvers = kwargs

    def resolve_related(self, data):
        for field_name, resolver in self._resolvers.items():
            value = data.get(field_name, None)
            if value is None:
                # If this field were required or non-nullable, the deserializer
                # would already have raised an exception.
                continue

            try:
                resolved = self.resolve_field(value, resolver)
            except ApiError as e:
                pointer = '/data/{}'.format(field_name)
                raise e.update({'source': {'pointer': pointer}})

            data[field_name] = resolved

        if self._item_class:
            return self._item_class(**data)

        return data

    def resolve_field(self, value, resolver):
        # marshmallow always uses lists here.
        many = isinstance(value, list)
        if many and not value:
            # As a tiny optimization, there's no need to resolve an empty list.
            return value

        if isinstance(resolver, Related):
            resolve_item = resolver.resolve_related
        else:
            resolve_item = resolver().resolve_related_item

        if many:
            return [resolve_item(item) for item in value]

        return resolve_item(value)

Fix variable names in Related

Fix variable names in Related

Response:
from .exceptions import ApiError

# -----------------------------------------------------------------------------

class Related(object):
    def __init__(self, item_class=None, **kwargs):
        self._item_class = item_class
        self._resolvers = kwargs

    def resolve_related(self, data):
        for field_name, resolver in self._resolvers.items():
            value = data.get(field_name, None)
            if value is None:
                # If this field were required or non-nullable, the deserializer
                # would already have raised an exception.
                continue

            try:
                resolved = self.resolve_field(value, resolver)
            except ApiError as e:
                pointer = '/data/{}'.format(field_name)
                raise e.update({'source': {'pointer': pointer}})

            data[field_name] = resolved

        if self._item_class:
            return self._item_class(**data)

        return data

    def resolve_field(self, value, resolver):
        # marshmallow always uses lists here.
        many = isinstance(value, list)
        if many and not value:
            # As a tiny optimization, there's no need to resolve an empty list.
            return value

        if isinstance(resolver, Related):
            resolve_item = resolver.resolve_related
        else:
            resolve_item = resolver().resolve_related_item

        if many:
            return [resolve_item(item) for item in value]

        return resolve_item(value)

Prompt:
Fix variable names in Related

from .exceptions import ApiError

# -----------------------------------------------------------------------------

class Related(object):
    def __init__(self, item_class=None, **kwargs):
        self._item_class = item_class
        self._view_classes = kwargs

    def resolve_related(self, data):
        for field_name, view_class in self._view_classes.items():
            value = data.get(field_name, None)
            if value is None:
                # If this field were required or non-nullable, the deserializer
                # would already have raised an exception.
                continue

            try:
                resolved = self.resolve_field(value, view_class)
            except ApiError as e:
                pointer = '/data/{}'.format(field_name)
                raise e.update({'source': {'pointer': pointer}})

            data[field_name] = resolved

        if self._item_class:
            return self._item_class(**data)

        return data

    def resolve_field(self, value, view_class):
        # marshmallow always uses lists here.
        many = isinstance(value, list)
        if many and not value:
            # As a tiny optimization, there's no need to resolve an empty list.
            return value

        if isinstance(view_class, Related):
            # This is not actually a view class.
            resolver = view_class.resolve_related
        else:
            resolver = view_class().resolve_related_item

        if many:
            return [resolver(item) for item in value]

        return resolver(value)


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

from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor

class DataScienceJobsSpider(CrawlSpider):
    log = getLogger(__name__)
    name = 'data-science-jobs'
    allowed_domains = ['www.data-science-jobs.com']
    start_urls = ['http://www.data-science-jobs.com']
    job_links = Rule(LinkExtractor(allow='detail\/'), callback='parse_job')
    pagination_links = Rule(LinkExtractor(allow='page=\d+'))
    rules = [job_links, pagination_links]

    def parse_job(self, response):
        self.log.info('Parsing %s', response.url)

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

from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor

class DataScienceJobsSpider(CrawlSpider):
    log = getLogger(__name__)
    name = 'data-science-jobs'
    allowed_domains = ['www.data-science-jobs.com']
    start_urls = ['http://www.data-science-jobs.com']
    job_links = Rule(LinkExtractor(allow='detail\/'), callback='parse_job')
    pagination_links = Rule(LinkExtractor(allow='page=\d+'))
    rules = [job_links, pagination_links]

    def parse_job(self, response):
        self.log.info('Parsing %s', response.url)

Prompt:
Rename the parser function to parse_jobs.

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

from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor

class DataScienceJobsSpider(CrawlSpider):
    log = getLogger(__name__)
    name = 'data-science-jobs'
    allowed_domains = ['www.data-science-jobs.com', 'fonts.googleapis.com', 'jobs.lever.com']
    start_urls = ['http://www.data-science-jobs.com/']
    test = Rule(LinkExtractor(allow='family'), callback='parse')
    test2 = Rule(LinkExtractor(allow='comtravo'), callback='parse')
    job_links = Rule(LinkExtractor(allow='detail\/'), callback='parse')
    pagination_links = Rule(LinkExtractor(allow='\?page=\d+'), callback='parse')
    rules = [job_links, pagination_links, test, test2]
    response = None

    def parse(self, response):
        self.log.info('Parsing %s', response.url)


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        start, end = 0, 0
        q = [(root, 0, 0)]
        cd = -1
        m = 0
        for v, d, c in q:
            if d != cd:
                start, end = c, c
                cd = d
            else:
                end = c
            m = max(m, end - start + 1)
            if v.left:
                q.append((v.left, d + 1, c << 1))
            if v.right:
                q.append((v.right, d + 1, (c << 1) | 1))
        return m

Add py solution for 662. Maximum Width of Binary Tree

662. Maximum Width of Binary Tree: https://leetcode.com/problems/maximum-width-of-binary-tree/

Response:
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def widthOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        start, end = 0, 0
        q = [(root, 0, 0)]
        cd = -1
        m = 0
        for v, d, c in q:
            if d != cd:
                start, end = c, c
                cd = d
            else:
                end = c
            m = max(m, end - start + 1)
            if v.left:
                q.append((v.left, d + 1, c << 1))
            if v.right:
                q.append((v.right, d + 1, (c << 1) | 1))
        return m

Prompt:
Add py solution for 662. Maximum Width of Binary Tree

662. Maximum Width of Binary Tree: https://leetcode.com/problems/maximum-width-of-binary-tree/


import unittest
import os
from test.util import ykman_cli

@unittest.skipIf(
    os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class TestExternalLibraries(unittest.TestCase):

    def test_ykman_version(self):
        output = ykman_cli('-v')
        # Test that major version is 1 on all libs
        self.assertIn('libykpers 1', output)
        self.assertIn('libu2f-host 1', output)
        self.assertIn('libusb 1', output)

    def test_ykman_version_not_found(self):
        output = ykman_cli('-v')
        self.assertNotIn('not found!', output)
        self.assertNotIn('<pyusb backend missing>', output)

Response:
import unittest
import os
from test.util import ykman_cli

@unittest.skipIf(
    os.environ.get('INTEGRATION_TESTS') != 'TRUE', 'INTEGRATION_TESTS != TRUE')
class TestExternalLibraries(unittest.TestCase):

    def test_ykman_version(self):
        output = ykman_cli('-v')
        # Test that major version is 1 on all libs
        self.assertIn('libykpers 1', output)
        self.assertIn('libu2f-host 1', output)
        self.assertIn('libusb 1', output)

    def test_ykman_version_not_found(self):
        output = ykman_cli('-v')
        self.assertNotIn('not found!', output)
        self.assertNotIn('<pyusb backend missing>', output)

Prompt:
Revert "Don't check INTEGRATION_TESTS env var in external libs test"

This reverts commit 648d02fbfca79241a65902f6dd9a7a767a0f633d.

import unittest
from test.util import ykman_cli

class TestExternalLibraries(unittest.TestCase):

    def test_ykman_version(self):
        output = ykman_cli('-v')
        # Test that major version is 1 on all libs
        self.assertIn('libykpers 1', output)
        self.assertIn('libu2f-host 1', output)
        self.assertIn('libusb 1', output)

    def test_ykman_version_not_found(self):
        output = ykman_cli('-v')
        self.assertNotIn('not found!', output)
        self.assertNotIn('<pyusb backend missing>', output)


# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save

class DirtyFieldsMixin(object):
    def __init__(self, *args, **kwargs):
        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
        post_save.connect(reset_state, sender=self.__class__,
                            dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)
        reset_state(sender=self.__class__, instance=self)

    def _as_dict(self):
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields])

    def get_dirty_fields(self):
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

    def is_dirty(self):
        # in order to be dirty we need to have been saved at least once, so we
        # check for a primary key and we need our dirty fields to not be empty
        if not self.pk:
            return True
        return {} != self.get_dirty_fields()

def reset_state(sender, instance, **kwargs):
    instance._original_state = instance._as_dict()

Response:
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save

class DirtyFieldsMixin(object):
    def __init__(self, *args, **kwargs):
        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
        post_save.connect(reset_state, sender=self.__class__,
                            dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)
        reset_state(sender=self.__class__, instance=self)

    def _as_dict(self):
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields])

    def get_dirty_fields(self):
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

    def is_dirty(self):
        # in order to be dirty we need to have been saved at least once, so we
        # check for a primary key and we need our dirty fields to not be empty
        if not self.pk:
            return True
        return {} != self.get_dirty_fields()

def reset_state(sender, instance, **kwargs):
    instance._original_state = instance._as_dict()

Prompt:
Check primary keys for foreign key and one-to-one fields

# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save

class DirtyFieldsMixin(object):
    def __init__(self, *args, **kwargs):
        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
        post_save.connect(reset_state, sender=self.__class__,
                            dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)
        reset_state(sender=self.__class__, instance=self)

    def _as_dict(self):
        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel])

    def get_dirty_fields(self):
        new_state = self._as_dict()
        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

    def is_dirty(self):
        # in order to be dirty we need to have been saved at least once, so we
        # check for a primary key and we need our dirty fields to not be empty
        if not self.pk:
            return True
        return {} != self.get_dirty_fields()

def reset_state(sender, instance, **kwargs):
    instance._original_state = instance._as_dict()


#!/usr/bin/env python

import socket, fcntl, sys

#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
   fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
   print 'An instance of this program is already running'
   sys.exit(0)

import Adafruit_CharLCD as LCD

lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)

listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

number_packets_received = 0

def print_lcd():
   lcd.clear()
   lcd.message('# of packets\nreceived: ' + str(number_packets_received))

if __name__ == '__main__':
   while True:
      print_lcd()
      print listener.recvfrom(7777)
      number_packets_received += 1

Fix header of Python file

Response:
#!/usr/bin/env python

import socket, fcntl, sys

#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
   fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
   print 'An instance of this program is already running'
   sys.exit(0)

import Adafruit_CharLCD as LCD

lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)

listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

number_packets_received = 0

def print_lcd():
   lcd.clear()
   lcd.message('# of packets\nreceived: ' + str(number_packets_received))

if __name__ == '__main__':
   while True:
      print_lcd()
      print listener.recvfrom(7777)
      number_packets_received += 1

Prompt:
Fix header of Python file

Now correctly points to the Python interpretor

#!/usr/bin/env/python

import socket, fcntl, sys

#Lock to only allow one instance of this program to run
pid_file = '/tmp/send.pid'
fp = open(pid_file, 'w')
try:
   fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
   print 'An instance of this program is already running'
   sys.exit(0)

import Adafruit_CharLCD as LCD

lcd = LCD.Adafruit_CharLCDPlate()
lcd.set_color(0,0,0)

listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)

number_packets_received = 0

def print_lcd():
   lcd.clear()
   lcd.message('# of packets\nreceived: ' + str(number_packets_received))

if __name__ == '__main__':
   while True:
      print_lcd()
      print listener.recvfrom(7777), '\n', type(listener)
      number_packets_received += 1


""" Run this file to check your python installation.
"""
from os.path import dirname, join

HERE = dirname(__file__)

def test_import_pandas():
    import pandas

def test_pandas_version():
    import pandas
    version_found = pandas.__version__.split(".")
    version_found = tuple(int(num) for num in version_found)
    assert version_found > (0, 15)

def test_import_numpy():
    import numpy

def test_import_matplotlib():
    import matplotlib.pyplot as plt
    plt.figure
    plt.plot
    plt.legend
    plt.imshow

def test_import_statsmodels():
    import statsmodels as sm
    from statsmodels.formula.api import ols
    from statsmodels.tsa.ar_model import AR

def test_read_html():
    import pandas
    pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
                     "sea_levels", "Obtaining Tide Gauge Data.html"))

def test_scrape_web():
    import pandas as pd
    pd.read_html("http://en.wikipedia.org/wiki/World_population")

if __name__ == "__main__":
    import nose
    nose.run(defaultTest=__name__)

Response:
""" Run this file to check your python installation.
"""
from os.path import dirname, join

HERE = dirname(__file__)

def test_import_pandas():
    import pandas

def test_pandas_version():
    import pandas
    version_found = pandas.__version__.split(".")
    version_found = tuple(int(num) for num in version_found)
    assert version_found > (0, 15)

def test_import_numpy():
    import numpy

def test_import_matplotlib():
    import matplotlib.pyplot as plt
    plt.figure
    plt.plot
    plt.legend
    plt.imshow

def test_import_statsmodels():
    import statsmodels as sm
    from statsmodels.formula.api import ols
    from statsmodels.tsa.ar_model import AR

def test_read_html():
    import pandas
    pandas.read_html(join(HERE, "demos", "climate_timeseries", "data",
                     "sea_levels", "Obtaining Tide Gauge Data.html"))

def test_scrape_web():
    import pandas as pd
    pd.read_html("http://en.wikipedia.org/wiki/World_population")

if __name__ == "__main__":
    import nose
    nose.run(defaultTest=__name__)

Prompt:
Add some more content in tests including with statsmodels.

""" Run this file to check your python installation.
"""

def test_import_pandas():
    import pandas

def test_pandas_version():
    import pandas
    version_found = pandas.__version__.split(".")
    version_found = tuple(int(num) for num in version_found)
    assert version_found > (0, 15)

def test_import_numpy():
    import numpy

def test_import_matplotlib():
    import matplotlib

def test_scrape_web():
    import pandas as pd
    pd.read_html("http://en.wikipedia.org/wiki/World_population")

if __name__ == "__main__":
    import nose
    nose.run(defaultTest=__name__)


from hash import HashTable
import io

words = []

with io.open('/usr/share/dict/words', 'r') as word_file:
    words = word_file.readlines()

def test_hash():
    t = HashTable()
    t.set('coffee', 'coffee')
    assert t.get('coffee') == 'coffee'

def test_duplicate_hash_val():
    t = HashTable()
    t.set('bob', 'bob')
    t.set('obb', 'obb')
    assert t.get('bob') == 'bob'
    assert t.get('obb') == 'obb'

def test_word_file():
    t = HashTable()
    for word in words:
        t.set(word, word)
    assert t.get(words[654]) == words[654]
    assert t.get(words[3541]) == words[3541]
    assert t.get(words[6541]) == words[6541]

Add tests for hash table

Add tests for hash table

Response:
from hash import HashTable
import io

words = []

with io.open('/usr/share/dict/words', 'r') as word_file:
    words = word_file.readlines()

def test_hash():
    t = HashTable()
    t.set('coffee', 'coffee')
    assert t.get('coffee') == 'coffee'

def test_duplicate_hash_val():
    t = HashTable()
    t.set('bob', 'bob')
    t.set('obb', 'obb')
    assert t.get('bob') == 'bob'
    assert t.get('obb') == 'obb'

def test_word_file():
    t = HashTable()
    for word in words:
        t.set(word, word)
    assert t.get(words[654]) == words[654]
    assert t.get(words[3541]) == words[3541]
    assert t.get(words[6541]) == words[6541]

Prompt: Add tests for hash table


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

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .ir import TranslatableTextNode

def gettext(s):
    return s

def extract(fileobj, keywords, comment_tags, options):
    '''Babel entry point that extracts translation strings from XML templates.
    '''
    from .xml_template import _Parser, _Compiler, expand
    source = fileobj.read()
    if isinstance(source, bytes):
        source = source.decode('utf-8')
    doc = _Parser(filename='<string>', source=source).parse()
    expand(doc)
    compiler = _Compiler(filename='<string>', doc=doc,
                         mode=options.get('mode', 'xml'),
                         is_fragment=options.get('is_fragment', False))
    ir = compiler.compile()
    for node in ir:
        if isinstance(node, TranslatableTextNode):
            if node.text.strip():
                for line in node.text.split('\n'):
                    yield (node.lineno, '_', line, [])

Fix issue with message extractor on Py2

Fix issue with message extractor on Py2

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

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .ir import TranslatableTextNode

def gettext(s):
    return s

def extract(fileobj, keywords, comment_tags, options):
    '''Babel entry point that extracts translation strings from XML templates.
    '''
    from .xml_template import _Parser, _Compiler, expand
    source = fileobj.read()
    if isinstance(source, bytes):
        source = source.decode('utf-8')
    doc = _Parser(filename='<string>', source=source).parse()
    expand(doc)
    compiler = _Compiler(filename='<string>', doc=doc,
                         mode=options.get('mode', 'xml'),
                         is_fragment=options.get('is_fragment', False))
    ir = compiler.compile()
    for node in ir:
        if isinstance(node, TranslatableTextNode):
            if node.text.strip():
                for line in node.text.split('\n'):
                    yield (node.lineno, '_', line, [])

Prompt:
Fix issue with message extractor on Py2

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

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .ir import TranslatableTextNode

def gettext(s):
    return s

def extract(fileobj, keywords, comment_tags, options):
    '''Babel entry point that extracts translation strings from XML templates.
    '''
    from .xml_template import _Parser, _Compiler, expand
    doc = _Parser(filename='<string>', source=fileobj.read()).parse()
    expand(doc)
    compiler = _Compiler(filename='<string>', doc=doc,
                         mode=options.get('mode', 'xml'),
                         is_fragment=options.get('is_fragment', False))
    ir = compiler.compile()
    for node in ir:
        if isinstance(node, TranslatableTextNode):
            if node.text.strip():
                for line in node.text.split('\n'):
                    yield (node.lineno, '_', line, [])


# -*- coding: utf-8 -*-
import os

from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3  # noqa

class CustomThemeBase(ThemeBase):
    FROIDE_THEME = 'froide_theme.theme'

    SITE_NAME = "My Froide"
    SITE_EMAIL = "info@example.com"
    SITE_URL = 'http://localhost:8000'

    SECRET_URLS = {
        "admin": "admin",
    }

    @property
    def LOCALE_PATHS(self):
        return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), '..', "locale")
            )
        ]

class Dev(CustomThemeBase, Base):
    pass

class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
    pass

class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
    pass

try:
    from .local_settings import *  # noqa
except ImportError:
    pass

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

from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3  # noqa

class CustomThemeBase(ThemeBase):
    FROIDE_THEME = 'froide_theme.theme'

    SITE_NAME = "My Froide"
    SITE_EMAIL = "info@example.com"
    SITE_URL = 'http://localhost:8000'

    SECRET_URLS = {
        "admin": "admin",
    }

    @property
    def LOCALE_PATHS(self):
        return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
            os.path.abspath(
                os.path.join(os.path.dirname(__file__), '..', "locale")
            )
        ]

class Dev(CustomThemeBase, Base):
    pass

class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
    pass

class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
    pass

try:
    from .local_settings import *  # noqa
except ImportError:
    pass

Prompt:
Add own locale directory to LOCALE_PATHS
# -*- coding: utf-8 -*-
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3  # noqa

class CustomThemeBase(ThemeBase):
    FROIDE_THEME = 'froide_theme.theme'

    SITE_NAME = "My Froide"
    SITE_EMAIL = "info@example.com"
    SITE_URL = 'http://localhost:8000'

    SECRET_URLS = {
        "admin": "admin",
    }

class Dev(CustomThemeBase, Base):
    pass

class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
    pass

class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
    pass

try:
    from .local_settings import *  # noqa
except ImportError:
    pass


# -*- coding: utf-8 -*-
import scrapy
import json

from locations.items import GeojsonPointItem

class SuperAmericaSpider(scrapy.Spider):
    name = "speedway"
    allowed_domains = ["www.speedway.com"]
    start_urls = (
        'https://www.speedway.com/GasPriceSearch',
    )

    def parse(self, response):
        yield scrapy.Request(
            'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
            callback=self.parse_search,
            method='POST',
            body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            }
        )

    def parse_search(self, response):
        data = json.loads(response.body_as_unicode())

        for store in data:
            properties = {
                'addr:full': store['address'],
                'addr:city': store['city'],
                'addr:state': store['state'],
                'addr:postcode': store['zip'],
                'phone': store['phoneNumber'],
                'ref': store['costCenterId'],
            }

            lon_lat = [
                store['longitude'],
                store['latitude'],
            ]

            yield GeojsonPointItem(
                properties=properties,
                lon_lat=lon_lat,
            )

Correct the name of the spider

Correct the name of the spider

Response:
# -*- coding: utf-8 -*-
import scrapy
import json

from locations.items import GeojsonPointItem

class SuperAmericaSpider(scrapy.Spider):
    name = "speedway"
    allowed_domains = ["www.speedway.com"]
    start_urls = (
        'https://www.speedway.com/GasPriceSearch',
    )

    def parse(self, response):
        yield scrapy.Request(
            'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
            callback=self.parse_search,
            method='POST',
            body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            }
        )

    def parse_search(self, response):
        data = json.loads(response.body_as_unicode())

        for store in data:
            properties = {
                'addr:full': store['address'],
                'addr:city': store['city'],
                'addr:state': store['state'],
                'addr:postcode': store['zip'],
                'phone': store['phoneNumber'],
                'ref': store['costCenterId'],
            }

            lon_lat = [
                store['longitude'],
                store['latitude'],
            ]

            yield GeojsonPointItem(
                properties=properties,
                lon_lat=lon_lat,
            )

Prompt:
Correct the name of the spider

# -*- coding: utf-8 -*-
import scrapy
import json

from locations.items import GeojsonPointItem

class SuperAmericaSpider(scrapy.Spider):
    name = "superamerica"
    allowed_domains = ["superamerica.com"]
    start_urls = (
        'https://www.speedway.com/GasPriceSearch',
    )

    def parse(self, response):
        yield scrapy.Request(
            'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
            callback=self.parse_search,
            method='POST',
            body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json',
            }
        )

    def parse_search(self, response):
        data = json.loads(response.body_as_unicode())

        for store in data:
            properties = {
                'addr:full': store['address'],
                'addr:city': store['city'],
                'addr:state': store['state'],
                'addr:postcode': store['zip'],
                'phone': store['phoneNumber'],
                'ref': store['costCenterId'],
            }

            lon_lat = [
                store['longitude'],
                store['latitude'],
            ]

            yield GeojsonPointItem(
                properties=properties,
                lon_lat=lon_lat,
            )


#!/usr/bin/env python
#
# dials.util.__init__.py
#
#  Copyright (C) 2013 Diamond Light Source
#
#  Author: James Parkhurst
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division

class HalError(RuntimeError):
    def __init__(self, string=''):

        # Get the username
        try:
            from getpass import getuser
            username = getuser()
        except Exception:
            username = 'Dave'

        # Put in HAL error text.
        text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
            username, string)

        # Init base class
        RuntimeError.__init__(self, text)

def halraiser(e):
    ''' Function to re-raise an exception with a Hal message. '''
    import logging

    # Get the log and write the error to the log file
    log = logging.getLogger(__name__)
    log.error(e)

    # Get the username
    try:
        from getpass import getuser
        username = getuser()
    except Exception:
        username = 'Humanoid'

    # Put in HAL error text.
    text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)

    # Append to exception
    if len(e.args) == 0:
        e.args = (text,)
    elif len(e.args) == 1:
        e.args = (text + ' ' + e.args[0],)
    else:
        e.args = (text,) + e.args

    # Reraise the exception
    raise

Print out errors to log.

Print out errors to log.

Response:
#!/usr/bin/env python
#
# dials.util.__init__.py
#
#  Copyright (C) 2013 Diamond Light Source
#
#  Author: James Parkhurst
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division

class HalError(RuntimeError):
    def __init__(self, string=''):

        # Get the username
        try:
            from getpass import getuser
            username = getuser()
        except Exception:
            username = 'Dave'

        # Put in HAL error text.
        text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
            username, string)

        # Init base class
        RuntimeError.__init__(self, text)

def halraiser(e):
    ''' Function to re-raise an exception with a Hal message. '''
    import logging

    # Get the log and write the error to the log file
    log = logging.getLogger(__name__)
    log.error(e)

    # Get the username
    try:
        from getpass import getuser
        username = getuser()
    except Exception:
        username = 'Humanoid'

    # Put in HAL error text.
    text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)

    # Append to exception
    if len(e.args) == 0:
        e.args = (text,)
    elif len(e.args) == 1:
        e.args = (text + ' ' + e.args[0],)
    else:
        e.args = (text,) + e.args

    # Reraise the exception
    raise

Prompt:
Print out errors to log.
#!/usr/bin/env python
#
# dials.util.__init__.py
#
#  Copyright (C) 2013 Diamond Light Source
#
#  Author: James Parkhurst
#
#  This code is distributed under the BSD license, a copy of which is
#  included in the root directory of this package.

from __future__ import division

class HalError(RuntimeError):
    def __init__(self, string=''):

        # Get the username
        try:
            from getpass import getuser
            username = getuser()
        except Exception:
            username = 'Dave'

        # Put in HAL error text.
        text = 'I\'m sorry {0}. I\'m afraid I can\'t do that. {1}'.format(
            username, string)

        # Init base class
        RuntimeError.__init__(self, text)

def halraiser(e):
    ''' Function to re-raise an exception with a Hal message. '''

    # Get the username
    try:
        from getpass import getuser
        username = getuser()
    except Exception:
        username = 'Humanoid'

    # Put in HAL error text.
    text = 'I\'m sorry {0}. I\'m afraid I can\'t do that.'.format(username)

    # Append to exception
    if len(e.args) == 0:
        e.args = (text,)
    elif len(e.args) == 1:
        e.args = (text + ' ' + e.args[0],)
    else:
        e.args = (text,) + e.args

    # Reraise the exception
    raise


def test_iris():
    from tsne import bh_sne
    from sklearn.datasets import load_iris

    iris = load_iris()

    X = iris.data
    y = iris.target

    X_2d = bh_sne(X)

Add test for iris, same as example notebook

Response:
def test_iris():
    from tsne import bh_sne
    from sklearn.datasets import load_iris

    iris = load_iris()

    X = iris.data
    y = iris.target

    X_2d = bh_sne(X)

Prompt: Add test for iris, same as example notebook


import sys
import os
import time
try:
    import subprocess
except ImportError:
    # use private copy for old Python versions
    import MonetDBtesting.subprocess26 as subprocess

def server():
    s = subprocess.Popen('%s "--dbinit=include sql;" --set gdk_readonly=yes' % os.getenv('MSERVER'),
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    s.stdin.write('\nio.printf("\\nReady.\\n");\n')
    s.stdin.flush()
    while True:
        ln = s.stdout.readline()
        if not ln:
            print 'Unexpected EOF from server'
            sys.exit(1)
        sys.stdout.write(ln)
        if 'Ready' in ln:
            break
    return s

def client():
    c = subprocess.Popen("%s" % os.getenv('SQL_CLIENT'),
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    return c

script1 = '''\
create table t2 (a int);
'''

def main():
    s = server()
    c = client()
    o, e = c.communicate(script1)
    sys.stdout.write(o)
    sys.stderr.write(e)
    o, e = s.communicate()
    sys.stdout.write(o)
    sys.stderr.write(e)

if __name__ == '__main__':
    main()

Response:
import sys
import os
import time
try:
    import subprocess
except ImportError:
    # use private copy for old Python versions
    import MonetDBtesting.subprocess26 as subprocess

def server():
    s = subprocess.Popen('%s "--dbinit=include sql;" --set gdk_readonly=yes' % os.getenv('MSERVER'),
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    s.stdin.write('\nio.printf("\\nReady.\\n");\n')
    s.stdin.flush()
    while True:
        ln = s.stdout.readline()
        if not ln:
            print 'Unexpected EOF from server'
            sys.exit(1)
        sys.stdout.write(ln)
        if 'Ready' in ln:
            break
    return s

def client():
    c = subprocess.Popen("%s" % os.getenv('SQL_CLIENT'),
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    return c

script1 = '''\
create table t2 (a int);
'''

def main():
    s = server()
    c = client()
    o, e = c.communicate(script1)
    sys.stdout.write(o)
    sys.stderr.write(e)
    o, e = s.communicate()
    sys.stdout.write(o)
    sys.stderr.write(e)

if __name__ == '__main__':
    main()

Prompt:
Use double quotes to quote command arguments.  The Windows command
parser doesn't recognize single quotes.

import sys
import os
import time
try:
    import subprocess
except ImportError:
    # use private copy for old Python versions
    import MonetDBtesting.subprocess26 as subprocess

def server():
    s = subprocess.Popen("%s --dbinit='include sql;' --set gdk_readonly=yes" % os.getenv('MSERVER'),
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    s.stdin.write('\nio.printf("\\nReady.\\n");\n')
    s.stdin.flush()
    while True:
        ln = s.stdout.readline()
        if not ln:
            print 'Unexpected EOF from server'
            sys.exit(1)
        sys.stdout.write(ln)
        if 'Ready' in ln:
            break
    return s

def client():
    c = subprocess.Popen("%s" % os.getenv('SQL_CLIENT'),
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE)
    return c

script1 = '''\
create table t2 (a int);
'''

def main():
    s = server()
    c = client()
    o, e = c.communicate(script1)
    sys.stdout.write(o)
    sys.stderr.write(e)
    o, e = s.communicate()
    sys.stdout.write(o)
    sys.stderr.write(e)

if __name__ == '__main__':
    main()


"""
Shared exception.
"""

class BadRequestError(Exception):
    pass

class ConflictError(Exception):
    pass

class NotFoundError(Exception):

    def __init__(self, status_code=None):
        super(NotFoundError, self).__init__()
        self.status_code = status_code

Response:
"""
Shared exception.
"""

class BadRequestError(Exception):
    pass

class ConflictError(Exception):
    pass

class NotFoundError(Exception):

    def __init__(self, status_code=None):
        super(NotFoundError, self).__init__()
        self.status_code = status_code

Prompt:
Fix for pypy compatibility: must super's __init__

"""
Shared exception.
"""

class BadRequestError(Exception):
    pass

class ConflictError(Exception):
    pass

class NotFoundError(Exception):

    def __init__(self, status_code=None):
        self.status_code = status_code


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

from distutils.core import setup

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

setup(
    name='pybrdst',
    packages=['pybrdst'],  # this must be the same as the name above
    version='0.1',
    description='Brazilian daylight saving time',
    long_description=long_description,
    author='João Carlos Mendes',
    author_email='joaocarlos.tmendes@gmail.com',
    url='https://github.com/joaocarlosmendes/pybrdst',
    download_url='https://github.com/joaocarlosmendes/pybrdst/releases/tag/0.1',
    license='MIT',
    keywords=['DST',
              'brazilian',
              'daylight',
              'saving',
              'horário',
              'verão',
              'brasileiro'],
    classifiers=[],
    )

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

from distutils.core import setup

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

setup(
    name='pybrdst',
    packages=['pybrdst'],  # this must be the same as the name above
    version='0.1',
    description='Brazilian daylight saving time',
    long_description=long_description,
    author='João Carlos Mendes',
    author_email='joaocarlos.tmendes@gmail.com',
    url='https://github.com/joaocarlosmendes/pybrdst',
    download_url='https://github.com/joaocarlosmendes/pybrdst/releases/tag/0.1',
    license='MIT',
    keywords=['DST',
              'brazilian',
              'daylight',
              'saving',
              'horário',
              'verão',
              'brasileiro'],
    classifiers=[],
    )

Prompt:
Remove parâmetros inutilizados e adiciona a descrição longa

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

from distutils.core import setup

with open('requirements.txt') as reqs:
    requirements = reqs.read().split()

setup(
    name='pybrdst',
    packages=['pybrdst'],  # this must be the same as the name above
    version='0.1',
    description='Brazilian daylight saving time',
    author='João Carlos Mendes',
    author_email='joaocarlos.tmendes@gmail.com',
    url='https://github.com/joaocarlosmendes/pybrdst',
    download_url='https://github.com/joaocarlosmendes/pybrdst/releases/tag/0.1',
    install_requires=requirements,  # noqa
    include_package_data=True,
    zip_safe=False,
    license='MIT',
    keywords=['DST',
              'brazilian',
              'daylight',
              'saving',
              'horário',
              'verão',
              'brasileiro'],
    classifiers=[],
    )


from invoke import run, task

TESTPYPI = "https://testpypi.python.org/pypi"

@task
def lint(ctx):
    """Run flake8 to lint code"""
    run("flake8")

@task
def freeze(ctx):
    """Freeze the pip requirements"""
    run("pip freeze -l > requirements.txt")

@task(lint)
def test(ctx):
    """Lint, unit test, and check setup.py"""
    cmd = "{} {}".format(
        "nosetests",
        "--with-coverage --cover-erase --cover-package=keysight --cover-html")
    run(cmd)

@task
def release(ctx, deploy=False, test=False, version=''):
    """Tag release, run Travis-CI, and deploy to PyPI
    """
    if test:
        run("python setup.py check")
        run("python setup.py register sdist upload --dry-run")

    if deploy:
        run("python setup.py check")
        if version:
            run("git checkout master")
            run("git tag -a v{ver} -m 'v{ver}'".format(ver=version))
            run("git push")
            run("git push origin --tags")
    else:
        print("- Have you updated the version?")
        print("- Have you updated CHANGELOG.md?")
        print("- Have you fixed any last minute bugs?")
        print("If you answered yes to all of the above questions,")
        print("then run `invoke release --deploy -vX.YY.ZZ` to:")
        print("- Checkout master")
        print("- Tag the git release with provided vX.YY.ZZ version")
        print("- Push the master branch and tags to repo")
        print("- Deploy to PyPi using Travis")

Add freeze task to invoke

Add freeze task to invoke

Response:
from invoke import run, task

TESTPYPI = "https://testpypi.python.org/pypi"

@task
def lint(ctx):
    """Run flake8 to lint code"""
    run("flake8")

@task
def freeze(ctx):
    """Freeze the pip requirements"""
    run("pip freeze -l > requirements.txt")

@task(lint)
def test(ctx):
    """Lint, unit test, and check setup.py"""
    cmd = "{} {}".format(
        "nosetests",
        "--with-coverage --cover-erase --cover-package=keysight --cover-html")
    run(cmd)

@task
def release(ctx, deploy=False, test=False, version=''):
    """Tag release, run Travis-CI, and deploy to PyPI
    """
    if test:
        run("python setup.py check")
        run("python setup.py register sdist upload --dry-run")

    if deploy:
        run("python setup.py check")
        if version:
            run("git checkout master")
            run("git tag -a v{ver} -m 'v{ver}'".format(ver=version))
            run("git push")
            run("git push origin --tags")
    else:
        print("- Have you updated the version?")
        print("- Have you updated CHANGELOG.md?")
        print("- Have you fixed any last minute bugs?")
        print("If you answered yes to all of the above questions,")
        print("then run `invoke release --deploy -vX.YY.ZZ` to:")
        print("- Checkout master")
        print("- Tag the git release with provided vX.YY.ZZ version")
        print("- Push the master branch and tags to repo")
        print("- Deploy to PyPi using Travis")

Prompt:
Add freeze task to invoke

from invoke import run, task

TESTPYPI = "https://testpypi.python.org/pypi"

@task
def lint(ctx):
    """Run flake8 to lint code"""
    run("flake8")

@task(lint)
def test(ctx):
    """Lint, unit test, and check setup.py"""
    cmd = "{} {}".format(
        "nosetests",
        "--with-coverage --cover-erase --cover-package=keysight --cover-html")
    run(cmd)

@task()
def release(ctx, deploy=False, test=False, version=''):
    """Tag release, run Travis-CI, and deploy to PyPI
    """
    if test:
        run("python setup.py check")
        run("python setup.py register sdist upload --dry-run")

    if deploy:
        run("python setup.py check")
        if version:
            run("git checkout master")
            run("git tag -a v{ver} -m 'v{ver}'".format(ver=version))
            run("git push")
            run("git push origin --tags")
    else:
        print("- Have you updated the version?")
        print("- Have you updated CHANGELOG.md?")
        print("- Have you fixed any last minute bugs?")
        print("If you answered yes to all of the above questions,")
        print("then run `invoke release --deploy -vX.YY.ZZ` to:")
        print("- Checkout master")
        print("- Tag the git release with provided vX.YY.ZZ version")
        print("- Push the master branch and tags to repo")
        print("- Deploy to PyPi using Travis")


import os
import sys

def getUserFilesDirectory():
    exe = sys.executable
    if hasattr(sys, 'frozen'):
        folder = os.path.dirname(exe)
    else:
        script = sys.argv[0]
        if exe.endswith("python") or exe.endswith("python.exe"):
            folder = os.path.dirname(os.path.dirname(os.path.dirname(script)))  # from src/mcedit, ../../
        else:
            folder = os.path.dirname(exe)

    dataDir = os.path.join(folder, "MCEdit User Data")

    if not os.path.exists(dataDir):
        os.makedirs(dataDir)
    return dataDir

Response:
import os
import sys

def getUserFilesDirectory():
    exe = sys.executable
    if hasattr(sys, 'frozen'):
        folder = os.path.dirname(exe)
    else:
        script = sys.argv[0]
        if exe.endswith("python") or exe.endswith("python.exe"):
            folder = os.path.dirname(os.path.dirname(os.path.dirname(script)))  # from src/mcedit, ../../
        else:
            folder = os.path.dirname(exe)

    dataDir = os.path.join(folder, "MCEdit User Data")

    if not os.path.exists(dataDir):
        os.makedirs(dataDir)
    return dataDir

Prompt:
Put data folder in ./ instead of ./src/mcedit when running from source (xxx work on this)

import os
import sys

def getUserFilesDirectory():
    exe = sys.executable
    if hasattr(sys, 'frozen'):
        folder = os.path.dirname(exe)
    else:
        script = sys.argv[0]
        if exe.endswith("python") or exe.endswith("python.exe"):
            folder = os.path.dirname(script)
        else:
            folder = os.path.dirname(exe)

    dataDir = os.path.join(folder, "MCEdit User Data")

    if not os.path.exists(dataDir):
        os.makedirs(dataDir)
    return dataDir


# Caesar Cipher

MAX_KEY_SIZE = 26

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        try:
            key = int(input())
        except ValueError:
            continue
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)

        else:
            translated += symbol

    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))

Response:
# Caesar Cipher

MAX_KEY_SIZE = 26

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        try:
            key = int(input())
        except ValueError:
            continue
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)

        else:
            translated += symbol

    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))

Prompt:
Modify the code in the getKey() function so that it gracefully ignores non-integer input.

# Caesar Cipher

MAX_KEY_SIZE = 26

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        key = int(input())
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)

        else:
            translated += symbol

    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))


# -*- coding: utf-8 -*-
import click

from . import __version__

class JungleCLI(click.MultiCommand):

    """Jangle CLI main class"""

    def list_commands(self, ctx):
        """return available modules"""
        return ['ec2', 'elb', 'emr', 'asg']

    def get_command(self, ctx, name):
        """get command"""
        try:
            mod = __import__('jungle.' + name, None, None, ['cli'])
            return mod.cli
        except ImportError:
            pass

cli = JungleCLI(help="aws operation cli (v{0})".format(__version__))

if __name__ == '__main__':
    cli()

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

from . import __version__

class JungleCLI(click.MultiCommand):

    """Jangle CLI main class"""

    def list_commands(self, ctx):
        """return available modules"""
        return ['ec2', 'elb', 'emr', 'asg']

    def get_command(self, ctx, name):
        """get command"""
        try:
            mod = __import__('jungle.' + name, None, None, ['cli'])
            return mod.cli
        except ImportError:
            pass

cli = JungleCLI(help="aws operation cli (v{0})".format(__version__))

if __name__ == '__main__':
    cli()

Prompt:
Fix unintended ImportError for wrong subcommnad

# -*- coding: utf-8 -*-
import click

from . import __version__

class JungleCLI(click.MultiCommand):

    """Jangle CLI main class"""

    def list_commands(self, ctx):
        """return available modules"""
        return ['ec2', 'elb', 'emr', 'asg']

    def get_command(self, ctx, name):
        """get command"""
        mod = __import__('jungle.' + name, None, None, ['cli'])
        return mod.cli

cli = JungleCLI(help="aws operation cli (v{})".format(__version__))

if __name__ == '__main__':
    cli()


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

import six

from .base import Property
from . import vmath

class Vector(Property):
    """class properties.Vector

    Vector property, using properties.vmath.Vector
    """

    _sphinx_prefix = 'properties.spatial'

    @property
    def default(self):
        return getattr(self, '_default', [] if self.repeated else None)

    @default.setter
    def default(self, value):
        self._default = self.validator(None, value).copy()

    def validator(self, instance, value):
        """return a Vector based on input if input is valid"""
        if isinstance(value, vmath.Vector):
            return value
        if isinstance(value, six.string_types):
            if value.upper() == 'X':
                return vmath.Vector(1, 0, 0)
            if value.upper() == 'Y':
                return vmath.Vector(0, 1, 0)
            if value.upper() == 'Z':
                return vmath.Vector(0, 0, 1)
        try:
            return vmath.Vector(value)
        except Exception:
            raise ValueError('{}: must be Vector with '
                             '3 elements'.format(self.name))

    def from_json(self, value):
        return vmath.Vector(*value)

Improve vector property error message

Improve vector property error message

Response:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import six

from .base import Property
from . import vmath

class Vector(Property):
    """class properties.Vector

    Vector property, using properties.vmath.Vector
    """

    _sphinx_prefix = 'properties.spatial'

    @property
    def default(self):
        return getattr(self, '_default', [] if self.repeated else None)

    @default.setter
    def default(self, value):
        self._default = self.validator(None, value).copy()

    def validator(self, instance, value):
        """return a Vector based on input if input is valid"""
        if isinstance(value, vmath.Vector):
            return value
        if isinstance(value, six.string_types):
            if value.upper() == 'X':
                return vmath.Vector(1, 0, 0)
            if value.upper() == 'Y':
                return vmath.Vector(0, 1, 0)
            if value.upper() == 'Z':
                return vmath.Vector(0, 0, 1)
        try:
            return vmath.Vector(value)
        except Exception:
            raise ValueError('{}: must be Vector with '
                             '3 elements'.format(self.name))

    def from_json(self, value):
        return vmath.Vector(*value)

Prompt:
Improve vector property error message

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

import six

from .base import Property
from . import vmath

class Vector(Property):
    """class properties.Vector

    Vector property, using properties.vmath.Vector
    """

    _sphinx_prefix = 'properties.spatial'

    @property
    def default(self):
        return getattr(self, '_default', [] if self.repeated else None)

    @default.setter
    def default(self, value):
        self._default = self.validator(None, value).copy()

    def validator(self, instance, value):
        """return a Vector based on input if input is valid"""
        if isinstance(value, vmath.Vector):
            return value
        if isinstance(value, six.string_types):
            if value.upper() == 'X':
                return vmath.Vector(1, 0, 0)
            if value.upper() == 'Y':
                return vmath.Vector(0, 1, 0)
            if value.upper() == 'Z':
                return vmath.Vector(0, 0, 1)
        try:
            return vmath.Vector(value)
        except Exception:
            raise ValueError('{} must be a Vector'.format(self.name))

    def from_json(self, value):
        return vmath.Vector(*value)


#!/usr/bin/python
import argparse
import socket
import sys

parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-s', '--source', metavar='ADDRESS')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-w', '--wait', metavar='SECONDS', type=int)
parser.add_argument('-z', '--zero', action='store_true')
parser.add_argument('host')
parser.add_argument('port')
args = parser.parse_args()

# Set a souce address for socket connection
source = ('', 0)
if args.source:
    source = (args.source, 0) # port 0 specifies that the OS will choose a port

# exit successfully if the connection succeeds
if args.zero:
    try:
        connection = socket.create_connection((args.host, args.port), args.wait, source)
        if args.verbose:
            print("Connection to {} {} port (tcp) succeeded!".format(args.host, args.port))
        sys.exit(0)
    except socket.error as msg:
        if args.verbose:
            print("Connection to {} {} port (tcp) failed. {}".format(args.host, args.port, msg))
        sys.exit(1)
else:
    print('Not implemented')

Support python 2 and 3

Response:
#!/usr/bin/python
import argparse
import socket
import sys

parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-s', '--source', metavar='ADDRESS')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-w', '--wait', metavar='SECONDS', type=int)
parser.add_argument('-z', '--zero', action='store_true')
parser.add_argument('host')
parser.add_argument('port')
args = parser.parse_args()

# Set a souce address for socket connection
source = ('', 0)
if args.source:
    source = (args.source, 0) # port 0 specifies that the OS will choose a port

# exit successfully if the connection succeeds
if args.zero:
    try:
        connection = socket.create_connection((args.host, args.port), args.wait, source)
        if args.verbose:
            print("Connection to {} {} port (tcp) succeeded!".format(args.host, args.port))
        sys.exit(0)
    except socket.error as msg:
        if args.verbose:
            print("Connection to {} {} port (tcp) failed. {}".format(args.host, args.port, msg))
        sys.exit(1)
else:
    print('Not implemented')

Prompt:
Support python 2 and 3

Add source argument.
Update arguments to use long names from GNU netcat.

#!/usr/bin/python2
import argparse
import socket
import sys

parser = argparse.ArgumentParser(description='Simple netcat in pure python.')
parser.add_argument('-z', '--scan', action='store_true')
parser.add_argument('-w', '--timeout', metavar='SECONDS', type=int)
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('host')
parser.add_argument('port', type=int)
args = parser.parse_args()

if args.scan:
    try:
        connection = socket.create_connection((args.host, args.port), args.timeout)
        if args.verbose:
            print "Connection to {} {} port (tcp) succeeded!".format(args.host, args.port)
        sys.exit(0)
    except socket.error as msg:
        if args.verbose:
            print "Connection to {} {} port (tcp) failed. {}".format(args.host, args.port, msg)
        sys.exit(1)
else:
    print 'Not implemented'


"""
    This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])

class DirectionsRequest(object):

	def __init__(self, **kwargs):
		self.mode = "driving"
		self.origin = kwargs['origin']
		self.destination = kwargs['destination']

	def set_api_key(self, key):
		self.api_key = key
		return self

Build custom route requester class

Build custom route requester class

Response:
"""
    This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])

class DirectionsRequest(object):

	def __init__(self, **kwargs):
		self.mode = "driving"
		self.origin = kwargs['origin']
		self.destination = kwargs['destination']

	def set_api_key(self, key):
		self.api_key = key
		return self

Prompt:
Build custom route requester class

"""
    This class holds all the necessary information required for a proposed route
"""
ACCEPTABLE_MODES = set(["driving", "walking", "bicycling", "transit"])

class DirectionsRequest(object):

	def __init__(self, mode="driving", **kwargs):
		self.mode = mode
		self.origin = kwargs['origin']
		self.destination = kwargs['destination']

	def set_api_key(self, key):
		self.api_key = key
		return self


import sys
import sip

import qtpy

__all__ = [
    'getQVariantValue',
    'wheelAngleDelta',
]

try:
    if qtpy.PYQT5:
        QVARIANT_API = 2
    else:
        QVARIANT_API = sip.getapi('QVariant')
except ValueError:
    QVARIANT_API = 1

if QVARIANT_API == 1:
    def getQVariantValue(variant):
        return variant.toPyObject()
else:
    def getQVariantValue(variant):
        return variant

if qtpy.PYQT5:
    def wheelAngleDelta(wheelEvent):
        return wheelEvent.angleDelta().y()
else:
    def wheelAngleDelta(wheelEvent):
        return wheelEvent.delta()

if qtpy.PYQT5:
    from qtpy.QtCore import QStandardPaths

    def getTemporaryFolder():
        return QStandardPaths.writableLocation(QStandardPaths.CacheLocation)

else:
    from qtpy.QtGui import QDesktopServices

    def getTemporaryFolder():
        return QDesktopServices.storageLocation(QDesktopServices.CacheLocation)

Response:
import sys
import sip

import qtpy

__all__ = [
    'getQVariantValue',
    'wheelAngleDelta',
]

try:
    if qtpy.PYQT5:
        QVARIANT_API = 2
    else:
        QVARIANT_API = sip.getapi('QVariant')
except ValueError:
    QVARIANT_API = 1

if QVARIANT_API == 1:
    def getQVariantValue(variant):
        return variant.toPyObject()
else:
    def getQVariantValue(variant):
        return variant

if qtpy.PYQT5:
    def wheelAngleDelta(wheelEvent):
        return wheelEvent.angleDelta().y()
else:
    def wheelAngleDelta(wheelEvent):
        return wheelEvent.delta()

if qtpy.PYQT5:
    from qtpy.QtCore import QStandardPaths

    def getTemporaryFolder():
        return QStandardPaths.writableLocation(QStandardPaths.CacheLocation)

else:
    from qtpy.QtGui import QDesktopServices

    def getTemporaryFolder():
        return QDesktopServices.storageLocation(QDesktopServices.CacheLocation)

Prompt:
Use Cache location instead of temp folder

import sys
import sip

import qtpy

__all__ = [
    'getQVariantValue',
    'wheelAngleDelta',
]

try:
    if qtpy.PYQT5:
        QVARIANT_API = 2
    else:
        QVARIANT_API = sip.getapi('QVariant')
except ValueError:
    QVARIANT_API = 1

if QVARIANT_API == 1:
    def getQVariantValue(variant):
        return variant.toPyObject()
else:
    def getQVariantValue(variant):
        return variant

if qtpy.PYQT5:
    def wheelAngleDelta(wheelEvent):
        return wheelEvent.angleDelta().y()
else:
    def wheelAngleDelta(wheelEvent):
        return wheelEvent.delta()

if qtpy.PYQT5:
    from qtpy.QtCore import QStandardPaths

    def getTemporaryFolder():
        return QStandardPaths.writableLocation(QStandardPaths.TempLocation)

else:
    from qtpy.QtGui import QDesktopServices

    def getTemporaryFolder():
        return QDesktopServices.storageLocation(QDesktopServices.TempLocation)


# Author: Ashley Anderson III <aganders3@gmail.com>
# Date: 2016-01-25 13:58

import numpy as np
import gpi

class ExternalNode(gpi.NodeAPI):
    """Transform coordinates from BNI conventions to BART conventions.

    INPUT:
        in - a numpy arrary of k-space coordinates in the BNI convention
            i.e. (-0.5, 0.5), dimensions: [readouts, pts, xy(z)]
    OUTPUT:
        out - a numpy array of k-space coordinates in the BART convention
            i.e. (-mtx/2, mtx/2), dimensions: [zyx, pts, readouts]
    WIDGETS:
        mtx - the resulting matrix size (assumed square/cubic)
    """

    # initialize the UI - add widgets and input/output ports
    def initUI(self):
        # Widgets
        self.addWidget('SpinBox', 'mtx', val=128, min=1, max=1024)
        # self.addWidget('DoubleSpinBox', 'bar', val=10, min=0, max=100)
        # self.addWidget('PushButton', 'baz', toggle=True)
        # self.addWidget('ExclusivePushButtons', 'qux',
        #              buttons=['Antoine', 'Colby', 'Trotter', 'Adair'], val=1)

        # IO Ports
        self.addInPort('in', 'NPYarray', ndim=3)
        self.addOutPort('out', 'NPYarray', dtype=np.complex64, ndim=3)

    # validate the data - runs immediately before compute
    # your last chance to show/hide/edit widgets
    # return 1 if the data is not valid - compute will not run
    # return 0 if the data is valid - compute will run
    def validate(self):
        in_data = self.getData('in')

        # TODO: make sure the input data is valid
        # [your code here]

        return 0

    # process the input data, send it to the output port
    # return 1 if the computation failed
    # return 0 if the computation was successful
    def compute(self):
        coords = self.getData('in').copy()
        mtx = self.getVal('mtx')

        # just transpose first to reverse dimensions
        coords = coords.T

        # adjust by the matrix size
        # TODO: account for "true resolution"
        coords *= mtx

        # reverse the xyz dimension
        coords[:,...] = coords[::-1,...]

        # pad the z-dimension with zeros if the trajectory is 2D
        if coords.shape[0] == 2:
            coords = np.pad(coords,
                            ((0,1), (0,0), (0,0)),
                            mode='constant',
                            constant_values=0)

        # if the trajectory is not 3D at this point, something has gone wrong
        if coords.shape[0] != 3:
            self.log.warn("The final dimensions of the input data must be 2 (xy), or 3 (xyz).")
            return 1

        self.setData('out', np.require(coords, dtype=np.complex64))

        return 0

Add node to convert BNI trajectories (e.g. from SpiralCoords) to BART trajectories.

Response:
# Author: Ashley Anderson III <aganders3@gmail.com>
# Date: 2016-01-25 13:58

import numpy as np
import gpi

class ExternalNode(gpi.NodeAPI):
    """Transform coordinates from BNI conventions to BART conventions.

    INPUT:
        in - a numpy arrary of k-space coordinates in the BNI convention
            i.e. (-0.5, 0.5), dimensions: [readouts, pts, xy(z)]
    OUTPUT:
        out - a numpy array of k-space coordinates in the BART convention
            i.e. (-mtx/2, mtx/2), dimensions: [zyx, pts, readouts]
    WIDGETS:
        mtx - the resulting matrix size (assumed square/cubic)
    """

    # initialize the UI - add widgets and input/output ports
    def initUI(self):
        # Widgets
        self.addWidget('SpinBox', 'mtx', val=128, min=1, max=1024)
        # self.addWidget('DoubleSpinBox', 'bar', val=10, min=0, max=100)
        # self.addWidget('PushButton', 'baz', toggle=True)
        # self.addWidget('ExclusivePushButtons', 'qux',
        #              buttons=['Antoine', 'Colby', 'Trotter', 'Adair'], val=1)

        # IO Ports
        self.addInPort('in', 'NPYarray', ndim=3)
        self.addOutPort('out', 'NPYarray', dtype=np.complex64, ndim=3)

    # validate the data - runs immediately before compute
    # your last chance to show/hide/edit widgets
    # return 1 if the data is not valid - compute will not run
    # return 0 if the data is valid - compute will run
    def validate(self):
        in_data = self.getData('in')

        # TODO: make sure the input data is valid
        # [your code here]

        return 0

    # process the input data, send it to the output port
    # return 1 if the computation failed
    # return 0 if the computation was successful
    def compute(self):
        coords = self.getData('in').copy()
        mtx = self.getVal('mtx')

        # just transpose first to reverse dimensions
        coords = coords.T

        # adjust by the matrix size
        # TODO: account for "true resolution"
        coords *= mtx

        # reverse the xyz dimension
        coords[:,...] = coords[::-1,...]

        # pad the z-dimension with zeros if the trajectory is 2D
        if coords.shape[0] == 2:
            coords = np.pad(coords,
                            ((0,1), (0,0), (0,0)),
                            mode='constant',
                            constant_values=0)

        # if the trajectory is not 3D at this point, something has gone wrong
        if coords.shape[0] != 3:
            self.log.warn("The final dimensions of the input data must be 2 (xy), or 3 (xyz).")
            return 1

        self.setData('out', np.require(coords, dtype=np.complex64))

        return 0

Prompt: Add node to convert BNI trajectories (e.g. from SpiralCoords) to BART trajectories.


# coding=utf-8
# flake8: noqa
import sys

if sys.version_info[0] == 3:
    from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
    # noinspection PyUnresolvedReferences
    from urllib.parse import quote
    ifilter = filter
    b_str = bytes
    u_str = str
    iteritems = lambda dic: dic.items()
else:
    from django.utils.encoding import smart_str as smart_b, force_unicode as force_u
    try:
        from django.utils.encoding import smart_text as smart_u
    except:
        # Django 1.3
        from django.utils.encoding import smart_unicode as smart_u
    # noinspection PyUnresolvedReferences
    from urllib2 import quote
    # noinspection PyUnresolvedReferences
    from itertools import ifilter
    b_str = str
    # noinspection PyUnresolvedReferences
    u_str = unicode
    iteritems = lambda dic: dic.iteritems()

try:
    from django.conf.urls import patterns, url, include
except ImportError:
    # noinspection PyUnresolvedReferences
    from django.conf.urls.defaults import patterns, url, include

# Calm down unused import warnings:
assert [smart_b, smart_u, force_u, quote, ifilter]

Fix smart_u for Django 1.3

Fix smart_u for Django 1.3

Response:
# coding=utf-8
# flake8: noqa
import sys

if sys.version_info[0] == 3:
    from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
    # noinspection PyUnresolvedReferences
    from urllib.parse import quote
    ifilter = filter
    b_str = bytes
    u_str = str
    iteritems = lambda dic: dic.items()
else:
    from django.utils.encoding import smart_str as smart_b, force_unicode as force_u
    try:
        from django.utils.encoding import smart_text as smart_u
    except:
        # Django 1.3
        from django.utils.encoding import smart_unicode as smart_u
    # noinspection PyUnresolvedReferences
    from urllib2 import quote
    # noinspection PyUnresolvedReferences
    from itertools import ifilter
    b_str = str
    # noinspection PyUnresolvedReferences
    u_str = unicode
    iteritems = lambda dic: dic.iteritems()

try:
    from django.conf.urls import patterns, url, include
except ImportError:
    # noinspection PyUnresolvedReferences
    from django.conf.urls.defaults import patterns, url, include

# Calm down unused import warnings:
assert [smart_b, smart_u, force_u, quote, ifilter]

Prompt:
Fix smart_u for Django 1.3
# coding=utf-8
# flake8: noqa
import sys

if sys.version_info[0] == 3:
    from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u
    # noinspection PyUnresolvedReferences
    from urllib.parse import quote
    ifilter = filter
    b_str = bytes
    u_str = str
    iteritems = lambda dic: dic.items()
else:
    from django.utils.encoding import smart_str as smart_b, force_unicode as force_u, smart_text as smart_u
    # noinspection PyUnresolvedReferences
    from urllib2 import quote
    # noinspection PyUnresolvedReferences
    from itertools import ifilter
    b_str = str
    # noinspection PyUnresolvedReferences
    u_str = unicode
    iteritems = lambda dic: dic.iteritems()

try:
    from django.conf.urls import patterns, url, include
except ImportError:
    # noinspection PyUnresolvedReferences
    from django.conf.urls.defaults import patterns, url, include

# Calm down unused import warnings:
assert [smart_b, smart_u, force_u, quote, ifilter]


import requests
import json
import time

ndex_base_url = 'http://services.bigmech.ndexbio.org'

def send_request(url_suffix, params):
    res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
    res_json = get_result(res)
    return res_json

def get_result(res):
    status = res.status_code
    if status == 200:
        return res.text
    task_id = res.json()['task_id']
    print 'NDEx task submitted...'
    time_used = 0
    try:
        while status != 200:
            res = requests.get(ndex_base_url + '/task/' + task_id)
            status = res.status_code
            if status != 200:
                time.sleep(5)
                time_used += 5
    except KeyError:
        next
        return None
    print 'NDEx task complete.'
    return res.text

Fix messages in NDEx client

Fix messages in NDEx client

Response:
import requests
import json
import time

ndex_base_url = 'http://services.bigmech.ndexbio.org'

def send_request(url_suffix, params):
    res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
    res_json = get_result(res)
    return res_json

def get_result(res):
    status = res.status_code
    if status == 200:
        return res.text
    task_id = res.json()['task_id']
    print 'NDEx task submitted...'
    time_used = 0
    try:
        while status != 200:
            res = requests.get(ndex_base_url + '/task/' + task_id)
            status = res.status_code
            if status != 200:
                time.sleep(5)
                time_used += 5
    except KeyError:
        next
        return None
    print 'NDEx task complete.'
    return res.text

Prompt:
Fix messages in NDEx client

import requests
import json
import time

ndex_base_url = 'http://services.bigmech.ndexbio.org'

def send_request(url_suffix, params):
    res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params))
    res_json = get_result(res)
    return res_json

def get_result(res):
    status = res.status_code
    if status == 200:
        return res.text
    task_id = res.json()['task_id']
    print 'NDEx services task submitted...' % task_id
    time_used = 0
    try:
        while status != 200:
            res = requests.get(ndex_base_url + '/task/' + task_id)
            status = res.status_code
            if status != 200:
                time.sleep(5)
                time_used += 5
    except KeyError:
        next
        return None
    print 'NDEx services task complete.' % task_id
    return res.text


# -*- coding: utf-8 -*-
import datetime
import dateutil.parser

from creditor.models import RecurringTransaction, TransactionTag
from creditor.tests.fixtures.recurring import MembershipfeeFactory
from django.core.management.base import BaseCommand, CommandError
from members.models import Member

class Command(BaseCommand):
    help = 'Update membership fee RecurringTransactions'

    def add_arguments(self, parser):
        parser.add_argument('oldamount', type=int)
        parser.add_argument('cutoffdate', type=str)
        parser.add_argument('newamount', type=int)

    def handle(self, *args, **options):
        cutoff_dt = dateutil.parser.parse(options['cutoffdate'])
        end_dt = cutoff_dt - datetime.timedelta(minutes=1)
        tgt_tag = TransactionTag.objects.get(label='Membership fee', tmatch='1')
        for rt in RecurringTransaction.objects.filter(
            rtype=RecurringTransaction.YEARLY,
            tag=tgt_tag,
            end=None,
            start__lt=cutoff_dt,
            amount=options['oldamount']
            ):
            rt.end = end_dt
            rt.save()
            newrt = MembershipfeeFactory.create(amount=options['newamount'], start=cutoff_dt, end=None, owner=rt.owner)
            if options['verbosity'] > 0:
                print("Generated RecurringTransaction %s" % newrt)

Add initial version of membership fee updater

Response:
# -*- coding: utf-8 -*-
import datetime
import dateutil.parser

from creditor.models import RecurringTransaction, TransactionTag
from creditor.tests.fixtures.recurring import MembershipfeeFactory
from django.core.management.base import BaseCommand, CommandError
from members.models import Member

class Command(BaseCommand):
    help = 'Update membership fee RecurringTransactions'

    def add_arguments(self, parser):
        parser.add_argument('oldamount', type=int)
        parser.add_argument('cutoffdate', type=str)
        parser.add_argument('newamount', type=int)

    def handle(self, *args, **options):
        cutoff_dt = dateutil.parser.parse(options['cutoffdate'])
        end_dt = cutoff_dt - datetime.timedelta(minutes=1)
        tgt_tag = TransactionTag.objects.get(label='Membership fee', tmatch='1')
        for rt in RecurringTransaction.objects.filter(
            rtype=RecurringTransaction.YEARLY,
            tag=tgt_tag,
            end=None,
            start__lt=cutoff_dt,
            amount=options['oldamount']
            ):
            rt.end = end_dt
            rt.save()
            newrt = MembershipfeeFactory.create(amount=options['newamount'], start=cutoff_dt, end=None, owner=rt.owner)
            if options['verbosity'] > 0:
                print("Generated RecurringTransaction %s" % newrt)

Prompt: Add initial version of membership fee updater


#!/usr/local/bin/python
# Code Fights Circle of Numbers Problem

def circleOfNumbers(n, firstNumber):
    mid = n / 2
    return (mid + firstNumber if firstNumber < mid else firstNumber - mid)

def main():
    tests = [
        [10, 2, 7],
        [10, 7, 2],
        [4, 1, 3],
        [6, 3, 0]
    ]

    for t in tests:
        res = circleOfNumbers(t[0], t[1])
        if t[2] == res:
            print("PASSED: circleOfNumbers({}, {}) returned {}"
                  .format(t[0], t[1], res))
        else:
            print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
                  .format(t[0], t[1], res, t[2]))

if __name__ == '__main__':
    main()

Response:
#!/usr/local/bin/python
# Code Fights Circle of Numbers Problem

def circleOfNumbers(n, firstNumber):
    mid = n / 2
    return (mid + firstNumber if firstNumber < mid else firstNumber - mid)

def main():
    tests = [
        [10, 2, 7],
        [10, 7, 2],
        [4, 1, 3],
        [6, 3, 0]
    ]

    for t in tests:
        res = circleOfNumbers(t[0], t[1])
        if t[2] == res:
            print("PASSED: circleOfNumbers({}, {}) returned {}"
                  .format(t[0], t[1], res))
        else:
            print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
                  .format(t[0], t[1], res, t[2]))

if __name__ == '__main__':
    main()

Prompt:
Solve Code Fights circle of numbers problem

#!/usr/local/bin/python
# Code Fights Circle of Numbers Problem

def circleOfNumbers(n, firstNumber):
    pass

def main():
    tests = [
        ["crazy", "dsbaz"],
        ["z", "a"]
    ]

    for t in tests:
        res = circleOfNumbers(t[0], t[1])
        if t[2] == res:
            print("PASSED: circleOfNumbers({}, {}) returned {}"
                  .format(t[0], t[1], res))
        else:
            print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
                  .format(t[0], t[1], res, t[2]))

if __name__ == '__main__':
    main()


__author__ = 'harsh'

LT = 0
GT = 1

def compare_ele(comp_type, ele1, ele2):
    if comp_type == LT:
        return ele1 < ele2
    elif comp_type == GT:
        return ele1 > ele2
    raise Exception("Compare type Undefined")

def heapsort(lst, comp_type=LT):
    """

    :param lst:
    """
    #heapify
    for start in range((len(lst)-2)/2, -1, -1):
        siftdown_min(lst, start, len(lst)-1)

    for end in range(len(lst)-1, 0, -1):
        lst[end], lst[0] = lst[0], lst[end]
        siftdown_min(lst, 0, end-1)
    return lst

def siftdown(lst, start, end, comp_type):
    root = start
    while True:
        child = root * 2 + 1
        if child > end:
            break
        if child + 1 <= end and compare_ele(lst[child], lst[child + 1], comp_type):
            child += 1
        if compare_ele(lst[root], lst[child], ~comp_type):
            lst[root], lst[child] = lst[child], lst[root]
            root = child
        else:
            break

def siftdown_min(lst, start, end):
    root = start
    while True:
        child = root * 2 + 1
        if child > end:
            break
        if child + 1 <= end and lst[child] > lst[child + 1]:
            child += 1
        if lst[root] > lst[child]:
            lst[root], lst[child] = lst[child], lst[root]
            root = child
        else:
            break

def main():
    arr = [7, 5, 3, 5, 2, 5, 3, 0]
    sorted_lst = heapsort(arr)
    print sorted_lst

main()

Add min and max heap sort

Add min and max heap sort

Response:
__author__ = 'harsh'

LT = 0
GT = 1

def compare_ele(comp_type, ele1, ele2):
    if comp_type == LT:
        return ele1 < ele2
    elif comp_type == GT:
        return ele1 > ele2
    raise Exception("Compare type Undefined")

def heapsort(lst, comp_type=LT):
    """

    :param lst:
    """
    #heapify
    for start in range((len(lst)-2)/2, -1, -1):
        siftdown_min(lst, start, len(lst)-1)

    for end in range(len(lst)-1, 0, -1):
        lst[end], lst[0] = lst[0], lst[end]
        siftdown_min(lst, 0, end-1)
    return lst

def siftdown(lst, start, end, comp_type):
    root = start
    while True:
        child = root * 2 + 1
        if child > end:
            break
        if child + 1 <= end and compare_ele(lst[child], lst[child + 1], comp_type):
            child += 1
        if compare_ele(lst[root], lst[child], ~comp_type):
            lst[root], lst[child] = lst[child], lst[root]
            root = child
        else:
            break

def siftdown_min(lst, start, end):
    root = start
    while True:
        child = root * 2 + 1
        if child > end:
            break
        if child + 1 <= end and lst[child] > lst[child + 1]:
            child += 1
        if lst[root] > lst[child]:
            lst[root], lst[child] = lst[child], lst[root]
            root = child
        else:
            break

def main():
    arr = [7, 5, 3, 5, 2, 5, 3, 0]
    sorted_lst = heapsort(arr)
    print sorted_lst

main()

Prompt: Add min and max heap sort