#!/usr/bin/env python
##########################################################################
#
# Copyright 2012 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/

import sys

if len(sys.argv) <= 1:
	print 'Please specify a file to read'
	sys.exit()

shaderTimes = {}
activeShader = 0

for line in open(sys.argv[1], 'r'):
    words = line.split(' ')

    if line.startswith('#'):
        continue

    if words[0:3] == ['use','shader','program']:
        activeShader = long(words[3])
    elif words[0] == 'call':
        id = long(words[1])
        func = words[-1]
        duration = long(words[3])

        if shaderTimes.has_key(activeShader):
            shaderTimes[activeShader]['draws'] += 1
            shaderTimes[activeShader]['duration'] += duration
            if duration > shaderTimes[activeShader]['longestDuration']:
                shaderTimes[activeShader]['longest'] = id
                shaderTimes[activeShader]['longestDuration'] = duration
        else:
            shaderTimes[activeShader] = {'draws': 1, 'duration': duration, 'longest': id, 'longestDuration': duration}

sortedShaderTimes = sorted(shaderTimes.items(), key=lambda x: x[1]['duration'], reverse=True)

print '+------------+--------------+--------------------+--------------+-------------+'
print '| Shader[id] |   Draws [#]  |   Duration [ns]  v | Per Call[ns] | Longest[id] |'
print '+------------+--------------+--------------------+--------------+-------------+'

for shader in sortedShaderTimes:
    id = str(shader[0]).rjust(10)
    draw = str(shader[1]['draws']).rjust(12)
    dura = str(shader[1]['duration']).rjust(18)
    perCall = str(shader[1]['duration'] / shader[1]['draws']).rjust(12)
    longest = str(shader[1]['longest']).rjust(11)
    print "| %s | %s | %s | %s | %s |" % (id, draw, dura, perCall, longest)

print '+------------+--------------+--------------------+--------------+-------------+'

Add a script to analyse profile output per shader.

Response:
#!/usr/bin/env python
##########################################################################
#
# Copyright 2012 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/

import sys

if len(sys.argv) <= 1:
	print 'Please specify a file to read'
	sys.exit()

shaderTimes = {}
activeShader = 0

for line in open(sys.argv[1], 'r'):
    words = line.split(' ')

    if line.startswith('#'):
        continue

    if words[0:3] == ['use','shader','program']:
        activeShader = long(words[3])
    elif words[0] == 'call':
        id = long(words[1])
        func = words[-1]
        duration = long(words[3])

        if shaderTimes.has_key(activeShader):
            shaderTimes[activeShader]['draws'] += 1
            shaderTimes[activeShader]['duration'] += duration
            if duration > shaderTimes[activeShader]['longestDuration']:
                shaderTimes[activeShader]['longest'] = id
                shaderTimes[activeShader]['longestDuration'] = duration
        else:
            shaderTimes[activeShader] = {'draws': 1, 'duration': duration, 'longest': id, 'longestDuration': duration}

sortedShaderTimes = sorted(shaderTimes.items(), key=lambda x: x[1]['duration'], reverse=True)

print '+------------+--------------+--------------------+--------------+-------------+'
print '| Shader[id] |   Draws [#]  |   Duration [ns]  v | Per Call[ns] | Longest[id] |'
print '+------------+--------------+--------------------+--------------+-------------+'

for shader in sortedShaderTimes:
    id = str(shader[0]).rjust(10)
    draw = str(shader[1]['draws']).rjust(12)
    dura = str(shader[1]['duration']).rjust(18)
    perCall = str(shader[1]['duration'] / shader[1]['draws']).rjust(12)
    longest = str(shader[1]['longest']).rjust(11)
    print "| %s | %s | %s | %s | %s |" % (id, draw, dura, perCall, longest)

print '+------------+--------------+--------------------+--------------+-------------+'

Prompt: Add a script to analyse profile output per shader.


from twisted.plugin import IPlugin
from txircd.factory import UserFactory
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements

class StatsPorts(ModuleData):
	implements(IPlugin, IModuleData)

	name = "StatsPorts"

	def actions(self):
		return [ ("statsruntype-ports", 10, self.listPorts) ]

	def listPorts(self):
		info = {}
		for portDesc, portData in self.ircd.boundPorts.iteritems():
			if isinstance(portData.factory, UserFactory):
				info[str(portData.port)] = "{} (clients)".format(portDesc)
			else:
				info[str(portData.port)] = "{} (servers)".format(portDesc)
		return info

statsPorts = StatsPorts()

Add STATS type to display the ports that the server is listening on

Response:
from twisted.plugin import IPlugin
from txircd.factory import UserFactory
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements

class StatsPorts(ModuleData):
	implements(IPlugin, IModuleData)

	name = "StatsPorts"

	def actions(self):
		return [ ("statsruntype-ports", 10, self.listPorts) ]

	def listPorts(self):
		info = {}
		for portDesc, portData in self.ircd.boundPorts.iteritems():
			if isinstance(portData.factory, UserFactory):
				info[str(portData.port)] = "{} (clients)".format(portDesc)
			else:
				info[str(portData.port)] = "{} (servers)".format(portDesc)
		return info

statsPorts = StatsPorts()

Prompt: Add STATS type to display the ports that the server is listening on


#!/usr/bin/env python
import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser

class PPSSPPGenerator(Generator):
    # Main entry of the module
    # Configure fba and return a command
    def generate(self, system, rom, playersControllers):
        if not system.config['configfile']:
            for index in playersControllers :
                controller = playersControllers[index]
                # we only care about player 1
                if controller.player != "1":
                    continue
                ppssppControllers.generateControllerConfig(controller)
                break

        # the command to run
        commandArray = [recalboxFiles.recalboxBins[system.config['emulator']], rom]
        # The next line is a reminder on how to quit PPSSPP with just the HK
        #commandArray = [recalboxFiles.recalboxBins[system.config['emulator']], rom, "--escape-exit"]
        return Command.Command(videomode=system.config['videomode'], array=commandArray, env={"XDG_CONFIG_HOME":recalboxFiles.CONF, "SDL_VIDEO_GL_DRIVER": "/usr/lib/libGLESv2.so"}, delay=1)

Remove a bad typo from reicast

Remove a bad typo from reicast

Response:
#!/usr/bin/env python
import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser

class PPSSPPGenerator(Generator):
    # Main entry of the module
    # Configure fba and return a command
    def generate(self, system, rom, playersControllers):
        if not system.config['configfile']:
            for index in playersControllers :
                controller = playersControllers[index]
                # we only care about player 1
                if controller.player != "1":
                    continue
                ppssppControllers.generateControllerConfig(controller)
                break

        # the command to run
        commandArray = [recalboxFiles.recalboxBins[system.config['emulator']], rom]
        # The next line is a reminder on how to quit PPSSPP with just the HK
        #commandArray = [recalboxFiles.recalboxBins[system.config['emulator']], rom, "--escape-exit"]
        return Command.Command(videomode=system.config['videomode'], array=commandArray, env={"XDG_CONFIG_HOME":recalboxFiles.CONF, "SDL_VIDEO_GL_DRIVER": "/usr/lib/libGLESv2.so"}, delay=1)

Prompt:
Remove a bad typo from reicast

#!/usr/bin/env python
import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser

class PPSSPPGenerator(Generator):
    # Main entry of the module
    # Configure fba and return a command
    def generate(self, system, rom, playersControllers):
        if not system.config['configfile']:
            # Write emu.cfg to map joysticks, init with the default emu.cfg
            Config = ConfigParser.ConfigParser()
            Config.read(recalboxFiles.reicastConfigInit)
            section = "input"
            # For each pad detected
            for index in playersControllers :
                controller = playersControllers[index]
                # we only care about player 1
                if controller.player != "1":
                    continue
                ppssppControllers.generateControllerConfig(controller)

        # the command to run
        #~ commandArray = [recalboxFiles.ppssppBin, rom, "--escape-exit"]
        commandArray = [recalboxFiles.recalboxBins[system.config['emulator']], rom]
        return Command.Command(videomode=system.config['videomode'], array=commandArray, env={"XDG_CONFIG_HOME":recalboxFiles.CONF, "SDL_VIDEO_GL_DRIVER": "/usr/lib/libGLESv2.so"}, delay=1)


from __future__ import unicode_literals

from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _

class TimestampMixin(models.Model):
    """Mixin for date and timestamp. Inherits django's models.Model."""

    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class SlugifyMixin():
    """
    Slugify specific field and pass as value to slug field in the model.

    This mixin helps in solving the problem of having case insensitive duplicates
    by creating a slug and ensuring uniqueness.
    Model field to be slugified should be passed as a string into a variable
    called slugify_field.
    Slug field in the model should be named slug.
    """

    def clean(self):
        if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
            slugify_field_value = getattr(self, self.slugify_field)
            self.slug = slugify(slugify_field_value)

            if self.__class__.objects.filter(slug=self.slug).exists():
                raise ValidationError(_("Entry with {0} - {1} already exists.".format(
                                        self.slugify_field, slugify_field_value)))

    def save(self, *args, **kwargs):
        self.clean()
        return super().save(*args, **kwargs)

Response:
from __future__ import unicode_literals

from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _

class TimestampMixin(models.Model):
    """Mixin for date and timestamp. Inherits django's models.Model."""

    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class SlugifyMixin():
    """
    Slugify specific field and pass as value to slug field in the model.

    This mixin helps in solving the problem of having case insensitive duplicates
    by creating a slug and ensuring uniqueness.
    Model field to be slugified should be passed as a string into a variable
    called slugify_field.
    Slug field in the model should be named slug.
    """

    def clean(self):
        if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
            slugify_field_value = getattr(self, self.slugify_field)
            self.slug = slugify(slugify_field_value)

            if self.__class__.objects.filter(slug=self.slug).exists():
                raise ValidationError(_("Entry with {0} - {1} already exists.".format(
                                        self.slugify_field, slugify_field_value)))

    def save(self, *args, **kwargs):
        self.clean()
        return super().save(*args, **kwargs)

Prompt:
Return user-friendly error message for SlugifyMixin class

from __future__ import unicode_literals

from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify

class TimestampMixin(models.Model):
    """Mixin for date and timestamp. Inherits django's models.Model."""

    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class SlugifyMixin():
    """
    Slugify specific field and pass as value to slug field in the model.

    This mixin helps in solving the problem of having case insensitive duplicates
    by creating a slug and ensuring uniqueness.
    Model field to be slugified should be passed as a string into a variable
    called slugify_field.
    Slug field in the model should be named slug.
    """

    def clean(self):
        if hasattr(self, 'slugify_field') and hasattr(self, 'slug'):
            self.slug = slugify(getattr(self, self.slugify_field))

            if self.__class__.objects.filter(slug=self.slug).exists():
                raise ValidationError("This object already exists.")

    def save(self, *args, **kwargs):
        self.clean()
        return super().save(*args, **kwargs)


# Created by JHJ on 2016. 10. 5.

from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static

from . import views

app_name = 'board'
urlpatterns = [
    url(r'^$', views.board_list, name='board_list'),
    url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
    url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
    url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
    url(r'^(?P<post_id>\d+)/like/$', views.like_post, name='like_post'),
    url(r'^(?P<post_id>\d+)/edit/$', views.edit_post, name='edit_post'),
    url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
    url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
    url(r'^(?P<post_id>\d+)/comment/(?P<comment_id>\d+)/delete/$', views.delete_comment, name='delete_comment'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Response:
# Created by JHJ on 2016. 10. 5.

from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static

from . import views

app_name = 'board'
urlpatterns = [
    url(r'^$', views.board_list, name='board_list'),
    url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
    url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
    url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
    url(r'^(?P<post_id>\d+)/like/$', views.like_post, name='like_post'),
    url(r'^(?P<post_id>\d+)/edit/$', views.edit_post, name='edit_post'),
    url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
    url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
    url(r'^(?P<post_id>\d+)/comment/(?P<comment_id>\d+)/delete/$', views.delete_comment, name='delete_comment'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Prompt:
Set url to serve uploaded file during development

# Created by JHJ on 2016. 10. 5.

from django.conf.urls import url

from . import views

app_name = 'board'
urlpatterns = [
    url(r'^$', views.board_list, name='board_list'),
    url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'),
    url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'),
    url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
    url(r'^(?P<post_id>\d+)/like/$', views.like_post, name='like_post'),
    url(r'^(?P<post_id>\d+)/edit/$', views.edit_post, name='edit_post'),
    url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'),
    url(r'^(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
    url(r'^(?P<post_id>\d+)/comment/(?P<comment_id>\d+)/delete/$', views.delete_comment, name='delete_comment'),
]


r"""

**openpnm.models.geometry**

----

This submodule contains pore-scale models that calculate geometrical properties

"""

from . import pore_size
from . import pore_seed
from . import pore_volume
from . import pore_surface_area
from . import pore_area
from . import throat_centroid
from . import throat_area
from . import throat_size
from . import throat_length
from . import throat_perimeter
from . import throat_surface_area
from . import throat_volume
from . import throat_shape_factor

Update init file in models.geometry

Update init file in models.geometry

Response:
r"""

**openpnm.models.geometry**

----

This submodule contains pore-scale models that calculate geometrical properties

"""

from . import pore_size
from . import pore_seed
from . import pore_volume
from . import pore_surface_area
from . import pore_area
from . import throat_centroid
from . import throat_area
from . import throat_size
from . import throat_length
from . import throat_perimeter
from . import throat_surface_area
from . import throat_volume
from . import throat_shape_factor

Prompt:
Update init file in models.geometry
r"""

**openpnm.models.geometry**

----

This submodule contains pore-scale models that calculate geometrical properties

"""

from . import pore_size
from . import pore_seed
from . import pore_volume
from . import pore_surface_area
from . import pore_area
from . import throat_area
from . import throat_equivalent_area
from . import throat_size
from . import throat_length
from . import throat_perimeter
from . import throat_surface_area
from . import throat_volume
from . import throat_shape_factor


CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"

DEFAULT_CONFIG = {
  "server": {
    "protocol": "https",
    "host": "synapse.isrd.isi.edu",
    "catalog_id": 1
  },
  "viewer_mode": "2d",
  "curator_mode": False,
  "cache_dir": "~/synspy"
}

Set prod server as config default.

Set prod server as config default.

Response:
CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"

DEFAULT_CONFIG = {
  "server": {
    "protocol": "https",
    "host": "synapse.isrd.isi.edu",
    "catalog_id": 1
  },
  "viewer_mode": "2d",
  "curator_mode": False,
  "cache_dir": "~/synspy"
}

Prompt:
Set prod server as config default.

CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"

DEFAULT_CONFIG = {
  "server": {
    "protocol": "https",
    "host": "",
    "catalog_id": 1
  },
  "viewer_mode": "2d",
  "curator_mode": False,
  "cache_dir": "~/synspy"
}


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

from xmanager.xm_local import experiment
from xmanager.xm_local.executors import *

create_experiment = experiment.create_experiment

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

from xmanager.xm_local import experiment
from xmanager.xm_local.executors import *

create_experiment = experiment.create_experiment

Prompt:
Make `DockerOptions` part of the `xm_local` module

PiperOrigin-RevId: 376139511
Change-Id: Ia0ec1337b9ef2c175dea6b0c45e0a99b285d2b31
GitOrigin-RevId: 799d3ef6a98a6e4922b0b60c190c0d82cd538548

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

from xmanager.xm_local import experiment
from xmanager.xm_local.executors import Caip
from xmanager.xm_local.executors import Kubernetes
from xmanager.xm_local.executors import Local
from xmanager.xm_local.executors import TensorboardCapability

create_experiment = experiment.create_experiment


import argparse
import re

from omftools.pyshadowdive.language import LanguageFile

re_non_alphanumeric = re.compile(r'[\W]+')

def txt(text: str) -> str:
    o = text.replace(' ', '_')
    o = re.sub(re_non_alphanumeric, '', o)
    o = o.upper()
    return o

def generate_enum(in_file: str, out_file: str):
    language = LanguageFile.load_native(in_file)
    assert len(language.titles) == len(language.strings)

    pairs = [(title, text) for title, text in zip(language.titles, language.strings)]
    with open(out_file, "wb") as fd:
        fd.write("enum TRANSLATION {\n".encode())

        for index, pair in enumerate(pairs, start=1):
            title, text = pair
            title = txt(title) if title else 'NONE'
            text = txt(text) if text else f'NONE_{index}'
            fd.write(f"    TXT__{title}__{text[:24]} = {index};\n".encode())

        fd.write("};\n".encode())

def main():
    parser = argparse.ArgumentParser(description="Generate enum header for language file")
    parser.add_argument("input_file", help="Input file")
    parser.add_argument("output_file", help="Output file")
    args = parser.parse_args()

    generate_enum(args.input_file, args.output_file)

if __name__ == "__main__":
    main()

Add tool for generating transtions enum

Add tool for generating transtions enum

Response:
import argparse
import re

from omftools.pyshadowdive.language import LanguageFile

re_non_alphanumeric = re.compile(r'[\W]+')

def txt(text: str) -> str:
    o = text.replace(' ', '_')
    o = re.sub(re_non_alphanumeric, '', o)
    o = o.upper()
    return o

def generate_enum(in_file: str, out_file: str):
    language = LanguageFile.load_native(in_file)
    assert len(language.titles) == len(language.strings)

    pairs = [(title, text) for title, text in zip(language.titles, language.strings)]
    with open(out_file, "wb") as fd:
        fd.write("enum TRANSLATION {\n".encode())

        for index, pair in enumerate(pairs, start=1):
            title, text = pair
            title = txt(title) if title else 'NONE'
            text = txt(text) if text else f'NONE_{index}'
            fd.write(f"    TXT__{title}__{text[:24]} = {index};\n".encode())

        fd.write("};\n".encode())

def main():
    parser = argparse.ArgumentParser(description="Generate enum header for language file")
    parser.add_argument("input_file", help="Input file")
    parser.add_argument("output_file", help="Output file")
    args = parser.parse_args()

    generate_enum(args.input_file, args.output_file)

if __name__ == "__main__":
    main()

Prompt: Add tool for generating transtions enum


"""
Interface to sed engine
- defines objects exported from this module
"""
from sed.engine.StreamEditor import StreamEditor
from sed.engine.sed_file_util import call_main
from sed.engine.match_engine import (
    ACCEPT,
    REJECT,
    NEXT,
    REPEAT,
    CUT,
)
from sed.engine.sed_regex import ANY

__all__ = [
    "StreamEditor",
    "call_main",
    "ACCEPT", "REJECT", "NEXT", "REPEAT", "CUT",
    "ANY",
]

Response:
"""
Interface to sed engine
- defines objects exported from this module
"""
from sed.engine.StreamEditor import StreamEditor
from sed.engine.sed_file_util import call_main
from sed.engine.match_engine import (
    ACCEPT,
    REJECT,
    NEXT,
    REPEAT,
    CUT,
)
from sed.engine.sed_regex import ANY

__all__ = [
    "StreamEditor",
    "call_main",
    "ACCEPT", "REJECT", "NEXT", "REPEAT", "CUT",
    "ANY",
]

Prompt:
Add CUT to list of externally visible objects

from sed.engine.StreamEditor import StreamEditor
from sed.engine.sed_file_util import call_main
from sed.engine.match_engine import ACCEPT, REJECT, NEXT, REPEAT, CUT
from sed.engine.sed_regex import ANY

__all__ = [
    "StreamEditor",
    "call_main",
    "ACCEPT", "REJECT", "NEXT", "REPEAT",
    "ANY",
]


# Skipping test_parser and test_all_fixers
# because of running
from lib2to3.tests import test_fixers, test_pytree, test_util
import unittest
from test.test_support import run_unittest, requires

# Don't run lib2to3 tests by default since they take too long
if __name__ != '__main__':
    requires('lib2to3')

def suite():
    tests = unittest.TestSuite()
    loader = unittest.TestLoader()
    for m in (test_fixers,test_pytree,test_util):
        tests.addTests(loader.loadTestsFromModule(m))
    return tests

def test_main():
    run_unittest(suite())

if __name__ == '__main__':
    test_main()

Response:
# Skipping test_parser and test_all_fixers
# because of running
from lib2to3.tests import test_fixers, test_pytree, test_util
import unittest
from test.test_support import run_unittest, requires

# Don't run lib2to3 tests by default since they take too long
if __name__ != '__main__':
    requires('lib2to3')

def suite():
    tests = unittest.TestSuite()
    loader = unittest.TestLoader()
    for m in (test_fixers,test_pytree,test_util):
        tests.addTests(loader.loadTestsFromModule(m))
    return tests

def test_main():
    run_unittest(suite())

if __name__ == '__main__':
    test_main()

Prompt:
Disable lib2to3 by default, unless run explicitly.

# Skipping test_parser and test_all_fixers
# because of running
from lib2to3.tests import test_fixers, test_pytree, test_util
import unittest
from test.test_support import run_unittest

def suite():
    tests = unittest.TestSuite()
    loader = unittest.TestLoader()
    for m in (test_fixers,test_pytree,test_util):
        tests.addTests(loader.loadTestsFromModule(m))
    return tests

def test_main():
    run_unittest(suite())

if __name__ == '__main__':
    test_main()


from sqlobject import *
from sqlobject.tests.dbtest import *

########################################
# Test hashing a column instance
########################################

class ClassHashTest(SQLObject):
    name = StringCol(length=50, alternateID=True, dbName='name_col')

def test_class_hash():
    setupClass(ClassHashTest)
    ClassHashTest(name='bob')

    b = ClassHashTest.byName('bob')
    hashed = hash(b)
    b.expire()
    b = ClassHashTest.byName('bob')
    assert hash(b) == hashed

Fix flake8 warning in test case

Fix flake8 warning in test case

Response:
from sqlobject import *
from sqlobject.tests.dbtest import *

########################################
# Test hashing a column instance
########################################

class ClassHashTest(SQLObject):
    name = StringCol(length=50, alternateID=True, dbName='name_col')

def test_class_hash():
    setupClass(ClassHashTest)
    ClassHashTest(name='bob')

    b = ClassHashTest.byName('bob')
    hashed = hash(b)
    b.expire()
    b = ClassHashTest.byName('bob')
    assert hash(b) == hashed

Prompt:
Fix flake8 warning in test case

from sqlobject import *
from sqlobject.tests.dbtest import *

########################################
# Test hashing a column instance
########################################

class ClassHashTest(SQLObject):
    name = StringCol(length=50, alternateID=True, dbName='name_col')

def test_class_hash():
    setupClass(ClassHashTest)
    ClassHashTest(name='bob')

    conn = ClassHashTest._connection
    b = ClassHashTest.byName('bob')
    hashed = hash(b)
    b.expire()
    b = ClassHashTest.byName('bob')
    assert hash(b) == hashed


import xyz
import os
import shutil

class Binutils(xyz.BuildProtocol):
    pkg_name = 'binutils'
    supported_targets = ['arm-none-eabi']

    def check(self, builder):
        if builder.target not in self.supported_targets:
            raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name))

    def configure(self, builder, config):
        builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib',
                                 config=config)

    def install(self, builder, config):
        super().install(builder, config)
        # For some reason binutils plonks libiberty.a in the output directory
        libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config)
        if os.path.exists(libdir):
            shutil.rmtree(libdir)
        # For now we strip the man pages.
        # man pages created on different systems are (for no good reason) different!
        man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config)
        shutil.rmtree(man_dir)

        # For now we strip the info pages too.
        # Different versino of texinfo product different output!
        info_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'info', config=config)
        shutil.rmtree(info_dir)

rules = Binutils()

Remove info dirs (for now)

Remove info dirs (for now)

Response:
import xyz
import os
import shutil

class Binutils(xyz.BuildProtocol):
    pkg_name = 'binutils'
    supported_targets = ['arm-none-eabi']

    def check(self, builder):
        if builder.target not in self.supported_targets:
            raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name))

    def configure(self, builder, config):
        builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib',
                                 config=config)

    def install(self, builder, config):
        super().install(builder, config)
        # For some reason binutils plonks libiberty.a in the output directory
        libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config)
        if os.path.exists(libdir):
            shutil.rmtree(libdir)
        # For now we strip the man pages.
        # man pages created on different systems are (for no good reason) different!
        man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config)
        shutil.rmtree(man_dir)

        # For now we strip the info pages too.
        # Different versino of texinfo product different output!
        info_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'info', config=config)
        shutil.rmtree(info_dir)

rules = Binutils()

Prompt:
Remove info dirs (for now)

import xyz
import os
import shutil

class Binutils(xyz.BuildProtocol):
    pkg_name = 'binutils'
    supported_targets = ['arm-none-eabi']

    def check(self, builder):
        if builder.target not in self.supported_targets:
            raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg_name))

    def configure(self, builder, config):
        builder.cross_configure('--disable-nls', '--enable-lto', '--enable-ld=yes', '--without-zlib',
                                 config=config)

    def install(self, builder, config):
        super().install(builder, config)
        # For some reason binutils plonks libiberty.a in the output directory
        libdir = builder.j('{install_dir_abs}', config['eprefix'][1:], 'lib', config=config)
        if os.path.exists(libdir):
            shutil.rmtree(libdir)
        # For now we strip the man pages.
        # man pages created on different systems are (for no good reason) different!
        man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config)
        shutil.rmtree(man_dir)

rules = Binutils()


#!/usr/bin/python
import json
import urllib
import sys

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits: print ' ', h['url']
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

if __name__ == '__main__':
  if len (sys.argv) < 2:
    print 'Usage: %s <search term>' % sys.argv[0]
    print '  Try using quotes if you want multiple terms'
    print '  Eg %s \"test results\"' % sys.argv[0]
    sys.exit(1)
  showsome(sys.argv[1])

Response:
#!/usr/bin/python
import json
import urllib
import sys

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits: print ' ', h['url']
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

if __name__ == '__main__':
  if len (sys.argv) < 2:
    print 'Usage: %s <search term>' % sys.argv[0]
    print '  Try using quotes if you want multiple terms'
    print '  Eg %s \"test results\"' % sys.argv[0]
    sys.exit(1)
  showsome(sys.argv[1])

Prompt:
Update of the google search code to be a command line program.

#!/usr/bin/python
import json
import urllib

def showsome(searchfor):
  query = urllib.urlencode({'q': searchfor})
  url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
  search_response = urllib.urlopen(url)
  search_results = search_response.read()
  results = json.loads(search_results)
  data = results['responseData']
  print 'Total results: %s' % data['cursor']['estimatedResultCount']
  hits = data['results']
  print 'Top %d hits:' % len(hits)
  for h in hits: print ' ', h['url']
  print 'For more results, see %s' % data['cursor']['moreResultsUrl']

showsome('gallery.php-systems.com')


import torchaudio
import librosa

# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio

T = torchaudio.transforms

# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]

audio_data = torch.tensor(audio_data).float().to(device)

# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack.

# resample the audio files to 8kHz from 16kHz
sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation")

audio_resample_1 = sample(audio_data)

# resample the audio back to 16kHz
sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation")

# Give audio_resample_2 as input to the asr model
audio_resample_2 = sample(audio_resample_1)

Format the code to black

Format the code to black

Response:
import torchaudio
import librosa

# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio

T = torchaudio.transforms

# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]

audio_data = torch.tensor(audio_data).float().to(device)

# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation, thereby prevents an adversarial attack.

# resample the audio files to 8kHz from 16kHz
sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation")

audio_resample_1 = sample(audio_data)

# resample the audio back to 16kHz
sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation")

# Give audio_resample_2 as input to the asr model
audio_resample_2 = sample(audio_resample_1)

Prompt:
Format the code to black
import torchaudio
import librosa

# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio

T = torchaudio.transforms

# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]

audio_data = torch.tensor(audio_data).float().to(device)

# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation,
# thereby prevents an adversarial attack.

# resample the audio files to 8kHz from 16kHz
sample = T.Resample(16000, 8000, resampling_method="sinc_interpolation")

audio_resample_1 = sample(audio_data)

# resample the audio back to 16kHz
sample = T.Resample(8000, 16000, resampling_method="sinc_interpolation")

# Give audio_resample_2 as input to the asr model
audio_resample_2 = sample(audio_resample_1)


from flask_mail import Message

from zou.app import mail, app

def send_email(subject, body, recipient_email, html=None):
    """
    Send an email with given subject and body to given recipient.
    """
    if html is None:
        html = body
    with app.app_context():
        mail_default_sender = app.config["MAIL_DEFAULT_SENDER"]
        message = Message(
            sender="Kitsu Bot <%s>" % mail_default_sender,
            body=body,
            html=html,
            subject=subject,
            recipients=[recipient_email]
        )
        mail.send(message)

Response:
from flask_mail import Message

from zou.app import mail, app

def send_email(subject, body, recipient_email, html=None):
    """
    Send an email with given subject and body to given recipient.
    """
    if html is None:
        html = body
    with app.app_context():
        mail_default_sender = app.config["MAIL_DEFAULT_SENDER"]
        message = Message(
            sender="Kitsu Bot <%s>" % mail_default_sender,
            body=body,
            html=html,
            subject=subject,
            recipients=[recipient_email]
        )
        mail.send(message)

Prompt:
Fix configuration of email default sender

from flask_mail import Message

from zou.app import mail, app

def send_email(subject, body, recipient_email, html=None):
    """
    Send an email with given subject and body to given recipient.
    """
    if html is None:
        html = body
    with app.app_context():
        message = Message(
            sender="Kitsu Bot <no-reply@cg-wire.com>",
            body=body,
            html=html,
            subject=subject,
            recipients=[recipient_email]
        )
        mail.send(message)


# Generated by Django 3.2.4 on 2021-10-27 14:41

from django.db import migrations

def get_birth_year(apps, schema_editor):
    Person = apps.get_model("people", "Person")
    for person in Person.objects.exclude(birth_date="").iterator():
        birth_year = person.birth_date.split("-")[0]
        person.birth_date = birth_year
        person.save()

class Migration(migrations.Migration):

    dependencies = [("people", "0033_auto_20210928_1007")]

    operations = [
        migrations.RunPython(get_birth_year, migrations.RunPython.noop)
    ]

Response:
# Generated by Django 3.2.4 on 2021-10-27 14:41

from django.db import migrations

def get_birth_year(apps, schema_editor):
    Person = apps.get_model("people", "Person")
    for person in Person.objects.exclude(birth_date="").iterator():
        birth_year = person.birth_date.split("-")[0]
        person.birth_date = birth_year
        person.save()

class Migration(migrations.Migration):

    dependencies = [("people", "0033_auto_20210928_1007")]

    operations = [
        migrations.RunPython(get_birth_year, migrations.RunPython.noop)
    ]

Prompt:
Improve performance of birth date data migration

# Generated by Django 3.2.4 on 2021-10-27 14:41

from django.db import migrations

def get_birth_year(apps, schema_editor):
    Person = apps.get_model("people", "Person")
    for person in Person.objects.all():
        birth_year = person.birth_date.split("-")[0]
        person.birth_date = birth_year
        person.save()

class Migration(migrations.Migration):

    dependencies = [("people", "0033_auto_20210928_1007")]

    operations = [
        migrations.RunPython(get_birth_year, migrations.RunPython.noop)
    ]


from . import google_drive
from grow.pods import pods
from grow.pods import storage
from grow.testing import testing
import cStringIO
import csv
import json
import unittest
import yaml

class BloggerTestCase(testing.TestCase):

    def test_run(self):
        pod = testing.create_pod()
        fields = {
            'preprocessors': [{
                'name': 'blogger',
                'kind': 'blogger',
                'blog_id': '4154157974596966834',
                'collection': '/content/posts/',
                'markdown': True,
                'authenticated': False,
                'inject': True,
            }],
        }
        pod.write_yaml('/podspec.yaml', fields)
        fields = {
            '$path': '/{date}/{slug}/',
            '$view': '/views/base.html',
        }
        pod.write_yaml('/content/posts/_blueprint.yaml', fields)
        content = '{{doc.html|safe}}'
        pod.write_file('/views/base.html', content)

        # Weak test to verify preprocessor runs.
        pod.preprocess(['blogger'])

        # Verify inject.
        collection = pod.get_collection('/content/posts')
        doc = collection.docs()[0]
        preprocessor = pod.list_preprocessors()[0]
        preprocessor.inject(doc)

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

Use different blog for test data.

Use different blog for test data.

Response:
from . import google_drive
from grow.pods import pods
from grow.pods import storage
from grow.testing import testing
import cStringIO
import csv
import json
import unittest
import yaml

class BloggerTestCase(testing.TestCase):

    def test_run(self):
        pod = testing.create_pod()
        fields = {
            'preprocessors': [{
                'name': 'blogger',
                'kind': 'blogger',
                'blog_id': '4154157974596966834',
                'collection': '/content/posts/',
                'markdown': True,
                'authenticated': False,
                'inject': True,
            }],
        }
        pod.write_yaml('/podspec.yaml', fields)
        fields = {
            '$path': '/{date}/{slug}/',
            '$view': '/views/base.html',
        }
        pod.write_yaml('/content/posts/_blueprint.yaml', fields)
        content = '{{doc.html|safe}}'
        pod.write_file('/views/base.html', content)

        # Weak test to verify preprocessor runs.
        pod.preprocess(['blogger'])

        # Verify inject.
        collection = pod.get_collection('/content/posts')
        doc = collection.docs()[0]
        preprocessor = pod.list_preprocessors()[0]
        preprocessor.inject(doc)

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

Prompt:
Use different blog for test data.

from . import google_drive
from grow.pods import pods
from grow.pods import storage
from grow.testing import testing
import cStringIO
import csv
import json
import unittest
import yaml

class BloggerTestCase(testing.TestCase):

    def test_run(self):
        pod = testing.create_pod()
        fields = {
            'preprocessors': [{
                'name': 'blogger',
                'kind': 'blogger',
                'blog_id': '10861780',  # Official Google blog.
                'collection': '/content/posts/',
                'markdown': True,
                'authenticated': False,
                'inject': True,
            }],
        }
        pod.write_yaml('/podspec.yaml', fields)
        fields = {
            '$path': '/{date}/{slug}/',
            '$view': '/views/base.html',
        }
        pod.write_yaml('/content/posts/_blueprint.yaml', fields)
        content = '{{doc.html|safe}}'
        pod.write_file('/views/base.html', content)

        # Weak test to verify preprocessor runs.
        pod.preprocess(['blogger'])

        # Verify inject.
        collection = pod.get_collection('/content/posts')
        doc = collection.docs()[0]
        preprocessor = pod.list_preprocessors()[0]
        preprocessor.inject(doc)

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


"""
Basic demo of summit-python that sends a simple SMS message from the
command-line.
"""

import argparse

from summit.rest import SummitRestClient

def main():
    parser = argparse.ArgumentParser(
        description="Command-line SMS sender using Corvisa's Summit API.")
    parser.add_argument('--key', required=True,
                        help="Your application's API key.")
    parser.add_argument('--secret', required=True,
                        help="Your application's API key secret.")
    parser.add_argument('--from', required=True, help=(
        "Number to send from. Must be an authorized number "
        "for your Summit app."))
    parser.add_argument('--to', required=True, help="Recipient of SMS message.")
    parser.add_argument('--message', required=True,
                        help="Body of the SMS message.")
    args = parser.parse_args()

    client = SummitRestClient(account=args.key, token=args.secret)
    resp, inst = client.messages.create(from_=from_number, to=to_number,
                                        body=args.message)
    print 'Responded with code: {}'.format(resp.status_code)
    print inst

if __name__ == '__main__':
    main()

Add demo script to send SMS message from command_line

Response:
"""
Basic demo of summit-python that sends a simple SMS message from the
command-line.
"""

import argparse

from summit.rest import SummitRestClient

def main():
    parser = argparse.ArgumentParser(
        description="Command-line SMS sender using Corvisa's Summit API.")
    parser.add_argument('--key', required=True,
                        help="Your application's API key.")
    parser.add_argument('--secret', required=True,
                        help="Your application's API key secret.")
    parser.add_argument('--from', required=True, help=(
        "Number to send from. Must be an authorized number "
        "for your Summit app."))
    parser.add_argument('--to', required=True, help="Recipient of SMS message.")
    parser.add_argument('--message', required=True,
                        help="Body of the SMS message.")
    args = parser.parse_args()

    client = SummitRestClient(account=args.key, token=args.secret)
    resp, inst = client.messages.create(from_=from_number, to=to_number,
                                        body=args.message)
    print 'Responded with code: {}'.format(resp.status_code)
    print inst

if __name__ == '__main__':
    main()

Prompt: Add demo script to send SMS message from command_line


from framework.celery_tasks import app as celery_app
from scripts.analytics.base import DateAnalyticsHarness
from scripts.analytics.node_log_events import NodeLogEvents
from scripts.analytics.user_domain_events import UserDomainEvents

class EventAnalyticsHarness(DateAnalyticsHarness):

    @property
    def analytics_classes(self):
        return [NodeLogEvents, UserDomainEvents]

@celery_app.task(name='scripts.run_keen_events')
def run_main(date):
    EventAnalyticsHarness().main(date)

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

Response:
from framework.celery_tasks import app as celery_app
from scripts.analytics.base import DateAnalyticsHarness
from scripts.analytics.node_log_events import NodeLogEvents
from scripts.analytics.user_domain_events import UserDomainEvents

class EventAnalyticsHarness(DateAnalyticsHarness):

    @property
    def analytics_classes(self):
        return [NodeLogEvents, UserDomainEvents]

@celery_app.task(name='scripts.run_keen_events')
def run_main(date):
    EventAnalyticsHarness().main(date)

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

Prompt:
Add new user domain event collector to main keen events script

from framework.celery_tasks import app as celery_app
from scripts.analytics.base import DateAnalyticsHarness
from scripts.analytics.node_log_events import NodeLogEvents

class EventAnalyticsHarness(DateAnalyticsHarness):

    @property
    def analytics_classes(self):
        return [NodeLogEvents]

@celery_app.task(name='scripts.run_keen_events')
def run_main(date):
    EventAnalyticsHarness().main(date)

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


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

import os

from .common import *  # noqa

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
    }
}

ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http'

TEMPLATE_CONTEXT_PROCESSORS += (
    "django.core.context_processors.debug",
)

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

INSTALLED_APPS += ('django_extensions',)

# settings for celery
BROKER_URL = os.environ.get("BROKER_URL", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", 'redis://redis:6379/0')

Response:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

import os

from .common import *  # noqa

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
    }
}

ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http'

TEMPLATE_CONTEXT_PROCESSORS += (
    "django.core.context_processors.debug",
)

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

INSTALLED_APPS += ('django_extensions',)

# settings for celery
BROKER_URL = os.environ.get("BROKER_URL", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", 'redis://redis:6379/0')

Prompt:
Revert back to original settings for Celery Broker

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

import os

from .common import *  # noqa

DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
    }
}

ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http'

TEMPLATE_CONTEXT_PROCESSORS += (
    "django.core.context_processors.debug",
)

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

INSTALLED_APPS += ('django_extensions',)

# settings for celery
BROKER_URL = os.environ.get("BROKER_URL", "redis://127.0.0.1:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", 'redis://127.0.0.1:6379/0')


#!/usr/bin/env python

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

import os
import sys

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

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

requires = ['pyrax==1.4.7',
            'ipython==0.13.2',
            'tornado==3.1',
            'pyzmq==13.1.0'
]

setup(name='ipynb_swiftstore',
      version='0.0.0',
      description='IPython notebook storage for OpenStack Swift',
      author='Kyle Kelley',
      author_email='rgbkrk@gmail.com',
      url='http://github.com/rgbkrk/ipynb-swiftstore',
      py_modules=['ipynb_swiftstore'],
      package_data={'': ['LICENSE']},
      include_package_data=False,
      install_requires=requires,
      license=open('LICENSE').read(),
      zip_safe=True,
      classifiers=(
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Environment :: OpenStack',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: System :: Distributed Computing',
      ),
)

Response:
#!/usr/bin/env python

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

import os
import sys

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

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

requires = ['pyrax==1.4.7',
            'ipython==0.13.2',
            'tornado==3.1',
            'pyzmq==13.1.0'
]

setup(name='ipynb_swiftstore',
      version='0.0.0',
      description='IPython notebook storage for OpenStack Swift',
      author='Kyle Kelley',
      author_email='rgbkrk@gmail.com',
      url='http://github.com/rgbkrk/ipynb-swiftstore',
      py_modules=['ipynb_swiftstore'],
      package_data={'': ['LICENSE']},
      include_package_data=False,
      install_requires=requires,
      license=open('LICENSE').read(),
      zip_safe=True,
      classifiers=(
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Environment :: OpenStack',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: System :: Distributed Computing',
      ),
)

Prompt:
Add pyzmq. Note: this package doesn't need it but IPython notebook does

#!/usr/bin/env python

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

import os
import sys

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

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

requires = ['pyrax==1.4.7',
            'ipython==0.13.2',
            'tornado==3.1',
]

setup(name='ipynb_swiftstore',
      version='0.0.0',
      description='IPython notebook storage for OpenStack Swift',
      author='Kyle Kelley',
      author_email='rgbkrk@gmail.com',
      url='http://github.com/rgbkrk/ipynb-swiftstore',
      py_modules=['ipynb_swiftstore'],
      package_data={'': ['LICENSE']},
      include_package_data=False,
      install_requires=requires,
      license=open('LICENSE').read(),
      zip_safe=True,
      classifiers=(
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Environment :: OpenStack',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: System :: Distributed Computing',
      ),
)


# This file was generated by 'versioneer.py' (0.15) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.

import json

version_json = '''
{
 "dirty": false,
 "error": null,
 "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122",
 "version": "5.0.4"
}
'''  # END VERSION_JSON

def get_versions():
    return json.loads(version_json)

Remove sys import in versioneer file

Remove sys import in versioneer file

Response:
# This file was generated by 'versioneer.py' (0.15) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.

import json

version_json = '''
{
 "dirty": false,
 "error": null,
 "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122",
 "version": "5.0.4"
}
'''  # END VERSION_JSON

def get_versions():
    return json.loads(version_json)

Prompt:
Remove sys import in versioneer file

# This file was generated by 'versioneer.py' (0.15) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.

import json
import sys

version_json = '''
{
 "dirty": false,
 "error": null,
 "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122",
 "version": "5.0.4"
}
'''  # END VERSION_JSON

def get_versions():
    return json.loads(version_json)


"""Write some logs."""

import sys
import time

from mdk import start
mdk = start()

def main():
    session = mdk.session()
    session.info("process1", "hello")
    time.sleep(5)
    sys.stdout.write(session.inject())
    sys.stdout.flush()
    mdk.stop()

if __name__ == '__main__':
    main()

Response:
"""Write some logs."""

import sys
import time

from mdk import start
mdk = start()

def main():
    session = mdk.session()
    session.info("process1", "hello")
    time.sleep(5)
    sys.stdout.write(session.inject())
    sys.stdout.flush()
    mdk.stop()

if __name__ == '__main__':
    main()

Prompt:
Increase sleep in test to reduce timing sensitivity with prod servers.

"""Write some logs."""

import sys
import time

from mdk import start
mdk = start()

def main():
    session = mdk.session()
    session.info("process1", "hello")
    time.sleep(1)
    sys.stdout.write(session.inject())
    sys.stdout.flush()
    mdk.stop()

if __name__ == '__main__':
    main()


from . import FixtureTest

class BusinessAndSpurRoutes(FixtureTest):

    def _check_route_relation(
            self, rel_id, way_id, tile, shield_text, network):
        z, x, y = map(int, tile.split('/'))

        self.load_fixtures([
            'https://www.openstreetmap.org/relation/%d' % (rel_id,),
        ], clip=self.tile_bbox(z, x, y))

        # check that First Capitol Dr, part of the above relation, is given
        # a network that includes the "business" extension.
        self.assert_has_feature(
            z, x, y, 'roads',
            {'id': way_id, 'shield_text': shield_text, 'network': network})

    def test_first_capitol_dr_i70_business(self):
        self._check_route_relation(
            1933234, 12276055, '16/16294/25097', '70', 'US:I:Business')

    def test_business_loop(self):
        self._check_route_relation(
            1935116, 5807439, '16/12285/23316', '15', 'US:I:Business:Loop')

    def test_nj_essex(self):
        self._check_route_relation(
            945855, 221295008, '16/19267/24623', '672', 'US:NJ:Essex:Spur')

    def test_nj_cr(self):
        self._check_route_relation(
            941526, 60523740, '16/19192/24767', '526', 'US:NJ:CR:Spur')

Response:
from . import FixtureTest

class BusinessAndSpurRoutes(FixtureTest):

    def _check_route_relation(
            self, rel_id, way_id, tile, shield_text, network):
        z, x, y = map(int, tile.split('/'))

        self.load_fixtures([
            'https://www.openstreetmap.org/relation/%d' % (rel_id,),
        ], clip=self.tile_bbox(z, x, y))

        # check that First Capitol Dr, part of the above relation, is given
        # a network that includes the "business" extension.
        self.assert_has_feature(
            z, x, y, 'roads',
            {'id': way_id, 'shield_text': shield_text, 'network': network})

    def test_first_capitol_dr_i70_business(self):
        self._check_route_relation(
            1933234, 12276055, '16/16294/25097', '70', 'US:I:Business')

    def test_business_loop(self):
        self._check_route_relation(
            1935116, 5807439, '16/12285/23316', '15', 'US:I:Business:Loop')

    def test_nj_essex(self):
        self._check_route_relation(
            945855, 221295008, '16/19267/24623', '672', 'US:NJ:Essex:Spur')

    def test_nj_cr(self):
        self._check_route_relation(
            941526, 60523740, '16/19192/24767', '526', 'US:NJ:CR:Spur')

Prompt:
Add more test cases for spur / business route modifiers.

from . import FixtureTest

class BusinessAndSpurRoutes(FixtureTest):

    def test_first_capitol_dr_i70_business(self):
        self.load_fixtures([
            'https://www.openstreetmap.org/relation/1933234',
        ])

        # check that First Capitol Dr, part of the above relation, is given
        # a network that includes the "business" extension.
        self.assert_has_feature(
            16, 16294, 25097, 'roads',
            {'id': 12276055, 'shield_text': '70', 'network': 'US:I:Business'})


import scrollphat
from pijobs.scrollphatjob import ScrollphatJob

class ScrollJob(ScrollphatJob):
    def default_options(self):
        opts = {
                'brightness': 2,
                'interval': 0.1,
                'sleep': 1.0,
        }
        return opts

    def init(self):
        self.set_brightness()
        self.set_rotate()
        self.write_message()

    def write_message(self):
        message = self.parse_message()
        scrollphat.write_string(message, 11)

    def message(self):
        return self.options['message']

    def parse_message(self):
        message = self.message() + '    '
        if self.options['upper'] == True:
            message = message.upper()
        return message

    def run(self):
        length = scrollphat.buffer_len()
        if self.options['loop'] == True:
            counter = 0
            while True:
                self.scroll()
                counter += 1
                if counter % length == 0:
                    time.sleep(self.options['sleep'])
        else:
            for i in range(length):
                self.scroll()
            self.sleep()

    def scroll(self):
        scrollphat.scroll()
        self.sleep_interval()

Add back rotatation for scroll job.

Add back rotatation for scroll job.

Response:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob

class ScrollJob(ScrollphatJob):
    def default_options(self):
        opts = {
                'brightness': 2,
                'interval': 0.1,
                'sleep': 1.0,
        }
        return opts

    def init(self):
        self.set_brightness()
        self.set_rotate()
        self.write_message()

    def write_message(self):
        message = self.parse_message()
        scrollphat.write_string(message, 11)

    def message(self):
        return self.options['message']

    def parse_message(self):
        message = self.message() + '    '
        if self.options['upper'] == True:
            message = message.upper()
        return message

    def run(self):
        length = scrollphat.buffer_len()
        if self.options['loop'] == True:
            counter = 0
            while True:
                self.scroll()
                counter += 1
                if counter % length == 0:
                    time.sleep(self.options['sleep'])
        else:
            for i in range(length):
                self.scroll()
            self.sleep()

    def scroll(self):
        scrollphat.scroll()
        self.sleep_interval()

Prompt:
Add back rotatation for scroll job.

import scrollphat
from pijobs.scrollphatjob import ScrollphatJob

class ScrollJob(ScrollphatJob):
    def default_options(self):
        opts = {
                'brightness': 2,
                'interval': 0.1,
                'sleep': 1.0,
        }
        return opts

    def init(self):
        self.set_brightness()
        self.write_message()

    def write_message(self):
        message = self.parse_message()
        scrollphat.write_string(message, 11)

    def message(self):
        return self.options['message']

    def parse_message(self):
        message = self.message() + '    '
        if self.options['upper'] == True:
            message = message.upper()
        return message

    def run(self):
        length = scrollphat.buffer_len()
        if self.options['loop'] == True:
            counter = 0
            while True:
                self.scroll()
                counter += 1
                if counter % length == 0:
                    time.sleep(self.options['sleep'])
        else:
            for i in range(length):
                self.scroll()
            self.sleep()

    def scroll(self):
        scrollphat.scroll()
        self.sleep_interval()


from motobot import command, action

@command('say')
def say_command(bot, message, database):
    masters = [
        "Moto-chan",
        "Motoko11",
        "MotoNyan",
        "Akahige",
        "betholas",
        "Baradium",
        "Cold_slither",
        "Drahken"
    ]

    if message.nick.lower() not in [x.lower() for x in masters]:
        return "Check your privilege!"
    else:
        args = message.message.split(' ')[1:]

        if len(args) < 2:
            return "You must specify both a channel and a message"
        else:
            channel = args[0]
            message = ' '.join(args[1:])
            if message.startswith('/me '):
                message = action(message[4:])
            bot.send('PRIVMSG {} :{}'.format(channel, message))

Add MotoNyan to mad hax

Add MotoNyan to mad hax

Response:
from motobot import command, action

@command('say')
def say_command(bot, message, database):
    masters = [
        "Moto-chan",
        "Motoko11",
        "MotoNyan",
        "Akahige",
        "betholas",
        "Baradium",
        "Cold_slither",
        "Drahken"
    ]

    if message.nick.lower() not in [x.lower() for x in masters]:
        return "Check your privilege!"
    else:
        args = message.message.split(' ')[1:]

        if len(args) < 2:
            return "You must specify both a channel and a message"
        else:
            channel = args[0]
            message = ' '.join(args[1:])
            if message.startswith('/me '):
                message = action(message[4:])
            bot.send('PRIVMSG {} :{}'.format(channel, message))

Prompt:
Add MotoNyan to mad hax

from motobot import command, action

@command('say')
def say_command(bot, message, database):
    masters = [
        "Moto-chan",
        "Motoko11",
        "Akahige",
        "betholas",
        "Baradium",
        "Cold_slither",
        "Drahken"
    ]

    if message.nick.lower() not in [x.lower() for x in masters]:
        return "Check your privilege!"
    else:
        args = message.message.split(' ')[1:]

        if len(args) < 2:
            return "You must specify both a channel and a message"
        else:
            channel = args[0]
            message = ' '.join(args[1:])
            if message.startswith('/me '):
                message = action(message[4:])
            bot.send('PRIVMSG {} :{}'.format(channel, message))


#!/usr/bin/env python

# Support setuptools or distutils
try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup

# Version info -- read without importing
_locals = {}
with open('invocations/_version.py') as fp:
    exec(fp.read(), None, _locals)
version = _locals['__version__']

setup(
    name='invocations',
    version=version,
    description='Reusable Invoke tasks',
    license='BSD',
    author='Jeff Forcier',
    author_email='jeff@bitprophet.org',
    url='http://pyinvoke.org',

    # Release requirements. See dev-requirements.txt for dev version reqs.
    requirements=['invoke>=0.1.0'],

    packages=find_packages(),

    classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: BSD License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: Software Development',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'Topic :: System :: Software Distribution',
          'Topic :: System :: Systems Administration',
    ],
)

Response:
#!/usr/bin/env python

# Support setuptools or distutils
try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup

# Version info -- read without importing
_locals = {}
with open('invocations/_version.py') as fp:
    exec(fp.read(), None, _locals)
version = _locals['__version__']

setup(
    name='invocations',
    version=version,
    description='Reusable Invoke tasks',
    license='BSD',
    author='Jeff Forcier',
    author_email='jeff@bitprophet.org',
    url='http://pyinvoke.org',

    # Release requirements. See dev-requirements.txt for dev version reqs.
    requirements=['invoke>=0.1.0'],

    packages=find_packages(),

    classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: BSD License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: Software Development',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'Topic :: System :: Software Distribution',
          'Topic :: System :: Systems Administration',
    ],
)

Prompt:
Switch to a Python3 Compataible open + read + exec vs execfile

#!/usr/bin/env python

# Support setuptools or distutils
try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup

# Version info -- read without importing
_locals = {}
version_module = execfile('invocations/_version.py', _locals)
version = _locals['__version__']

setup(
    name='invocations',
    version=version,
    description='Reusable Invoke tasks',
    license='BSD',
    author='Jeff Forcier',
    author_email='jeff@bitprophet.org',
    url='http://pyinvoke.org',

    # Release requirements. See dev-requirements.txt for dev version reqs.
    requirements=['invoke>=0.1.0'],

    packages=find_packages(),

    classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: BSD License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Unix',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Topic :: Software Development',
          'Topic :: Software Development :: Build Tools',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules',
          'Topic :: System :: Software Distribution',
          'Topic :: System :: Systems Administration',
    ],
)


import numpy as np

a: np.ndarray
generator = (i for i in range(10))

np.require(a, requirements=1)  # E: No overload variant
np.require(a, requirements="TEST")  # E: incompatible type

np.zeros("test")  # E: incompatible type
np.zeros()  # E: Missing positional argument

np.ones("test")  # E: incompatible type
np.ones()  # E: Missing positional argument

np.array(0, float, True)  # E: Too many positional

np.linspace(None, 'bob')  # E: No overload variant
np.linspace(0, 2, num=10.0)  # E: No overload variant
np.linspace(0, 2, endpoint='True')  # E: No overload variant
np.linspace(0, 2, retstep=b'False')  # E: No overload variant
np.linspace(0, 2, dtype=0)  # E: No overload variant
np.linspace(0, 2, axis=None)  # E: No overload variant

np.logspace(None, 'bob')  # E: Argument 1
np.logspace(0, 2, base=None)  # E: Argument "base"

np.geomspace(None, 'bob')  # E: Argument 1

np.stack(generator)  # E: No overload variant
np.hstack({1, 2})  # E: incompatible type
np.vstack(1)  # E: incompatible type

Fix two failing typing tests

Response:
import numpy as np

a: np.ndarray
generator = (i for i in range(10))

np.require(a, requirements=1)  # E: No overload variant
np.require(a, requirements="TEST")  # E: incompatible type

np.zeros("test")  # E: incompatible type
np.zeros()  # E: Missing positional argument

np.ones("test")  # E: incompatible type
np.ones()  # E: Missing positional argument

np.array(0, float, True)  # E: Too many positional

np.linspace(None, 'bob')  # E: No overload variant
np.linspace(0, 2, num=10.0)  # E: No overload variant
np.linspace(0, 2, endpoint='True')  # E: No overload variant
np.linspace(0, 2, retstep=b'False')  # E: No overload variant
np.linspace(0, 2, dtype=0)  # E: No overload variant
np.linspace(0, 2, axis=None)  # E: No overload variant

np.logspace(None, 'bob')  # E: Argument 1
np.logspace(0, 2, base=None)  # E: Argument "base"

np.geomspace(None, 'bob')  # E: Argument 1

np.stack(generator)  # E: No overload variant
np.hstack({1, 2})  # E: incompatible type
np.vstack(1)  # E: incompatible type

Prompt:
TST: Fix two failing typing tests

Mypy 0.800 changed one of its error messages;
the `fail` tests have now been altered to reflect this change

import numpy as np

a: np.ndarray
generator = (i for i in range(10))

np.require(a, requirements=1)  # E: No overload variant
np.require(a, requirements="TEST")  # E: incompatible type

np.zeros("test")  # E: incompatible type
np.zeros()  # E: Too few arguments

np.ones("test")  # E: incompatible type
np.ones()  # E: Too few arguments

np.array(0, float, True)  # E: Too many positional

np.linspace(None, 'bob')  # E: No overload variant
np.linspace(0, 2, num=10.0)  # E: No overload variant
np.linspace(0, 2, endpoint='True')  # E: No overload variant
np.linspace(0, 2, retstep=b'False')  # E: No overload variant
np.linspace(0, 2, dtype=0)  # E: No overload variant
np.linspace(0, 2, axis=None)  # E: No overload variant

np.logspace(None, 'bob')  # E: Argument 1
np.logspace(0, 2, base=None)  # E: Argument "base"

np.geomspace(None, 'bob')  # E: Argument 1

np.stack(generator)  # E: No overload variant
np.hstack({1, 2})  # E: incompatible type
np.vstack(1)  # E: incompatible type


from setuptools import setup, find_packages

# Prevent "TypeError: 'NoneType' object is not callable" error
# when running python setup.py test
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
    import multiprocessing
except ImportError:
    pass

setup(
    name='cmakelists_parsing',
    version='0.1',
    author='Issac Trotts',
    author_email='itrotts@willowgarage.com',
    url='http://github.com/ijt/cmakelists_parsing',
    description='Parser for CMakeLists.txt files',
    packages=find_packages(),
    zip_safe=False,
    install_requires=['pyPEG2'],
    tests_require=['nose'],
    test_suite='nose.collector',
    include_package_data=True,
    entry_points = {
        'console_scripts': [
            'pprint_cmakelists = cmakelists_parsing.parsing:main',
        ]
    })

Response:
from setuptools import setup, find_packages

# Prevent "TypeError: 'NoneType' object is not callable" error
# when running python setup.py test
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
    import multiprocessing
except ImportError:
    pass

setup(
    name='cmakelists_parsing',
    version='0.1',
    author='Issac Trotts',
    author_email='itrotts@willowgarage.com',
    url='http://github.com/ijt/cmakelists_parsing',
    description='Parser for CMakeLists.txt files',
    packages=find_packages(),
    zip_safe=False,
    install_requires=['pyPEG2'],
    tests_require=['nose'],
    test_suite='nose.collector',
    include_package_data=True,
    entry_points = {
        'console_scripts': [
            'pprint_cmakelists = cmakelists_parsing.parsing:main',
        ]
    })

Prompt:
Fix entry point for pretty printing script.

from setuptools import setup, find_packages

# Prevent "TypeError: 'NoneType' object is not callable" error
# when running python setup.py test
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
    import multiprocessing
except ImportError:
    pass

setup(
    name='cmakelists_parsing',
    version='0.1',
    author='Issac Trotts',
    author_email='itrotts@willowgarage.com',
    url='http://github.com/ijt/cmakelists_parsing',
    description='Parser for CMakeLists.txt files',
    packages=find_packages(),
    zip_safe=False,
    install_requires=['pyPEG2'],
    tests_require=['nose'],
    test_suite='nose.collector',
    include_package_data=True,
    entry_points = {
        'console_scripts': [
            'pprint_cmakelists = my_package.some_module:main_func',
        ]
    })


import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory

from api.webview.views import DocumentList, status

django.setup()

class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_source_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_individual_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/dudley1'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_status(self):
        view = status
        request = self.factory.get(
            '/status'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

Add test for status view

Add test for status view

Response:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory

from api.webview.views import DocumentList, status

django.setup()

class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_source_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_individual_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/dudley1'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_status(self):
        view = status
        request = self.factory.get(
            '/status'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

Prompt:
Add test for status view

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")

import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory

from api.webview.views import DocumentList

django.setup()

class APIViewTests(TestCase):

    def setUp(self):
        self.factory = APIRequestFactory()

    def test_document_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_source_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)

    def test_individual_view(self):
        view = DocumentList.as_view()
        request = self.factory.get(
            '/documents/dudley_weekly/dudley1'
        )
        response = view(request)

        self.assertEqual(response.status_code, 200)


from __future__ import unicode_literals

from django.contrib.contenttypes.models import ContentType
from django.core import serializers as django_serializers
from django.core.management.base import BaseCommand
from reversion.models import Version, Revision

from nodeconductor.quotas import models
from nodeconductor.quotas.utils import get_models_with_quotas

class Command(BaseCommand):
    """ Recalculate all quotas """

    def handle(self, *args, **options):
        for model in get_models_with_quotas():
            if hasattr(model, 'GLOBAL_COUNT_QUOTA_NAME'):
                quota, _ = models.Quota.objects.get_or_create(name=model.GLOBAL_COUNT_QUOTA_NAME)
                for index, instance in enumerate(model.objects.all().order_by('created')):
                    revision = Revision.objects.create()
                    revision.date_created = instance.created
                    revision.save()

                    quota.usage = index + 1
                    serializer = django_serializers.get_serializer('json')()
                    serialized_data = serializer.serialize([quota])

                    Version.objects.create(
                        revision=revision,
                        object_id=quota.id,
                        object_id_int=quota.id,
                        content_type=ContentType.objects.get_for_model(quota),
                        format='json',
                        serialized_data=serialized_data,
                        object_repr=str(quota),
                    )

Implement command for quotas history population

 - itacloud-5296

Response:
from __future__ import unicode_literals

from django.contrib.contenttypes.models import ContentType
from django.core import serializers as django_serializers
from django.core.management.base import BaseCommand
from reversion.models import Version, Revision

from nodeconductor.quotas import models
from nodeconductor.quotas.utils import get_models_with_quotas

class Command(BaseCommand):
    """ Recalculate all quotas """

    def handle(self, *args, **options):
        for model in get_models_with_quotas():
            if hasattr(model, 'GLOBAL_COUNT_QUOTA_NAME'):
                quota, _ = models.Quota.objects.get_or_create(name=model.GLOBAL_COUNT_QUOTA_NAME)
                for index, instance in enumerate(model.objects.all().order_by('created')):
                    revision = Revision.objects.create()
                    revision.date_created = instance.created
                    revision.save()

                    quota.usage = index + 1
                    serializer = django_serializers.get_serializer('json')()
                    serialized_data = serializer.serialize([quota])

                    Version.objects.create(
                        revision=revision,
                        object_id=quota.id,
                        object_id_int=quota.id,
                        content_type=ContentType.objects.get_for_model(quota),
                        format='json',
                        serialized_data=serialized_data,
                        object_repr=str(quota),
                    )

Prompt:
Implement command for quotas history population

 - itacloud-5296


# Copyright 2014 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 logging
import time
import unittest

from telemetry import decorators
from telemetry.core import platform as platform_module

class PlatformBackendTest(unittest.TestCase):
  @decorators.Disabled('mavericks')  # crbug.com/423688
  def testPowerMonitoringSync(self):
    # Tests that the act of monitoring power doesn't blow up.
    platform = platform_module.GetHostPlatform()
    can_monitor_power = platform.CanMonitorPower()
    self.assertIsInstance(can_monitor_power, bool)
    if not can_monitor_power:
      logging.warning('Test not supported on this platform.')
      return

    browser_mock = lambda: None
    # Android needs to access the package of the monitored app.
    if platform.GetOSName() == 'android':
      # pylint: disable=W0212
      browser_mock._browser_backend = lambda: None
      # Monitor the launcher, which is always present.
      browser_mock._browser_backend.package = 'com.android.launcher'

    platform.StartMonitoringPower(browser_mock)
    time.sleep(0.001)
    output = platform.StopMonitoringPower()
    self.assertTrue(output.has_key('energy_consumption_mwh'))
    self.assertTrue(output.has_key('identifier'))

Response:
# Copyright 2014 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 logging
import time
import unittest

from telemetry import decorators
from telemetry.core import platform as platform_module

class PlatformBackendTest(unittest.TestCase):
  @decorators.Disabled('mavericks')  # crbug.com/423688
  def testPowerMonitoringSync(self):
    # Tests that the act of monitoring power doesn't blow up.
    platform = platform_module.GetHostPlatform()
    can_monitor_power = platform.CanMonitorPower()
    self.assertIsInstance(can_monitor_power, bool)
    if not can_monitor_power:
      logging.warning('Test not supported on this platform.')
      return

    browser_mock = lambda: None
    # Android needs to access the package of the monitored app.
    if platform.GetOSName() == 'android':
      # pylint: disable=W0212
      browser_mock._browser_backend = lambda: None
      # Monitor the launcher, which is always present.
      browser_mock._browser_backend.package = 'com.android.launcher'

    platform.StartMonitoringPower(browser_mock)
    time.sleep(0.001)
    output = platform.StopMonitoringPower()
    self.assertTrue(output.has_key('energy_consumption_mwh'))
    self.assertTrue(output.has_key('identifier'))

Prompt:
[telemetry] Disable power and smoke unit tests on Mac 10.9.

powermetrics is failing on the bots.

BUG=423688
TEST=trybots
R=tonyg

Review URL: https://codereview.chromium.org/746793002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#305147}

# Copyright 2014 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 logging
import time
import unittest

from telemetry.core import platform as platform_module

class PlatformBackendTest(unittest.TestCase):
  def testPowerMonitoringSync(self):
    # Tests that the act of monitoring power doesn't blow up.
    platform = platform_module.GetHostPlatform()
    can_monitor_power = platform.CanMonitorPower()
    self.assertIsInstance(can_monitor_power, bool)
    if not can_monitor_power:
      logging.warning('Test not supported on this platform.')
      return

    browser_mock = lambda: None
    # Android needs to access the package of the monitored app.
    if platform.GetOSName() == 'android':
      # pylint: disable=W0212
      browser_mock._browser_backend = lambda: None
      # Monitor the launcher, which is always present.
      browser_mock._browser_backend.package = 'com.android.launcher'

    platform.StartMonitoringPower(browser_mock)
    time.sleep(0.001)
    output = platform.StopMonitoringPower()
    self.assertTrue(output.has_key('energy_consumption_mwh'))
    self.assertTrue(output.has_key('identifier'))


import numpy as np
import scipy.sparse as sparse
import argparse, os
from itertools import izip as zip

# Uses the output of nodal_projection_matrix.py to aggregate signals
# into the nodal domain.

parser = argparse.ArgumentParser(description='Wind conversion options')
parser.add_argument('-r', '--indir', help='Input directory for forecast files', default='../../Data/Signal_Converted', metavar="load root")
parser.add_argument('-o', '--outdir', help='Output directory for forecast files', default='../../Data/Nodal_Signal', metavar="load outroot")
parser.add_argument('-f', '--first', help='First year to extract', default=2012, type=int, metavar="first year")
parser.add_argument('-l', '--last', help='Last year to extract', default=2014, type=int, metavar="last year")
parser.add_argument('-fm', help='First month to extract', default=1, type=int, metavar="first month")
parser.add_argument('-lm', help='Last month to extract', default=12, type=int, metavar="last month")

args = parser.parse_args()

loadtransfer = np.load('../../Data/Metadata/loadtransfercsr_ECMWF.npz')
loadtransfer = sparse.csr_matrix((loadtransfer['data'], loadtransfer['indices'], loadtransfer['indptr']), shape=loadtransfer['shape'])

loadname = 'load-{0:04d}{1:02d}.npz'

indirls = sorted(os.listdir(args.indir))

loadls = [x for x in indirls if 'load-' in x]

startidx = loadls.index(loadname.format(args.first, args.fm))

try:
    stopidx = loadls.index(loadname.format(args.last+int(args.lm == 12), args.lm % 12+1))
    loadls = loadls[startidx:stopidx]
except ValueError:
    print 'Stopdate + 1 month not found - assuming we need to use all directories'
    loadls = loadls[startidx:]

for loadfile in loadls:
    print loadfile
    dataf = np.load(args.indir + '/' + loadfile)
    dates = dataf['dates']
    data = dataf['data']
    shape = data.shape
    outdata = loadtransfer.dot(np.reshape(data, (shape[0], shape[1]*shape[2])).T).T
    np.savez_compressed(args.outdir + '/' + loadfile, data=outdata, dates=dates)

Add projection to nodal load

Add projection to nodal load

Response:
import numpy as np
import scipy.sparse as sparse
import argparse, os
from itertools import izip as zip

# Uses the output of nodal_projection_matrix.py to aggregate signals
# into the nodal domain.

parser = argparse.ArgumentParser(description='Wind conversion options')
parser.add_argument('-r', '--indir', help='Input directory for forecast files', default='../../Data/Signal_Converted', metavar="load root")
parser.add_argument('-o', '--outdir', help='Output directory for forecast files', default='../../Data/Nodal_Signal', metavar="load outroot")
parser.add_argument('-f', '--first', help='First year to extract', default=2012, type=int, metavar="first year")
parser.add_argument('-l', '--last', help='Last year to extract', default=2014, type=int, metavar="last year")
parser.add_argument('-fm', help='First month to extract', default=1, type=int, metavar="first month")
parser.add_argument('-lm', help='Last month to extract', default=12, type=int, metavar="last month")

args = parser.parse_args()

loadtransfer = np.load('../../Data/Metadata/loadtransfercsr_ECMWF.npz')
loadtransfer = sparse.csr_matrix((loadtransfer['data'], loadtransfer['indices'], loadtransfer['indptr']), shape=loadtransfer['shape'])

loadname = 'load-{0:04d}{1:02d}.npz'

indirls = sorted(os.listdir(args.indir))

loadls = [x for x in indirls if 'load-' in x]

startidx = loadls.index(loadname.format(args.first, args.fm))

try:
    stopidx = loadls.index(loadname.format(args.last+int(args.lm == 12), args.lm % 12+1))
    loadls = loadls[startidx:stopidx]
except ValueError:
    print 'Stopdate + 1 month not found - assuming we need to use all directories'
    loadls = loadls[startidx:]

for loadfile in loadls:
    print loadfile
    dataf = np.load(args.indir + '/' + loadfile)
    dates = dataf['dates']
    data = dataf['data']
    shape = data.shape
    outdata = loadtransfer.dot(np.reshape(data, (shape[0], shape[1]*shape[2])).T).T
    np.savez_compressed(args.outdir + '/' + loadfile, data=outdata, dates=dates)

Prompt: Add projection to nodal load


try:
    import thread
except :
    import _thread as thread

import threading
from time import sleep

def bar(y):
    z = 100 + y
    print("Z=%d"%z)

t = None
def foo(x):
    global t
    y = x + 1
    print("Y=%d"%y)

    t = threading.Thread(target=bar, args=(y,))
    t.start()

id = thread.start_new_thread(foo, (1,))

while True:
    sleep(1)

Response:
try:
    import thread
except :
    import _thread as thread

import threading
from time import sleep

def bar(y):
    z = 100 + y
    print("Z=%d"%z)

t = None
def foo(x):
    global t
    y = x + 1
    print("Y=%d"%y)

    t = threading.Thread(target=bar, args=(y,))
    t.start()

id = thread.start_new_thread(foo, (1,))

while True:
    sleep(1)

Prompt:
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.

try:
    import thread
except :
    import _thread as thread

import threading

def bar(y):
    z = 100 + y
    print("Z=%d"%z)

t = None
def foo(x):
    global t
    y = x + 1
    print("Y=%d"%y)

    t = threading.Thread(target=bar, args=(y,))
    t.start()

id = thread.start_new_thread(foo, (1,))

while True:
    pass


SECRET_KEY = 'SEKRIT'

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.auth',
    'django.contrib.admin',
    'tests',
)

ROOT_URLCONF = 'tests.urls'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'enumfields.db',
        'TEST_NAME': 'enumfields.db',
    },
}

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

DEBUG = True

STATIC_URL = "/static/"

Response:
SECRET_KEY = 'SEKRIT'

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.auth',
    'django.contrib.admin',
    'tests',
)

ROOT_URLCONF = 'tests.urls'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'enumfields.db',
        'TEST_NAME': 'enumfields.db',
    },
}

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

DEBUG = True

STATIC_URL = "/static/"

Prompt:
Add new required middleware to make tests pass on Django 1.7

SECRET_KEY = 'SEKRIT'

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.auth',
    'django.contrib.admin',
    'tests',
)

ROOT_URLCONF = 'tests.urls'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'enumfields.db',
        'TEST_NAME': 'enumfields.db',
    },
}

DEBUG = True

STATIC_URL = "/static/"