from twisted.internet import reactor, task
from twisted.internet.defer import Deferred, succeed
from twisted.python.failure import Failure

def test_deferred():
    return task.deferLater(reactor, 0.05, lambda: None)

def test_failure():
    """
    Test that we can check for a failure in an asynchronously-called function.
    """

    # Create one Deferred for the result of the test function.
    deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails)

    # Create another Deferred, which will give the opposite result of
    # deferredThatFails (that is, which will succeed if deferredThatFails fails
    # and vice versa).
    deferredThatSucceeds = Deferred()

    # It's tempting to just write something like:
    #
    #     deferredThatFails.addCallback(deferredThatSucceeds.errback)
    #     deferredThatFails.addErrback (deferredThatSucceeds.callback)
    #
    # Unfortunately, that doesn't work. The problem is that each callbacks or
    # errbacks in a Deferred's callback/errback chain is passed the result of
    # the previous callback/errback, and execution switches between those
    # chains depending on whether that result is a failure or not. So if a
    # callback returns a failure, we switch to the errbacks, and if an errback
    # doesn't return a failure, we switch to the callbacks. If we use the
    # above, then when deferredThatFails fails, the following will happen:
    #
    #   - deferredThatFails' first (and only) errback is called: the function
    #     deferredThatSucceeds.callback. It is passed some sort of failure
    #     object.
    #   - This causes deferredThatSucceeds to fire. We start its callback
    #     chain, passing in that same failure object that was passed to
    #     deferredThatFails' errback chain.
    #   - Since this is a failure object, we switch to the errback chain of
    #     deferredThatSucceeds. I believe this happens before the first
    #     callback is executed, because that callback is probably something
    #     setup by pytest that would cause the test to pass. So it looks like
    #     what's happening is we're bypassing that function entirely, and going
    #     straight to the errback, which causes the test to fail.
    #
    # The solution is to instead create two functions of our own, which call
    # deferredThatSucceeds.callback and .errback but change whether the
    # argument is a failure so that it won't cause us to switch between the
    # callback and errback chains.

    def passTest(arg):
        # arg is a failure object of some sort. Don't pass it to callback
        # because otherwise it'll trigger the errback, which will cause the
        # test to fail.
        deferredThatSucceeds.callback(None)
    def failTest(arg):
        # Manufacture a failure to pass to errback because otherwise twisted
        # will switch to the callback chain, causing the test to pass.
        theFailure = Failure(AssertionError("functionThatFails didn't fail"))
        deferredThatSucceeds.errback(theFailure)

    deferredThatFails.addCallbacks(failTest, passTest)

    return deferredThatSucceeds

def functionThatFails():
    assert False

Response:
from twisted.internet import reactor, task
from twisted.internet.defer import Deferred, succeed
from twisted.python.failure import Failure

def test_deferred():
    return task.deferLater(reactor, 0.05, lambda: None)

def test_failure():
    """
    Test that we can check for a failure in an asynchronously-called function.
    """

    # Create one Deferred for the result of the test function.
    deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails)

    # Create another Deferred, which will give the opposite result of
    # deferredThatFails (that is, which will succeed if deferredThatFails fails
    # and vice versa).
    deferredThatSucceeds = Deferred()

    # It's tempting to just write something like:
    #
    #     deferredThatFails.addCallback(deferredThatSucceeds.errback)
    #     deferredThatFails.addErrback (deferredThatSucceeds.callback)
    #
    # Unfortunately, that doesn't work. The problem is that each callbacks or
    # errbacks in a Deferred's callback/errback chain is passed the result of
    # the previous callback/errback, and execution switches between those
    # chains depending on whether that result is a failure or not. So if a
    # callback returns a failure, we switch to the errbacks, and if an errback
    # doesn't return a failure, we switch to the callbacks. If we use the
    # above, then when deferredThatFails fails, the following will happen:
    #
    #   - deferredThatFails' first (and only) errback is called: the function
    #     deferredThatSucceeds.callback. It is passed some sort of failure
    #     object.
    #   - This causes deferredThatSucceeds to fire. We start its callback
    #     chain, passing in that same failure object that was passed to
    #     deferredThatFails' errback chain.
    #   - Since this is a failure object, we switch to the errback chain of
    #     deferredThatSucceeds. I believe this happens before the first
    #     callback is executed, because that callback is probably something
    #     setup by pytest that would cause the test to pass. So it looks like
    #     what's happening is we're bypassing that function entirely, and going
    #     straight to the errback, which causes the test to fail.
    #
    # The solution is to instead create two functions of our own, which call
    # deferredThatSucceeds.callback and .errback but change whether the
    # argument is a failure so that it won't cause us to switch between the
    # callback and errback chains.

    def passTest(arg):
        # arg is a failure object of some sort. Don't pass it to callback
        # because otherwise it'll trigger the errback, which will cause the
        # test to fail.
        deferredThatSucceeds.callback(None)
    def failTest(arg):
        # Manufacture a failure to pass to errback because otherwise twisted
        # will switch to the callback chain, causing the test to pass.
        theFailure = Failure(AssertionError("functionThatFails didn't fail"))
        deferredThatSucceeds.errback(theFailure)

    deferredThatFails.addCallbacks(failTest, passTest)

    return deferredThatSucceeds

def functionThatFails():
    assert False

Prompt:
Add an example Twisted test that expects failure.

from twisted.internet import reactor, task

def test_deferred():
    return task.deferLater(reactor, 0.05, lambda: None)


"""
Export colormaps from Python / matplotlib to JavaScript.
"""

# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------

import json

from matplotlib.colors import Colormap

import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy as np

# -----------------------------------------------------------------------------
# MAIN CODE
# -----------------------------------------------------------------------------

if __name__ == "__main__":

    # Loop over all matplotlib colormaps and store them in a dictionary. This
    # dictionary contains the colors of the colormap as list of lists (= RGB
    # tuples), and whether or not the colormap should be interpolated (= false
    # for qualitative colormaps).
    colormaps = {}
    for name in dir(cm):

        # Skip reversed colormaps (they don't contain additional information)
        if name.endswith("_r"):
            continue

        # If `cmap` is a colormap, we can store the association information
        if isinstance(cmap := getattr(cm, name), Colormap):

            # Evaluate colormap on the grid to get colors, drop alpha channel
            # information, and round to a reasonable precision
            colors = np.around(cmap(np.linspace(0, 1, cmap.N))[:, 0:3], 4)

            # Store relevant colormap information
            colormaps[cmap.name] = {
                "interpolate": cmap.N >= 256,
                "colors": colors.tolist(),
            }

    # Save colormap data and shortcuts to data.js. The contents of this file
    # need to be copied manually to js-colormaps.js.
    with open("data.js", "w") as json_file:

        # Write the data dictionary to data.js
        json_file.write(f"const data = {json.dumps(colormaps)};")
        json_file.write('\n\n')

        # Write partial function applications to data.js so that we can use
        # a colormap by its name --- e.g., call viridis(0.5) to evaluate the
        # viridis colormap at a value of 0.5.
        for name in colormaps.keys():
            json_file.write(f"const {name} = partial('{name}');\n")
            json_file.write(f"const {name}_r = partial('{name}_r');\n")

    # Final words
    print("\nExported data to data.js, please copy to js-colormaps.js!\n")

Update script to export colormaps

Update script to export colormaps

Response:
"""
Export colormaps from Python / matplotlib to JavaScript.
"""

# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------

import json

from matplotlib.colors import Colormap

import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy as np

# -----------------------------------------------------------------------------
# MAIN CODE
# -----------------------------------------------------------------------------

if __name__ == "__main__":

    # Loop over all matplotlib colormaps and store them in a dictionary. This
    # dictionary contains the colors of the colormap as list of lists (= RGB
    # tuples), and whether or not the colormap should be interpolated (= false
    # for qualitative colormaps).
    colormaps = {}
    for name in dir(cm):

        # Skip reversed colormaps (they don't contain additional information)
        if name.endswith("_r"):
            continue

        # If `cmap` is a colormap, we can store the association information
        if isinstance(cmap := getattr(cm, name), Colormap):

            # Evaluate colormap on the grid to get colors, drop alpha channel
            # information, and round to a reasonable precision
            colors = np.around(cmap(np.linspace(0, 1, cmap.N))[:, 0:3], 4)

            # Store relevant colormap information
            colormaps[cmap.name] = {
                "interpolate": cmap.N >= 256,
                "colors": colors.tolist(),
            }

    # Save colormap data and shortcuts to data.js. The contents of this file
    # need to be copied manually to js-colormaps.js.
    with open("data.js", "w") as json_file:

        # Write the data dictionary to data.js
        json_file.write(f"const data = {json.dumps(colormaps)};")
        json_file.write('\n\n')

        # Write partial function applications to data.js so that we can use
        # a colormap by its name --- e.g., call viridis(0.5) to evaluate the
        # viridis colormap at a value of 0.5.
        for name in colormaps.keys():
            json_file.write(f"const {name} = partial('{name}');\n")
            json_file.write(f"const {name}_r = partial('{name}_r');\n")

    # Final words
    print("\nExported data to data.js, please copy to js-colormaps.js!\n")

Prompt: Update script to export colormaps


from PyQt5.Qsci import QsciScintilla, QsciLexerPython

class TextArea(QsciScintilla):
    def __init__(self):
        super().__init__()

        self.filePath = "Untitled"

        self.pythonLexer = QsciLexerPython(self)
        self.setLexer(self.pythonLexer)
        self.setMargins(1)
        self.setMarginType(0, QsciScintilla.NumberMargin)
        self.setUtf8(True)
        self.setIndentationsUseTabs(False)
        self.setTabWidth(4)
        self.setIndentationGuides(False)
        self.setAutoIndent(True)

    def changeMarginWidth(self):
        numLines = self.lines()

        self.setMarginWidth(0, "00" * len(str(numLines)))

    def updateFont(self, newFont):
        self.lexer().setFont(newFont)

Response:
from PyQt5.Qsci import QsciScintilla, QsciLexerPython

class TextArea(QsciScintilla):
    def __init__(self):
        super().__init__()

        self.filePath = "Untitled"

        self.pythonLexer = QsciLexerPython(self)
        self.setLexer(self.pythonLexer)
        self.setMargins(1)
        self.setMarginType(0, QsciScintilla.NumberMargin)
        self.setUtf8(True)
        self.setIndentationsUseTabs(False)
        self.setTabWidth(4)
        self.setIndentationGuides(False)
        self.setAutoIndent(True)

    def changeMarginWidth(self):
        numLines = self.lines()

        self.setMarginWidth(0, "00" * len(str(numLines)))

    def updateFont(self, newFont):
        self.lexer().setFont(newFont)

Prompt:
Remove debugging print statement from changeMarginWidth

from PyQt5.Qsci import QsciScintilla, QsciLexerPython

class TextArea(QsciScintilla):
    def __init__(self):
        super().__init__()

        self.filePath = "Untitled"

        self.pythonLexer = QsciLexerPython(self)
        self.setLexer(self.pythonLexer)
        self.setMargins(1)
        self.setMarginType(0, QsciScintilla.NumberMargin)
        self.setUtf8(True)
        self.setIndentationsUseTabs(False)
        self.setTabWidth(4)
        self.setIndentationGuides(False)
        self.setAutoIndent(True)

    def changeMarginWidth(self):
        numLines = self.lines()
        print(len(str(numLines)))

        self.setMarginWidth(0, "00" * len(str(numLines)))

    def updateFont(self, newFont):
        self.lexer().setFont(newFont)


from .models import Star
from employees.models import Employee
from rest_framework import serializers

class EmployeeSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ('pk', 'username', 'first_name', 'last_name')

class StarSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory')

class StarSmallSerializer(serializers.ModelSerializer):
    from_user = EmployeeSimpleSerializer()

    class Meta:
        model = Star
        depth = 1
        fields = ('pk', 'date', 'text', 'category', 'from_user')

class StarSwaggerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        fields = ('pk', 'category', 'subcategory', 'text')

class StarEmployeesSubcategoriesSerializer(serializers.Serializer):
    subcategory__pk = serializers.IntegerField()
    subcategory__name = serializers.CharField(max_length=100)
    num_stars = serializers.IntegerField()

class StarTopEmployeeLists(serializers.Serializer):
    to_user__id = serializers.IntegerField()
    to_user__username = serializers.CharField(max_length=100)
    to_user__first_name = serializers.CharField(max_length=100)
    to_user__last_name = serializers.CharField(max_length=100)
    num_stars = serializers.IntegerField()

Response:
from .models import Star
from employees.models import Employee
from rest_framework import serializers

class EmployeeSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ('pk', 'username', 'first_name', 'last_name')

class StarSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory')

class StarSmallSerializer(serializers.ModelSerializer):
    from_user = EmployeeSimpleSerializer()

    class Meta:
        model = Star
        depth = 1
        fields = ('pk', 'date', 'text', 'category', 'from_user')

class StarSwaggerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        fields = ('pk', 'category', 'subcategory', 'text')

class StarEmployeesSubcategoriesSerializer(serializers.Serializer):
    subcategory__pk = serializers.IntegerField()
    subcategory__name = serializers.CharField(max_length=100)
    num_stars = serializers.IntegerField()

class StarTopEmployeeLists(serializers.Serializer):
    to_user__id = serializers.IntegerField()
    to_user__username = serializers.CharField(max_length=100)
    to_user__first_name = serializers.CharField(max_length=100)
    to_user__last_name = serializers.CharField(max_length=100)
    num_stars = serializers.IntegerField()

Prompt:
Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields

from .models import Star
from rest_framework import serializers

class StarSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory')

class StarSmallSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        depth = 1
        fields = ('pk', 'date', 'text', 'category', 'from_user')

class StarSwaggerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Star
        fields = ('pk', 'category', 'subcategory', 'text')

class StarEmployeesSubcategoriesSerializer(serializers.Serializer):
    subcategory__pk = serializers.IntegerField()
    subcategory__name = serializers.CharField(max_length=100)
    num_stars = serializers.IntegerField()

class StarTopEmployeeLists(serializers.Serializer):
    to_user__id = serializers.IntegerField()
    to_user__username = serializers.CharField(max_length=100)
    to_user__first_name = serializers.CharField(max_length=100)
    to_user__last_name = serializers.CharField(max_length=100)
    num_stars = serializers.IntegerField()


import json

import requests

class RPCClient(object):
    def __init__(self, hostname, port):

        self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc'
        self.id = 0

    def _do_rpc(self, method, params=None):

        self.id += 1
        data = {'method': method, 'jsonrpc': '2.0', 'id': self.id}
        if params is not None:
            data['params'] = params

        return requests.request('POST', self.url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

    def set_repeat(self):

        self._do_rpc('core.tracklist.set_repeat', {'value': True})

    def get_current_track_uri(self):

        response = self._do_rpc('core.playback.get_current_tl_track')
        return response.json()['result']['track']['uri']

Response:
import json

import requests

class RPCClient(object):
    def __init__(self, hostname, port):

        self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc'
        self.id = 0

    def _do_rpc(self, method, params=None):

        self.id += 1
        data = {'method': method, 'jsonrpc': '2.0', 'id': self.id}
        if params is not None:
            data['params'] = params

        return requests.request('POST', self.url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

    def set_repeat(self):

        self._do_rpc('core.tracklist.set_repeat', {'value': True})

    def get_current_track_uri(self):

        response = self._do_rpc('core.playback.get_current_tl_track')
        return response.json()['result']['track']['uri']

Prompt:
Fix formatting errors reported by flake8.

import json

import requests

class RPCClient(object):
    def __init__(self, hostname, port):

        self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc'
        self.id = 0

    def _do_rpc(self, method, params=None):

        self.id += 1
        data = { 'method': method, 'jsonrpc': '2.0', 'id': self.id }
        if params is not None:
            data['params'] = params

        return requests.request('POST', self.url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

    def set_repeat(self):

        self._do_rpc('core.tracklist.set_repeat', {'value': True})

    def get_current_track_uri(self):

        response = self._do_rpc('core.playback.get_current_tl_track')
        return response.json()['result']['track']['uri']


import sys

from setuptools import setup, find_packages

import populous

requirements = [
    "click",
    "cached-property",
    "Faker",
    "dateutils",
    "PyYAML",
    "peloton_bloomfilters"
]

if sys.version_info < (3, 2):
    requirements.append('functools32')

setup(
    name="populous",
    version=populous.__version__,
    url=populous.__url__,
    description=populous.__doc__,
    author=populous.__author__,
    license=populous.__license__,
    long_description="TODO",
    packages=find_packages(),
    install_requires=requirements,
    extras_require={
        'tests': ['tox', 'pytest', 'pytest-mock', 'flake8'],
    },
    entry_points={
        'console_scripts': [
            'populous = populous.__main__:cli'
        ]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Topic :: Utilities",
    ],
    keywords='populous populate database',
)

Response:
import sys

from setuptools import setup, find_packages

import populous

requirements = [
    "click",
    "cached-property",
    "Faker",
    "dateutils",
    "PyYAML",
    "peloton_bloomfilters"
]

if sys.version_info < (3, 2):
    requirements.append('functools32')

setup(
    name="populous",
    version=populous.__version__,
    url=populous.__url__,
    description=populous.__doc__,
    author=populous.__author__,
    license=populous.__license__,
    long_description="TODO",
    packages=find_packages(),
    install_requires=requirements,
    extras_require={
        'tests': ['tox', 'pytest', 'pytest-mock', 'flake8'],
    },
    entry_points={
        'console_scripts': [
            'populous = populous.__main__:cli'
        ]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Topic :: Utilities",
    ],
    keywords='populous populate database',
)

Prompt:
Use new 'Faker' package for fake-factory

import sys

from setuptools import setup, find_packages

import populous

requirements = [
    "click",
    "cached-property",
    "fake-factory",
    "dateutils",
    "PyYAML",
    "peloton_bloomfilters"
]

if sys.version_info < (3, 2):
    requirements.append('functools32')

setup(
    name="populous",
    version=populous.__version__,
    url=populous.__url__,
    description=populous.__doc__,
    author=populous.__author__,
    license=populous.__license__,
    long_description="TODO",
    packages=find_packages(),
    install_requires=requirements,
    extras_require={
        'tests': ['tox', 'pytest', 'pytest-mock', 'flake8'],
    },
    entry_points={
        'console_scripts': [
            'populous = populous.__main__:cli'
        ]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Topic :: Utilities",
    ],
    keywords='populous populate database',
)


from django.conf.urls import patterns, include, url
from django.contrib import admin

from accounts import views as views

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'django_inventory.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^django/inventory/$', 'inventory.views.index'),
    url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'),
    url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'),
    url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'),
    url(r'^django/create/inventory/$', 'inventory.views.create'),
    url(r'^django/accounts/users/$', views.UserView.as_view({'get': 'list', 'post': 'create'})),
    url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'),
    url(r'^django/admin/', include(admin.site.urls)),
)

Response:
from django.conf.urls import patterns, include, url
from django.contrib import admin

from accounts import views as views

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'django_inventory.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^django/inventory/$', 'inventory.views.index'),
    url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'),
    url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'),
    url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'),
    url(r'^django/create/inventory/$', 'inventory.views.create'),
    url(r'^django/accounts/users/$', views.UserView.as_view({'get': 'list', 'post': 'create'})),
    url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'),
    url(r'^django/admin/', include(admin.site.urls)),
)

Prompt:
Add get and post functionality to the auth user stuff.

from django.conf.urls import patterns, include, url
from django.contrib import admin

from accounts import views as views

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'django_inventory.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^django/inventory/$', 'inventory.views.index'),
    url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'),
    url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'),
    url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'),
    url(r'^django/create/inventory/$', 'inventory.views.create'),
    url(r'^django/accounts/users/$', views.UserView.as_view()),
    url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'),
    url(r'^django/admin/', include(admin.site.urls)),
)


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

import concurrent.futures

from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever

def create_player_seasons(simulation=False):

    data_retriever = PlayerDataRetriever()

    with session_scope() as session:

        players = session.query(Player).all()[:]

        with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
            future_tasks = {
                threads.submit(
                    data_retriever.retrieve_player_seasons,
                    player.player_id, simulation
                ): player for player in players
            }
            for future in concurrent.futures.as_completed(future_tasks):
                try:
                    plr_seasons = future.result()
                except Exception as e:
                    print("Concurrent task generated an exception: %s" % e)

Update player season retrieval function

Update player season retrieval function

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

import concurrent.futures

from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever

def create_player_seasons(simulation=False):

    data_retriever = PlayerDataRetriever()

    with session_scope() as session:

        players = session.query(Player).all()[:]

        with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
            future_tasks = {
                threads.submit(
                    data_retriever.retrieve_player_seasons,
                    player.player_id, simulation
                ): player for player in players
            }
            for future in concurrent.futures.as_completed(future_tasks):
                try:
                    plr_seasons = future.result()
                except Exception as e:
                    print("Concurrent task generated an exception: %s" % e)

Prompt:
Update player season retrieval function

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

import concurrent.futures

from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever

def create_player_seasons(simulation=False):

    data_retriever = PlayerDataRetriever()

    with session_scope() as session:

        players = session.query(Player).all()[:25]

        with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
            future_tasks = {
                threads.submit(
                    data_retriever.retrieve_player_seasons,
                    player.player_id, simulation
                ): player for player in players
            }
            for future in concurrent.futures.as_completed(future_tasks):
                try:
                    plr_seasons = future.result()
                    print(len(plr_seasons))
                except Exception as e:
                    print("Concurrent task generated an exception: %s" % e)


"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection

class BrocadeNosSSH(CiscoSSHConnection):
    """Support for Brocade NOS/VDX."""
    def enable(self, *args, **kwargs):
        """No enable mode on Brocade VDX."""
        pass

    def exit_enable_mode(self, *args, **kwargs):
        """No enable mode on Brocade VDX."""
        pass

    def special_login_handler(self, delay_factor=1):
        """Adding a delay after login."""
        delay_factor = self.select_delay_factor(delay_factor)
        self.write_channel(self.RETURN)
        time.sleep(1 * delay_factor)

    def save_config(self):
        """Save Config for Brocade VDX."""
        self.send_command('copy running-config startup-config', '[Y/N]')
        self.send_command('y')

Add save_config for brocade VDX

Add save_config for brocade VDX

Response:
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection

class BrocadeNosSSH(CiscoSSHConnection):
    """Support for Brocade NOS/VDX."""
    def enable(self, *args, **kwargs):
        """No enable mode on Brocade VDX."""
        pass

    def exit_enable_mode(self, *args, **kwargs):
        """No enable mode on Brocade VDX."""
        pass

    def special_login_handler(self, delay_factor=1):
        """Adding a delay after login."""
        delay_factor = self.select_delay_factor(delay_factor)
        self.write_channel(self.RETURN)
        time.sleep(1 * delay_factor)

    def save_config(self):
        """Save Config for Brocade VDX."""
        self.send_command('copy running-config startup-config', '[Y/N]')
        self.send_command('y')

Prompt:
Add save_config for brocade VDX

"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection

class BrocadeNosSSH(CiscoSSHConnection):
    """Support for Brocade NOS/VDX."""
    def enable(self, *args, **kwargs):
        """No enable mode on Brocade VDX."""
        pass

    def exit_enable_mode(self, *args, **kwargs):
        """No enable mode on Brocade VDX."""
        pass

    def special_login_handler(self, delay_factor=1):
        """Adding a delay after login."""
        delay_factor = self.select_delay_factor(delay_factor)
        self.write_channel(self.RETURN)
        time.sleep(1 * delay_factor)


from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Article(Base):
    """Model for Articles"""
    __tablename__ = 'articles'

    _id = Column(Integer, primary_key=True)
    source = Column(String)
    title = Column(String)
    url = Column(String)
    author = Column(String)
    date_published = Column(DateTime)

    def __init__(self, article):
        self.source = article.source
        self.title = article.title
        self.url = article.url
        self.author = article.author
        self.date_published = article.date_published

    def __repr__(self):
        return ("<Article(source={0}, title={1}, url={2}, author={3}, "
                "date_published={4})>".format(self.source, self.title,
                self.url, self.author, self.date_published))

engine = create_engine('')
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
db_session = DBSession()

Define repr for Article model

Define repr for Article model

Response:
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Article(Base):
    """Model for Articles"""
    __tablename__ = 'articles'

    _id = Column(Integer, primary_key=True)
    source = Column(String)
    title = Column(String)
    url = Column(String)
    author = Column(String)
    date_published = Column(DateTime)

    def __init__(self, article):
        self.source = article.source
        self.title = article.title
        self.url = article.url
        self.author = article.author
        self.date_published = article.date_published

    def __repr__(self):
        return ("<Article(source={0}, title={1}, url={2}, author={3}, "
                "date_published={4})>".format(self.source, self.title,
                self.url, self.author, self.date_published))

engine = create_engine('')
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
db_session = DBSession()

Prompt:
Define repr for Article model

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class Article(Base):
    """Model for Articles"""
    __tablename__ = 'articles'

    _id = Column(Integer, primary_key=True)
    source = Column(String)
    title = Column(String)
    url = Column(String)
    author = Column(String)
    date_published = Column(DateTime)

    def __init__(self, article):
        self.source = article.source
        self.title = article.title
        self.url = article.url
        self.author = article.author
        self.date_published = article.date_published

    def __repr__(self):
        return "<Article(source={0})>"

engine = create_engine('')
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
db_session = DBSession()


import sys
import argparse
import json
import urllib
import subprocess
from time import sleep

LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log"

def parseLine(line):
    try:
        data = json.loads(line)
        msg = urllib.unquote(data['message'])
        print(msg)
    except:
        pass

def runTail(logFile):
    cmd = ['tail', '-n', '100', '-f', LOG_FILE]
    while (True):
        try:
            proc = subprocess.Popen(cmd, \
                                    stdout=subprocess.PIPE, \
                                    universal_newlines=True)

            for line in iter(proc.stdout.readline, ''):
                yield line

            proc.stdout.close()
            proc.wait()
        except subprocess.CalledProcessError:
            print 'Failed to open the log file, will try again...'
            sleep(2)
            continue

def main():
    p = argparse.ArgumentParser(description='Paradrop log tool')
    p.add_argument('-f',
                   help='Wait for additional data to be appended to the log file when end of file is reached',
                   action='store_true',
                   dest='f')
    args = p.parse_args()

    try:
        if args.f:
            for line in runTail(LOG_FILE):
                parseLine(line)
        else:
            with open(LOG_FILE, "r") as inputFile:
                for line in inputFile:
                    parseLine(line)
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == "__main__":
    main()

Response:
import sys
import argparse
import json
import urllib
import subprocess
from time import sleep

LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log"

def parseLine(line):
    try:
        data = json.loads(line)
        msg = urllib.unquote(data['message'])
        print(msg)
    except:
        pass

def runTail(logFile):
    cmd = ['tail', '-n', '100', '-f', LOG_FILE]
    while (True):
        try:
            proc = subprocess.Popen(cmd, \
                                    stdout=subprocess.PIPE, \
                                    universal_newlines=True)

            for line in iter(proc.stdout.readline, ''):
                yield line

            proc.stdout.close()
            proc.wait()
        except subprocess.CalledProcessError:
            print 'Failed to open the log file, will try again...'
            sleep(2)
            continue

def main():
    p = argparse.ArgumentParser(description='Paradrop log tool')
    p.add_argument('-f',
                   help='Wait for additional data to be appended to the log file when end of file is reached',
                   action='store_true',
                   dest='f')
    args = p.parse_args()

    try:
        if args.f:
            for line in runTail(LOG_FILE):
                parseLine(line)
        else:
            with open(LOG_FILE, "r") as inputFile:
                for line in inputFile:
                    parseLine(line)
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == "__main__":
    main()

Prompt:
Make sure the paradrop.pdlog retry when the log file does not exist

import sys
import argparse
import json
import urllib
import subprocess

LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log"

def parseLine(line):
    try:
        data = json.loads(line)
        msg = urllib.unquote(data['message'])
        print(msg)
    except:
        pass

def runTail(logFile):
    cmd = ['tail', '-n', '100', '-f', LOG_FILE]
    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE, universal_newlines=True)
    for line in iter(proc.stdout.readline, ''):
        yield line

    proc.stdout.close()
    return_code = proc.wait()
    if return_code:
        raise subprocess.CalledProcessError(return_code, cmd)

def main():
    p = argparse.ArgumentParser(description='Paradrop log tool')
    p.add_argument('-f',
                   help='Wait for additional data to be appended to the log file when end of file is reached',
                   action='store_true',
                   dest='f')
    args = p.parse_args()

    try:
        if args.f:
            for line in runTail(LOG_FILE):
                parseLine(line)
        else:
            with open(LOG_FILE, "r") as inputFile:
                for line in inputFile:
                    parseLine(line)
    except KeyboardInterrupt:
        sys.exit(0)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
from .test import *  # noqa

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'test_db',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': 'localhost',
        # Set to empty string for default.
        'PORT': '',
    }
}

Fix wrong db name for travis.

Fix wrong db name for travis.

Response:
# -*- coding: utf-8 -*-
from .test import *  # noqa

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'test_db',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': 'localhost',
        # Set to empty string for default.
        'PORT': '',
    }
}

Prompt:
Fix wrong db name for travis.

# -*- coding: utf-8 -*-
from .test import *  # noqa

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'gis',
        'USER': 'postgres',
        'PASSWORD': '',
        'HOST': 'localhost',
        # Set to empty string for default.
        'PORT': '',
    }
}


SECRET_KEY = 'changeme please'

# TODO -- May I set this to true?
FAS_OPENID_CHECK_CERT = False

#ADMIN_GROUPS = ['sysadmin-web']

FMN_FEDORA_OPENID = 'https://id.fedoraproject.org'

Response:
SECRET_KEY = 'changeme please'

# TODO -- May I set this to true?
FAS_OPENID_CHECK_CERT = False

#ADMIN_GROUPS = ['sysadmin-web']

FMN_FEDORA_OPENID = 'https://id.fedoraproject.org'

Prompt:
Add a configuration key for the URL of the Fedora OpenID server
SECRET_KEY = 'changeme please'

# TODO -- May I set this to true?
FAS_OPENID_CHECK_CERT = False

#ADMIN_GROUPS = ['sysadmin-web']


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

import uuid

from openstack.network.v2 import security_group
from openstack.network.v2 import security_group_rule
from openstack.tests.functional import base

class TestSecurityGroupRule(base.BaseFunctionalTest):

    NAME = uuid.uuid4().hex
    IPV4 = 'IPv4'
    PROTO = 'tcp'
    PORT = 22
    DIR = 'ingress'
    ID = None
    RULE_ID = None

    @classmethod
    def setUpClass(cls):
        super(TestSecurityGroupRule, cls).setUpClass()
        sot = cls.conn.network.create_security_group(name=cls.NAME)
        assert isinstance(sot, security_group.SecurityGroup)
        cls.assertIs(cls.NAME, sot.name)
        cls.ID = sot.id
        rul = cls.conn.network.create_security_group_rule(
            direction=cls.DIR, ethertype=cls.IPV4,
            port_range_max=cls.PORT, port_range_min=cls.PORT,
            protocol=cls.PROTO, security_group_id=cls.ID)
        assert isinstance(rul, security_group_rule.SecurityGroupRule)
        cls.assertIs(cls.ID, rul.security_group_id)
        cls.RULE_ID = rul.id

    @classmethod
    def tearDownClass(cls):
        sot = cls.conn.network.delete_security_group_rule(cls.RULE_ID,
                                                          ignore_missing=False)
        cls.assertIs(None, sot)
        sot = cls.conn.network.delete_security_group(cls.ID,
                                                     ignore_missing=False)
        cls.assertIs(None, sot)

    def test_find(self):
        sot = self.conn.network.find_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)

    def test_get(self):
        sot = self.conn.network.get_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)
        self.assertEqual(self.DIR, sot.direction)
        self.assertEqual(self.PROTO, sot.protocol)
        self.assertEqual(self.PORT, sot.port_range_min)
        self.assertEqual(self.PORT, sot.port_range_max)
        self.assertEqual(self.ID, sot.security_group_id)

    def test_list(self):
        ids = [o.id for o in self.conn.network.security_group_rules()]
        self.assertIn(self.RULE_ID, ids)

Add functional tests for security group rule

Tests:
test_find
test_get
test_list

Change-Id: If54342ec8c57b926a5217d888a43dcd98223bd69

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

import uuid

from openstack.network.v2 import security_group
from openstack.network.v2 import security_group_rule
from openstack.tests.functional import base

class TestSecurityGroupRule(base.BaseFunctionalTest):

    NAME = uuid.uuid4().hex
    IPV4 = 'IPv4'
    PROTO = 'tcp'
    PORT = 22
    DIR = 'ingress'
    ID = None
    RULE_ID = None

    @classmethod
    def setUpClass(cls):
        super(TestSecurityGroupRule, cls).setUpClass()
        sot = cls.conn.network.create_security_group(name=cls.NAME)
        assert isinstance(sot, security_group.SecurityGroup)
        cls.assertIs(cls.NAME, sot.name)
        cls.ID = sot.id
        rul = cls.conn.network.create_security_group_rule(
            direction=cls.DIR, ethertype=cls.IPV4,
            port_range_max=cls.PORT, port_range_min=cls.PORT,
            protocol=cls.PROTO, security_group_id=cls.ID)
        assert isinstance(rul, security_group_rule.SecurityGroupRule)
        cls.assertIs(cls.ID, rul.security_group_id)
        cls.RULE_ID = rul.id

    @classmethod
    def tearDownClass(cls):
        sot = cls.conn.network.delete_security_group_rule(cls.RULE_ID,
                                                          ignore_missing=False)
        cls.assertIs(None, sot)
        sot = cls.conn.network.delete_security_group(cls.ID,
                                                     ignore_missing=False)
        cls.assertIs(None, sot)

    def test_find(self):
        sot = self.conn.network.find_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)

    def test_get(self):
        sot = self.conn.network.get_security_group_rule(self.RULE_ID)
        self.assertEqual(self.RULE_ID, sot.id)
        self.assertEqual(self.DIR, sot.direction)
        self.assertEqual(self.PROTO, sot.protocol)
        self.assertEqual(self.PORT, sot.port_range_min)
        self.assertEqual(self.PORT, sot.port_range_max)
        self.assertEqual(self.ID, sot.security_group_id)

    def test_list(self):
        ids = [o.id for o in self.conn.network.security_group_rules()]
        self.assertIn(self.RULE_ID, ids)

Prompt:
Add functional tests for security group rule

Tests:
test_find
test_get
test_list

Change-Id: If54342ec8c57b926a5217d888a43dcd98223bd69


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

import os
import unittest
from unittest import mock

from yanico import config

class TestUserPath(unittest.TestCase):
    """Test for yanico.config.user_path()."""

    @mock.patch.dict(os.environ, {'HOME': 'spam'})
    def test_path(self):
        """Expect filepath joinning '.yanico.conf' under $HOME."""
        if os.sep == '\\':
            expect = 'spam\\.yanico.conf'
        elif os.sep == '/':
            expect = 'spam/.yanico.conf'
        result = config.user_path()
        self.assertEqual(result, expect)

Add test case for user path

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

import os
import unittest
from unittest import mock

from yanico import config

class TestUserPath(unittest.TestCase):
    """Test for yanico.config.user_path()."""

    @mock.patch.dict(os.environ, {'HOME': 'spam'})
    def test_path(self):
        """Expect filepath joinning '.yanico.conf' under $HOME."""
        if os.sep == '\\':
            expect = 'spam\\.yanico.conf'
        elif os.sep == '/':
            expect = 'spam/.yanico.conf'
        result = config.user_path()
        self.assertEqual(result, expect)

Prompt:
Add test case for user path

Expect filepath joinning '.yanico.conf' under $HOME.

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

import unittest

class TestUserPath(unittest.TestCase):
    """Test for yanico.config.user_path()."""


"""
raven.transport.requests
~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from raven.conf import defaults
from raven.transport.http import HTTPTransport

try:
    import requests
    has_requests = True
except:
    has_requests = False

class RequestsHTTPTransport(HTTPTransport):

    scheme = ['requests+http', 'requests+https']

    def __init__(self, parsed_url, timeout=defaults.TIMEOUT, verify_ssl=True,
                 ca_certs=defaults.CA_BUNDLE):
        if not has_requests:
            raise ImportError('RequestsHTTPTransport requires requests.')

        super(RequestsHTTPTransport, self).__init__(parsed_url,
                                                    timeout=timeout,
                                                    verify_ssl=verify_ssl,
                                                    ca_certs=ca_certs)

        # remove the requests+ from the protocol, as it is not a real protocol
        self._url = self._url.split('+', 1)[-1]

    def send(self, data, headers):
        if self.verify_ssl:
            # If SSL verification is enabled use the provided CA bundle to
            # perform the verification.
            self.verify_ssl = self.ca_certs
        requests.post(self._url, data=data, headers=headers,
                      verify=self.verify_ssl, timeout=self.timeout)

Response:
"""
raven.transport.requests
~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from raven.conf import defaults
from raven.transport.http import HTTPTransport

try:
    import requests
    has_requests = True
except:
    has_requests = False

class RequestsHTTPTransport(HTTPTransport):

    scheme = ['requests+http', 'requests+https']

    def __init__(self, parsed_url, timeout=defaults.TIMEOUT, verify_ssl=True,
                 ca_certs=defaults.CA_BUNDLE):
        if not has_requests:
            raise ImportError('RequestsHTTPTransport requires requests.')

        super(RequestsHTTPTransport, self).__init__(parsed_url,
                                                    timeout=timeout,
                                                    verify_ssl=verify_ssl,
                                                    ca_certs=ca_certs)

        # remove the requests+ from the protocol, as it is not a real protocol
        self._url = self._url.split('+', 1)[-1]

    def send(self, data, headers):
        if self.verify_ssl:
            # If SSL verification is enabled use the provided CA bundle to
            # perform the verification.
            self.verify_ssl = self.ca_certs
        requests.post(self._url, data=data, headers=headers,
                      verify=self.verify_ssl, timeout=self.timeout)

Prompt:
Add support for the verify_ssl, ca_certs and timeout parameters for the request transport.

"""
raven.transport.requests
~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

from raven.transport.http import HTTPTransport

try:
    import requests
    has_requests = True
except:
    has_requests = False

class RequestsHTTPTransport(HTTPTransport):

    scheme = ['requests+http', 'requests+https']

    def __init__(self, parsed_url):
        if not has_requests:
            raise ImportError('RequestsHTTPTransport requires requests.')

        super(RequestsHTTPTransport, self).__init__(parsed_url)

        # remove the requests+ from the protocol, as it is not a real protocol
        self._url = self._url.split('+', 1)[-1]

    def send(self, data, headers):
        requests.post(self._url, data=data, headers=headers)


import requests

class ZabbixError(Exception):
    pass

class Api(object):
    def __init__(self, server='http://localhost/zabbix'):
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
        self.url = server + '/api_jsonrpc.php'
        self.auth = ''
        self.id = 0

    def do_request(self, method, params=None):
        json_payload = {
            'jsonrpc': '2.0',
            'method': method,
            'params': params or {},
            'auth': self.auth,
            'id': self.id,
        }
        self.id += 1
        response = self.session.post(self.url, data = json.dumps(json_payload))

        if response.status_code != 200:
            raise ZabbixError("HTTP ERROR %S: %S" % (response.status, response.reason))
        if response.text == '':
            raise ZabbixError("Received empty response")

        return response.json()

Response:
import requests

class ZabbixError(Exception):
    pass

class Api(object):
    def __init__(self, server='http://localhost/zabbix'):
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
        self.url = server + '/api_jsonrpc.php'
        self.auth = ''
        self.id = 0

    def do_request(self, method, params=None):
        json_payload = {
            'jsonrpc': '2.0',
            'method': method,
            'params': params or {},
            'auth': self.auth,
            'id': self.id,
        }
        self.id += 1
        response = self.session.post(self.url, data = json.dumps(json_payload))

        if response.status_code != 200:
            raise ZabbixError("HTTP ERROR %S: %S" % (response.status, response.reason))
        if response.text == '':
            raise ZabbixError("Received empty response")

        return response.json()

Prompt:
Create do_requestion function to be used by other methods.

import requests

class Api(object):
    def __init__(self, server='http://localhost/zabbix'):
        self.session = requests.Session()
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
        self.url = server + '/api_jsonrpc.php'
        self.auth = ''
        self.id = 0


from pymouse import PyMouse
import time
# This script demonstrates the possibility to use a mouse as an unbound sensor.
# To do that the cursor position is brought back to the middle of the screen at each step, and the distance moved by the mouse are integrated
# This script is intended to be used with a second external mouse.
# This can be achieved using MPX, and inverting the laptop mouse and externa mouse.
# Warning: it may be difficult to stop this script with the mouse, so be sure you are able to do it with keyboard command!
cursor = PyMouse()
x = 0
y = 0
screen_size = cursor.screen_size()
cursor.move(screen_size[0]/2, screen_size[1]/2)
while True:
  p = cursor.position()
  x = x + p[0] - screen_size[0]/2
  y = y + p[1] - screen_size[1]/2
  print x, y, p[0] - s[0]/2, p[1] - s[1]/2
  cursor.move(screen_size[0]/2, screen_size[1]/	2)
  time.sleep(0.01)

Add a test to check if an optical mouse can be used as a course sensor

Response:
from pymouse import PyMouse
import time
# This script demonstrates the possibility to use a mouse as an unbound sensor.
# To do that the cursor position is brought back to the middle of the screen at each step, and the distance moved by the mouse are integrated
# This script is intended to be used with a second external mouse.
# This can be achieved using MPX, and inverting the laptop mouse and externa mouse.
# Warning: it may be difficult to stop this script with the mouse, so be sure you are able to do it with keyboard command!
cursor = PyMouse()
x = 0
y = 0
screen_size = cursor.screen_size()
cursor.move(screen_size[0]/2, screen_size[1]/2)
while True:
  p = cursor.position()
  x = x + p[0] - screen_size[0]/2
  y = y + p[1] - screen_size[1]/2
  print x, y, p[0] - s[0]/2, p[1] - s[1]/2
  cursor.move(screen_size[0]/2, screen_size[1]/	2)
  time.sleep(0.01)

Prompt: Add a test to check if an optical mouse can be used as a course sensor


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r"^$", views.request_view, name="request_site"),
    url(r"^approve$", views.approve_view, name="approve_site"),
    url(r"^admin$", views.approve_admin_view, name="admin_site")
]

Use r-strings for URL regexes

Use r-strings for URL regexes

Response:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r"^$", views.request_view, name="request_site"),
    url(r"^approve$", views.approve_view, name="approve_site"),
    url(r"^admin$", views.approve_admin_view, name="admin_site")
]

Prompt:
Use r-strings for URL regexes

from django.conf.urls import url

from . import views

urlpatterns = [
    url("^$", views.request_view, name="request_site"),
    url("^approve$", views.approve_view, name="approve_site"),
    url("^admin$", views.approve_admin_view, name="admin_site")
]


import binascii
import datetime
import <error descr="No module named 'nonexistent'">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)

Response:
import binascii
import datetime
import <error descr="No module named 'nonexistent'">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)

Prompt:
i18n: Fix test data in an env test on skeleton generation

GitOrigin-RevId: 7be12c5b3b3a333e7e3afebe45fe32770bbdfa81
import binascii
import datetime
import <error descr="No module named nonexistent">nonexistent</error>

print(binascii)
print(datetime)
print(nonexistent)


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

"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

from collections import Counter

from ..shop.models import PaymentState

def count_ordered_articles(article):
    """Count how often the article has been ordered, grouped by the
    order's payment state.
    """
    # Ensure every payment state is present in the resulting dictionary,
    # even if no orders of the corresponding payment state exist for the
    # article.
    counter = Counter({state: 0 for state in PaymentState})

    for order_item in article.order_items:
        counter[order_item.order.payment_state] += order_item.quantity

    return dict(counter)

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

"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

from collections import Counter

from ..shop.models import PaymentState

def count_ordered_articles(article):
    """Count how often the article has been ordered, grouped by the
    order's payment state.
    """
    # Ensure every payment state is present in the resulting dictionary,
    # even if no orders of the corresponding payment state exist for the
    # article.
    counter = Counter({state: 0 for state in PaymentState})

    for order_item in article.order_items:
        counter[order_item.order.payment_state] += order_item.quantity

    return dict(counter)

Prompt:
Make sure every payment state is present in the counter.

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

"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 Jochen Kupperschmidt
"""

from collections import Counter

from ..shop.models import PaymentState

def count_ordered_articles(article):
    """Count how often the article has been ordered, grouped by the
    order's payment state.
    """
    counter = Counter({state: 0 for state in PaymentState})

    for order_item in article.order_items:
        counter[order_item.order.payment_state] += order_item.quantity

    return dict(counter)


from time import time
from itertools import permutations

DIGITS = '1234567890'
DIVS = [2, 3, 5, 7, 11, 13, 17]

def check_divs(pandigital):
    for i in range(1, 8):
        if int(pandigital[i:i+3]) % DIVS[i-1]:
            return False
    return True

def main():
    print sum(
        [int(''.join(p)) for p in permutations(DIGITS) if check_divs(''.join(p))]
    )

if __name__ == '__main__':
    t = time()
    main()
    print 'Time:', time() - t

Add problem 42, pandigital substrings divisible by first primes

Response:
from time import time
from itertools import permutations

DIGITS = '1234567890'
DIVS = [2, 3, 5, 7, 11, 13, 17]

def check_divs(pandigital):
    for i in range(1, 8):
        if int(pandigital[i:i+3]) % DIVS[i-1]:
            return False
    return True

def main():
    print sum(
        [int(''.join(p)) for p in permutations(DIGITS) if check_divs(''.join(p))]
    )

if __name__ == '__main__':
    t = time()
    main()
    print 'Time:', time() - t

Prompt: Add problem 42, pandigital substrings divisible by first primes


"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants

class Version(object):
    """Representation of an IATI Standard Version Number."""

    def __init__(self, version_string):
        """Initialise a Version Number.

        Args:
            version_string (str): A string representation of an IATI version number.

        Raises:
            TypeError: If an attempt to pass something that is not a string is made.
            ValueError: If a provided string is not a version number.

        """
        if not isinstance(version_string, str):
            raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))

        if not version_string in iati.constants.STANDARD_VERSIONS:
            raise ValueError('A valid version number must be specified.')

Response:
"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants

class Version(object):
    """Representation of an IATI Standard Version Number."""

    def __init__(self, version_string):
        """Initialise a Version Number.

        Args:
            version_string (str): A string representation of an IATI version number.

        Raises:
            TypeError: If an attempt to pass something that is not a string is made.
            ValueError: If a provided string is not a version number.

        """
        if not isinstance(version_string, str):
            raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))

        if not version_string in iati.constants.STANDARD_VERSIONS:
            raise ValueError('A valid version number must be specified.')

Prompt:
Document the current state of the Version class.

"""A module containing components that describe the IATI Standard itself (rather than the parts it is made up of)."""
import iati.constants

class Version(object):
    """Representation of an IATI Standard Version Number."""

    def __init__(self, version_string):
        """Initialise a Version Number."""
        if not isinstance(version_string, str):
            raise TypeError('A Version object must be created from a string, not a {0}'.format(type(version_string)))

        if not version_string in iati.constants.STANDARD_VERSIONS:
            raise ValueError('A valid version number must be specified.')


import numpy as np

from sklearn.datasets import make_classification
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge

from sklearn.utils.testing import assert_array_almost_equal

X, y = make_classification(n_classes=2, random_state=0)
Y = np.array([y, y]).T

def test_kernel_ridge():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed():
    K = np.dot(X, X.T)
    pred = KernelRidge(kernel="linear").fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed_sample_weight():
    K = np.dot(X, X.T)
    K2 = K.copy()
    sw = np.ones(X.shape[0]) / float(X.shape[0])
    KernelRidge(kernel="precomputed").fit(K, y, sample_weight=sw)
    assert_array_almost_equal(K, K2)

def test_kernel_ridge_multi_output():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X)
    assert_array_almost_equal(pred, pred2)

    pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    pred3 = np.array([pred3, pred3]).T
    assert_array_almost_equal(pred2, pred3)

TEST Added tests for KernelRidge based on @mblondel's code in lightning

Response:
import numpy as np

from sklearn.datasets import make_classification
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge

from sklearn.utils.testing import assert_array_almost_equal

X, y = make_classification(n_classes=2, random_state=0)
Y = np.array([y, y]).T

def test_kernel_ridge():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed():
    K = np.dot(X, X.T)
    pred = KernelRidge(kernel="linear").fit(X, y).predict(X)
    pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K)
    assert_array_almost_equal(pred, pred2)

def test_kernel_ridge_precomputed_sample_weight():
    K = np.dot(X, X.T)
    K2 = K.copy()
    sw = np.ones(X.shape[0]) / float(X.shape[0])
    KernelRidge(kernel="precomputed").fit(K, y, sample_weight=sw)
    assert_array_almost_equal(K, K2)

def test_kernel_ridge_multi_output():
    pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X)
    pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X)
    assert_array_almost_equal(pred, pred2)

    pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X)
    pred3 = np.array([pred3, pred3]).T
    assert_array_almost_equal(pred2, pred3)

Prompt: TEST Added tests for KernelRidge based on @mblondel's code in lightning


import numpy as np
from numpy.testing import *

def check_float_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(float(x)))

def test_float_types():
    """ Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.float, np.double, np.longdouble] :
        yield check_float_type, t

def check_complex_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(complex(x)))
        assert_equal(str(tp(x*1j)), str(complex(x*1j)))
        assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)))

def test_complex_types():
    """Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.cfloat, np.cdouble, np.clongdouble] :
        yield check_complex_type, t

if __name__ == "__main__":
    run_module_suite()

Response:
import numpy as np
from numpy.testing import *

def check_float_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(float(x)))

def test_float_types():
    """ Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.float, np.double, np.longdouble] :
        yield check_float_type, t

def check_complex_type(tp):
    for x in [0, 1,-1, 1e10, 1e20] :
        assert_equal(str(tp(x)), str(complex(x)))
        assert_equal(str(tp(x*1j)), str(complex(x*1j)))
        assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)))

def test_complex_types():
    """Check formatting.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.cfloat, np.cdouble, np.clongdouble] :
        yield check_complex_type, t

if __name__ == "__main__":
    run_module_suite()

Prompt:
Use parametric tests for format tests so that it is clearer which type is failing.

import numpy as np
from numpy.testing import *

class TestPrint(TestCase):

    def test_float_types(self) :
        """ Check formatting.

            This is only for the str function, and only for simple types.
            The precision of np.float and np.longdouble aren't the same as the
            python float precision.

        """
        for t in [np.float, np.double, np.longdouble] :
            for x in [0, 1,-1, 1e10, 1e20] :
                assert_equal(str(t(x)), str(float(x)))

    def test_complex_types(self) :
        """Check formatting.

            This is only for the str function, and only for simple types.
            The precision of np.float and np.longdouble aren't the same as the
            python float precision.

        """
        for t in [np.cfloat, np.cdouble, np.clongdouble] :
            for x in [0, 1,-1, 1e10, 1e20] :
                assert_equal(str(t(x)), str(complex(x)))
                assert_equal(str(t(x*1j)), str(complex(x*1j)))
                assert_equal(str(t(x + x*1j)), str(complex(x + x*1j)))

if __name__ == "__main__":
    run_module_suite()


#!/usr/bin/env python

'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''

class Item(object):
    def __init__(self, value, next_item=None):
        self.value = value
        self.next_item = next_item

    def __str__(self):
        return self.value

class Stack(object):
    def __init__(self, top=None):
        self.top = top

    def push(self, value):
        item = Item(value)
        item.next_item = self.top
        self.top = item

    def pop(self):
        try:
            pop_item = self.top
            self.top = pop_item.next_item
            return pop_item.value
        except AttributeError:
            raise ValueError('No items in stack')

    def peek(self):
        return self.top.value

Add pop method on Stack class

Add pop method on Stack class

Response:
#!/usr/bin/env python

'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''

class Item(object):
    def __init__(self, value, next_item=None):
        self.value = value
        self.next_item = next_item

    def __str__(self):
        return self.value

class Stack(object):
    def __init__(self, top=None):
        self.top = top

    def push(self, value):
        item = Item(value)
        item.next_item = self.top
        self.top = item

    def pop(self):
        try:
            pop_item = self.top
            self.top = pop_item.next_item
            return pop_item.value
        except AttributeError:
            raise ValueError('No items in stack')

    def peek(self):
        return self.top.value

Prompt:
Add pop method on Stack class

#!/usr/bin/env python

'''Implementation of a simple stack data structure.
The stack has push, pop, and peek methods. Items in the stack have a value,
and next_item attribute. The stack has a top attribute.
'''

class Item(object):
    def __init__(self, value, next_item=None):
        self.value = value
        self.next_item = next_item

    def __str__(self):
        return self.value

class Stack(object):
    def __init__(self, top=None):
        self.top = top

    def push(self, value):
        item = Item(value)
        item.next_item = self.top
        self.top = item

    def pop(self):
        pass

    def peek(self):
        return self.top.value


import unittest

from githubtrending import trending as githubtrending

from . import data

class TestGithubTrending(unittest.TestCase):

    def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = githubtrending.read_page(url)
            self.assertEqual(status_code, expected_status_code)

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

Add test case for read_page

Test: Add test case for read_page

Response:
import unittest

from githubtrending import trending as githubtrending

from . import data

class TestGithubTrending(unittest.TestCase):

    def test_read_page(self):
        for each in data.READ_PAGE_DATA:
            url = each.get('url')
            expected_status_code = each.get('status_code')
            response, status_code = githubtrending.read_page(url)
            self.assertEqual(status_code, expected_status_code)

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

Prompt: Test: Add test case for read_page


#!python
# coding=utf-8

def isstr(s):
    try:
        return isinstance(s, basestring)
    except NameError:
        return isinstance(s, str)

def cf_safe_name(name):
    import re
    if isstr(name):
        if re.match('^[0-9_]', name):
            # Add a letter to the front
            name = "v_{}".format(name)
        return re.sub(r'[^_a-zA-Z0-9]', "_", name)

Fix cf_safe_name for python 2.7

Fix cf_safe_name for python 2.7

Response:
#!python
# coding=utf-8

def isstr(s):
    try:
        return isinstance(s, basestring)
    except NameError:
        return isinstance(s, str)

def cf_safe_name(name):
    import re
    if isstr(name):
        if re.match('^[0-9_]', name):
            # Add a letter to the front
            name = "v_{}".format(name)
        return re.sub(r'[^_a-zA-Z0-9]', "_", name)

Prompt:
Fix cf_safe_name for python 2.7

#!python
# coding=utf-8

def cf_safe_name(name):
    import re
    if isinstance(name, str):
        if re.match('^[0-9_]', name):
            # Add a letter to the front
            name = "v_{}".format(name)
        return re.sub(r'[^_a-zA-Z0-9]', "_", name)


"""Configuration."""

import logging
import os
import re

from google.appengine.ext.appstats import recording

logging.info('Loading %s from %s', __name__, __file__)

# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
  app = recording.appstats_wsgi_middleware(app)
  return app

# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'

# Custom Appstats path normalization.
def appstats_normalize_path(path):
    if path.startswith('/user/'):
        return '/user/X'
    if path.startswith('/user_popup/'):
        return '/user_popup/X'
    if path.startswith('/rss/'):
        i = path.find('/', 5)
        if i > 0:
            return path[:i] + '/X'
    return re.sub(r'\d+', 'X', path)

# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')

# Fail early if we can't import Django 1.x.  Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
             django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"

Switch Django version from 1.0 to 1.1

Switch Django version from 1.0 to 1.1

Response:
"""Configuration."""

import logging
import os
import re

from google.appengine.ext.appstats import recording

logging.info('Loading %s from %s', __name__, __file__)

# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
  app = recording.appstats_wsgi_middleware(app)
  return app

# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'

# Custom Appstats path normalization.
def appstats_normalize_path(path):
    if path.startswith('/user/'):
        return '/user/X'
    if path.startswith('/user_popup/'):
        return '/user_popup/X'
    if path.startswith('/rss/'):
        i = path.find('/', 5)
        if i > 0:
            return path[:i] + '/X'
    return re.sub(r'\d+', 'X', path)

# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')

# Fail early if we can't import Django 1.x.  Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
             django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"

Prompt:
Switch Django version from 1.0 to 1.1

"""Configuration."""

import logging
import os
import re

from google.appengine.ext.appstats import recording

logging.info('Loading %s from %s', __name__, __file__)

# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
  app = recording.appstats_wsgi_middleware(app)
  return app

# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'

# Custom Appstats path normalization.
def appstats_normalize_path(path):
    if path.startswith('/user/'):
        return '/user/X'
    if path.startswith('/user_popup/'):
        return '/user_popup/X'
    if path.startswith('/rss/'):
        i = path.find('/', 5)
        if i > 0:
            return path[:i] + '/X'
    return re.sub(r'\d+', 'X', path)

# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')

# Fail early if we can't import Django 1.x.  Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
             django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"


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

import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog

def uibei(order, energy_lo, temp, chem_potential):
    """
    Upper incomplete Bose-Einstein integral.
    """
    kT = temp * constants.k_B

    reduced_energy_lo = energy_lo / kT
    reduced_chem_potential = chem_potential / kT

    prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \
        (constants.h**3 * constants.c**2)

    summand = 0

    for indx in range(1, order + 2):
        expt = (reduced_chem_potential - reduced_energy_lo).decompose()
        term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1)
        summand += term

    return summand

Add first draft of upper incomplete Bose-Einstein integral

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

import numpy as np
from astropy import constants
from astropy import units
from sympy.mpmath import polylog

def uibei(order, energy_lo, temp, chem_potential):
    """
    Upper incomplete Bose-Einstein integral.
    """
    kT = temp * constants.k_B

    reduced_energy_lo = energy_lo / kT
    reduced_chem_potential = chem_potential / kT

    prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \
        (constants.h**3 * constants.c**2)

    summand = 0

    for indx in range(1, order + 2):
        expt = (reduced_chem_potential - reduced_energy_lo).decompose()
        term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1)
        summand += term

    return summand

Prompt: Add first draft of upper incomplete Bose-Einstein integral


try:
    import wpilib
except ImportError:
    from pyfrc import wpilib

import timed_shoot

class HotShootAutonomous(timed_shoot.TimedShootAutonomous):
    '''
        Based on the TimedShootAutonomous mode. Modified to allow
        shooting based on whether the hot goal is enabled or not.
    '''

    DEFAULT = False
    MODE_NAME = "Hot Aim shoot"

    def __init__(self, components):
        super().__init__(components)

        wpilib.SmartDashboard.PutNumber('DriveStrafeSpeed', 0.5)
        wpilib.SmartDashboard.PutBoolean('IsHotLeft', False)
        wpilib.SmartDashboard.PutBoolean('IsHotRight', False)

    def on_enable(self):
        '''these are called when autonomous starts'''

        super().on_enable()

        self.drive_strafe_speed = wpilib.SmartDashboard.GetNumber('DriveStrafeSpeed')

        print("-> Drive strafe:", self.drive_strafe_speed)

        self.decided = False
        self.start_time = None

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, time_elapsed):
        '''The actual autonomous program'''

        # decide if it's hot or not
        if not self.decided:
            self.hotLeft = wpilib.SmartDashboard.GetBoolean("IsHotLeft")
            self.hotRight = wpilib.SmartDashboard.GetBoolean("IsHotRight")

            if (self.hotLeft or self.hotRight) and not (self.hotLeft and self.hotRight):
                self.decided = True

                if self.hotLeft:
                    self.drive_strafe_speed *= -1

            elif time_elapsed > 6:
                # at 6 seconds, give up and shoot anyways
                self.decided = True

        # always keep the arm down
        self.intake.armDown()

        # wait a split second for the arm to come down, then
        # keep bringing the catapult down so we're ready to go
        if time_elapsed > 0.3:
            self.catapult.pulldown()

        # wait some period before we start driving
        if time_elapsed < self.drive_wait:
            pass

        else:

            if self.decided:

                # only set this once, so we can calculate time from this
                # point on
                if self.start_time is None:
                    self.start_time = time_elapsed

                time_elapsed = time_elapsed - self.start_time

                if time_elapsed < self.drive_time:
                    # Drive slowly forward for N seconds
                    self.drive.move(self.drive_strafe_speed, self.drive_speed, 0)

                elif time_elapsed < self.drive_time + 1.0:
                    # Finally, fire and keep firing for 1 seconds
                    self.catapult.launchNoSensor()

Add an autonomous mode to strafe and shoot. Doesn't work

Response:
try:
    import wpilib
except ImportError:
    from pyfrc import wpilib

import timed_shoot

class HotShootAutonomous(timed_shoot.TimedShootAutonomous):
    '''
        Based on the TimedShootAutonomous mode. Modified to allow
        shooting based on whether the hot goal is enabled or not.
    '''

    DEFAULT = False
    MODE_NAME = "Hot Aim shoot"

    def __init__(self, components):
        super().__init__(components)

        wpilib.SmartDashboard.PutNumber('DriveStrafeSpeed', 0.5)
        wpilib.SmartDashboard.PutBoolean('IsHotLeft', False)
        wpilib.SmartDashboard.PutBoolean('IsHotRight', False)

    def on_enable(self):
        '''these are called when autonomous starts'''

        super().on_enable()

        self.drive_strafe_speed = wpilib.SmartDashboard.GetNumber('DriveStrafeSpeed')

        print("-> Drive strafe:", self.drive_strafe_speed)

        self.decided = False
        self.start_time = None

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, time_elapsed):
        '''The actual autonomous program'''

        # decide if it's hot or not
        if not self.decided:
            self.hotLeft = wpilib.SmartDashboard.GetBoolean("IsHotLeft")
            self.hotRight = wpilib.SmartDashboard.GetBoolean("IsHotRight")

            if (self.hotLeft or self.hotRight) and not (self.hotLeft and self.hotRight):
                self.decided = True

                if self.hotLeft:
                    self.drive_strafe_speed *= -1

            elif time_elapsed > 6:
                # at 6 seconds, give up and shoot anyways
                self.decided = True

        # always keep the arm down
        self.intake.armDown()

        # wait a split second for the arm to come down, then
        # keep bringing the catapult down so we're ready to go
        if time_elapsed > 0.3:
            self.catapult.pulldown()

        # wait some period before we start driving
        if time_elapsed < self.drive_wait:
            pass

        else:

            if self.decided:

                # only set this once, so we can calculate time from this
                # point on
                if self.start_time is None:
                    self.start_time = time_elapsed

                time_elapsed = time_elapsed - self.start_time

                if time_elapsed < self.drive_time:
                    # Drive slowly forward for N seconds
                    self.drive.move(self.drive_strafe_speed, self.drive_speed, 0)

                elif time_elapsed < self.drive_time + 1.0:
                    # Finally, fire and keep firing for 1 seconds
                    self.catapult.launchNoSensor()

Prompt: Add an autonomous mode to strafe and shoot. Doesn't work


import bz2
import urllib.request
import os
import os.path

DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024

def download_and_unbzip(url, dest_file):
    source = urllib.request.urlopen(url)
    decompressor = bz2.BZ2Decompressor()
    with open(dest_file, 'wb') as dest_file:
        while True:
            data = source.read(CHUNK)
            if not data:
                break
            dest_file.write(decompressor.decompress(data))

if __name__ == '__main__':
    if not os.path.isdir(DATA_DIR):
        os.mkdir(DATA_DIR)
    download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)

Create dir before data downloading

Create dir before data downloading

Response:
import bz2
import urllib.request
import os
import os.path

DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024

def download_and_unbzip(url, dest_file):
    source = urllib.request.urlopen(url)
    decompressor = bz2.BZ2Decompressor()
    with open(dest_file, 'wb') as dest_file:
        while True:
            data = source.read(CHUNK)
            if not data:
                break
            dest_file.write(decompressor.decompress(data))

if __name__ == '__main__':
    if not os.path.isdir(DATA_DIR):
        os.mkdir(DATA_DIR)
    download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)

Prompt:
Create dir before data downloading

import bz2
import urllib.request

OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024

def download_and_unbzip(url, dest_file):
    source = urllib.request.urlopen(url)
    decompressor = bz2.BZ2Decompressor()
    with open(dest_file, 'wb') as dest_file:
        while True:
            data = source.read(CHUNK)
            if not data:
                break
            dest_file.write(decompressor.decompress(data))

if __name__ == '__main__':
    download_and_unbzip(OPEN_CORPORA_URL, OPEN_CORPORA_DEST_FILE)


from djet import assertions, restframework
from rest_framework import status
import djoser.constants
import djoser.utils
import djoser.views

class RootViewTest(restframework.APIViewTestCase,
                   assertions.StatusCodeAssertionsMixin):
    view_class = djoser.views.RootView

    def test_get_should_return_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, response.data)

    def test_all_urlpattern_names_are_in_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        for urlpattern_name in urlpattern_names:
            self.assertIn(urlpattern_name, response.data)

    def test_non_existent_urlpattern_results_in_empty_string(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)

        urlpattern_names = ['non-existent-urlpattern']
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, {urlpattern_names[0]: ''})

Add test for non existent url pattern

Add test for non existent url pattern

Response:
from djet import assertions, restframework
from rest_framework import status
import djoser.constants
import djoser.utils
import djoser.views

class RootViewTest(restframework.APIViewTestCase,
                   assertions.StatusCodeAssertionsMixin):
    view_class = djoser.views.RootView

    def test_get_should_return_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, response.data)

    def test_all_urlpattern_names_are_in_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        for urlpattern_name in urlpattern_names:
            self.assertIn(urlpattern_name, response.data)

    def test_non_existent_urlpattern_results_in_empty_string(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)

        urlpattern_names = ['non-existent-urlpattern']
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, {urlpattern_names[0]: ''})

Prompt:
Add test for non existent url pattern

from djet import assertions, restframework
from rest_framework import status
import djoser.constants
import djoser.utils
import djoser.views

class RootViewTest(restframework.APIViewTestCase,
                   assertions.StatusCodeAssertionsMixin):
    view_class = djoser.views.RootView

    def test_get_should_return_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        urls_map = view_object.get_urls_map(request, urlpattern_names, None)
        self.assertEquals(urls_map, response.data)

    def test_all_urlpattern_names_are_in_urls_map(self):
        request = self.factory.get()
        view_object = self.create_view_object(request)
        response = view_object.dispatch(request)

        self.assert_status_equal(response, status.HTTP_200_OK)
        urlpattern_names = view_object.aggregate_djoser_urlpattern_names()
        for urlpattern_name in urlpattern_names:
            self.assertIn(urlpattern_name, response.data)


# Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})

    @api.model
    def create(self, vals):
        if vals.get('warehouse_id', False):
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', vals['warehouse_id'])], limit=1)
            if picking_type_id:
                vals.update({'picking_type_id': picking_type_id.id})
        return super().create(vals)

Set Picking Type in Create

Response:
# Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})

    @api.model
    def create(self, vals):
        if vals.get('warehouse_id', False):
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', vals['warehouse_id'])], limit=1)
            if picking_type_id:
                vals.update({'picking_type_id': picking_type_id.id})
        return super().create(vals)

Prompt:
[IMP] Set Picking Type in Create

[IMP] Flake8

# Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).

from odoo import api, fields, models

class StockRequestOrder(models.Model):
    _inherit = 'stock.request.order'

    @api.model
    def _get_default_picking_type(self):
        return self.env['stock.picking.type'].search([
            ('code', '=', 'stock_request_order'),
            ('warehouse_id.company_id', 'in',
             [self.env.context.get('company_id', self.env.user.company_id.id),
              False])],
            limit=1).id

    picking_type_id = fields.Many2one(
        'stock.picking.type', 'Operation Type',
        default=_get_default_picking_type, required=True)

    @api.onchange('warehouse_id')
    def onchange_warehouse_picking_id(self):
        if self.warehouse_id:
            picking_type_id = self.env['stock.picking.type'].\
                search([('code', '=', 'stock_request_order'),
                        ('warehouse_id', '=', self.warehouse_id.id)], limit=1)
            if picking_type_id:
                    self._origin.write({'picking_type_id': picking_type_id.id})


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

from feincms.models import Page

def handler(request, path):
    page = Page.objects.page_for_path_or_404(path)

    return render_to_response(page.template.path, {
        'page': page,
        }, context_instance=RequestContext(request))

Add basic cms page handler

Add basic cms page handler

Response:
from django.shortcuts import render_to_response
from django.template import RequestContext

from feincms.models import Page

def handler(request, path):
    page = Page.objects.page_for_path_or_404(path)

    return render_to_response(page.template.path, {
        'page': page,
        }, context_instance=RequestContext(request))

Prompt: Add basic cms page handler