#!/usr/bin/env python
# -*- coding: utf-8 -*
import json
from django import forms
from django.template.loader import render_to_string

from .models import Field, FieldOption

class JSONField(forms.TextInput):
    model = Field
    def render(self, name, value, attrs=None):
        elements = []
        try:
            values = json.loads(value)
        except TypeError:
            values = {}
        objs = self.model.objects.filter(
            application__contains=self.attrs.get('_model', None))
        for obj in objs:
            o = {}
            o['name'] = obj.name
            o['slug'] = obj.slug

            element_attr = {}
            element_attr['name'] = obj.name
            element_attr['slug'] = obj.slug
            """
            element_attr['value'] = '1'
            element_attr['obj_value'] = values.get(obj.slug, '')
            """

            if obj.type in ["checkbox", "radiobox"]:
                obj_value = []
                fo = FieldOption.objects.filter(field=obj)
                for i in fo:
                    key = "{}_{}".format(obj.slug, i.option.slug)
                    obj_value.append(values.get(key, ''))
                element_attr['list'] = zip(fo, obj_value)

            o['element'] = render_to_string(
                "admin/opps/fields/json_{}.html".format(obj.type),
                dictionary=element_attr
            )
            elements.append(o)

        return render_to_string(
            "admin/opps/fields/json.html",
            {"elements": elements,
             "name": name,
             "value": value})

Response:
<DELETE> Option, <DELETE_END> <INSERT> try:
            <INSERT_END> <INSERT> except TypeError:
            values = {}
        <INSERT_END> <REPLACE_OLD> self.model.objects.all()
 <REPLACE_NEW> self.model.objects.filter(
            application__contains=self.attrs.get('_model', None))
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*
import json
from django import forms
from django.template.loader import render_to_string

from .models import Field, FieldOption

class JSONField(forms.TextInput):
    model = Field
    def render(self, name, value, attrs=None):
        elements = []
        try:
            values = json.loads(value)
        except TypeError:
            values = {}
        objs = self.model.objects.filter(
            application__contains=self.attrs.get('_model', None))
        for obj in objs:
            o = {}
            o['name'] = obj.name
            o['slug'] = obj.slug

            element_attr = {}
            element_attr['name'] = obj.name
            element_attr['slug'] = obj.slug
            """
            element_attr['value'] = '1'
            element_attr['obj_value'] = values.get(obj.slug, '')
            """

            if obj.type in ["checkbox", "radiobox"]:
                obj_value = []
                fo = FieldOption.objects.filter(field=obj)
                for i in fo:
                    key = "{}_{}".format(obj.slug, i.option.slug)
                    obj_value.append(values.get(key, ''))
                element_attr['list'] = zip(fo, obj_value)

            o['element'] = render_to_string(
                "admin/opps/fields/json_{}.html".format(obj.type),
                dictionary=element_attr
            )
            elements.append(o)

        return render_to_string(
            "admin/opps/fields/json.html",
            {"elements": elements,
             "name": name,
             "value": value})

Prompt:
Fix bug TypeError, not exist values (json) is dict None

#!/usr/bin/env python
# -*- coding: utf-8 -*
import json
from django import forms
from django.template.loader import render_to_string

from .models import Field, Option, FieldOption

class JSONField(forms.TextInput):
    model = Field
    def render(self, name, value, attrs=None):
        elements = []
        values = json.loads(value)
        objs = self.model.objects.all()
        for obj in objs:
            o = {}
            o['name'] = obj.name
            o['slug'] = obj.slug

            element_attr = {}
            element_attr['name'] = obj.name
            element_attr['slug'] = obj.slug
            """
            element_attr['value'] = '1'
            element_attr['obj_value'] = values.get(obj.slug, '')
            """

            if obj.type in ["checkbox", "radiobox"]:
                obj_value = []
                fo = FieldOption.objects.filter(field=obj)
                for i in fo:
                    key = "{}_{}".format(obj.slug, i.option.slug)
                    obj_value.append(values.get(key, ''))
                element_attr['list'] = zip(fo, obj_value)

            o['element'] = render_to_string(
                "admin/opps/fields/json_{}.html".format(obj.type),
                dictionary=element_attr
            )
            elements.append(o)

        return render_to_string(
            "admin/opps/fields/json.html",
            {"elements": elements,
             "name": name,
             "value": value})


import engine

VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
    (0, 0), (-1, -1),
    (96, 49), (96, 48),
    (105, 49), (104, 48),
    (96, 56), (97, 57),
    (105, 56), (104, 57)
    ]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8']

def test_coord_to_a1():
    for coord in VALID_COORDS:
        assert engine._coord_to_a1.get(coord, False) is not False
    for coord in INVALID_COORDS:
        assert engine._coord_to_a1.get(coord, False) is False

def test_a1_to_coord():
    for a1 in VALID_A1:
        assert engine._a1_to_coord.get(a1, False) is not False
    for a1 in INVALID_A1:
        assert engine._a1_to_coord.get(a1, False) is False

def test_is_coord_on_board():
    for coord in VALID_COORDS:
        assert engine._is_coord_on_board(coord) is True
    for coord in INVALID_COORDS:
        assert engine._is_coord_on_board(coord) is False

Response:
<INSERT> False

def test_is_coord_on_board():
    for coord in VALID_COORDS:
        assert engine._is_coord_on_board(coord) is True
    for coord in INVALID_COORDS:
        assert engine._is_coord_on_board(coord) is <INSERT_END> <|endoftext|> import engine

VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
    (0, 0), (-1, -1),
    (96, 49), (96, 48),
    (105, 49), (104, 48),
    (96, 56), (97, 57),
    (105, 56), (104, 57)
    ]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8']

def test_coord_to_a1():
    for coord in VALID_COORDS:
        assert engine._coord_to_a1.get(coord, False) is not False
    for coord in INVALID_COORDS:
        assert engine._coord_to_a1.get(coord, False) is False

def test_a1_to_coord():
    for a1 in VALID_A1:
        assert engine._a1_to_coord.get(a1, False) is not False
    for a1 in INVALID_A1:
        assert engine._a1_to_coord.get(a1, False) is False

def test_is_coord_on_board():
    for coord in VALID_COORDS:
        assert engine._is_coord_on_board(coord) is True
    for coord in INVALID_COORDS:
        assert engine._is_coord_on_board(coord) is False

Prompt:
Add test_is_coord_on_board() to assert the function returns True if the coordinate is on the board and False otherwise

import engine

VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
    (0, 0), (-1, -1),
    (96, 49), (96, 48),
    (105, 49), (104, 48),
    (96, 56), (97, 57),
    (105, 56), (104, 57)
    ]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8']

def test_coord_to_a1():
    for coord in VALID_COORDS:
        assert engine._coord_to_a1.get(coord, False) is not False
    for coord in INVALID_COORDS:
        assert engine._coord_to_a1.get(coord, False) is False

def test_a1_to_coord():
    for a1 in VALID_A1:
        assert engine._a1_to_coord.get(a1, False) is not False
    for a1 in INVALID_A1:
        assert engine._a1_to_coord.get(a1, False) is False


import time

import pytest

def test_version(client):
	expected_keys = {"Repo", "Commit", "Version"}
	resp_version = client.version()
	assert set(resp_version.keys()).issuperset(expected_keys)

def test_id(client):
	expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
	resp_id = client.id()
	assert set(resp_id.keys()).issuperset(expected_keys)

#################
# Shutdown test #
#################

@pytest.mark.last
def test_daemon_stop(daemon, client):
	# The value for the `daemon` “fixture” is injected using a pytest plugin
	# with access to the created daemon subprocess object defined directly
	# in the `test/run-test.py` file
	if not daemon:
		pytest.skip("Not started using `test/run-test.py`")

	def daemon_is_running():
		return daemon.poll() is None

	# Daemon should still be running at this point
	assert daemon_is_running()

	# Send stop request
	client.stop()

	# Wait for daemon process to disappear
	#
	#XXX: 10s is apparently not enough for slow Travis CI on Windows.
	for _ in range(20000):
		if not daemon_is_running():
			break
		time.sleep(0.001)

	# Daemon should not be running anymore
	assert not daemon_is_running()

Response:
<REPLACE_OLD> disappear
	for <REPLACE_NEW> disappear
	#
	#XXX: 10s is apparently not enough for slow Travis CI on Windows.
	for <REPLACE_END> <REPLACE_OLD> range(10000):
		if <REPLACE_NEW> range(20000):
		if <REPLACE_END> <|endoftext|> import time

import pytest

def test_version(client):
	expected_keys = {"Repo", "Commit", "Version"}
	resp_version = client.version()
	assert set(resp_version.keys()).issuperset(expected_keys)

def test_id(client):
	expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
	resp_id = client.id()
	assert set(resp_id.keys()).issuperset(expected_keys)

#################
# Shutdown test #
#################

@pytest.mark.last
def test_daemon_stop(daemon, client):
	# The value for the `daemon` “fixture” is injected using a pytest plugin
	# with access to the created daemon subprocess object defined directly
	# in the `test/run-test.py` file
	if not daemon:
		pytest.skip("Not started using `test/run-test.py`")

	def daemon_is_running():
		return daemon.poll() is None

	# Daemon should still be running at this point
	assert daemon_is_running()

	# Send stop request
	client.stop()

	# Wait for daemon process to disappear
	#
	#XXX: 10s is apparently not enough for slow Travis CI on Windows.
	for _ in range(20000):
		if not daemon_is_running():
			break
		time.sleep(0.001)

	# Daemon should not be running anymore
	assert not daemon_is_running()

Prompt:
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs
import time

import pytest

def test_version(client):
	expected_keys = {"Repo", "Commit", "Version"}
	resp_version = client.version()
	assert set(resp_version.keys()).issuperset(expected_keys)

def test_id(client):
	expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"}
	resp_id = client.id()
	assert set(resp_id.keys()).issuperset(expected_keys)

#################
# Shutdown test #
#################

@pytest.mark.last
def test_daemon_stop(daemon, client):
	# The value for the `daemon` “fixture” is injected using a pytest plugin
	# with access to the created daemon subprocess object defined directly
	# in the `test/run-test.py` file
	if not daemon:
		pytest.skip("Not started using `test/run-test.py`")

	def daemon_is_running():
		return daemon.poll() is None

	# Daemon should still be running at this point
	assert daemon_is_running()

	# Send stop request
	client.stop()

	# Wait for daemon process to disappear
	for _ in range(10000):
		if not daemon_is_running():
			break
		time.sleep(0.001)

	# Daemon should not be running anymore
	assert not daemon_is_running()


#
# Description:
#   This is the main of the poolWatcher
#
# Arguments: (eventually)
#   $1 = poll period (in seconds)
#   $2 = advertize rate (every $2 loops)
#   $3 = glidein submit_dir
#
# Author:
#   Igor Sfiligoi (Feb 13th 2007)
#

import os
import os.path
import sys
import traceback
import time
sys.path.append("../lib")

import condorMonitor

while 1:
    status=condorMonitor.CondorStatus()
    status.load()
    ssite=condorMonitor.Summarize(status,lambda el:[el['GLIDEIN_Site'],el['State']])
    sites=ssite.countStored()
    print time.ctime()
    for s in sites.keys():
	states=sites[s]
	if states.has_key('Claimed'):
          claimed=states['Claimed']
        else:
          claimed=0
        if states.has_key('Unclaimed'):
          unclaimed=states['Unclaimed']
        else:
          unclaimed=0

        print "Site: '%s' Claimed: %i Unclaimed: %i"%(s,claimed,unclaimed)
    time.sleep(30)

Response:
<REPLACE_OLD> gsite=condorMonitor.Group(status,lambda el:el['GLIDEIN_Site'],lambda el:el)
 <REPLACE_NEW> ssite=condorMonitor.Summarize(status,lambda el:[el['GLIDEIN_Site'],el['State']])
 <REPLACE_END> <REPLACE_OLD> gsite.load()
    sites=gsite.fetchStored()
 <REPLACE_NEW> sites=ssite.countStored()
 <REPLACE_END> <REPLACE_OLD> sites.keys():
 <REPLACE_NEW> sites.keys():
	states=sites[s]
	if states.has_key('Claimed'):
          claimed=states['Claimed']
        else:
          claimed=0
        if states.has_key('Unclaimed'):
          unclaimed=states['Unclaimed']
        else:
          unclaimed=0

 <REPLACE_END> <REPLACE_OLD> VMs: %i"%(s,len(sites[s]))
 <REPLACE_NEW> Claimed: %i Unclaimed: %i"%(s,claimed,unclaimed)
 <REPLACE_END> <|endoftext|> #
# Description:
#   This is the main of the poolWatcher
#
# Arguments: (eventually)
#   $1 = poll period (in seconds)
#   $2 = advertize rate (every $2 loops)
#   $3 = glidein submit_dir
#
# Author:
#   Igor Sfiligoi (Feb 13th 2007)
#

import os
import os.path
import sys
import traceback
import time
sys.path.append("../lib")

import condorMonitor

while 1:
    status=condorMonitor.CondorStatus()
    status.load()
    ssite=condorMonitor.Summarize(status,lambda el:[el['GLIDEIN_Site'],el['State']])
    sites=ssite.countStored()
    print time.ctime()
    for s in sites.keys():
	states=sites[s]
	if states.has_key('Claimed'):
          claimed=states['Claimed']
        else:
          claimed=0
        if states.has_key('Unclaimed'):
          unclaimed=states['Unclaimed']
        else:
          unclaimed=0

        print "Site: '%s' Claimed: %i Unclaimed: %i"%(s,claimed,unclaimed)
    time.sleep(30)

Prompt:
Add distinction between claimed and unclaimed

#
# Description:
#   This is the main of the poolWatcher
#
# Arguments: (eventually)
#   $1 = poll period (in seconds)
#   $2 = advertize rate (every $2 loops)
#   $3 = glidein submit_dir
#
# Author:
#   Igor Sfiligoi (Feb 13th 2007)
#

import os
import os.path
import sys
import traceback
import time
sys.path.append("../lib")

import condorMonitor

while 1:
    status=condorMonitor.CondorStatus()
    status.load()
    gsite=condorMonitor.Group(status,lambda el:el['GLIDEIN_Site'],lambda el:el)
    gsite.load()
    sites=gsite.fetchStored()
    print time.ctime()
    for s in sites.keys():
        print "Site: '%s' VMs: %i"%(s,len(sites[s]))
    time.sleep(30)


from tota.utils import closest, distance, sort_by_distance, possible_moves
from tota import settings

__author__ = "angvp"

def create():

    def lenovo_hero_logic(self, things, t):
        # some useful data about the enemies I can see in the map
        enemy_team = settings.ENEMY_TEAMS[self.team]
        enemies = [thing for thing in things.values()
                   if thing.team == enemy_team]
        closest_enemy = closest(self, enemies)
        closest_enemy_distance = distance(self, closest_enemy)

        real_life = (self.life / self.max_life) * 100

        # now lets decide what to do
        if int(real_life) < 85 and self.can('heal', t):
            # if I'm hurt and can heal, heal
            if closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('fireball', t):
                return 'fireball', closest_enemy.position
            elif closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('stun', t):
                return 'stun', closest_enemy.position
            elif closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('attack', t):
                return 'attack', closest_enemy.position
            else:
                return 'heal', self.position
        else:
            # else, try to attack
            if closest_enemy:
                # there is an enemy
                if closest_enemy_distance <= settings.STUN_DISTANCE and self.can('stun', t):
                    # try to stun him
                    return 'stun', closest_enemy.position
                if closest_enemy_distance <= settings.FIREBALL_DISTANCE and self.can('fireball', t) and closest_enemy_distance > settings.FIREBALL_RADIUS:
                    # else try to fireball him, but only if I'm not in range
                    return 'fireball', closest_enemy.position
                elif closest_enemy_distance <= settings.HERO_ATTACK_DISTANCE:
                    # else try to attack him
                    return 'attack', closest_enemy.position
                else:
                    # of finally just move to him (if I have life > 50)
                    moves = sort_by_distance(closest_enemy,
                                             possible_moves(self, things))
                    if len(moves) > 0:
                        back_moves = moves[len(moves)-1]
                    else:
                        back_moves = self.position
                    if moves and int(real_life) > 50:
                        return 'move', moves[0]
                    else:
                        return 'move', back_moves

        # can't do the things I want. Do nothing.
        return None

    return lenovo_hero_logic

Add a modified version of simple bot

Add a modified version of simple bot

Response:
<REPLACE_OLD>  <REPLACE_NEW> from tota.utils import closest, distance, sort_by_distance, possible_moves
from tota import settings

__author__ = "angvp"

def create():

    def lenovo_hero_logic(self, things, t):
        # some useful data about the enemies I can see in the map
        enemy_team = settings.ENEMY_TEAMS[self.team]
        enemies = [thing for thing in things.values()
                   if thing.team == enemy_team]
        closest_enemy = closest(self, enemies)
        closest_enemy_distance = distance(self, closest_enemy)

        real_life = (self.life / self.max_life) * 100

        # now lets decide what to do
        if int(real_life) < 85 and self.can('heal', t):
            # if I'm hurt and can heal, heal
            if closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('fireball', t):
                return 'fireball', closest_enemy.position
            elif closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('stun', t):
                return 'stun', closest_enemy.position
            elif closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('attack', t):
                return 'attack', closest_enemy.position
            else:
                return 'heal', self.position
        else:
            # else, try to attack
            if closest_enemy:
                # there is an enemy
                if closest_enemy_distance <= settings.STUN_DISTANCE and self.can('stun', t):
                    # try to stun him
                    return 'stun', closest_enemy.position
                if closest_enemy_distance <= settings.FIREBALL_DISTANCE and self.can('fireball', t) and closest_enemy_distance > settings.FIREBALL_RADIUS:
                    # else try to fireball him, but only if I'm not in range
                    return 'fireball', closest_enemy.position
                elif closest_enemy_distance <= settings.HERO_ATTACK_DISTANCE:
                    # else try to attack him
                    return 'attack', closest_enemy.position
                else:
                    # of finally just move to him (if I have life > 50)
                    moves = sort_by_distance(closest_enemy,
                                             possible_moves(self, things))
                    if len(moves) > 0:
                        back_moves = moves[len(moves)-1]
                    else:
                        back_moves = self.position
                    if moves and int(real_life) > 50:
                        return 'move', moves[0]
                    else:
                        return 'move', back_moves

        # can't do the things I want. Do nothing.
        return None

    return lenovo_hero_logic
 <REPLACE_END> <|endoftext|> from tota.utils import closest, distance, sort_by_distance, possible_moves
from tota import settings

__author__ = "angvp"

def create():

    def lenovo_hero_logic(self, things, t):
        # some useful data about the enemies I can see in the map
        enemy_team = settings.ENEMY_TEAMS[self.team]
        enemies = [thing for thing in things.values()
                   if thing.team == enemy_team]
        closest_enemy = closest(self, enemies)
        closest_enemy_distance = distance(self, closest_enemy)

        real_life = (self.life / self.max_life) * 100

        # now lets decide what to do
        if int(real_life) < 85 and self.can('heal', t):
            # if I'm hurt and can heal, heal
            if closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('fireball', t):
                return 'fireball', closest_enemy.position
            elif closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('stun', t):
                return 'stun', closest_enemy.position
            elif closest_enemy_distance <= settings.HEAL_DISTANCE and self.can('attack', t):
                return 'attack', closest_enemy.position
            else:
                return 'heal', self.position
        else:
            # else, try to attack
            if closest_enemy:
                # there is an enemy
                if closest_enemy_distance <= settings.STUN_DISTANCE and self.can('stun', t):
                    # try to stun him
                    return 'stun', closest_enemy.position
                if closest_enemy_distance <= settings.FIREBALL_DISTANCE and self.can('fireball', t) and closest_enemy_distance > settings.FIREBALL_RADIUS:
                    # else try to fireball him, but only if I'm not in range
                    return 'fireball', closest_enemy.position
                elif closest_enemy_distance <= settings.HERO_ATTACK_DISTANCE:
                    # else try to attack him
                    return 'attack', closest_enemy.position
                else:
                    # of finally just move to him (if I have life > 50)
                    moves = sort_by_distance(closest_enemy,
                                             possible_moves(self, things))
                    if len(moves) > 0:
                        back_moves = moves[len(moves)-1]
                    else:
                        back_moves = self.position
                    if moves and int(real_life) > 50:
                        return 'move', moves[0]
                    else:
                        return 'move', back_moves

        # can't do the things I want. Do nothing.
        return None

    return lenovo_hero_logic

Prompt: Add a modified version of simple bot


# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from armet.http import request, response

class Request(request.Request):
    """Implements the request abstraction for cyclone.
    """

    def __init__(self, handler):
        self.handler = handler

        # This is the python request object
        self.request = handler.request

    @property
    def url(self):
        return self.request.full_url()

    @property
    def path(self):
        return self.request.path

    @path.setter
    def path(self, value):
        self.request.path = value

    @property
    def method(self):
        return self.request.method

    @method.setter
    def method(self, value):
        self.request.method = value.upper()

    def __getitem__(self, name):
        return self.request.headers[name]

    def __iter__(self):
        return iter(self.request.headers)

    def __len__(self):
        return len(self.request.headers)

    def __contains__(self, item):
        return item in self.request.headers

class Response(response.Response):
    """Implements the response abstraction for cyclone.
    """

    def __init__(self, handler):
        self.handler = handler

    def __setitem__(self, name, value):
        self.handler.set_header(name, value)

    def __getitem__(self, name):
        # Cyclone doesn't provide a way to get headers normally, so break
        # into the private methods to retrieve the header.  Note that
        # this doesn't retrieve multi-value headers.  However, armet should
        # handle multi-value wrangling itself.
        return self.handler._headers[name]

Response:
<DELETE> armet import utils
from <DELETE_END> <INSERT> def __init__(self, handler):
        self.handler = handler

        # This is the python request object
        self.request = handler.request

    <INSERT_END> <REPLACE_OLD> @utils.memoize_single
 <REPLACE_NEW> def url(self):
        return self.request.full_url()

    @property
    def path(self):
        return self.request.path

    @path.setter
    def path(self, value):
        self.request.path = value

    @property
 <REPLACE_END> <REPLACE_OLD> pass

    def __getitem__(self):
        pass

 <REPLACE_NEW> return self.request.method

    @method.setter
    def method(self, value):
        self.request.method = value.upper()

    def __getitem__(self, name):
        return self.request.headers[name]

 <REPLACE_END> <REPLACE_OLD> pass

 <REPLACE_NEW> return iter(self.request.headers)

 <REPLACE_END> <REPLACE_OLD> pass

class <REPLACE_NEW> return len(self.request.headers)

    def __contains__(self, item):
        return item in self.request.headers

class <REPLACE_END> <REPLACE_OLD> """
 <REPLACE_NEW> """

    def __init__(self, handler):
        self.handler = handler

    def __setitem__(self, name, value):
        self.handler.set_header(name, value)

    def __getitem__(self, name):
        # Cyclone doesn't provide a way to get headers normally, so break
        # into the private methods to retrieve the header.  Note that
        # this doesn't retrieve multi-value headers.  However, armet should
        # handle multi-value wrangling itself.
        return self.handler._headers[name]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from armet.http import request, response

class Request(request.Request):
    """Implements the request abstraction for cyclone.
    """

    def __init__(self, handler):
        self.handler = handler

        # This is the python request object
        self.request = handler.request

    @property
    def url(self):
        return self.request.full_url()

    @property
    def path(self):
        return self.request.path

    @path.setter
    def path(self, value):
        self.request.path = value

    @property
    def method(self):
        return self.request.method

    @method.setter
    def method(self, value):
        self.request.method = value.upper()

    def __getitem__(self, name):
        return self.request.headers[name]

    def __iter__(self):
        return iter(self.request.headers)

    def __len__(self):
        return len(self.request.headers)

    def __contains__(self, item):
        return item in self.request.headers

class Response(response.Response):
    """Implements the response abstraction for cyclone.
    """

    def __init__(self, handler):
        self.handler = handler

    def __setitem__(self, name, value):
        self.handler.set_header(name, value)

    def __getitem__(self, name):
        # Cyclone doesn't provide a way to get headers normally, so break
        # into the private methods to retrieve the header.  Note that
        # this doesn't retrieve multi-value headers.  However, armet should
        # handle multi-value wrangling itself.
        return self.handler._headers[name]

Prompt:
Implement the cyclone request/response object

# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from armet import utils
from armet.http import request, response

class Request(request.Request):
    """Implements the request abstraction for cyclone.
    """

    @property
    @utils.memoize_single
    def method(self):
        pass

    def __getitem__(self):
        pass

    def __iter__(self):
        pass

    def __len__(self):
        pass

class Response(response.Response):
    """Implements the response abstraction for cyclone.
    """


# vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Wrapper functions for the _image_enhance C extension."""

from gi.repository import GdkPixbuf, GLib
from vimiv import _image_enhance

def enhance_bc(pixbuf, brightness, contrast):
    """Enhance brightness and contrast of a GdkPixbuf.Pixbuf.

    Args:
        pixbuf: Original GdkPixbuf.Pixbuf to work with.
        brightness: Float between -1.0 and 1.0 to change brightness.
        contrast: Float between -1.0 and 1.0 to change contrast.
    Return:
        The enhanced GdkPixbuf.Pixbuf
    """
    data = pixbuf.get_pixels()
    has_alpha = pixbuf.get_has_alpha()
    c_has_alpha = 1 if has_alpha else 0  # Numbers are easier for C
    # Update plain bytes using C extension
    # Pylint does not read this properly
    # pylint: disable=no-member
    data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
    gdata = GLib.Bytes.new(data)
    return GdkPixbuf.Pixbuf.new_from_bytes(gdata,
                                           pixbuf.get_colorspace(),
                                           has_alpha,
                                           pixbuf.get_bits_per_sample(),
                                           pixbuf.get_width(),
                                           pixbuf.get_height(),
                                           pixbuf.get_rowstride())

Response:
<DELETE> width = pixbuf.get_width()
    height = pixbuf.get_height()
    <DELETE_END> <DELETE> rowstride = 4 * width if has_alpha else 3 * width
    <DELETE_END> <REPLACE_OLD> GdkPixbuf.Pixbuf.new_from_bytes(
        gdata, GdkPixbuf.Colorspace.RGB, has_alpha, 8, width, height, rowstride)
 <REPLACE_NEW> GdkPixbuf.Pixbuf.new_from_bytes(gdata,
                                           pixbuf.get_colorspace(),
                                           has_alpha,
                                           pixbuf.get_bits_per_sample(),
                                           pixbuf.get_width(),
                                           pixbuf.get_height(),
                                           pixbuf.get_rowstride())
 <REPLACE_END> <|endoftext|> # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Wrapper functions for the _image_enhance C extension."""

from gi.repository import GdkPixbuf, GLib
from vimiv import _image_enhance

def enhance_bc(pixbuf, brightness, contrast):
    """Enhance brightness and contrast of a GdkPixbuf.Pixbuf.

    Args:
        pixbuf: Original GdkPixbuf.Pixbuf to work with.
        brightness: Float between -1.0 and 1.0 to change brightness.
        contrast: Float between -1.0 and 1.0 to change contrast.
    Return:
        The enhanced GdkPixbuf.Pixbuf
    """
    data = pixbuf.get_pixels()
    has_alpha = pixbuf.get_has_alpha()
    c_has_alpha = 1 if has_alpha else 0  # Numbers are easier for C
    # Update plain bytes using C extension
    # Pylint does not read this properly
    # pylint: disable=no-member
    data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
    gdata = GLib.Bytes.new(data)
    return GdkPixbuf.Pixbuf.new_from_bytes(gdata,
                                           pixbuf.get_colorspace(),
                                           has_alpha,
                                           pixbuf.get_bits_per_sample(),
                                           pixbuf.get_width(),
                                           pixbuf.get_height(),
                                           pixbuf.get_rowstride())

Prompt:
Use rowstride directly from GdkPixbuf in enhance

The custom calculation of rowstride failed for images with weird
dimensions and completely broke enhance.

fixes #51

# vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Wrapper functions for the _image_enhance C extension."""

from gi.repository import GdkPixbuf, GLib
from vimiv import _image_enhance

def enhance_bc(pixbuf, brightness, contrast):
    """Enhance brightness and contrast of a GdkPixbuf.Pixbuf.

    Args:
        pixbuf: Original GdkPixbuf.Pixbuf to work with.
        brightness: Float between -1.0 and 1.0 to change brightness.
        contrast: Float between -1.0 and 1.0 to change contrast.
    Return:
        The enhanced GdkPixbuf.Pixbuf
    """
    width = pixbuf.get_width()
    height = pixbuf.get_height()
    data = pixbuf.get_pixels()
    has_alpha = pixbuf.get_has_alpha()
    c_has_alpha = 1 if has_alpha else 0  # Numbers are easier for C
    rowstride = 4 * width if has_alpha else 3 * width
    # Update plain bytes using C extension
    # Pylint does not read this properly
    # pylint: disable=no-member
    data = _image_enhance.enhance_bc(data, c_has_alpha, brightness, contrast)
    gdata = GLib.Bytes.new(data)
    return GdkPixbuf.Pixbuf.new_from_bytes(
        gdata, GdkPixbuf.Colorspace.RGB, has_alpha, 8, width, height, rowstride)


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

from oslo_config import cfg
from oslo_log import log

from octavia.common import config

LOG = log.getLogger(__name__)

def prepare_service(argv=None):
    """Sets global config from config file and sets up logging."""
    argv = argv or []
    config.init(argv[1:])
    log.set_defaults()
    config.setup_logging(cfg.CONF)

Response:
<REPLACE_OLD> config
from octavia.i18n import _LI

LOG <REPLACE_NEW> config

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

from oslo_config import cfg
from oslo_log import log

from octavia.common import config

LOG = log.getLogger(__name__)

def prepare_service(argv=None):
    """Sets global config from config file and sets up logging."""
    argv = argv or []
    config.init(argv[1:])
    log.set_defaults()
    config.setup_logging(cfg.CONF)

Prompt:
Remove bad INFO log "Starting Octavia API server"

This log is also display for health_manager and house_keeping service.
Api service already display "Starting API server on..." in INFO level.

Change-Id: I0a3ff91b556accdfadbad797488d17ae7a95d85b

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

from oslo_config import cfg
from oslo_log import log

from octavia.common import config
from octavia.i18n import _LI

LOG = log.getLogger(__name__)

def prepare_service(argv=None):
    """Sets global config from config file and sets up logging."""
    argv = argv or []
    config.init(argv[1:])
    LOG.info(_LI('Starting Octavia API server'))
    log.set_defaults()
    config.setup_logging(cfg.CONF)


def parseinfo_context(parseinfo, context_amount = 3):
    buffer = parseinfo.buffer
    context_start_line = max(parseinfo.line - 1 - context_amount, 0)
    before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1)
    lines = buffer.get_lines(parseinfo.line, parseinfo.endline)
    after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount)

    # Must insert later characters first; if you start with earlier characters, they change
    # the indices for later inserts.
    lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos))
    lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos))

    return "".join(before_context_lines + lines + after_context_lines)

def _add_str_at_before_whitespace(string, character, index):
    while string[index - 1].isspace():
        index = index - 1
    return _add_str_at(string, character, index)

def _add_str_at(string, character, index):
    return string[:index] + character + string[index:]

Response:
<REPLACE_OLD> lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos))
 <REPLACE_NEW> # Must insert later characters first; if you start with earlier characters, they change
    # the indices for later inserts.
 <REPLACE_END> <REPLACE_OLD> _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1)

 <REPLACE_NEW> _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos))
    lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos))

 <REPLACE_END> <REPLACE_OLD> _add_char_at_before_whitespace(string, <REPLACE_NEW> _add_str_at_before_whitespace(string, <REPLACE_END> <REPLACE_OLD> _add_char_at(string, <REPLACE_NEW> _add_str_at(string, <REPLACE_END> <REPLACE_OLD> _add_char_at(string, <REPLACE_NEW> _add_str_at(string, <REPLACE_END> <|endoftext|> def parseinfo_context(parseinfo, context_amount = 3):
    buffer = parseinfo.buffer
    context_start_line = max(parseinfo.line - 1 - context_amount, 0)
    before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1)
    lines = buffer.get_lines(parseinfo.line, parseinfo.endline)
    after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount)

    # Must insert later characters first; if you start with earlier characters, they change
    # the indices for later inserts.
    lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos))
    lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos))

    return "".join(before_context_lines + lines + after_context_lines)

def _add_str_at_before_whitespace(string, character, index):
    while string[index - 1].isspace():
        index = index - 1
    return _add_str_at(string, character, index)

def _add_str_at(string, character, index):
    return string[:index] + character + string[index:]

Prompt:
Use ">>" for indicating next event, fix bug with indexing

def parseinfo_context(parseinfo, context_amount = 3):
    buffer = parseinfo.buffer
    context_start_line = max(parseinfo.line - 1 - context_amount, 0)
    before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1)
    lines = buffer.get_lines(parseinfo.line, parseinfo.endline)
    after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount)

    lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos))
    lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1)

    return "".join(before_context_lines + lines + after_context_lines)

def _add_char_at_before_whitespace(string, character, index):
    while string[index - 1].isspace():
        index = index - 1
    return _add_char_at(string, character, index)

def _add_char_at(string, character, index):
    return string[:index] + character + string[index:]


# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _

from microcms.conf import settings
from microcms.models import Meta

class MetaAdmin(admin.ModelAdmin):
    list_display = ('flatpage',)
    list_filter = ('flatpage',)
    ordering = ('flatpage',)
    search_fields = ('flatpage',)

admin.site.register(Meta, MetaAdmin)

class MetaInline(admin.StackedInline):
    model = Meta

class FlatPageAdmin(StockFlatPageAdmin):
    fieldsets = (
        (None, {'fields': ('url', 'title', 'content')}),
        (_('Advanced options'),
         {'classes': ('collapse closed',),
          'fields': ('enable_comments',
                     'registration_required',
                     'template_name')
         }
        ),
    )
    inlines = [MetaInline]

    class Media:
        js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]

    def save_model(self, request, obj, form, change):
        # Get the site with the lower id
        site = Site.objects.order_by('id')[0]
        obj.save()
        obj.sites.add(site)

admin.site.unregister(FlatPage)

admin.site.register(FlatPage, FlatPageAdmin)

Response:
<REPLACE_OLD> Site

from <REPLACE_NEW> Site
from django.utils.translation import ugettext_lazy as _

from <REPLACE_END> <INSERT> fieldsets = (
        (None, {'fields': ('url', 'title', 'content')}),
        (_('Advanced options'),
         {'classes': ('collapse closed',),
          'fields': ('enable_comments',
                     'registration_required',
                     'template_name')
         }
        ),
    )
    <INSERT_END> <REPLACE_OLD> settings.TINYMCE_SETUP_URL]

admin.site.unregister(FlatPage)

admin.site.register(FlatPage, <REPLACE_NEW> settings.TINYMCE_SETUP_URL]

    def save_model(self, request, obj, form, change):
        # Get the site with the lower id
        site = Site.objects.order_by('id')[0]
        obj.save()
        obj.sites.add(site)

admin.site.unregister(FlatPage)

admin.site.register(FlatPage, <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _

from microcms.conf import settings
from microcms.models import Meta

class MetaAdmin(admin.ModelAdmin):
    list_display = ('flatpage',)
    list_filter = ('flatpage',)
    ordering = ('flatpage',)
    search_fields = ('flatpage',)

admin.site.register(Meta, MetaAdmin)

class MetaInline(admin.StackedInline):
    model = Meta

class FlatPageAdmin(StockFlatPageAdmin):
    fieldsets = (
        (None, {'fields': ('url', 'title', 'content')}),
        (_('Advanced options'),
         {'classes': ('collapse closed',),
          'fields': ('enable_comments',
                     'registration_required',
                     'template_name')
         }
        ),
    )
    inlines = [MetaInline]

    class Media:
        js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]

    def save_model(self, request, obj, form, change):
        # Get the site with the lower id
        site = Site.objects.order_by('id')[0]
        obj.save()
        obj.sites.add(site)

admin.site.unregister(FlatPage)

admin.site.register(FlatPage, FlatPageAdmin)

Prompt:
Insert automatically flatpage default site

# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site

from microcms.conf import settings
from microcms.models import Meta

class MetaAdmin(admin.ModelAdmin):
    list_display = ('flatpage',)
    list_filter = ('flatpage',)
    ordering = ('flatpage',)
    search_fields = ('flatpage',)

admin.site.register(Meta, MetaAdmin)

class MetaInline(admin.StackedInline):
    model = Meta

class FlatPageAdmin(StockFlatPageAdmin):
    inlines = [MetaInline]

    class Media:
        js = [settings.TINYMCE_URL, settings.TINYMCE_SETUP_URL]

admin.site.unregister(FlatPage)

admin.site.register(FlatPage, FlatPageAdmin)


# This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option

# Be explicit about the worker class
worker_class = "sync"

# Set timeout to the same value as the default one from Amazon ELB (60 secs).
timeout = 60

# Recycle worker processes after 100k requests to prevent memory leaks
# from effecting us
max_requests = 100000

# Avoid too much output on the console
loglevel = "warning"

def post_worker_init(worker):
    from random import randint

    # Use 10% jitter, to prevent all workers from restarting at once,
    # as they get an almost equal number of requests
    jitter = randint(0, max_requests // 10)
    worker.max_requests += jitter

    # Actually initialize the application
    worker.wsgi(None, None)

Response:
<REPLACE_OLD> secs).
# It should be 60 seconds, but gunicorn halves the configured value,
# see https://github.com/benoitc/gunicorn/issues/829
timeout <REPLACE_NEW> secs).
timeout <REPLACE_END> <REPLACE_OLD> 120

# <REPLACE_NEW> 60

# <REPLACE_END> <|endoftext|> # This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option

# Be explicit about the worker class
worker_class = "sync"

# Set timeout to the same value as the default one from Amazon ELB (60 secs).
timeout = 60

# Recycle worker processes after 100k requests to prevent memory leaks
# from effecting us
max_requests = 100000

# Avoid too much output on the console
loglevel = "warning"

def post_worker_init(worker):
    from random import randint

    # Use 10% jitter, to prevent all workers from restarting at once,
    # as they get an almost equal number of requests
    jitter = randint(0, max_requests // 10)
    worker.max_requests += jitter

    # Actually initialize the application
    worker.wsgi(None, None)

Prompt:
Update gunicorn timeout after gunicorn issue was answered.

# This file contains gunicorn configuration setttings, as described at
# http://docs.gunicorn.org/en/latest/settings.html
# The file is loaded via the -c ichnaea.gunicorn_config command line option

# Be explicit about the worker class
worker_class = "sync"

# Set timeout to the same value as the default one from Amazon ELB (60 secs).
# It should be 60 seconds, but gunicorn halves the configured value,
# see https://github.com/benoitc/gunicorn/issues/829
timeout = 120

# Recycle worker processes after 100k requests to prevent memory leaks
# from effecting us
max_requests = 100000

# Avoid too much output on the console
loglevel = "warning"

def post_worker_init(worker):
    from random import randint

    # Use 10% jitter, to prevent all workers from restarting at once,
    # as they get an almost equal number of requests
    jitter = randint(0, max_requests // 10)
    worker.max_requests += jitter

    # Actually initialize the application
    worker.wsgi(None, None)


""" Utility functions for PhotoScan processing """

import os, sys
import PhotoScan

def align_and_clean_photos(chunk):
    ncameras = len(chunk.cameras)
    for frame in chunk.frames:
        frame.matchPhotos()

    chunk.alignCameras()
    for camera in chunk.cameras:
        if camera.transform is None:
            chunk.remove(camera)

    naligned = len(chunk.cameras)
    print('%d/%d cameras aligned' % (naligned, ncameras))

def export_dems(resolution, formatstring, pathname)
    if not os.path.isdir(pathname):
        os.mkdir(pathname)
    if pathname[-1:] is not '/':
        pathname = ''.join(pathname, '/')

    nchunks = len(PhotoScan.app.document.chunks)
    nexported = nchunks
    for chunk in PhotoScan.app.document.chunks:
        filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
        exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
        if not exported:
            print('Export failed:', chunk.label)
            nexported -= 1

    print('%d/%d DEMs exported' % (nexported, nchunks))

Check for trailing slash in path

Check for trailing slash in path

Response:
<INSERT> if pathname[-1:] is not '/':
        pathname = ''.join(pathname, '/')
    <INSERT_END> <|endoftext|> """ Utility functions for PhotoScan processing """

import os, sys
import PhotoScan

def align_and_clean_photos(chunk):
    ncameras = len(chunk.cameras)
    for frame in chunk.frames:
        frame.matchPhotos()

    chunk.alignCameras()
    for camera in chunk.cameras:
        if camera.transform is None:
            chunk.remove(camera)

    naligned = len(chunk.cameras)
    print('%d/%d cameras aligned' % (naligned, ncameras))

def export_dems(resolution, formatstring, pathname)
    if not os.path.isdir(pathname):
        os.mkdir(pathname)
    if pathname[-1:] is not '/':
        pathname = ''.join(pathname, '/')

    nchunks = len(PhotoScan.app.document.chunks)
    nexported = nchunks
    for chunk in PhotoScan.app.document.chunks:
        filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
        exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
        if not exported:
            print('Export failed:', chunk.label)
            nexported -= 1

    print('%d/%d DEMs exported' % (nexported, nchunks))

Prompt:
Check for trailing slash in path
""" Utility functions for PhotoScan processing """

import os, sys
import PhotoScan

def align_and_clean_photos(chunk):
    ncameras = len(chunk.cameras)
    for frame in chunk.frames:
        frame.matchPhotos()

    chunk.alignCameras()
    for camera in chunk.cameras:
        if camera.transform is None:
            chunk.remove(camera)

    naligned = len(chunk.cameras)
    print('%d/%d cameras aligned' % (naligned, ncameras))

def export_dems(resolution, formatstring, pathname)
    if not os.path.isdir(pathname):
        os.mkdir(pathname)

    nchunks = len(PhotoScan.app.document.chunks)
    nexported = nchunks
    for chunk in PhotoScan.app.document.chunks:
        filename = ''.join([pathname, chunk.label.split(' '), '.', formatstring])
        exported = chunk.exportDem(filename, format=formatstring, dx=resolution, dy=resolution)
        if not exported:
            print('Export failed:', chunk.label)
            nexported -= 1

    print('%d/%d DEMs exported' % (nexported, nchunks))


from setuptools import setup
setup(
    name='aws-helpers',
    description='Set of AWS helper scripts',
    url='https://github.com/otype/aws-helpers',
    author='Hans-Gunther Schmidt',
    author_email='hans@otype.de',
    version='0.1',
    install_requires=['awscli==1.12.2'],
    scripts=['src/aws-instances', 'src/aws-instances.py']
 )

Response:
<REPLACE_OLD> install_requires=['awscli', 'boto'],
 <REPLACE_NEW> install_requires=['awscli==1.12.2'],
 <REPLACE_END> <|endoftext|> from setuptools import setup
setup(
    name='aws-helpers',
    description='Set of AWS helper scripts',
    url='https://github.com/otype/aws-helpers',
    author='Hans-Gunther Schmidt',
    author_email='hans@otype.de',
    version='0.1',
    install_requires=['awscli==1.12.2'],
    scripts=['src/aws-instances', 'src/aws-instances.py']
 )

Prompt:
Fix awscli to 1.12.2 as there are errors in later versions

from setuptools import setup
setup(
    name='aws-helpers',
    description='Set of AWS helper scripts',
    url='https://github.com/otype/aws-helpers',
    author='Hans-Gunther Schmidt',
    author_email='hans@otype.de',
    version='0.1',
    install_requires=['awscli', 'boto'],
    scripts=['src/aws-instances', 'src/aws-instances.py']
 )


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

from setuptools import setup, find_packages

def get_deps():
  import re

  deps_raw = [ line.strip() for line in open("deps.txt")]
  deps = []
  for dep in deps_raw:
    if not dep or dep.startswith("#"):
      continue
    m = re.search("#egg=(.*)", dep)
    if m:
      dep = m.group(1)
    deps.append(dep)
  return deps

metadata = dict(
  name='Yaka Core',
  version='0.1dev',
  url='http://www.yaka.biz/',
  license='LGPL',
  author='Stefane Fermigier',
  author_email='sf@fermigier.com',
  description='Enterprise social networking meets CRM',
  long_description=__doc__,
  packages=['yaka'],
  platforms='any',
  classifiers=[
    'Development Status :: 3 - Alpha',
    'Environment :: Web Environment',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    ],
  # Setuptools specific
  install_requires=get_deps(),
  include_package_data=True,
  zip_safe=False,
)

setup(**metadata)

Fix build broken by previous commit.

Fix build broken by previous commit.

Response:
<REPLACE_OLD> find_packages

deps <REPLACE_NEW> find_packages

def get_deps():
  import re

  deps_raw <REPLACE_END> <REPLACE_OLD> line.strip()
 <REPLACE_NEW> line.strip() for line in open("deps.txt")]
  deps = []
  for dep in deps_raw:
    if not dep or dep.startswith("#"):
 <REPLACE_END> <INSERT> continue
 <INSERT_END> <REPLACE_OLD> for line in open("deps.txt")
 <REPLACE_NEW> m = re.search("#egg=(.*)", dep)
    if m:
 <REPLACE_END> <INSERT> dep = m.group(1)
 <INSERT_END> <REPLACE_OLD> if line and not line.startswith("#") ]

metadata <REPLACE_NEW> deps.append(dep)
  return deps

metadata <REPLACE_END> <REPLACE_OLD> Unsupported by distutils.
 <REPLACE_NEW> Setuptools specific
 <REPLACE_END> <REPLACE_OLD> #install_requires=deps,
 <REPLACE_NEW> install_requires=get_deps(),
 <REPLACE_END> <REPLACE_OLD> #include_package_data=True,
 <REPLACE_NEW> include_package_data=True,
 <REPLACE_END> <REPLACE_OLD> #zip_safe=False,
)

setup(**metadata)
 <REPLACE_NEW> zip_safe=False,
)

setup(**metadata)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from setuptools import setup, find_packages

def get_deps():
  import re

  deps_raw = [ line.strip() for line in open("deps.txt")]
  deps = []
  for dep in deps_raw:
    if not dep or dep.startswith("#"):
      continue
    m = re.search("#egg=(.*)", dep)
    if m:
      dep = m.group(1)
    deps.append(dep)
  return deps

metadata = dict(
  name='Yaka Core',
  version='0.1dev',
  url='http://www.yaka.biz/',
  license='LGPL',
  author='Stefane Fermigier',
  author_email='sf@fermigier.com',
  description='Enterprise social networking meets CRM',
  long_description=__doc__,
  packages=['yaka'],
  platforms='any',
  classifiers=[
    'Development Status :: 3 - Alpha',
    'Environment :: Web Environment',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    ],
  # Setuptools specific
  install_requires=get_deps(),
  include_package_data=True,
  zip_safe=False,
)

setup(**metadata)

Prompt:
Fix build broken by previous commit.

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

from setuptools import setup, find_packages

deps = [ line.strip()
         for line in open("deps.txt")
         if line and not line.startswith("#") ]

metadata = dict(
  name='Yaka Core',
  version='0.1dev',
  url='http://www.yaka.biz/',
  license='LGPL',
  author='Stefane Fermigier',
  author_email='sf@fermigier.com',
  description='Enterprise social networking meets CRM',
  long_description=__doc__,
  packages=['yaka'],
  platforms='any',
  classifiers=[
    'Development Status :: 3 - Alpha',
    'Environment :: Web Environment',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    ],
  # Unsupported by distutils.
  #install_requires=deps,
  #include_package_data=True,
  #zip_safe=False,
)

setup(**metadata)


from __future__ import absolute_import, unicode_literals

from mopidy import config

def test_core_schema_has_cache_dir():
    assert 'cache_dir' in config._core_schema
    assert isinstance(config._core_schema['cache_dir'], config.Path)

def test_core_schema_has_config_dir():
    assert 'config_dir' in config._core_schema
    assert isinstance(config._core_schema['config_dir'], config.Path)

def test_core_schema_has_data_dir():
    assert 'data_dir' in config._core_schema
    assert isinstance(config._core_schema['data_dir'], config.Path)

def test_core_schema_has_max_tracklist_length():
    assert 'max_tracklist_length' in config._core_schema
    max_tracklist_length_schema = config._core_schema['max_tracklist_length']
    assert isinstance(max_tracklist_length_schema, config.Integer)
    assert max_tracklist_length_schema._minimum == 1
    assert max_tracklist_length_schema._maximum == 10000

tests: Add tests for defaults in core schema config

Tests check if default core schema has cache_dir, config_dir, data_dir and max_tracklist_length and if they have proper type

Response:
<INSERT> from __future__ import absolute_import, unicode_literals

from mopidy import config

def test_core_schema_has_cache_dir():
 <INSERT_END> <INSERT>   assert 'cache_dir' in config._core_schema
    assert isinstance(config._core_schema['cache_dir'], config.Path)

def test_core_schema_has_config_dir():
    assert 'config_dir' in config._core_schema
    assert isinstance(config._core_schema['config_dir'], config.Path)

def test_core_schema_has_data_dir():
    assert 'data_dir' in config._core_schema
    assert isinstance(config._core_schema['data_dir'], config.Path)

def test_core_schema_has_max_tracklist_length():
    assert 'max_tracklist_length' in config._core_schema
    max_tracklist_length_schema = config._core_schema['max_tracklist_length']
    assert isinstance(max_tracklist_length_schema, config.Integer)
    assert max_tracklist_length_schema._minimum == 1
    assert max_tracklist_length_schema._maximum == 10000
 <INSERT_END> <|endoftext|> from __future__ import absolute_import, unicode_literals

from mopidy import config

def test_core_schema_has_cache_dir():
    assert 'cache_dir' in config._core_schema
    assert isinstance(config._core_schema['cache_dir'], config.Path)

def test_core_schema_has_config_dir():
    assert 'config_dir' in config._core_schema
    assert isinstance(config._core_schema['config_dir'], config.Path)

def test_core_schema_has_data_dir():
    assert 'data_dir' in config._core_schema
    assert isinstance(config._core_schema['data_dir'], config.Path)

def test_core_schema_has_max_tracklist_length():
    assert 'max_tracklist_length' in config._core_schema
    max_tracklist_length_schema = config._core_schema['max_tracklist_length']
    assert isinstance(max_tracklist_length_schema, config.Integer)
    assert max_tracklist_length_schema._minimum == 1
    assert max_tracklist_length_schema._maximum == 10000

Prompt:
tests: Add tests for defaults in core schema config

Tests check if default core schema has cache_dir, config_dir, data_dir and max_tracklist_length and if they have proper type


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np

class TestNTC(object):
    def test_ntc_resistance(self):
        # Values arbitrarily from Murata NCP15WB473D03RC
        assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
        assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
        assert_approx_equal(ntc_resistance("47k", "4050K", "-18°C"), 463773.791)
        assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
        assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)

Add more NTC unit tests

Add more NTC unit tests

Response:
<INSERT> "-18°C"), 463773.791)
        assert_approx_equal(ntc_resistance("47k", "4050K", <INSERT_END> <|endoftext|> #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np

class TestNTC(object):
    def test_ntc_resistance(self):
        # Values arbitrarily from Murata NCP15WB473D03RC
        assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
        assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
        assert_approx_equal(ntc_resistance("47k", "4050K", "-18°C"), 463773.791)
        assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
        assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)

Prompt:
Add more NTC unit tests

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np

class TestNTC(object):
    def test_ntc_resistance(self):
        # Values arbitrarily from Murata NCP15WB473D03RC
        assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
        assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
        assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
        assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)


import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier

scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils

parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')

test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
#X_test = test.ix[:,1:]
X_test = test.ix[:9,1:]

X_test.fillna(-1, inplace=True)

print "predict RandomForest Classifier..."

probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]

result = pd.DataFrame(columns = {'hotel_cluster'})

result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])

result.hotel_cluster.to_csv(utils.model_path +
	'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')

Handle missing value in predit rf

Handle missing value in predit rf

Response:
<REPLACE_OLD> +'.pkl')
X_test <REPLACE_NEW> +'.pkl')
#X_test <REPLACE_END> <REPLACE_OLD> test.ix[:,1:]

print <REPLACE_NEW> test.ix[:,1:]
X_test = test.ix[:9,1:]

X_test.fillna(-1, inplace=True)

print <REPLACE_END> <|endoftext|> import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier

scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils

parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')

test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
#X_test = test.ix[:,1:]
X_test = test.ix[:9,1:]

X_test.fillna(-1, inplace=True)

print "predict RandomForest Classifier..."

probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]

result = pd.DataFrame(columns = {'hotel_cluster'})

result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])

result.hotel_cluster.to_csv(utils.model_path +
	'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')

Prompt:
Handle missing value in predit rf

import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier

scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils

parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')

test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
X_test = test.ix[:,1:]

print "predict RandomForest Classifier..."

probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]

result = pd.DataFrame(columns = {'hotel_cluster'})

result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])

result.hotel_cluster.to_csv(utils.model_path +
	'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')


"""Test file for the ordered dictionary module, odict.py."""

from neuroimaging.externals.scipy.testing import *

from neuroimaging.utils.odict import odict

class TestOdict(TestCase):
    def setUp(self):
        print 'setUp'
        self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))

    def test_copy(self):
        """Test odict.copy method."""
        print self.thedict
        cpydict = self.thedict.copy()
        assert cpydict == self.thedict
        # test that it's a copy and not a reference
        assert cpydict is not self.thedict

if __name__ == "__main__":
    nose.runmodule()

Fix nose call so tests run in __main__.

Response:
<REPLACE_OLD> nose.run(argv=['', __file__])
 <REPLACE_NEW> nose.runmodule()
 <REPLACE_END> <|endoftext|> """Test file for the ordered dictionary module, odict.py."""

from neuroimaging.externals.scipy.testing import *

from neuroimaging.utils.odict import odict

class TestOdict(TestCase):
    def setUp(self):
        print 'setUp'
        self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))

    def test_copy(self):
        """Test odict.copy method."""
        print self.thedict
        cpydict = self.thedict.copy()
        assert cpydict == self.thedict
        # test that it's a copy and not a reference
        assert cpydict is not self.thedict

if __name__ == "__main__":
    nose.runmodule()

Prompt:
BUG: Fix nose call so tests run in __main__.
"""Test file for the ordered dictionary module, odict.py."""

from neuroimaging.externals.scipy.testing import *

from neuroimaging.utils.odict import odict

class TestOdict(TestCase):
    def setUp(self):
        print 'setUp'
        self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))

    def test_copy(self):
        """Test odict.copy method."""
        print self.thedict
        cpydict = self.thedict.copy()
        assert cpydict == self.thedict
        # test that it's a copy and not a reference
        assert cpydict is not self.thedict

if __name__ == "__main__":
    nose.run(argv=['', __file__])


# -*- coding: utf-8 -*-
# Copyright (C) 2009  Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

{
    'name': 'Brazilian Localisation ZIP Codes',
    'license': 'AGPL-3',
    'author': 'Akretion, Odoo Community Association (OCA)',
    'version': '9.0.1.0.0',
    'depends': [
        'l10n_br_base',
    ],
    'data': [
        'views/l10n_br_zip_view.xml',
        'views/res_partner_view.xml',
        'views/res_company_view.xml',
        'views/res_bank_view.xml',
        'wizard/l10n_br_zip_search_view.xml',
        'security/ir.model.access.csv',
    ],
    'test': [
        'test/zip_demo.yml'
    ],
    'category': 'Localization',
    'installable': True,
}

Change the version of module.

[MIG] Change the version of module.

Response:
<REPLACE_OLD> '8.0.1.0.1',
 <REPLACE_NEW> '9.0.1.0.0',
 <REPLACE_END> <REPLACE_OLD> ['test/zip_demo.yml'],
 <REPLACE_NEW> [
        'test/zip_demo.yml'
    ],
 <REPLACE_END> <REPLACE_OLD> False,
}
 <REPLACE_NEW> True,
}
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright (C) 2009  Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

{
    'name': 'Brazilian Localisation ZIP Codes',
    'license': 'AGPL-3',
    'author': 'Akretion, Odoo Community Association (OCA)',
    'version': '9.0.1.0.0',
    'depends': [
        'l10n_br_base',
    ],
    'data': [
        'views/l10n_br_zip_view.xml',
        'views/res_partner_view.xml',
        'views/res_company_view.xml',
        'views/res_bank_view.xml',
        'wizard/l10n_br_zip_search_view.xml',
        'security/ir.model.access.csv',
    ],
    'test': [
        'test/zip_demo.yml'
    ],
    'category': 'Localization',
    'installable': True,
}

Prompt:
[MIG] Change the version of module.

# -*- coding: utf-8 -*-
# Copyright (C) 2009  Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

{
    'name': 'Brazilian Localisation ZIP Codes',
    'license': 'AGPL-3',
    'author': 'Akretion, Odoo Community Association (OCA)',
    'version': '8.0.1.0.1',
    'depends': [
        'l10n_br_base',
    ],
    'data': [
        'views/l10n_br_zip_view.xml',
        'views/res_partner_view.xml',
        'views/res_company_view.xml',
        'views/res_bank_view.xml',
        'wizard/l10n_br_zip_search_view.xml',
        'security/ir.model.access.csv',
    ],
    'test': ['test/zip_demo.yml'],
    'category': 'Localization',
    'installable': False,
}


import unittest, argparse
from echolalia.formatter.yamler import Formatter

class YamlerTestCase(unittest.TestCase):

  def setUp(self):
    self.parser = argparse.ArgumentParser()
    self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
    self.formatter = Formatter()

  def test_add_args(self):
    new_parser = self.formatter.add_args(self.parser)
    self.assertEqual(new_parser, self.parser)

  def test_marshall_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args([])
    result = self.formatter.marshall(args, self.data)
    expect = "- char: a\n  order: 1\n- char: b\n  order: 2\n- char: c\n  order: 3\n"
    self.assertEqual(result, expect)

Add tests for formatter yaml

Add tests for formatter yaml

Response:
<INSERT> import unittest, argparse
from echolalia.formatter.yamler import Formatter

class YamlerTestCase(unittest.TestCase):

 <INSERT_END> <INSERT> def setUp(self):
    self.parser = argparse.ArgumentParser()
    self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
    self.formatter = Formatter()

  def test_add_args(self):
    new_parser = self.formatter.add_args(self.parser)
    self.assertEqual(new_parser, self.parser)

  def test_marshall_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args([])
    result = self.formatter.marshall(args, self.data)
    expect = "- char: a\n  order: 1\n- char: b\n  order: 2\n- char: c\n  order: 3\n"
    self.assertEqual(result, expect)
 <INSERT_END> <|endoftext|> import unittest, argparse
from echolalia.formatter.yamler import Formatter

class YamlerTestCase(unittest.TestCase):

  def setUp(self):
    self.parser = argparse.ArgumentParser()
    self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
    self.formatter = Formatter()

  def test_add_args(self):
    new_parser = self.formatter.add_args(self.parser)
    self.assertEqual(new_parser, self.parser)

  def test_marshall_header(self):
    new_parser = self.formatter.add_args(self.parser)
    args = new_parser.parse_args([])
    result = self.formatter.marshall(args, self.data)
    expect = "- char: a\n  order: 1\n- char: b\n  order: 2\n- char: c\n  order: 3\n"
    self.assertEqual(result, expect)

Prompt: Add tests for formatter yaml


# coding=utf8

# Local modules
from common import debug
from common.action import action_classes
from common.telegram import telegram_utils

from dailydevo import cac_utils

class CACDevoAction(action_classes.Action):
    def identifier(self):
        return "/cacdevo"

    def name(self):
        return "Center for Action and Contemplation Devotional"

    def resolve(self, userObj):
        passage = cac_utils.get_cacdevo(userObj.get_version())

        if passage is not None:
            telegram_utils.send_msg(passage, userObj.get_uid())

        return True

def get():
    return [
        CACDevoAction()
    ]

Fix for CACDevo hidden functionality

Fix for CACDevo hidden functionality

Response:
<REPLACE_OLD> userObj.get_uid())

def <REPLACE_NEW> userObj.get_uid())

        return True

def <REPLACE_END> <|endoftext|> # coding=utf8

# Local modules
from common import debug
from common.action import action_classes
from common.telegram import telegram_utils

from dailydevo import cac_utils

class CACDevoAction(action_classes.Action):
    def identifier(self):
        return "/cacdevo"

    def name(self):
        return "Center for Action and Contemplation Devotional"

    def resolve(self, userObj):
        passage = cac_utils.get_cacdevo(userObj.get_version())

        if passage is not None:
            telegram_utils.send_msg(passage, userObj.get_uid())

        return True

def get():
    return [
        CACDevoAction()
    ]

Prompt:
Fix for CACDevo hidden functionality

# coding=utf8

# Local modules
from common import debug
from common.action import action_classes
from common.telegram import telegram_utils

from dailydevo import cac_utils

class CACDevoAction(action_classes.Action):
    def identifier(self):
        return "/cacdevo"

    def name(self):
        return "Center for Action and Contemplation Devotional"

    def resolve(self, userObj):
        passage = cac_utils.get_cacdevo(userObj.get_version())

        if passage is not None:
            telegram_utils.send_msg(passage, userObj.get_uid())

def get():
    return [
        CACDevoAction()
    ]


from ovp_core.emails import BaseMail

class UserMail(BaseMail):
  """
  This class is responsible for firing emails for Users
  """
  def __init__(self, user, async_mail=None):
    super(UserMail, self).__init__(user.email, async_mail)

  def sendWelcome(self, context={}):
    """
    Sent when user registers
    """
    return self.sendEmail('welcome', 'Welcome', context)

  def sendRecoveryToken(self, context):
    """
    Sent when volunteer requests recovery token
    """
    context.update({
      'user_email': user.email
      })
    return self.sendEmail('recoveryToken', 'Password recovery', context)

Response:
<REPLACE_OLD> self.email_address
 <REPLACE_NEW> user.email
 <REPLACE_END> <|endoftext|> from ovp_core.emails import BaseMail

class UserMail(BaseMail):
  """
  This class is responsible for firing emails for Users
  """
  def __init__(self, user, async_mail=None):
    super(UserMail, self).__init__(user.email, async_mail)

  def sendWelcome(self, context={}):
    """
    Sent when user registers
    """
    return self.sendEmail('welcome', 'Welcome', context)

  def sendRecoveryToken(self, context):
    """
    Sent when volunteer requests recovery token
    """
    context.update({
      'user_email': user.email
      })
    return self.sendEmail('recoveryToken', 'Password recovery', context)

Prompt:
Revert "fix getting user email for recoveryToken"

This reverts commit a47b098e4d644391213958f9e05c179a7410208d.

from ovp_core.emails import BaseMail

class UserMail(BaseMail):
  """
  This class is responsible for firing emails for Users
  """
  def __init__(self, user, async_mail=None):
    super(UserMail, self).__init__(user.email, async_mail)

  def sendWelcome(self, context={}):
    """
    Sent when user registers
    """
    return self.sendEmail('welcome', 'Welcome', context)

  def sendRecoveryToken(self, context):
    """
    Sent when volunteer requests recovery token
    """
    context.update({
      'user_email': self.email_address
      })
    return self.sendEmail('recoveryToken', 'Password recovery', context)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pikalang module.

A brainfuck derivative based off the vocabulary of Pikachu from Pokemon.

Copyright (c) 2019 Blake Grotewold
"""

from __future__ import print_function

import sys
import os

from pikalang.interpreter import PikalangProgram

def load_source(file):
    if os.path.isfile(file):
        if os.path.splitext(file)[1] == ".pokeball":
            with open(file, "r") as pikalang_file:
                pikalang_data = pikalang_file.read()

            return pikalang_data

        else:
            print("pikalang: file is not a pokeball", file=sys.stderr)
            return False

    else:
        print("pikalang: file does not exist", file=sys.stderr)
        return False

def evaluate(source):
    """Run Pikalang system."""

    program = PikalangProgram(source)
    program.run()

Add proper printing for py2

Add proper printing for py2

Response:
<REPLACE_OLD> Grotewold
"""

import <REPLACE_NEW> Grotewold
"""

from __future__ import print_function

import <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pikalang module.

A brainfuck derivative based off the vocabulary of Pikachu from Pokemon.

Copyright (c) 2019 Blake Grotewold
"""

from __future__ import print_function

import sys
import os

from pikalang.interpreter import PikalangProgram

def load_source(file):
    if os.path.isfile(file):
        if os.path.splitext(file)[1] == ".pokeball":
            with open(file, "r") as pikalang_file:
                pikalang_data = pikalang_file.read()

            return pikalang_data

        else:
            print("pikalang: file is not a pokeball", file=sys.stderr)
            return False

    else:
        print("pikalang: file does not exist", file=sys.stderr)
        return False

def evaluate(source):
    """Run Pikalang system."""

    program = PikalangProgram(source)
    program.run()

Prompt:
Add proper printing for py2

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pikalang module.

A brainfuck derivative based off the vocabulary of Pikachu from Pokemon.

Copyright (c) 2019 Blake Grotewold
"""

import sys
import os

from pikalang.interpreter import PikalangProgram

def load_source(file):
    if os.path.isfile(file):
        if os.path.splitext(file)[1] == ".pokeball":
            with open(file, "r") as pikalang_file:
                pikalang_data = pikalang_file.read()

            return pikalang_data

        else:
            print("pikalang: file is not a pokeball", file=sys.stderr)
            return False

    else:
        print("pikalang: file does not exist", file=sys.stderr)
        return False

def evaluate(source):
    """Run Pikalang system."""

    program = PikalangProgram(source)
    program.run()


from typing import List
import json

class ETK(object):

    def __init__(self):
        pass

    def get_glossary(self, file_path) -> List[str]:
        """
        A glossary is a text file, one entry per line.

        Args:
            file_path (str): path to a text file containing a glossary.

        Returns: List of the strings in the glossary.
        """
        #to-do: this should be a list, not a dict
        res = dict()
        with open(file_path) as fp:
            line = fp.readline().rstrip('\n')
            while line:
                res[line] = line
                line = fp.readline().rstrip('\n')
        return res

    def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
        # cache parsed json_path, not a string, globally

        containers = doc.cdr_document['__content_strict']
        # containers = doc.select_containers(json_path)
        if isinstance(containers, list):
            for c in containers:
                segment = c.get(input_key)
                tokens = doc.get_tokens(segment)
        else:
            segment = containers.get(input_key)
            tokens = doc.get_tokens(segment)

        fake_extraction = [i.text for i in tokens]
        doc.store_extraction(extractor, fake_extraction, containers, output_key)
        print(json.dumps(doc.cdr_document, indent=2))
            # if extractor.requires_tokens():
            #     tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
            #     if tokens:
            #         extraction = extractor.extract(tokens, doc)
            #         doc.store_extraction(extractor, extraction, c, output_key)

Add comments and typing annotations

Add comments and typing annotations

Response:
<INSERT> from typing <INSERT_END> <INSERT> List
import <INSERT_END> <REPLACE_OLD> file_path):
 <REPLACE_NEW> file_path) -> List[str]:
        """
        A glossary is a text file, one entry per line.

        Args:
            file_path (str): path to a text file containing a glossary.

        Returns: List of the strings in the glossary.
        """
        #to-do: this should be a list, not a dict
 <REPLACE_END> <REPLACE_OLD> res

 <REPLACE_NEW> res

 <REPLACE_END> <|endoftext|> from typing import List
import json

class ETK(object):

    def __init__(self):
        pass

    def get_glossary(self, file_path) -> List[str]:
        """
        A glossary is a text file, one entry per line.

        Args:
            file_path (str): path to a text file containing a glossary.

        Returns: List of the strings in the glossary.
        """
        #to-do: this should be a list, not a dict
        res = dict()
        with open(file_path) as fp:
            line = fp.readline().rstrip('\n')
            while line:
                res[line] = line
                line = fp.readline().rstrip('\n')
        return res

    def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
        # cache parsed json_path, not a string, globally

        containers = doc.cdr_document['__content_strict']
        # containers = doc.select_containers(json_path)
        if isinstance(containers, list):
            for c in containers:
                segment = c.get(input_key)
                tokens = doc.get_tokens(segment)
        else:
            segment = containers.get(input_key)
            tokens = doc.get_tokens(segment)

        fake_extraction = [i.text for i in tokens]
        doc.store_extraction(extractor, fake_extraction, containers, output_key)
        print(json.dumps(doc.cdr_document, indent=2))
            # if extractor.requires_tokens():
            #     tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
            #     if tokens:
            #         extraction = extractor.extract(tokens, doc)
            #         doc.store_extraction(extractor, extraction, c, output_key)

Prompt:
Add comments and typing annotations

import json

class ETK(object):

    def __init__(self):
        pass

    def get_glossary(self, file_path):
        res = dict()
        with open(file_path) as fp:
            line = fp.readline().rstrip('\n')
            while line:
                res[line] = line
                line = fp.readline().rstrip('\n')
        return res

    def invoke_extractor(self, extractor=None, doc=None, json_path=None, input_key=None, output_key=None):
        # cache parsed json_path, not a string, globally

        containers = doc.cdr_document['__content_strict']
        # containers = doc.select_containers(json_path)
        if isinstance(containers, list):
            for c in containers:
                segment = c.get(input_key)
                tokens = doc.get_tokens(segment)
        else:
            segment = containers.get(input_key)
            tokens = doc.get_tokens(segment)

        fake_extraction = [i.text for i in tokens]
        doc.store_extraction(extractor, fake_extraction, containers, output_key)
        print(json.dumps(doc.cdr_document, indent=2))
            # if extractor.requires_tokens():
            #     tokens = doc.get_tokens(segment, tokenizer=extractor.preferred_tokenizer())
            #     if tokens:
            #         extraction = extractor.extract(tokens, doc)
            #         doc.store_extraction(extractor, extraction, c, output_key)


import logging

log = logging.getLogger(__name__)

Remove flask usage in init

Remove flask usage in init

Response:
<REPLACE_OLD> logging

from flask import Flask

log <REPLACE_NEW> logging

log <REPLACE_END> <REPLACE_OLD> logging.getLogger(__name__)

def create_app(config_dict):
    app = Flask(__name__, static_folder=None)
    app.config.update(**config_dict)

    from uiharu.api.views import api as api_blueprint
    from uiharu.weather.views import weather as weather_blueprint

    app.register_blueprint(api_blueprint, url_prefix='/api/v1')
    app.register_blueprint(weather_blueprint)

    log.info(app.url_map)

    return app
 <REPLACE_NEW> logging.getLogger(__name__)

 <REPLACE_END> <|endoftext|> import logging

log = logging.getLogger(__name__)

Prompt:
Remove flask usage in init

import logging

from flask import Flask

log = logging.getLogger(__name__)

def create_app(config_dict):
    app = Flask(__name__, static_folder=None)
    app.config.update(**config_dict)

    from uiharu.api.views import api as api_blueprint
    from uiharu.weather.views import weather as weather_blueprint

    app.register_blueprint(api_blueprint, url_prefix='/api/v1')
    app.register_blueprint(weather_blueprint)

    log.info(app.url_map)

    return app


# Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

class CST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=-6)

    def tzname(self, dt):
        return "US/Central"

    def dst(self, dt):
        return timedelta(0)

cst = CST()

class Schedule_Handler(webapp2.RequestHandler):
    def get(self):
        schedule = BlockModels.schedule()
        tlocal = datetime.now(cst)
        formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
        template_values = {
            'schedule': schedule,
            'localtime': formNow,
        }

        template = jinja_environment.get_template('schedule.html')
        self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([
    ('/schedule', Schedule_Handler)
], debug=True)

Response:
<REPLACE_OLD> MainHandler(webapp2.RequestHandler):
 <REPLACE_NEW> Schedule_Handler(webapp2.RequestHandler):
 <REPLACE_END> <REPLACE_OLD> jinja_environment.get_template('Prototype1.html')
 <REPLACE_NEW> jinja_environment.get_template('schedule.html')
 <REPLACE_END> <REPLACE_OLD> ('/', MainHandler)
], <REPLACE_NEW> ('/schedule', Schedule_Handler)
], <REPLACE_END> <|endoftext|> # Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

class CST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=-6)

    def tzname(self, dt):
        return "US/Central"

    def dst(self, dt):
        return timedelta(0)

cst = CST()

class Schedule_Handler(webapp2.RequestHandler):
    def get(self):
        schedule = BlockModels.schedule()
        tlocal = datetime.now(cst)
        formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
        template_values = {
            'schedule': schedule,
            'localtime': formNow,
        }

        template = jinja_environment.get_template('schedule.html')
        self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([
    ('/schedule', Schedule_Handler)
], debug=True)

Prompt:
Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule”

# Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *

jinja_environment = jinja2.Environment(autoescape=True,
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

class CST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=-6)

    def tzname(self, dt):
        return "US/Central"

    def dst(self, dt):
        return timedelta(0)

cst = CST()

class MainHandler(webapp2.RequestHandler):
    def get(self):
        schedule = BlockModels.schedule()
        tlocal = datetime.now(cst)
        formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
        template_values = {
            'schedule': schedule,
            'localtime': formNow,
        }

        template = jinja_environment.get_template('Prototype1.html')
        self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)


import numpy as np
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal

import nibabel as nib
from dipy.data import get_data, get_sphere
from dipy.reconst.recspeed import peak_finding
from dipy.reconst.gqi import GeneralizedQSampling
from dipy.reconst.dsi import DiffusionSpectrumImaging

def test_dandelion():

    fimg,fbvals,fbvecs=get_data('small_101D')
    bvals=np.loadtxt(fbvals)
    gradients=np.loadtxt(fbvecs).T
    data=nib.load(fimg).get_data()

    """
    print(bvals.shape, gradients.shape, data.shape)
    sd=SphericalDandelion(data,bvals,gradients)

    sdf=sd.spherical_diffusivity(data[5,5,5])

    XA=sd.xa()
    np.set_printoptions(2)
    print XA.min(),XA.max(),XA.mean()
    print sdf*10**4
    """

TEST added test for dsi

TEST added test for dsi

Response:
<INSERT> import numpy as np
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal

import nibabel as nib
from dipy.data import get_data, get_sphere
from dipy.reconst.recspeed import peak_finding
from dipy.reconst.gqi import GeneralizedQSampling
from dipy.reconst.dsi import DiffusionSpectrumImaging

def test_dandelion():
 <INSERT_END> <INSERT>
    fimg,fbvals,fbvecs=get_data('small_101D')
    bvals=np.loadtxt(fbvals)
    gradients=np.loadtxt(fbvecs).T
    data=nib.load(fimg).get_data()

    """
    print(bvals.shape, gradients.shape, data.shape)
    sd=SphericalDandelion(data,bvals,gradients)

    sdf=sd.spherical_diffusivity(data[5,5,5])

    XA=sd.xa()
    np.set_printoptions(2)
    print XA.min(),XA.max(),XA.mean()
    print sdf*10**4
    """

 <INSERT_END> <|endoftext|> import numpy as np
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal

import nibabel as nib
from dipy.data import get_data, get_sphere
from dipy.reconst.recspeed import peak_finding
from dipy.reconst.gqi import GeneralizedQSampling
from dipy.reconst.dsi import DiffusionSpectrumImaging

def test_dandelion():

    fimg,fbvals,fbvecs=get_data('small_101D')
    bvals=np.loadtxt(fbvals)
    gradients=np.loadtxt(fbvecs).T
    data=nib.load(fimg).get_data()

    """
    print(bvals.shape, gradients.shape, data.shape)
    sd=SphericalDandelion(data,bvals,gradients)

    sdf=sd.spherical_diffusivity(data[5,5,5])

    XA=sd.xa()
    np.set_printoptions(2)
    print XA.min(),XA.max(),XA.mean()
    print sdf*10**4
    """

Prompt: TEST added test for dsi


import unittest

from app.calculator import Calculator

class TestCalculator(unittest.TestCase):

    def setUp(self):
        self.calc = Calculator()

    def test_calculator_addition_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.addition(2,2)
        self.assertEqual(4, result)

    def test_calculator_subtraction_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.substraction(4,2)
        self.assertEqual(2, result)

    def test_calculator_division_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.division(5,2)
        self.assertEqual(2.5, result)

Add new test for division

Add new test for division

Response:
<INSERT> result)

    def test_calculator_division_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.division(5,2)
        self.assertEqual(2.5, <INSERT_END> <|endoftext|> import unittest

from app.calculator import Calculator

class TestCalculator(unittest.TestCase):

    def setUp(self):
        self.calc = Calculator()

    def test_calculator_addition_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.addition(2,2)
        self.assertEqual(4, result)

    def test_calculator_subtraction_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.substraction(4,2)
        self.assertEqual(2, result)

    def test_calculator_division_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.division(5,2)
        self.assertEqual(2.5, result)

Prompt:
Add new test for division

import unittest

from app.calculator import Calculator

class TestCalculator(unittest.TestCase):

    def setUp(self):
        self.calc = Calculator()

    def test_calculator_addition_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.addition(2,2)
        self.assertEqual(4, result)

    def test_calculator_subtraction_method_returns_correct_result(self):
        calc = Calculator()
        result = calc.substraction(4,2)
        self.assertEqual(2, result)


#!/usr/bin/python
"""
T Macrina
160314

Make TIF images of all H5 files in directory
**All H5 files must have "img" group

Args:
	sys.argv[1]: full path to the H5 image directory

Returns:
	TIF files (extension changed to .tif) saved in the same directory
"""

from PIL import Image
import numpy as np
import h5py
import os
import sys

def h5_to_array(fn):
	"""Open H5 file with "img" group & convert to numpy ndarray of dtype

	Args:
		fn: filename (full path) of the image

	Returns:
		An ndarray of dtype
	"""
	f = h5py.File(fn, "r")
	return np.array(f["/main"]).T

def write_array_to_sections(fn, arr):
	"""Split 3d ndarray along z dim into 2d sections & save as tifs
	"""
	for i in range(arr.shape[2]):
		section = arr[:,:,i]
		new_fn = os.path.splitext(fn)[0] + "_%03d.tif" % (i+1)
		write_to_tif(new_fn, section)

def write_to_tif(fn, arr):
	"""Write ndarray to tif file
	"""
	img = Image.fromarray(arr)
	img.save(fn)

def main():
	"""Make TIF images of all H5 matrices in directory
	"""
	dir = os.getcwd()
	file = sys.argv[1]
	files = os.listdir(dir)
	if file.endswith(".h5") or file.endswith(".hdf5"):
		fn = os.path.join(dir, file)
		arr = h5_to_array(fn)
		write_array_to_sections(fn, arr)

if __name__ == '__main__':
	main()

Include Python script to convert 3D stack into dir of tif images

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/python
"""
T Macrina
160314

Make TIF images of all H5 files in directory
**All H5 files must have "img" group

Args:
	sys.argv[1]: full path to the H5 image directory

Returns:
	TIF files (extension changed to .tif) saved in the same directory
"""

from PIL import Image
import numpy as np
import h5py
import os
import sys

def h5_to_array(fn):
	"""Open H5 file with "img" group & convert to numpy ndarray of dtype

	Args:
		fn: filename (full path) of the image

	Returns:
		An ndarray of dtype
	"""
	f = h5py.File(fn, "r")
	return np.array(f["/main"]).T

def write_array_to_sections(fn, arr):
	"""Split 3d ndarray along z dim into 2d sections & save as tifs
	"""
	for i in range(arr.shape[2]):
		section = arr[:,:,i]
		new_fn = os.path.splitext(fn)[0] + "_%03d.tif" % (i+1)
		write_to_tif(new_fn, section)

def write_to_tif(fn, arr):
	"""Write ndarray to tif file
	"""
	img = Image.fromarray(arr)
	img.save(fn)

def main():
	"""Make TIF images of all H5 matrices in directory
	"""
	dir = os.getcwd()
	file = sys.argv[1]
	files = os.listdir(dir)
	if file.endswith(".h5") or file.endswith(".hdf5"):
		fn = os.path.join(dir, file)
		arr = h5_to_array(fn)
		write_array_to_sections(fn, arr)

if __name__ == '__main__':
	main() <REPLACE_END> <|endoftext|> #!/usr/bin/python
"""
T Macrina
160314

Make TIF images of all H5 files in directory
**All H5 files must have "img" group

Args:
	sys.argv[1]: full path to the H5 image directory

Returns:
	TIF files (extension changed to .tif) saved in the same directory
"""

from PIL import Image
import numpy as np
import h5py
import os
import sys

def h5_to_array(fn):
	"""Open H5 file with "img" group & convert to numpy ndarray of dtype

	Args:
		fn: filename (full path) of the image

	Returns:
		An ndarray of dtype
	"""
	f = h5py.File(fn, "r")
	return np.array(f["/main"]).T

def write_array_to_sections(fn, arr):
	"""Split 3d ndarray along z dim into 2d sections & save as tifs
	"""
	for i in range(arr.shape[2]):
		section = arr[:,:,i]
		new_fn = os.path.splitext(fn)[0] + "_%03d.tif" % (i+1)
		write_to_tif(new_fn, section)

def write_to_tif(fn, arr):
	"""Write ndarray to tif file
	"""
	img = Image.fromarray(arr)
	img.save(fn)

def main():
	"""Make TIF images of all H5 matrices in directory
	"""
	dir = os.getcwd()
	file = sys.argv[1]
	files = os.listdir(dir)
	if file.endswith(".h5") or file.endswith(".hdf5"):
		fn = os.path.join(dir, file)
		arr = h5_to_array(fn)
		write_array_to_sections(fn, arr)

if __name__ == '__main__':
	main()

Prompt: Include Python script to convert 3D stack into dir of tif images