from MaxCliquesPercolation import MaxCliquesPercolationWeighted
from pygraphc.optimization.SimulatedAnnealing import SimulatedAnnealing
from numpy import linspace

class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
    def __init__(self, graph, edges_weight, nodes_id, k, threshold, tmin, tmax, alpha, energy_type, max_iteration):
        super(MaxCliquesPercolationSA, self).__init__(graph, edges_weight, nodes_id, k, threshold)
        self.Tmin = tmin
        self.Tmax = tmax
        self.alpha = alpha
        self.energy_type = energy_type
        self.max_iteration = max_iteration

    def get_maxcliques_percolation_sa(self):
        # run max_clique
        max_cliques = self._find_maxcliques()

        # get maximal node for all maximal cliques to generate k
        max_node = 0
        for max_clique in max_cliques:
            current_len = len(max_clique)
            if max_node < current_len:
                max_node = current_len

        parameters = {
            'k': list(xrange(2, max_node)),
            'I': linspace(0.1, 0.9, 9)
        }

        sa = SimulatedAnnealing(self.Tmin, self.Tmax, self.alpha, parameters, self.energy_type, self.max_iteration)
        initial_parameter = sa.get_parameter()

        # get maximal clique percolation

Add constructor and get method with SA

Add constructor and get method with SA

Response:
from MaxCliquesPercolation import MaxCliquesPercolationWeighted
from pygraphc.optimization.SimulatedAnnealing import SimulatedAnnealing
from numpy import linspace

class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
    def __init__(self, graph, edges_weight, nodes_id, k, threshold, tmin, tmax, alpha, energy_type, max_iteration):
        super(MaxCliquesPercolationSA, self).__init__(graph, edges_weight, nodes_id, k, threshold)
        self.Tmin = tmin
        self.Tmax = tmax
        self.alpha = alpha
        self.energy_type = energy_type
        self.max_iteration = max_iteration

    def get_maxcliques_percolation_sa(self):
        # run max_clique
        max_cliques = self._find_maxcliques()

        # get maximal node for all maximal cliques to generate k
        max_node = 0
        for max_clique in max_cliques:
            current_len = len(max_clique)
            if max_node < current_len:
                max_node = current_len

        parameters = {
            'k': list(xrange(2, max_node)),
            'I': linspace(0.1, 0.9, 9)
        }

        sa = SimulatedAnnealing(self.Tmin, self.Tmax, self.alpha, parameters, self.energy_type, self.max_iteration)
        initial_parameter = sa.get_parameter()

        # get maximal clique percolation

Prompt:
Add constructor and get method with SA

from MaxCliquesPercolation import MaxCliquesPercolationWeighted

class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
    def __init__(self, graph, edges_weight, nodes_id, k, threshold):
        super(MaxCliquesPercolationSA, self).__init__(graph, edges_weight, nodes_id, k, threshold)

    def get_maxcliques_percolation_sa(self):
        pass


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

from django import template
from Instanssi.ext_blog.models import BlogEntry

register = template.Library()

@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
    entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
    return {'entries': entries}

@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
    return {'event_id': event_id}

@register.simple_tag
def blog_rss_url(event_id):
    return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'

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

from django import template
from Instanssi.ext_blog.models import BlogEntry

register = template.Library()

@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
    entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
    return {'entries': entries}

@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
    return {'event_id': event_id}

@register.simple_tag
def blog_rss_url(event_id):
    return 'http://instanssi.org/blog/'+str(event_id)+'/rss/'

Prompt:
ext_blog: Tag for getting a valid RSS feed url for event.

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

from django import template
from Instanssi.ext_blog.models import BlogEntry

register = template.Library()

@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
    entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
    return {'entries': entries}

@register.inclusion_tag('ext_blog/blog_rss_tag.html')
def render_blog_rss_tag(event_id):
    return {'event_id': event_id}


from setuptools import setup

setup(
    name='kubespawner',
    version='0.1',
    install_requires=[
        'requests-futures>=0.9.7',
        'jupyterhub>=0.4.0',
    ],
    description='JupyterHub Spawner targetting Kubernetes',
    url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
    author='Yuvi Panda',
    author_email='yuvipanda@riseup.net',
    license='BSD',
    packages=['kubespawner'],
)

Add explit dependencies to packaging

Add explit dependencies to packaging

Response:
from setuptools import setup

setup(
    name='kubespawner',
    version='0.1',
    install_requires=[
        'requests-futures>=0.9.7',
        'jupyterhub>=0.4.0',
    ],
    description='JupyterHub Spawner targetting Kubernetes',
    url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
    author='Yuvi Panda',
    author_email='yuvipanda@riseup.net',
    license='BSD',
    packages=['kubespawner'],
)

Prompt:
Add explit dependencies to packaging

from setuptools import setup

setup(
    name='kubespawner',
    version='0.1',
    description='JupyterHub Spawner targetting Kubernetes',
    url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
    author='Yuvi Panda',
    author_email='yuvipanda@riseup.net',
    license='BSD',
    packages=['kubespawner'],
)


from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField

class Image(models.Model):
    """
    The Image model holds an image and related data.

    The Created and Modified time fields are created automatically by
    Django when the object is created or modified, and can not be altered.

    This model uses Django's built-ins for holding the image location and
    data in the database, as well as for keeping created and modified
    timestamps.
    """

    image = models.ImageField(upload_to='images/')
    caption = models.TextField()

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Vendor(models.Model):
    """
    The Vendor model holds the information for a vendor, including the
    geographic location as a pair of latitudinal/logitudinal coordinates,
    a street address, and an optional text description of their location
    (in case the address/coordinates are of, say, a dock instead of a shop).
    """
    pass

Response:
from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField

class Image(models.Model):
    """
    The Image model holds an image and related data.

    The Created and Modified time fields are created automatically by
    Django when the object is created or modified, and can not be altered.

    This model uses Django's built-ins for holding the image location and
    data in the database, as well as for keeping created and modified
    timestamps.
    """

    image = models.ImageField(upload_to='images/')
    caption = models.TextField()

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Vendor(models.Model):
    """
    The Vendor model holds the information for a vendor, including the
    geographic location as a pair of latitudinal/logitudinal coordinates,
    a street address, and an optional text description of their location
    (in case the address/coordinates are of, say, a dock instead of a shop).
    """
    pass

Prompt:
Change image upload directory to images/

from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField

class Image(models.Model):
    """
    The Image model holds an image and related data.

    The Created and Modified time fields are created automatically by
    Django when the object is created or modified, and can not be altered.

    This model uses Django's built-ins for holding the image location and
    data in the database, as well as for keeping created and modified
    timestamps.
    """

    image = models.ImageField(upload_to='/')
    caption = models.TextField()

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Vendor(models.Model):
    """
    The Vendor model holds the information for a vendor, including the
    geographic location as a pair of latitudinal/logitudinal coordinates,
    a street address, and an optional text description of their location
    (in case the address/coordinates are of, say, a dock instead of a shop).
    """
    pass


from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements

class UserhostCommand(ModuleData, Command):
	implements(IPlugin, IModuleData, ICommand)

	name = "UserhostCommand"
	core = True

	def userCommands(self):
		return [ ("USERHOST", 1, self) ]

	def parseParams(self, user, params, prefix, tags):
		if not params:
			user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters")
			return None
		return {
			"nicks": params[:5]
		}

	def execute(self, user, data):
		userHosts = []
		for nick in data["nicks"]:
			if nick not in self.ircd.userNicks:
				continue
			targetUser = self.ircd.users[self.ircd.userNicks[nick]]
			output = targetUser.nick
			if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, "", users=[targetUser]):
				output += "*"
			output += "="
			if targetUser.metadataKeyExists("away"):
				output += "-"
			else:
				output += "+"
			output += "{}@{}".format(targetUser.ident, targetUser.host())
			userHosts.append(output)
		user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts))
		return True

userhostCmd = UserhostCommand()

Response:
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements

class UserhostCommand(ModuleData, Command):
	implements(IPlugin, IModuleData, ICommand)

	name = "UserhostCommand"
	core = True

	def userCommands(self):
		return [ ("USERHOST", 1, self) ]

	def parseParams(self, user, params, prefix, tags):
		if not params:
			user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters")
			return None
		return {
			"nicks": params[:5]
		}

	def execute(self, user, data):
		userHosts = []
		for nick in data["nicks"]:
			if nick not in self.ircd.userNicks:
				continue
			targetUser = self.ircd.users[self.ircd.userNicks[nick]]
			output = targetUser.nick
			if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, "", users=[targetUser]):
				output += "*"
			output += "="
			if targetUser.metadataKeyExists("away"):
				output += "-"
			else:
				output += "+"
			output += "{}@{}".format(targetUser.ident, targetUser.host())
			userHosts.append(output)
		user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts))
		return True

userhostCmd = UserhostCommand()

Prompt:
Check away status of the target, not user, of USERHOST

from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements

class UserhostCommand(ModuleData, Command):
	implements(IPlugin, IModuleData, ICommand)

	name = "UserhostCommand"
	core = True

	def userCommands(self):
		return [ ("USERHOST", 1, self) ]

	def parseParams(self, user, params, prefix, tags):
		if not params:
			user.sendSingleError("UserhostParams", irc.ERR_NEEDMOREPARAMS, "USERHOST", "Not enough parameters")
			return None
		return {
			"nicks": params[:5]
		}

	def execute(self, user, data):
		userHosts = []
		for nick in data["nicks"]:
			if nick not in self.ircd.userNicks:
				continue
			targetUser = self.ircd.users[self.ircd.userNicks[nick]]
			output = targetUser.nick
			if self.ircd.runActionUntilValue("userhasoperpermission", targetUser, "", users=[targetUser]):
				output += "*"
			output += "="
			if user.metadataKeyExists("away"):
				output += "-"
			else:
				output += "+"
			output += "{}@{}".format(targetUser.ident, targetUser.host())
			userHosts.append(output)
		user.sendMessage(irc.RPL_USERHOST, " ".join(userHosts))
		return True

userhostCmd = UserhostCommand()


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

from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName
from ..models import User
from .. import lastuser

__all__ = ['UserGroupForm']

class UserGroupForm(forms.Form):
    name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()])
    title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()])
    users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()],
        usermodel=User, lastuser=lastuser)

Change to user select widget

Change to user select widget

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

from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName
from ..models import User
from .. import lastuser

__all__ = ['UserGroupForm']

class UserGroupForm(forms.Form):
    name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()])
    title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()])
    users = forms.UserSelectMultiField(__("Users"), validators=[forms.validators.DataRequired()],
        usermodel=User, lastuser=lastuser)

Prompt:
Change to user select widget

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

from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName

__all__ = ['UserGroupForm']

class UserGroupForm(forms.Form):
    name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), AvailableName()])
    title = forms.StringField(__("Title"), validators=[forms.validators.DataRequired()])
    users = forms.TextAreaField(__("Users"), validators=[forms.validators.DataRequired()],
        description=__("Usernames or email addresses, one per line"))


import plotly.offline as py_offline

### Offline Mode

def run_from_ipython():
    try:
        __IPYTHON__
        return True
    except NameError:
        return False

def go_offline(connected=False):
    if run_from_ipython():
        try:
            py_offline.init_notebook_mode(connected)
        except TypeError:
            #For older versions of plotly
            py_offline.init_notebook_mode()
        py_offline.__PLOTLY_OFFLINE_INITIALIZED=True

def go_online():
	py_offline.__PLOTLY_OFFLINE_INITIALIZED=False

def is_offline():
	return py_offline.__PLOTLY_OFFLINE_INITIALIZED

def upgrade(url=None):
	from .auth import get_config_file
	if not url:
		if 'http' not in get_config_file()['offline_url']:
			raise Exception("No default offline URL set \n"
							"Please run cf.set_config_file(offline_url=xx) to set \n"
							"the default offline URL.")
		else:
			url=get_config_file()['offline_url']
	py_offline.download_plotlyjs(url)

Response:
import plotly.offline as py_offline

### Offline Mode

def run_from_ipython():
    try:
        __IPYTHON__
        return True
    except NameError:
        return False

def go_offline(connected=False):
    if run_from_ipython():
        try:
            py_offline.init_notebook_mode(connected)
        except TypeError:
            #For older versions of plotly
            py_offline.init_notebook_mode()
        py_offline.__PLOTLY_OFFLINE_INITIALIZED=True

def go_online():
	py_offline.__PLOTLY_OFFLINE_INITIALIZED=False

def is_offline():
	return py_offline.__PLOTLY_OFFLINE_INITIALIZED

def upgrade(url=None):
	from .auth import get_config_file
	if not url:
		if 'http' not in get_config_file()['offline_url']:
			raise Exception("No default offline URL set \n"
							"Please run cf.set_config_file(offline_url=xx) to set \n"
							"the default offline URL.")
		else:
			url=get_config_file()['offline_url']
	py_offline.download_plotlyjs(url)

Prompt:
Call init_notebook_mode only if inside IPython

import plotly.offline as py_offline

### Offline Mode

def go_offline(connected=False):
	try:
		py_offline.init_notebook_mode(connected)
	except TypeError:
		#For older versions of plotly
		py_offline.init_notebook_mode()
	py_offline.__PLOTLY_OFFLINE_INITIALIZED=True

def go_online():
	py_offline.__PLOTLY_OFFLINE_INITIALIZED=False

def is_offline():
	return py_offline.__PLOTLY_OFFLINE_INITIALIZED

def upgrade(url=None):
	from .auth import get_config_file
	if not url:
		if 'http' not in get_config_file()['offline_url']:
			raise Exception("No default offline URL set \n"
							"Please run cf.set_config_file(offline_url=xx) to set \n"
							"the default offline URL.")
		else:
			url=get_config_file()['offline_url']
	py_offline.download_plotlyjs(url)


import json
import pprint
import requests

def sample_valid_reddit_response():

	r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
	response_json = r.json()

	if 'data' not in response_json:
		print("Trying again")
		response_json = sample_valid_reddit_response()
	return response_json

def save_sample():
	response_json = sample_valid_reddit_response()

	del response_json['data']['children']

	with open('sample_response.json', 'w+') as f:
		json.dump(response_json, f, indent=5)

Move stuff to function for ross

Move stuff to function for ross

Response:
import json
import pprint
import requests

def sample_valid_reddit_response():

	r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
	response_json = r.json()

	if 'data' not in response_json:
		print("Trying again")
		response_json = sample_valid_reddit_response()
	return response_json

def save_sample():
	response_json = sample_valid_reddit_response()

	del response_json['data']['children']

	with open('sample_response.json', 'w+') as f:
		json.dump(response_json, f, indent=5)

Prompt:
Move stuff to function for ross

import json
import pprint
import requests

def sample_valid_reddit_response():

	r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
	response_json = r.json()

	if 'data' not in response_json:
		print("Trying again")
		response_json = sample_valid_reddit_response()
	return response_json

response_json = sample_valid_reddit_response()

del response_json['data']['children']
with open('sample_response.json', 'w+') as f:
	json.dump(response_json, f, indent=5)


def detselect(detector_object, suffix="_stats_total1"):
    """Switch the active detector and set some internal state"""
    gs.DETS =[detector_object]
    gs.PLOT_Y = detector_object.name + suffix
    gs.TABLE_COLS = [gs.PLOT_Y]

def chx_plot_motor(scan):
    fig = None
    if gs.PLOTMODE == 1:
        fig = plt.gcf()
    elif gs.PLOTMODE == 2:
        fig = plt.gcf()
        fig.clear()
    elif gs.PLOTMODE == 3:
        fig = plt.figure()
    return LivePlot(gs.PLOT_Y, scan.motor._name, fig=fig)

dscan.default_sub_factories['all'][1] = chx_plot_motor

gs.PLOTMODE = 1

from bluesky.global_state import resume, abort, stop, panic, all_is_well, state

Response:
def detselect(detector_object, suffix="_stats_total1"):
    """Switch the active detector and set some internal state"""
    gs.DETS =[detector_object]
    gs.PLOT_Y = detector_object.name + suffix
    gs.TABLE_COLS = [gs.PLOT_Y]

def chx_plot_motor(scan):
    fig = None
    if gs.PLOTMODE == 1:
        fig = plt.gcf()
    elif gs.PLOTMODE == 2:
        fig = plt.gcf()
        fig.clear()
    elif gs.PLOTMODE == 3:
        fig = plt.figure()
    return LivePlot(gs.PLOT_Y, scan.motor._name, fig=fig)

dscan.default_sub_factories['all'][1] = chx_plot_motor

gs.PLOTMODE = 1

from bluesky.global_state import resume, abort, stop, panic, all_is_well, state

Prompt:
ENH: Add 'better' plotting control for live plots

def detselect(detector_object, suffix="_stats_total1"):
    """Switch the active detector and set some internal state"""
    gs.DETS =[detector_object]
    gs.PLOT_Y = detector_object.name + suffix
    gs.TABLE_COLS = [gs.PLOT_Y]


from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery

class DownloadFileQuery(ServiceOperationQuery):

    def __init__(self, web, file_url, file_object):
        """
        A download file content query

        :type file_url: str
        :type web: office365.sharepoint.webs.web.Web
        :type file_object: typing.IO
        """

        def _construct_download_query(request):
            request.method = HttpMethod.Get
            self.context.after_execute(_process_response)

        def _process_response(response):
            """
            :type response: RequestOptions
            """
            file_object.write(response.content)

        # Sharepoint Endpoint bug: https://github.com/SharePoint/sp-dev-docs/issues/2630
        file_url = ODataPathParser.encode_method_value(file_url)

        super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativePath(decodedurl={0})/$value".format(file_url))

        self.context.before_execute(_construct_download_query)

Response:
from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery

class DownloadFileQuery(ServiceOperationQuery):

    def __init__(self, web, file_url, file_object):
        """
        A download file content query

        :type file_url: str
        :type web: office365.sharepoint.webs.web.Web
        :type file_object: typing.IO
        """

        def _construct_download_query(request):
            request.method = HttpMethod.Get
            self.context.after_execute(_process_response)

        def _process_response(response):
            """
            :type response: RequestOptions
            """
            file_object.write(response.content)

        # Sharepoint Endpoint bug: https://github.com/SharePoint/sp-dev-docs/issues/2630
        file_url = ODataPathParser.encode_method_value(file_url)

        super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativePath(decodedurl={0})/$value".format(file_url))

        self.context.before_execute(_construct_download_query)

Prompt:
Support correctly weird characters in filenames when downloading

This commit add support for the following:
- Correctly encoded oData parameter sent to the endpoint.
- Support for # and % in filenames by using a newer 365 endpoint.

Summary:

Current implementation was injecting an URL directly quoted to
the endpoint, instead of encoding as an oData value. This was
solved by using the encode_method_value method. This fixes
issues when the file contains weird characters, like slashes
and single quotes.

The getFileServerByUrl endpoint does not support some characters
in filenames, like # and %. A newer endpoint
(getFileByServerRelativePath) is used instead, which allows to
download files with those characters.

from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation_query import ServiceOperationQuery

class DownloadFileQuery(ServiceOperationQuery):

    def __init__(self, web, file_url, file_object):
        """
        A download file content query

        :type file_url: str
        :type web: office365.sharepoint.webs.web.Web
        :type file_object: typing.IO
        """

        def _construct_download_query(request):
            request.method = HttpMethod.Get
            self.context.after_execute(_process_response)

        def _process_response(response):
            """
            :type response: RequestOptions
            """
            file_object.write(response.content)

        super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativeUrl('{0}')/\$value".format(file_url))
        self.context.before_execute(_construct_download_query)


import subprocess
from unittest.mock import patch
from django.test import TestCase

from vcs_info_panel.clients.git import GitClient

def without_git_repository(func):
    def inner(*args, **kwargs):
        with patch('subprocess.check_output') as _check_output:
            _check_output.side_effect = subprocess.CalledProcessError(128,
                                                                      ['git', 'rev-parse', '--is-inside-work-tree'],
                                                                      'fatal: Not a git repository (or any of the parent directories): .git')
        return func(*args, **kwargs)
    return inner

class GitClientTestCase(TestCase):
    def setUp(self):
        self.client = GitClient()

    def _test_called_check_output(self, commands):
        with patch('subprocess.check_output') as _check_output:
            _check_output.assert_called_with(commands)

    def test_base_command(self):
        self.assertEqual(self.client.base_command, 'git')

    def test_is_repository_with_repository(self):
        with patch('subprocess.check_output') as _check_output:
            _check_output.return_value = b'true'
            self.assertEqual(self.client.is_repository(), True)
            _check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])

    @without_git_repository
    def test_is_repository_without_repository(self):
        self.assertEqual(self.client.is_repository(), True)

Response:
import subprocess
from unittest.mock import patch
from django.test import TestCase

from vcs_info_panel.clients.git import GitClient

def without_git_repository(func):
    def inner(*args, **kwargs):
        with patch('subprocess.check_output') as _check_output:
            _check_output.side_effect = subprocess.CalledProcessError(128,
                                                                      ['git', 'rev-parse', '--is-inside-work-tree'],
                                                                      'fatal: Not a git repository (or any of the parent directories): .git')
        return func(*args, **kwargs)
    return inner

class GitClientTestCase(TestCase):
    def setUp(self):
        self.client = GitClient()

    def _test_called_check_output(self, commands):
        with patch('subprocess.check_output') as _check_output:
            _check_output.assert_called_with(commands)

    def test_base_command(self):
        self.assertEqual(self.client.base_command, 'git')

    def test_is_repository_with_repository(self):
        with patch('subprocess.check_output') as _check_output:
            _check_output.return_value = b'true'
            self.assertEqual(self.client.is_repository(), True)
            _check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])

    @without_git_repository
    def test_is_repository_without_repository(self):
        self.assertEqual(self.client.is_repository(), True)

Prompt:
Use decorator to patch git repository is not exist

import subprocess
from unittest.mock import patch
from django.test import TestCase

from vcs_info_panel.clients.git import GitClient

class GitClientTestCase(TestCase):
    def setUp(self):
        self.client = GitClient()

    def _test_called_check_output(self, commands):
        with patch('subprocess.check_output') as _check_output:
            _check_output.assert_called_with(commands)

    def test_base_command(self):
        self.assertEqual(self.client.base_command, 'git')

    def test_is_repository_with_repository(self):
        with patch('subprocess.check_output') as _check_output:
            _check_output.return_value = b'true'
            self.assertEqual(self.client.is_repository(), True)
            _check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])

    def _patch_without_repository(self, func):
        with patch('subprocess.check_output') as _check_output:
            _check_output.side_effect = subprocess.CalledProcessError(128,
                                                                     ['git', 'rev-parse', '--is-inside-work-tree'],
                                                                     'fatal: Not a git repository (or any of the parent directories): .git')

    def test_is_repository_without_repository(self):
        def _func(_check_output):
            self.assertEqual(self.client.is_repository(), False)
            _check_output.assert_called_once_with(['git', 'rev-parse', '--is-inside-work-tree'])
        self._patch_without_repository(_func)


import unittest

import numpy

import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing

class TestForget(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)
        self.y = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)
        self.gz = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)

    def check_forward(self, x_data, y_data):
        x = chainer.Variable(x_data)
        y = chainer.Variable(y_data)
        z = functions.forget(lambda x, y: (x + y + x,), x, y)
        gradient_check.assert_allclose(x_data + y_data + x_data, z.data)

    def test_forward_cpu(self):
        self.check_forward(self.x, self.y)

    def check_backward(self, x_data, y_data, gz_data):
        x = chainer.Variable(x_data)
        y = chainer.Variable(y_data)
        z = functions.forget(lambda x, y: (x + y + x,), x, y)
        z.grad = gz_data
        z.backward()

        gradient_check.assert_allclose(x.grad, gz_data * 2)
        gradient_check.assert_allclose(y.grad, gz_data)

    def test_backward_cpu(self):
        self.check_backward(self.x, self.y, self.gz)

class TestForgetError(unittest.TestCase):

    def test_not_callable(self):
        with self.assertRaises(TypeError):
            functions.forget(1)

    def test_invalid_type(self):
        with self.assertRaisesRegexp(RuntimeError, 'int'):
            functions.forget(lambda: 1)

    def test_invalid_tuple_type(self):
        with self.assertRaisesRegexp(RuntimeError, '1-th.*int'):
            functions.forget(lambda: (1,))

testing.run_module(__name__, __file__)

Add test for forget function

Add test for forget function

Response:
import unittest

import numpy

import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing

class TestForget(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)
        self.y = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)
        self.gz = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)

    def check_forward(self, x_data, y_data):
        x = chainer.Variable(x_data)
        y = chainer.Variable(y_data)
        z = functions.forget(lambda x, y: (x + y + x,), x, y)
        gradient_check.assert_allclose(x_data + y_data + x_data, z.data)

    def test_forward_cpu(self):
        self.check_forward(self.x, self.y)

    def check_backward(self, x_data, y_data, gz_data):
        x = chainer.Variable(x_data)
        y = chainer.Variable(y_data)
        z = functions.forget(lambda x, y: (x + y + x,), x, y)
        z.grad = gz_data
        z.backward()

        gradient_check.assert_allclose(x.grad, gz_data * 2)
        gradient_check.assert_allclose(y.grad, gz_data)

    def test_backward_cpu(self):
        self.check_backward(self.x, self.y, self.gz)

class TestForgetError(unittest.TestCase):

    def test_not_callable(self):
        with self.assertRaises(TypeError):
            functions.forget(1)

    def test_invalid_type(self):
        with self.assertRaisesRegexp(RuntimeError, 'int'):
            functions.forget(lambda: 1)

    def test_invalid_tuple_type(self):
        with self.assertRaisesRegexp(RuntimeError, '1-th.*int'):
            functions.forget(lambda: (1,))

testing.run_module(__name__, __file__)

Prompt: Add test for forget function


# A simple loadtest using locust.
# launch using: locust -f simpleloadtest.py --host=http://pencilcode.net

from locust import HttpLocust, TaskSet, task
import simplejson, random

class MyTaskSet(TaskSet):
    def userbase(self, user):
      return self.client.base_url.replace('//', '//' + user + '.')

    def topget(self, url):
      return self.client.get(url, headers={"User-Agent":"locust"})

    def myget(self, user, url):
      return self.client.get(self.userbase(user) + url,
          headers={"User-Agent":"locust"})

    def mypost(self, user, url, data):
      return self.client.post(self.userbase(user) + url, data,
          headers={"User-Agent":"locust"})

    # @task(1)
    def index(self):
        for url in ['/', '/welcome.css', '/image/vpencil-20-64.png',
            '/image/art.png', '/image/music.png', '/image/adventure.png',
            '/lib/jquery.js', '/lib/jquery.autocomplete.min.js',
            '/load/?callback=loadusers']:
          self.topget(url)
        for url in ['/home/promo1', '/home/goldwheel-code.png',
            '/lib/seedrandom.js', '/turtlebits.js']:
          self.myget('promo', url)

    # @task(1)
    def edit(self):
        topdir = self.topget("/load/").json()
        randuser = random.choice(topdir['list'])
        randname = randuser['name']
        if 'd' not in randuser['mode']:
          return
        for url in ['/edit/', '/editor.js', '/favicon.ico',
            '/apple-touch-icon.png', '/load']:
          mydir = self.myget(randname, url)

    @task(1)
    def browserandom(self):
        topdir = self.topget("/load/").json()
        randuser = random.choice(topdir['list'])
        randname = randuser['name']
        if 'd' in randuser['mode']:
          try:
            mydir = self.myget(randname, '/load/').json()
          except:
            print 'error listing', randuser
            return
          randfile = random.choice(mydir['list'])['name']
          try:
            self.myget(randname, '/load/' + randfile).json()
          except:
            print 'error reading', randuser, randfile

    @task(1)
    def livetestsave(self):
        myok = self.mypost('livetest', '/save/loadtest', {
          'data': 'pen red\nfor [1..4]\n  fd 100\n  rt 90',
          'key': '123'
        }).json()

class MyLocust(HttpLocust):
    task_set = MyTaskSet
    min_wait =  5000
    max_wait = 15000

Add a simple load test.

Add a simple load test.

Response:
# A simple loadtest using locust.
# launch using: locust -f simpleloadtest.py --host=http://pencilcode.net

from locust import HttpLocust, TaskSet, task
import simplejson, random

class MyTaskSet(TaskSet):
    def userbase(self, user):
      return self.client.base_url.replace('//', '//' + user + '.')

    def topget(self, url):
      return self.client.get(url, headers={"User-Agent":"locust"})

    def myget(self, user, url):
      return self.client.get(self.userbase(user) + url,
          headers={"User-Agent":"locust"})

    def mypost(self, user, url, data):
      return self.client.post(self.userbase(user) + url, data,
          headers={"User-Agent":"locust"})

    # @task(1)
    def index(self):
        for url in ['/', '/welcome.css', '/image/vpencil-20-64.png',
            '/image/art.png', '/image/music.png', '/image/adventure.png',
            '/lib/jquery.js', '/lib/jquery.autocomplete.min.js',
            '/load/?callback=loadusers']:
          self.topget(url)
        for url in ['/home/promo1', '/home/goldwheel-code.png',
            '/lib/seedrandom.js', '/turtlebits.js']:
          self.myget('promo', url)

    # @task(1)
    def edit(self):
        topdir = self.topget("/load/").json()
        randuser = random.choice(topdir['list'])
        randname = randuser['name']
        if 'd' not in randuser['mode']:
          return
        for url in ['/edit/', '/editor.js', '/favicon.ico',
            '/apple-touch-icon.png', '/load']:
          mydir = self.myget(randname, url)

    @task(1)
    def browserandom(self):
        topdir = self.topget("/load/").json()
        randuser = random.choice(topdir['list'])
        randname = randuser['name']
        if 'd' in randuser['mode']:
          try:
            mydir = self.myget(randname, '/load/').json()
          except:
            print 'error listing', randuser
            return
          randfile = random.choice(mydir['list'])['name']
          try:
            self.myget(randname, '/load/' + randfile).json()
          except:
            print 'error reading', randuser, randfile

    @task(1)
    def livetestsave(self):
        myok = self.mypost('livetest', '/save/loadtest', {
          'data': 'pen red\nfor [1..4]\n  fd 100\n  rt 90',
          'key': '123'
        }).json()

class MyLocust(HttpLocust):
    task_set = MyTaskSet
    min_wait =  5000
    max_wait = 15000

Prompt: Add a simple load test.


#!/usr/bin/env python

import os
import codecs
from setuptools import setup, find_packages

# Utility function to read the README file.
# Used for the long_description.  It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
    file_path = os.path.join(os.path.dirname(__file__), fname)
    return codecs.open(file_path, encoding='utf-8').read()

setup(
    name='rds-log',
    use_scm_version=True,
    description='A utility to download AWS RDS logs',
    author='Andreas Pelme',
    author_email='andreas@pelme.se',
    url='https://github.com/pelme/rds-log',
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires=[
        'boto3==1.4.7',
        'click==5.1',
    ],
    setup_requires=[
        'setuptools_scm==1.7.0',
    ],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Programming Language :: Python :: 3.4',
    ],
    entry_points={
        'console_scripts': 'rds-log-stream=_rds_log.commands.rds_log_stream:main'
    },
)

Response:
#!/usr/bin/env python

import os
import codecs
from setuptools import setup, find_packages

# Utility function to read the README file.
# Used for the long_description.  It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
    file_path = os.path.join(os.path.dirname(__file__), fname)
    return codecs.open(file_path, encoding='utf-8').read()

setup(
    name='rds-log',
    use_scm_version=True,
    description='A utility to download AWS RDS logs',
    author='Andreas Pelme',
    author_email='andreas@pelme.se',
    url='https://github.com/pelme/rds-log',
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires=[
        'boto3==1.4.7',
        'click==5.1',
    ],
    setup_requires=[
        'setuptools_scm==1.7.0',
    ],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Programming Language :: Python :: 3.4',
    ],
    entry_points={
        'console_scripts': 'rds-log-stream=_rds_log.commands.rds_log_stream:main'
    },
)

Prompt:
Update boto3 requirement to latest version

#!/usr/bin/env python

import os
import codecs
from setuptools import setup, find_packages

# Utility function to read the README file.
# Used for the long_description.  It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
    file_path = os.path.join(os.path.dirname(__file__), fname)
    return codecs.open(file_path, encoding='utf-8').read()

setup(
    name='rds-log',
    use_scm_version=True,
    description='A utility to download AWS RDS logs',
    author='Andreas Pelme',
    author_email='andreas@pelme.se',
    url='https://github.com/pelme/rds-log',
    packages=find_packages(),
    long_description=read('README.rst'),
    install_requires=[
        'boto3==1.1.2',
        'click==5.1',
    ],
    setup_requires=[
        'setuptools_scm==1.7.0',
    ],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Programming Language :: Python :: 3.4',
    ],
    entry_points={
        'console_scripts': 'rds-log-stream=_rds_log.commands.rds_log_stream:main'
    },
)


from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys

class Command(BaseCommand):
    args = ''
    help = 'Builds top'
    def handle(self, *args, **options):
        category = sys.argv[2]
        c = Counter()
        values = {'favorite': 10, 'like': 2, 'neutral': 0.5, 'dislike': -1}
        anime_ids = Anime.objects.exclude(**{category: 1}).values_list('id', flat=True)
        nb_ratings = Counter()
        nb_stars = Counter()
        for rating in Rating.objects.filter(work_id__in=anime_ids).select_related('work__anime__' + category):
            contestant = getattr(rating.work.anime, category)
            nb_ratings[contestant] += 1
            if rating.choice == 'favorite':
                nb_stars[contestant] += 1
            c[contestant] += values.get(rating.choice, 0)
        top = []
        for i, (artist, score) in enumerate(c.most_common(20)):
            top.append(dict(rank=i + 1, name=str(artist), id=artist.id, score=score, nb_ratings=nb_ratings[artist], nb_stars=nb_stars[artist]))
        print(json.dumps(top))

Add ID to Artist in Top

Add ID to Artist in Top

Response:
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys

class Command(BaseCommand):
    args = ''
    help = 'Builds top'
    def handle(self, *args, **options):
        category = sys.argv[2]
        c = Counter()
        values = {'favorite': 10, 'like': 2, 'neutral': 0.5, 'dislike': -1}
        anime_ids = Anime.objects.exclude(**{category: 1}).values_list('id', flat=True)
        nb_ratings = Counter()
        nb_stars = Counter()
        for rating in Rating.objects.filter(work_id__in=anime_ids).select_related('work__anime__' + category):
            contestant = getattr(rating.work.anime, category)
            nb_ratings[contestant] += 1
            if rating.choice == 'favorite':
                nb_stars[contestant] += 1
            c[contestant] += values.get(rating.choice, 0)
        top = []
        for i, (artist, score) in enumerate(c.most_common(20)):
            top.append(dict(rank=i + 1, name=str(artist), id=artist.id, score=score, nb_ratings=nb_ratings[artist], nb_stars=nb_stars[artist]))
        print(json.dumps(top))

Prompt:
Add ID to Artist in Top

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys

class Command(BaseCommand):
    args = ''
    help = 'Builds top'
    def handle(self, *args, **options):
        category = sys.argv[2]
        c = Counter()
        values = {'favorite': 10, 'like': 2, 'neutral': 0.5, 'dislike': -1}
        anime_ids = Anime.objects.exclude(**{category: 1}).values_list('id', flat=True)
        nb_ratings = Counter()
        nb_stars = Counter()
        for rating in Rating.objects.filter(work_id__in=anime_ids).select_related('work__anime__' + category):
            contestant = getattr(rating.work.anime, category)
            nb_ratings[contestant] += 1
            if rating.choice == 'favorite':
                nb_stars[contestant] += 1
            c[contestant] += values.get(rating.choice, 0)
        top = []
        for i, (artist, score) in enumerate(c.most_common(20)):
            top.append(dict(rank=i + 1, name=str(artist), score=score, nb_ratings=nb_ratings[artist], nb_stars=nb_stars[artist]))
        print(json.dumps(top))


# Do not commit secrets to VCS.

# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`

from icekit.project.settings.icekit import *  # glamkit, icekit

# Override the default ICEkit settings to form project settings.

Use ICEkit settings by default again.

Use ICEkit settings by default again.

Response:
# Do not commit secrets to VCS.

# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`

from icekit.project.settings.icekit import *  # glamkit, icekit

# Override the default ICEkit settings to form project settings.

Prompt:
Use ICEkit settings by default again.

# Do not commit secrets to VCS.

# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`

from icekit.project.settings.glamkit import *  # glamkit, icekit

# Override the default ICEkit settings to form project settings.


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

urlpatterns = patterns('django.contrib.auth.views',

    url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
    url(r'^logout/$', 'logout_then_login',name='logout'))

Add name to logout url regex

Add name to logout url regex

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

urlpatterns = patterns('django.contrib.auth.views',

    url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
    url(r'^logout/$', 'logout_then_login',name='logout'))

Prompt:
Add name to logout url regex

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

urlpatterns = patterns('django.contrib.auth.views',

    url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
    url(r'^logout/$', 'logout_then_login'))


# You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

# Exampe:
# Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
# Output: [-1,3,-1]
# Explanation:
#     For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
#     For number 1 in the first array, the next greater number for it in the second array is 3.
#     For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

def nextGreaterElement(findNums, nums):
  """
  :type findNums: List[int]
  :type nums: List[int]
  :rtype: List[int]
  """
  greaterNumbers = []
  for i in range(len(findNums)):
    index = nums.index(findNums[i])
    for x in range(index, len(nums)):
      if nums[x] > findNums[i]:
        greaterNumbers.append(nums[x])
        break
      elif x == (len(nums) - 1):
        greaterNumbers.append(-1)
  return greaterNumbers

findNums = [4,1,2]
nums = [1,2,3,4]
print(nextGreaterElement(findNums, nums))

Solve Next Greater Element I

Solve Next Greater Element I

Response:
# You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

# Exampe:
# Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
# Output: [-1,3,-1]
# Explanation:
#     For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
#     For number 1 in the first array, the next greater number for it in the second array is 3.
#     For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

def nextGreaterElement(findNums, nums):
  """
  :type findNums: List[int]
  :type nums: List[int]
  :rtype: List[int]
  """
  greaterNumbers = []
  for i in range(len(findNums)):
    index = nums.index(findNums[i])
    for x in range(index, len(nums)):
      if nums[x] > findNums[i]:
        greaterNumbers.append(nums[x])
        break
      elif x == (len(nums) - 1):
        greaterNumbers.append(-1)
  return greaterNumbers

findNums = [4,1,2]
nums = [1,2,3,4]
print(nextGreaterElement(findNums, nums))

Prompt: Solve Next Greater Element I


#!/usr/bin/env python

"""Software Carpentry Nano Installer for Windows

Installs nano and makes it the default editor in msysgit

To use:

1. Install Python
2. Install msysgit
   http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git
3. Run swc_nano_installer.py
   You should be able to simply double click the file in Windows

This is a stripped down version of swc_windows_installer.py
originally written by Ethan White and W. Trevor Price.

"""

try:  # Python 3
    from io import BytesIO as _BytesIO
except ImportError:  # Python 2
    from StringIO import StringIO as _BytesIO
import os
try:  # Python 3
    from urllib.request import urlopen as _urlopen
except ImportError:  # Python 2
    from urllib2 import urlopen as _urlopen
import zipfile

def install_nano(install_dir):
    """Download and install the nano text editor"""
    url = "http://www.nano-editor.org/dist/v2.2/NT/nano-2.2.6.zip"
    r = _urlopen(url)
    nano_zip_content = _BytesIO(r.read())
    nano_zip = zipfile.ZipFile(nano_zip_content)
    nano_files = ['nano.exe', 'cygwin1.dll', 'cygintl-8.dll',
                  'cygiconv-2.dll', 'cyggcc_s-1.dll']
    for file_name in nano_files:
        nano_zip.extract(file_name, install_dir)

def make_bashrc(home_dir, nano_dir):
    """Creates a .bashrc file for nano setup

    Adds nano to the path and sets the default editor to nano

    """

    nano_path = make_posix_path(nano_dir)
    contents = '\n'.join([
        'export PATH=$PATH:%s' % nano_path,
        'export EDITOR=nano',
            '',
            ])
    with open(os.path.join(home_dir, '.bashrc'), 'w') as f:
        f.write(contents)

def make_posix_path(windows_path):
    """Convert a Windows path to a posix path"""
    return windows_path.replace('\\', '/').replace('C:', '/c')

def main():
    home_dir = os.path.expanduser("~")
    nano_dir = os.path.join(home_dir, '.nano')
    #home_dir = "/home/ethan/swc-nano-test"
    if not os.path.exists(nano_dir):
        os.makedirs(nano_dir)
    install_nano(nano_dir)
    make_bashrc(home_dir, nano_dir)

if __name__ == '__main__':
    main()

Add a Nano installer for Windows

Add a Nano installer for Windows

1. Downloads and installs Nano into the users home directory
2. Adds Nano to the path
3. Makes Nano the default editor

Response:
#!/usr/bin/env python

"""Software Carpentry Nano Installer for Windows

Installs nano and makes it the default editor in msysgit

To use:

1. Install Python
2. Install msysgit
   http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git
3. Run swc_nano_installer.py
   You should be able to simply double click the file in Windows

This is a stripped down version of swc_windows_installer.py
originally written by Ethan White and W. Trevor Price.

"""

try:  # Python 3
    from io import BytesIO as _BytesIO
except ImportError:  # Python 2
    from StringIO import StringIO as _BytesIO
import os
try:  # Python 3
    from urllib.request import urlopen as _urlopen
except ImportError:  # Python 2
    from urllib2 import urlopen as _urlopen
import zipfile

def install_nano(install_dir):
    """Download and install the nano text editor"""
    url = "http://www.nano-editor.org/dist/v2.2/NT/nano-2.2.6.zip"
    r = _urlopen(url)
    nano_zip_content = _BytesIO(r.read())
    nano_zip = zipfile.ZipFile(nano_zip_content)
    nano_files = ['nano.exe', 'cygwin1.dll', 'cygintl-8.dll',
                  'cygiconv-2.dll', 'cyggcc_s-1.dll']
    for file_name in nano_files:
        nano_zip.extract(file_name, install_dir)

def make_bashrc(home_dir, nano_dir):
    """Creates a .bashrc file for nano setup

    Adds nano to the path and sets the default editor to nano

    """

    nano_path = make_posix_path(nano_dir)
    contents = '\n'.join([
        'export PATH=$PATH:%s' % nano_path,
        'export EDITOR=nano',
            '',
            ])
    with open(os.path.join(home_dir, '.bashrc'), 'w') as f:
        f.write(contents)

def make_posix_path(windows_path):
    """Convert a Windows path to a posix path"""
    return windows_path.replace('\\', '/').replace('C:', '/c')

def main():
    home_dir = os.path.expanduser("~")
    nano_dir = os.path.join(home_dir, '.nano')
    #home_dir = "/home/ethan/swc-nano-test"
    if not os.path.exists(nano_dir):
        os.makedirs(nano_dir)
    install_nano(nano_dir)
    make_bashrc(home_dir, nano_dir)

if __name__ == '__main__':
    main()

Prompt:
Add a Nano installer for Windows

1. Downloads and installs Nano into the users home directory
2. Adds Nano to the path
3. Makes Nano the default editor


import sys, os, re, shutil
from nose.tools import *

import logging
logger = logging.getLogger(__name__)

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from qipipe.interfaces import MapCTP

ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
"""The test parent directory."""

RESULTS = os.path.join(ROOT, 'results', 'staging', 'map_ctp')
"""The test results directory."""

from nipype import config
cfg = dict(logging=dict(workflow_level='DEBUG', log_directory=RESULTS, log_to_file=True),
    execution=dict(crashdump_dir=RESULTS, create_report=False))
config.update_config(cfg)

COLLECTION = 'Sarcoma'
"""The test collection."""

SUBJECTS = ["Sarcoma%02d" %  i for i in range(8, 12)]

PAT = "ptid/(Sarcoma\d{2})\s*=\s*QIN-\w+-\d{2}-(\d{4})"

class TestMapCTP:
    """Map CTP unit tests."""

    def tearDown(self):
        shutil.rmtree(RESULTS, True)

    def test_map_ctp(self):
        logger.debug("Testing Map CTP on %s..." % SUBJECTS)
        map_ctp = MapCTP(collection=COLLECTION, patient_ids=SUBJECTS, dest=RESULTS)
        result = map_ctp.run()
        prop_file = result.outputs.out_file
        assert_true(os.path.exists(prop_file), "Property file was not created: %s" % prop_file)
        assert_equal(RESULTS, os.path.dirname(prop_file), "Property file was not created in %s: %s" % (RESULTS, prop_file))
        for line in open(prop_file).readlines():
            qin_id, ctp_suffix = re.match(PAT, line).groups()
            assert_true(qin_id in SUBJECTS, "Subject id not found: %s" % qin_id)
            qin_nbr = int(qin_id[-2:])
            ctp_nbr = int(ctp_suffix)
            assert_equal(qin_nbr, ctp_nbr, "Patient number incorrect; expected: %d found: %d" % (qin_nbr, ctp_nbr))

if __name__ == "__main__":
    import nose

    nose.main(defaultTest=__name__)

Test the Map CTP interface.

Test the Map CTP interface.

Response:
import sys, os, re, shutil
from nose.tools import *

import logging
logger = logging.getLogger(__name__)

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from qipipe.interfaces import MapCTP

ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
"""The test parent directory."""

RESULTS = os.path.join(ROOT, 'results', 'staging', 'map_ctp')
"""The test results directory."""

from nipype import config
cfg = dict(logging=dict(workflow_level='DEBUG', log_directory=RESULTS, log_to_file=True),
    execution=dict(crashdump_dir=RESULTS, create_report=False))
config.update_config(cfg)

COLLECTION = 'Sarcoma'
"""The test collection."""

SUBJECTS = ["Sarcoma%02d" %  i for i in range(8, 12)]

PAT = "ptid/(Sarcoma\d{2})\s*=\s*QIN-\w+-\d{2}-(\d{4})"

class TestMapCTP:
    """Map CTP unit tests."""

    def tearDown(self):
        shutil.rmtree(RESULTS, True)

    def test_map_ctp(self):
        logger.debug("Testing Map CTP on %s..." % SUBJECTS)
        map_ctp = MapCTP(collection=COLLECTION, patient_ids=SUBJECTS, dest=RESULTS)
        result = map_ctp.run()
        prop_file = result.outputs.out_file
        assert_true(os.path.exists(prop_file), "Property file was not created: %s" % prop_file)
        assert_equal(RESULTS, os.path.dirname(prop_file), "Property file was not created in %s: %s" % (RESULTS, prop_file))
        for line in open(prop_file).readlines():
            qin_id, ctp_suffix = re.match(PAT, line).groups()
            assert_true(qin_id in SUBJECTS, "Subject id not found: %s" % qin_id)
            qin_nbr = int(qin_id[-2:])
            ctp_nbr = int(ctp_suffix)
            assert_equal(qin_nbr, ctp_nbr, "Patient number incorrect; expected: %d found: %d" % (qin_nbr, ctp_nbr))

if __name__ == "__main__":
    import nose

    nose.main(defaultTest=__name__)

Prompt: Test the Map CTP interface.


from django import template
from django.utils.safestring import mark_safe

from favicon.models import Favicon, config

register = template.Library()

@register.simple_tag(takes_context=True)
def placeFavicon(context):
    """
    Gets Favicon-URL for the Model.

    Template Syntax:

        {% placeFavicon %}

    """
    fav = Favicon.objects.filter(isFavicon=True).first()
    if not fav:
        return mark_safe('<!-- no favicon -->')
    html = ''
    for rel in config:
        for size in sorted(config[rel], reverse=True):
            n = fav.get_favicon(size=size, rel=rel)
            html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % (
                n.rel, n.size, n.size, n.faviconImage.url)

    default_fav = fav.get_favicon(size=32, rel='shortcut icon')
    html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % (
        default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url)

    return mark_safe(html)

Response:
from django import template
from django.utils.safestring import mark_safe

from favicon.models import Favicon, config

register = template.Library()

@register.simple_tag(takes_context=True)
def placeFavicon(context):
    """
    Gets Favicon-URL for the Model.

    Template Syntax:

        {% placeFavicon %}

    """
    fav = Favicon.objects.filter(isFavicon=True).first()
    if not fav:
        return mark_safe('<!-- no favicon -->')
    html = ''
    for rel in config:
        for size in sorted(config[rel], reverse=True):
            n = fav.get_favicon(size=size, rel=rel)
            html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % (
                n.rel, n.size, n.size, n.faviconImage.url)

    default_fav = fav.get_favicon(size=32, rel='shortcut icon')
    html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % (
        default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url)

    return mark_safe(html)

Prompt:
Mark comment as safe. Otherwise it is displayed.
from django import template
from django.utils.safestring import mark_safe

from favicon.models import Favicon, config

register = template.Library()

@register.simple_tag(takes_context=True)
def placeFavicon(context):
    """
    Gets Favicon-URL for the Model.

    Template Syntax:

        {% placeFavicon %}

    """
    fav = Favicon.objects.filter(isFavicon=True).first()
    if not fav:
        return '<!-- no favicon -->'
    html = ''
    for rel in config:
        for size in sorted(config[rel], reverse=True):
            n = fav.get_favicon(size=size, rel=rel)
            html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % (
                n.rel, n.size, n.size, n.faviconImage.url)

    default_fav = fav.get_favicon(size=32, rel='shortcut icon')
    html += '<link rel="%s" sizes="%sx%s" href="%s"/>' % (
        default_fav.rel, default_fav.size, default_fav.size, default_fav.faviconImage.url)

    return mark_safe(html)


from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register

@register.simple_tag(takes_context=True)
def translate_url(context, language):
    if hasattr(context.get('object', None), 'get_absolute_url'):
        with translation.override(language):
            return context['object'].get_absolute_url()

    view = resolve(context['request'].path)
    args = [a for a in view.args if a is not None]
    kwargs = {k:v for k,v in view.kwargs.items() if v is not None}
    with translation.override(language):
        return reverse(view.view_name, args=args, kwargs=kwargs)

Response:
from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register

@register.simple_tag(takes_context=True)
def translate_url(context, language):
    if hasattr(context.get('object', None), 'get_absolute_url'):
        with translation.override(language):
            return context['object'].get_absolute_url()

    view = resolve(context['request'].path)
    args = [a for a in view.args if a is not None]
    kwargs = {k:v for k,v in view.kwargs.items() if v is not None}
    with translation.override(language):
        return reverse(view.view_name, args=args, kwargs=kwargs)

Prompt:
Fix getting the translated urls for material detail views

from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register

@register.simple_tag(takes_context=True)
def translate_url(context, language):
    view = resolve(context['request'].path)
    args = [a for a in view.args if a is not None]
    kwargs = {k:v for k,v in view.kwargs.items() if v is not None}
    with translation.override(language):
        url = reverse(view.view_name, args=args, kwargs=kwargs)
    return url


Add new line at end of file

Add new line at end of file

Response:
class PyhunterError(Exception):
    """
    Generic exception class for the library
    """
    pass

class MissingCompanyError(PyhunterError):
    pass

class MissingNameError(PyhunterError):
    pass

class HunterApiError(PyhunterError):
    """
    Represents something went wrong in the call to the Hunter API
    """
    pass

Prompt:
Add new line at end of file

class PyhunterError(Exception):
    """
    Generic exception class for the library
    """
    pass

class MissingCompanyError(PyhunterError):
    pass

class MissingNameError(PyhunterError):
    pass

class HunterApiError(PyhunterError):
    """
    Represents something went wrong in the call to the Hunter API
    """
    pass


from django.conf.urls import url

from . import views

app_name = 'event'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
    url(r'^artist/(?P<pk>\d+)/$', views.ArtistDetailView.as_view(), name='artist_detail'),
    url(r'^event/$', views.EventView.as_view(), name='event'),
    url(r'^venue/$', views.VenueView.as_view(), name='venue'),
    url(r'^profile/$', views.ProfileView.as_view(), name='profile'),
]

Fix Artist detail view url

Fix Artist detail view url

Response:
from django.conf.urls import url

from . import views

app_name = 'event'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
    url(r'^artist/(?P<pk>\d+)/$', views.ArtistDetailView.as_view(), name='artist_detail'),
    url(r'^event/$', views.EventView.as_view(), name='event'),
    url(r'^venue/$', views.VenueView.as_view(), name='venue'),
    url(r'^profile/$', views.ProfileView.as_view(), name='profile'),
]

Prompt:
Fix Artist detail view url

from django.conf.urls import url

from . import views

app_name = 'event'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
    url(r'^artist/(?P<pk>\d+)$', views.ArtistDetailView.as_view(), name='artist_detail'),
    url(r'^event/$', views.EventView.as_view(), name='event'),
    url(r'^venue/$', views.VenueView.as_view(), name='venue'),
    url(r'^profile/$', views.ProfileView.as_view(), name='profile'),
]


import os
import cv2
from base_camera import BaseCamera

class Camera(BaseCamera):
    video_source = 0

    def __init__(self):
        if os.environ.get('OPENCV_CAMERA_SOURCE'):
            Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
        super(Camera, self).__init__()

    @staticmethod
    def set_video_source(source):
        Camera.video_source = source

    @staticmethod
    def frames():
        camera = cv2.VideoCapture(Camera.video_source)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        while True:
            # read current frame
            _, img = camera.read()

            # encode as a jpeg image and return it
            yield cv2.imencode('.jpg', img)[1].tobytes()

Response:
import os
import cv2
from base_camera import BaseCamera

class Camera(BaseCamera):
    video_source = 0

    def __init__(self):
        if os.environ.get('OPENCV_CAMERA_SOURCE'):
            Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
        super(Camera, self).__init__()

    @staticmethod
    def set_video_source(source):
        Camera.video_source = source

    @staticmethod
    def frames():
        camera = cv2.VideoCapture(Camera.video_source)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        while True:
            # read current frame
            _, img = camera.read()

            # encode as a jpeg image and return it
            yield cv2.imencode('.jpg', img)[1].tobytes()

Prompt:
Use OPENCV_CAMERA_SOURCE environment variable to set source

import cv2
from base_camera import BaseCamera

class Camera(BaseCamera):
    video_source = 0

    @staticmethod
    def set_video_source(source):
        Camera.video_source = source

    @staticmethod
    def frames():
        camera = cv2.VideoCapture(Camera.video_source)
        if not camera.isOpened():
            raise RuntimeError('Could not start camera.')

        while True:
            # read current frame
            _, img = camera.read()

            # encode as a jpeg image and return it
            yield cv2.imencode('.jpg', img)[1].tobytes()


from distutils.core import setup

setup(
    name='flickruper',
    version='0.1.0',
    author='Igor Katson',
    author_email='igor.katson@gmail.com',
    py_modules=['flickruper'],
    scripts=['bin/flickruper'],
    entry_points={
        'console_scripts': ['flickruper = flickruper:main'],
    },
    url='https://github.com/ikatson/flickruper',
    license='LICENSE.txt',
    description='Multi-threaded uploader for Flickr',
    long_description=open('README.rst').read(),
    install_requires=[
        "flickrapi>=1.4.4",
    ],
)

Make it installable with PyPI

Make it installable with PyPI

Response:
from distutils.core import setup

setup(
    name='flickruper',
    version='0.1.0',
    author='Igor Katson',
    author_email='igor.katson@gmail.com',
    py_modules=['flickruper'],
    scripts=['bin/flickruper'],
    entry_points={
        'console_scripts': ['flickruper = flickruper:main'],
    },
    url='https://github.com/ikatson/flickruper',
    license='LICENSE.txt',
    description='Multi-threaded uploader for Flickr',
    long_description=open('README.rst').read(),
    install_requires=[
        "flickrapi>=1.4.4",
    ],
)

Prompt:
Make it installable with PyPI

from distutils.core import setup

setup(
    name='flickruper',
    version='0.1.0',
    author='Igor Katson',
    author_email='igor.katson@gmail.com',
    py_modules=['flickruper'],
    scripts=['bin/flickruper'],
    entry_points={
        'console_scripts': ['flickruper = flickruper:main'],
    },
    url='http://pypi.python.org/pypi/flickruper/',
    license='LICENSE.txt',
    description='Multi-threaded uploader for Flickr',
    long_description=open('README.rst').read(),
    install_requires=[
        "flickrapi>=1.4.4",
    ],
)


"""
Hacker News Top:
  -Get top stories from Hacker News' official API
  -Record all users who comment on those stories

Author: Rylan Santinon
"""

from api_connector import *
from csv_io import *

def main():
  conn = ApiConnector()
  csvio = CsvIo()
  article_list = conn.get_top()
  stories = []

  for i in article_list:
    try:
      story = conn.get_item(i)
      if story.get("deleted"):
	continue
      print csvio.story_to_csv(story)
      stories.append(story)
    except NetworkError as e:
      print e

  csvio.write_stories_csv(stories)

  for story in stories:
    try:
      conn.get_kids(story)
    except NetworkError as e:
      print e

  users = []
  for u in sorted(conn.user_dict.keys()):
    try:
      userjson = conn.get_user(u)
      users.append(userjson)
      print u
    except NetworkError as e:
      print e

  csvio.write_users_csv(users)

if __name__ == '__main__':
  csvio = CsvIo()
  main()
  csvio.concat_users()
  csvio.concat_stories()

Use common object for csvio calls

Use common object for csvio calls

Response:
"""
Hacker News Top:
  -Get top stories from Hacker News' official API
  -Record all users who comment on those stories

Author: Rylan Santinon
"""

from api_connector import *
from csv_io import *

def main():
  conn = ApiConnector()
  csvio = CsvIo()
  article_list = conn.get_top()
  stories = []

  for i in article_list:
    try:
      story = conn.get_item(i)
      if story.get("deleted"):
	continue
      print csvio.story_to_csv(story)
      stories.append(story)
    except NetworkError as e:
      print e

  csvio.write_stories_csv(stories)

  for story in stories:
    try:
      conn.get_kids(story)
    except NetworkError as e:
      print e

  users = []
  for u in sorted(conn.user_dict.keys()):
    try:
      userjson = conn.get_user(u)
      users.append(userjson)
      print u
    except NetworkError as e:
      print e

  csvio.write_users_csv(users)

if __name__ == '__main__':
  csvio = CsvIo()
  main()
  csvio.concat_users()
  csvio.concat_stories()

Prompt:
Use common object for csvio calls

"""
Hacker News Top:
  -Get top stories from Hacker News' official API
  -Record all users who comment on those stories

Author: Rylan Santinon
"""

from api_connector import *
from csv_io import *

def main():
  conn = ApiConnector()
  csvio = CsvIo()
  article_list = conn.get_top()
  stories = []

  for i in article_list:
    try:
      story = conn.get_item(i)
      if story.get("deleted"):
	continue
      print csvio.story_to_csv(story)
      stories.append(story)
    except NetworkError as e:
      print e

  csvio.write_stories_csv(stories)

  for story in stories:
    try:
      conn.get_kids(story)
    except NetworkError as e:
      print e

  users = []
  for u in sorted(conn.user_dict.keys()):
    try:
      userjson = conn.get_user(u)
      users.append(userjson)
      print u
    except NetworkError as e:
      print e

  csvio.write_users_csv(users)

if __name__ == '__main__':
  main()
  CsvIo().concat_users()
  CsvIo().concat_stories()


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

try:
    import click
except ImportError:
    raise ImportError("Cauldron.ext.click requires the click package.")

from ...api import use

__all__ = ['backend', 'service']

def select_backend(ctx, param, value):
    """Callback to set the Cauldron backend."""
    if not value or ctx.resilient_parsing:
        return
    use(str(value))

def backend(default=None):
    """Click options to set up a Cauldron backend."""
    option = click.option("-k", "--backend", expose_value=False, is_eager=True,
                 callback=select_backend, help="Set the Cauldron backend.",
                 default=default)
    def decorate(func):
        return option(func)

    return decorate

backend_option = backend

def construct_service(ctx, param, value):
    """Construct a service."""
    if not value:
        return
    from Cauldron import ktl
    return ktl.Service(str(value))

def service(default=None, backend=True):
    """Add a service argument which returns a ktl.Service class."""
    option = click.option("-s", "--service", callback=construct_service,
                          help="KTL Service name to use.", default=default)

    backend_default = None
    if backend and isinstance(backend, str):
        backend_default = backend

    def decorate(func):
        if backend:
            func = backend_option(default=backend_default)(func)
        return option(func)
    return decorate

Fix a bug in Cauldron click extension

Fix a bug in Cauldron click extension

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

try:
    import click
except ImportError:
    raise ImportError("Cauldron.ext.click requires the click package.")

from ...api import use

__all__ = ['backend', 'service']

def select_backend(ctx, param, value):
    """Callback to set the Cauldron backend."""
    if not value or ctx.resilient_parsing:
        return
    use(str(value))

def backend(default=None):
    """Click options to set up a Cauldron backend."""
    option = click.option("-k", "--backend", expose_value=False, is_eager=True,
                 callback=select_backend, help="Set the Cauldron backend.",
                 default=default)
    def decorate(func):
        return option(func)

    return decorate

backend_option = backend

def construct_service(ctx, param, value):
    """Construct a service."""
    if not value:
        return
    from Cauldron import ktl
    return ktl.Service(str(value))

def service(default=None, backend=True):
    """Add a service argument which returns a ktl.Service class."""
    option = click.option("-s", "--service", callback=construct_service,
                          help="KTL Service name to use.", default=default)

    backend_default = None
    if backend and isinstance(backend, str):
        backend_default = backend

    def decorate(func):
        if backend:
            func = backend_option(default=backend_default)(func)
        return option(func)
    return decorate

Prompt:
Fix a bug in Cauldron click extension

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

try:
    import click
except ImportError:
    raise ImportError("Cauldron.ext.click requires the click package.")

from ...api import use

__all__ = ['backend', 'service']

def select_backend(ctx, param, value):
    """Callback to set the Cauldron backend."""
    if not value or ctx.resilient_parsing:
        return
    use(str(value))

def backend(default=None):
    """Click options to set up a Cauldron backend."""
    option = click.option("-k", "--backend", expose_value=False, is_eager=True,
                 callback=select_backend, help="Set the Cauldron backend.",
                 default=default)
    def decorate(func):
        return option(func)

    return decorate

backend_option = backend

def construct_service(ctx, param, value):
    """Construct a service."""
    if not value:
        return
    from Cauldron import ktl
    return ktl.Service(str(value))

def service(default=None, backend=True):
    """Add a service argument which returns a ktl.Service class."""
    option = click.option("-s", "--service", callback=construct_service,
                          help="KTL Service name to use.", default=default)

    backend_default = None
    if backend and isinstance(backend, str):
        backend_default = backend

    def decorate(func):
        if backend:
            func = backend_option(default=backend_default)(func)
        return option(func)


# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-09-11 21:35
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('resale', '0003_change_coords'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='resaleapartment',
            options={'ordering': ('-id',), 'permissions': (('can_add_change_delete_all_resale', 'Имеет доступ к чужим данным по вторичке'),), 'verbose_name': 'объект вторичка', 'verbose_name_plural': 'объекты вторички'},
        ),
    ]

Add skipped migration in resale app connected with ordering.

Response:
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-09-11 21:35
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('resale', '0003_change_coords'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='resaleapartment',
            options={'ordering': ('-id',), 'permissions': (('can_add_change_delete_all_resale', 'Имеет доступ к чужим данным по вторичке'),), 'verbose_name': 'объект вторичка', 'verbose_name_plural': 'объекты вторички'},
        ),
    ]

Prompt: Add skipped migration in resale app connected with ordering.


"""Tests for functions that calculate plasma parameters using cython."""

import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter

from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants import c, m_p, m_e, e, mu0

from plasmapy.physics.parameters_cython import (thermal_speed,
                                 )
def test_thermal_speed():
    r"""Test for cythonized version of thermal_speed()."""
    trueVal = 593083.619464999
    T = 11604
    methodVal = thermal_speed(T, particle="e", method="most_probable")
    testTrue = np.isclose(methodVal,
                          trueVal,
                          rtol=0.0,
                          atol=1e-16)
    exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
    assert testTrue, exceptStr

Update tests for cython parameters

Update tests for cython parameters

Response:
"""Tests for functions that calculate plasma parameters using cython."""

import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter

from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants import c, m_p, m_e, e, mu0

from plasmapy.physics.parameters_cython import (thermal_speed,
                                 )
def test_thermal_speed():
    r"""Test for cythonized version of thermal_speed()."""
    trueVal = 593083.619464999
    T = 11604
    methodVal = thermal_speed(T, particle="e", method="most_probable")
    testTrue = np.isclose(methodVal,
                          trueVal,
                          rtol=0.0,
                          atol=1e-16)
    exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
    assert testTrue, exceptStr

Prompt:
Update tests for cython parameters

"""Tests for functions that calculate plasma parameters using cython."""

import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter

from ...utils.exceptions import RelativityWarning, RelativityError
from ...utils.exceptions import PhysicsError
from ...constants import c, m_p, m_e, e, mu0

from ..parameters_cython import (thermal_speed,
                                 )

def test_thermal_speed():
    r"""Test for cythonized version of thermal_speed()."""
    trueVal = 593083.619464999
    T = 11604
    methodVal = thermal_speed(T, particle="e", method="most_probable")
    testTrue = np.isclose(methodVal,
                          trueVal,
                          rtol=0.0,
                          atol=1e-16)
    exceptStr = f'Thermal speed value is {methodVal}, should be {trueVal}.'
    assert testTrue, exceptStr


from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache

class ManagerLRUCache(object):
    """ Override capacity in settings.
    """
    def __init__(self, name, default_capacity=100, threshold=.5):
        self.name = name
        self.default_capacity = default_capacity
        self.threshold = threshold

    @property
    def cache(self):
        if not manager.stack:
            return None
        threadlocals = manager.stack[0]
        if self.name not in threadlocals:
            registry = threadlocals['registry']
            capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
            threadlocals[self.name] = LRUCache(capacity, self.threshold)
        return threadlocals[self.name]

    def get(self, key, default=None):
        cache = self.cache
        if cache is None:
            return default
        try:
            return cache[key]
        except KeyError:
            return default

    def __contains__(self, key):
        cache = self.cache
        if cache is None:
            return False
        return key in cache

    def __setitem__(self, key, value):
        cache = self.cache
        if cache is None:
            return
        self.cache[key] = value

Response:
from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache

class ManagerLRUCache(object):
    """ Override capacity in settings.
    """
    def __init__(self, name, default_capacity=100, threshold=.5):
        self.name = name
        self.default_capacity = default_capacity
        self.threshold = threshold

    @property
    def cache(self):
        if not manager.stack:
            return None
        threadlocals = manager.stack[0]
        if self.name not in threadlocals:
            registry = threadlocals['registry']
            capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
            threadlocals[self.name] = LRUCache(capacity, self.threshold)
        return threadlocals[self.name]

    def get(self, key, default=None):
        cache = self.cache
        if cache is None:
            return default
        try:
            return cache[key]
        except KeyError:
            return default

    def __contains__(self, key):
        cache = self.cache
        if cache is None:
            return False
        return key in cache

    def __setitem__(self, key, value):
        cache = self.cache
        if cache is None:
            return
        self.cache[key] = value

Prompt:
Use LRUCache correctly (minimal improvement)

from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache

class ManagerLRUCache(object):
    """ Override capacity in settings.
    """
    def __init__(self, name, default_capacity=100, threshold=.5):
        self.name = name
        self.default_capacity = default_capacity
        self.threshold = threshold

    @property
    def cache(self):
        if not manager.stack:
            return None
        threadlocals = manager.stack[0]
        if self.name not in threadlocals:
            registry = threadlocals['registry']
            capacity = int(registry.settings.get(self.name + '.capacity', self.default_capacity))
            threadlocals[self.name] = LRUCache(capacity, self.threshold)
        return threadlocals[self.name]

    def get(self, key, default=None):
        cache = self.cache
        if cache is None:
            return
        cached = cache.get(key)
        if cached is not None:
            return cached[1]
        return default

    def __contains__(self, key):
        cache = self.cache
        if cache is None:
            return False
        return key in cache

    def __setitem__(self, key, value):
        cache = self.cache
        if cache is None:
            return
        self.cache[key] = value


import nltk.corpus.reader.bnc
import time

start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
                                            fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
                                            lazy=False)  # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')

Load BNC into memory and time process.

Load BNC into memory and time process.

Response:
import nltk.corpus.reader.bnc
import time

start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
                                            fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
                                            lazy=False)  # found here: https://github.com/nltk/nltk/issues/781 talk about how much more efficient it is
time_taken = time.perf_counter() - start_time
print('\n|| Successfully loaded the British National Corpus in {:.1f}'.format(time_taken), 'seconds. ||\n')

Prompt:
Load BNC into memory and time process.

import nltk.corpus.reader.bnc


import sys
import os

from os.path import join
from setuptools import setup

# Also in twarc.py
__version__ = '1.4.0'

if sys.version_info[0] < 3:
    dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
    dependencies = open(join('requirements', 'python3.txt')).read().split()

if __name__ == "__main__":
    setup(
        name='twarc',
        version=__version__,
        url='https://github.com/docnow/twarc',
        author='Ed Summers',
        author_email='ehs@pobox.com',
        packages=['twarc',],
        description='Archive tweets from the command line',
        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
        install_requires=dependencies,
        setup_requires=['pytest-runner'],
        tests_require=['pytest'],
        entry_points={'console_scripts': ['twarc = twarc:main']}
    )

Add python_requires to help pip

Response:
import sys
import os

from os.path import join
from setuptools import setup

# Also in twarc.py
__version__ = '1.4.0'

if sys.version_info[0] < 3:
    dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
    dependencies = open(join('requirements', 'python3.txt')).read().split()

if __name__ == "__main__":
    setup(
        name='twarc',
        version=__version__,
        url='https://github.com/docnow/twarc',
        author='Ed Summers',
        author_email='ehs@pobox.com',
        packages=['twarc',],
        description='Archive tweets from the command line',
        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
        install_requires=dependencies,
        setup_requires=['pytest-runner'],
        tests_require=['pytest'],
        entry_points={'console_scripts': ['twarc = twarc:main']}
    )

Prompt:
Add python_requires to help pip

When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.

For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450
import sys
import os

from os.path import join
from setuptools import setup

# Also in twarc.py
__version__ = '1.4.0'

if sys.version_info[0] < 3:
    dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
    dependencies = open(join('requirements', 'python3.txt')).read().split()

if __name__ == "__main__":
    setup(
        name='twarc',
        version=__version__,
        url='https://github.com/docnow/twarc',
        author='Ed Summers',
        author_email='ehs@pobox.com',
        packages=['twarc',],
        description='Archive tweets from the command line',
        install_requires=dependencies,
        setup_requires=['pytest-runner'],
        tests_require=['pytest'],
        entry_points={'console_scripts': ['twarc = twarc:main']}
    )


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

import unittest

from pyauto import PyUITest

class SimpleTest(PyUITest):

  def testCanOpenGoogle(self):
    self.NavigateToURL("http://www.google.com")

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

Create a placeholder for pyauto test scripts.

Including a hello world script.

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

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

Response:
#!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from pyauto import PyUITest

class SimpleTest(PyUITest):

  def testCanOpenGoogle(self):
    self.NavigateToURL("http://www.google.com")

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

Prompt:
Create a placeholder for pyauto test scripts.

Including a hello world script.

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

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


import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse

def our_app():
    app = Flask(__name__)
    app.test_value = 0
    FlaskJSON(app)

    @app.route('/increment')
    def increment():
        app.test_value += 1
        return json_response(value=app.test_value)

    return app

class OurAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = our_app()
        self.app.config['TESTING'] = True

        # We have to change response class manually since TESTING flag is
        # set after Flask-JSON initialization.
        self.app.response_class = JsonTestResponse
        self.client = self.app.test_client()

    def test_app(self):
        r = self.client.get('/increment')

        # Here is how we can access to JSON.
        assert 'value' in r.json
        assert r.json['value'] == 1

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

Add example usage of the JsonTestResponse.

Response:
import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse

def our_app():
    app = Flask(__name__)
    app.test_value = 0
    FlaskJSON(app)

    @app.route('/increment')
    def increment():
        app.test_value += 1
        return json_response(value=app.test_value)

    return app

class OurAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = our_app()
        self.app.config['TESTING'] = True

        # We have to change response class manually since TESTING flag is
        # set after Flask-JSON initialization.
        self.app.response_class = JsonTestResponse
        self.client = self.app.test_client()

    def test_app(self):
        r = self.client.get('/increment')

        # Here is how we can access to JSON.
        assert 'value' in r.json
        assert r.json['value'] == 1

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

Prompt: Add example usage of the JsonTestResponse.


from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check

@describe.attributes(
    W=Synapses("Weights matrix",
        lambda obj: (obj.nO, obj.nI),
        lambda W, ops: None)
)
class Softmax(Affine):
    name = 'softmax'
    @check.arg(1, has_shape(('nB', 'nI')))
    def predict(self, input__BI):
        output__BO = self.ops.affine(self.W, self.b, input__BI)
        output__BO = self.ops.softmax(output__BO, inplace=False)
        return output__BO

    @check.arg(1, has_shape(('nB', 'nI')))
    def begin_update(self, input__BI, drop=0.):
        output__BO = self.predict(input__BI)
        @check.arg(0, has_shape(('nB', 'nO')))
        def finish_update(grad__BO, sgd=None):
            self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True)
            self.d_b += grad__BO.sum(axis=0)
            grad__BI = self.ops.gemm(grad__BO, self.W)
            if sgd is not None:
                sgd(self._mem.weights, self._mem.gradient, key=self.id)
            return grad__BI
        return output__BO, finish_update

Fix gemm calls in Softmax

Fix gemm calls in Softmax

Response:
from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check

@describe.attributes(
    W=Synapses("Weights matrix",
        lambda obj: (obj.nO, obj.nI),
        lambda W, ops: None)
)
class Softmax(Affine):
    name = 'softmax'
    @check.arg(1, has_shape(('nB', 'nI')))
    def predict(self, input__BI):
        output__BO = self.ops.affine(self.W, self.b, input__BI)
        output__BO = self.ops.softmax(output__BO, inplace=False)
        return output__BO

    @check.arg(1, has_shape(('nB', 'nI')))
    def begin_update(self, input__BI, drop=0.):
        output__BO = self.predict(input__BI)
        @check.arg(0, has_shape(('nB', 'nO')))
        def finish_update(grad__BO, sgd=None):
            self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True)
            self.d_b += grad__BO.sum(axis=0)
            grad__BI = self.ops.gemm(grad__BO, self.W)
            if sgd is not None:
                sgd(self._mem.weights, self._mem.gradient, key=self.id)
            return grad__BI
        return output__BO, finish_update

Prompt:
Fix gemm calls in Softmax

from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check

@describe.attributes(
    W=Synapses("Weights matrix",
        lambda obj: (obj.nO, obj.nI),
        lambda W, ops: None)
)
class Softmax(Affine):
    name = 'softmax'
    @check.arg(1, has_shape(('nB', 'nI')))
    def predict(self, input__BI):
        output__BO = self.ops.affine(self.W, self.b, input__BI)
        output__BO = self.ops.softmax(output__BO, inplace=False)
        return output__BO

    @check.arg(1, has_shape(('nB', 'nI')))
    def begin_update(self, input__BI, drop=0.):
        output__BO = self.predict(input__BI)
        @check.arg(0, has_shape(('nB', 'nO')))
        def finish_update(grad__BO, sgd=None):
            self.d_W += self.ops.batch_outer(grad__BO, input__BI)
            self.d_b += grad__BO.sum(axis=0)
            grad__BI = self.ops.dot(grad__BO, self.W)
            if sgd is not None:
                sgd(self._mem.weights, self._mem.gradient, key=self.id)
            return grad__BI
        return output__BO, finish_update


from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest

test_data = """
@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://example.org/alice> a foaf:Person;
    foaf:name "Alice";
    foaf:knows <http://example.org/bob> ."""

test_query = """
BASE <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE { [ a :Person; :name ?name ]. }
}"""

class TestSparqlJsonResults(unittest.TestCase):

    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringIO(test_data), format="n3")

    def test_base_ref(self):
        rt=self.graph.query(test_query).serialize("python")
        self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)

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

Test for use of BASE <..>

Test for use of BASE <..>

Response:
from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest

test_data = """
@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://example.org/alice> a foaf:Person;
    foaf:name "Alice";
    foaf:knows <http://example.org/bob> ."""

test_query = """
BASE <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE { [ a :Person; :name ?name ]. }
}"""

class TestSparqlJsonResults(unittest.TestCase):

    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringIO(test_data), format="n3")

    def test_base_ref(self):
        rt=self.graph.query(test_query).serialize("python")
        self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)

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

Prompt: Test for use of BASE <..>