Add test for missing staticfiles.json

Add test for missing staticfiles.json

--- utils/tests/test_pipeline.py
+++ utils/tests/test_pipeline.py
@@ -1,11 +1,22 @@
+import os
 from io import StringIO

+from django.conf import settings
 from django.core.management import call_command
+from django.core.management.base import CommandError
 from django.test import TestCase

 class PipelineTestCase(TestCase):
+    def setUp(self):
+        file_path = os.path.join(settings.STATIC_ROOT, 'staticfiles.json')
+        if os.path.isfile(file_path):
+            os.remove(file_path)

     def test_success(self):
         call_command('collectstatic', '--noinput', stdout=StringIO())
         call_command('clean_staticfilesjson', stdout=StringIO())
+
+    def test_missing_staticfilesjson(self):
+        with self.assertRaises(CommandError):
+            call_command('clean_staticfilesjson', stdout=StringIO())

<|original_code|>
from io import StringIO

from django.core.management import call_command
from django.test import TestCase

class PipelineTestCase(TestCase):

    def test_success(self):
        call_command('collectstatic', '--noinput', stdout=StringIO())
        call_command('clean_staticfilesjson', stdout=StringIO())

<|edits_diff|>
--- utils/tests/test_pipeline.py
+++ utils/tests/test_pipeline.py
@@ -1,10 +1,17 @@
+import os
 from io import StringIO

+from django.conf import settings
 from django.core.management import call_command
+from django.core.management.base import CommandError
 from django.test import TestCase

 class PipelineTestCase(TestCase):
+    def setUp(self):
+        file_path = os.path.join(settings.STATIC_ROOT, 'staticfiles.json')
+        if os.path.isfile(file_path):
+            os.remove(file_path)

     def test_success(self):
         call_command('collectstatic', '--noinput', stdout=StringIO())
<|current_version|>
import os
from io import StringIO

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase

class PipelineTestCase(TestCase):
    def setUp(self):
        file_path = os.path.join(settings.STATIC_ROOT, 'staticfiles.json')
        if os.path.isfile(file_path):
            os.remove(file_path)

    def test_success(self):
        call_command('collectstatic', '--noinput', stdout=StringIO())
        call_command('clean_staticfilesjson', stdout=StringIO())

<|next_version|>
import os
from io import StringIO

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase

class PipelineTestCase(TestCase):
    def setUp(self):
        file_path = os.path.join(settings.STATIC_ROOT, 'staticfiles.json')
        if os.path.isfile(file_path):
            os.remove(file_path)

    def test_success(self):
        call_command('collectstatic', '--noinput', stdout=StringIO())
        call_command('clean_staticfilesjson', stdout=StringIO())

    def test_missing_staticfilesjson(self):
        with self.assertRaises(CommandError):
            call_command('clean_staticfilesjson', stdout=StringIO())


Change to correct directory when testing

--- bdp/runtests.py
+++ bdp/runtests.py
@@ -13,7 +13,9 @@
     Main eintry point
     """
     projects = PYPROJECTS.split(',')
+    projects_root = os.getcwd()
     for project in projects:
+        os.chdir(project)
         cmd = shlex.split('bin/django jenkins')
         proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
         proc.communicate()
@@ -21,6 +23,7 @@
             print "Error while testing"
         else:
             print "Success in testing"
+        os.chdir(projects_root)

 if __name__ == "__main__":
     run()

<|original_code|>
"""
Module runtests.py -

Runs all unittests configured in different buildout projects.
"""
import os
import subprocess, shlex

PYPROJECTS = 'platform/frontend'

def run():
    """
    Main eintry point
    """
    projects = PYPROJECTS.split(',')
    for project in projects:
        cmd = shlex.split('bin/django jenkins')
        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
        proc.communicate()
        if proc.returncode != 0:
            print "Error while testing"
        else:
            print "Success in testing"

if __name__ == "__main__":
    run()

<|edits_diff|>
--- bdp/runtests.py
+++ bdp/runtests.py
@@ -13,7 +13,9 @@
     Main eintry point
     """
     projects = PYPROJECTS.split(',')
+    projects_root = os.getcwd()
     for project in projects:
+        os.chdir(project)
         cmd = shlex.split('bin/django jenkins')
         proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
         proc.communicate()
<|current_version|>
"""
Module runtests.py -

Runs all unittests configured in different buildout projects.
"""
import os
import subprocess, shlex

PYPROJECTS = 'platform/frontend'

def run():
    """
    Main eintry point
    """
    projects = PYPROJECTS.split(',')
    projects_root = os.getcwd()
    for project in projects:
        os.chdir(project)
        cmd = shlex.split('bin/django jenkins')
        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
        proc.communicate()
        if proc.returncode != 0:
            print "Error while testing"
        else:
            print "Success in testing"

if __name__ == "__main__":
    run()

<|next_version|>
"""
Module runtests.py -

Runs all unittests configured in different buildout projects.
"""
import os
import subprocess, shlex

PYPROJECTS = 'platform/frontend'

def run():
    """
    Main eintry point
    """
    projects = PYPROJECTS.split(',')
    projects_root = os.getcwd()
    for project in projects:
        os.chdir(project)
        cmd = shlex.split('bin/django jenkins')
        proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
        proc.communicate()
        if proc.returncode != 0:
            print "Error while testing"
        else:
            print "Success in testing"
        os.chdir(projects_root)

if __name__ == "__main__":
    run()


Add unit test for getting reaction rate names

--- unit_tests/test_analyse_idynomics.py
+++ unit_tests/test_analyse_idynomics.py
@@ -5,6 +5,7 @@
 class TestAnalyseiDynomics:
     expected_solutes = ['MyAtmos', 'pressure']
     expected_species = ['MyBact']
+    expected_reaction_rates = ['MyGrowth-rate']
     expected_timesteps = 2
     expected_dimensions = (20.0, 20.0, 2.0)

@@ -23,6 +24,10 @@
         actual_species = self.analysis.species_names
         assert_list_equal(self.expected_species, actual_species)

+    def test_reaction_rate_names(self):
+        actual_reaction_rates = self.analysis.reaction_rate_names
+        assert_list_equal(self.expected_reaction_rates, actual_reaction_rates)
+
     def test_total_timesteps(self):
         actual_timesteps = self.analysis.total_timesteps
         assert_equals(self.expected_timesteps, actual_timesteps)
@@ -30,3 +35,5 @@
     def test_world_dimensions(self):
         actual_dimensions = self.analysis.world_dimensions
         assert_equal(self.expected_dimensions, actual_dimensions)
+
+

<|original_code|>
from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath

class TestAnalyseiDynomics:
    expected_solutes = ['MyAtmos', 'pressure']
    expected_species = ['MyBact']
    expected_timesteps = 2
    expected_dimensions = (20.0, 20.0, 2.0)

    def setUp(self):
        self.directory = join(dirname(realpath(__file__)), 'test_data')
        self.analysis = AnalyseiDynomics(self.directory)

    def test_init(self):
        assert_is(self.directory, self.analysis.directory)

    def test_solute_names(self):
        actual_solutes = self.analysis.solute_names
        assert_list_equal(self.expected_solutes, actual_solutes)

    def test_species_names(self):
        actual_species = self.analysis.species_names
        assert_list_equal(self.expected_species, actual_species)

    def test_total_timesteps(self):
        actual_timesteps = self.analysis.total_timesteps
        assert_equals(self.expected_timesteps, actual_timesteps)

    def test_world_dimensions(self):
        actual_dimensions = self.analysis.world_dimensions
        assert_equal(self.expected_dimensions, actual_dimensions)

<|edits_diff|>
--- unit_tests/test_analyse_idynomics.py
+++ unit_tests/test_analyse_idynomics.py
@@ -5,6 +5,7 @@
 class TestAnalyseiDynomics:
     expected_solutes = ['MyAtmos', 'pressure']
     expected_species = ['MyBact']
+    expected_reaction_rates = ['MyGrowth-rate']
     expected_timesteps = 2
     expected_dimensions = (20.0, 20.0, 2.0)

@@ -23,6 +24,10 @@
         actual_species = self.analysis.species_names
         assert_list_equal(self.expected_species, actual_species)

+    def test_reaction_rate_names(self):
+        actual_reaction_rates = self.analysis.reaction_rate_names
+        assert_list_equal(self.expected_reaction_rates, actual_reaction_rates)
+
     def test_total_timesteps(self):
         actual_timesteps = self.analysis.total_timesteps
         assert_equals(self.expected_timesteps, actual_timesteps)
<|current_version|>
from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath

class TestAnalyseiDynomics:
    expected_solutes = ['MyAtmos', 'pressure']
    expected_species = ['MyBact']
    expected_reaction_rates = ['MyGrowth-rate']
    expected_timesteps = 2
    expected_dimensions = (20.0, 20.0, 2.0)

    def setUp(self):
        self.directory = join(dirname(realpath(__file__)), 'test_data')
        self.analysis = AnalyseiDynomics(self.directory)

    def test_init(self):
        assert_is(self.directory, self.analysis.directory)

    def test_solute_names(self):
        actual_solutes = self.analysis.solute_names
        assert_list_equal(self.expected_solutes, actual_solutes)

    def test_species_names(self):
        actual_species = self.analysis.species_names
        assert_list_equal(self.expected_species, actual_species)

    def test_reaction_rate_names(self):
        actual_reaction_rates = self.analysis.reaction_rate_names
        assert_list_equal(self.expected_reaction_rates, actual_reaction_rates)

    def test_total_timesteps(self):
        actual_timesteps = self.analysis.total_timesteps
        assert_equals(self.expected_timesteps, actual_timesteps)

    def test_world_dimensions(self):
        actual_dimensions = self.analysis.world_dimensions
        assert_equal(self.expected_dimensions, actual_dimensions)

<|next_version|>
from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath

class TestAnalyseiDynomics:
    expected_solutes = ['MyAtmos', 'pressure']
    expected_species = ['MyBact']
    expected_reaction_rates = ['MyGrowth-rate']
    expected_timesteps = 2
    expected_dimensions = (20.0, 20.0, 2.0)

    def setUp(self):
        self.directory = join(dirname(realpath(__file__)), 'test_data')
        self.analysis = AnalyseiDynomics(self.directory)

    def test_init(self):
        assert_is(self.directory, self.analysis.directory)

    def test_solute_names(self):
        actual_solutes = self.analysis.solute_names
        assert_list_equal(self.expected_solutes, actual_solutes)

    def test_species_names(self):
        actual_species = self.analysis.species_names
        assert_list_equal(self.expected_species, actual_species)

    def test_reaction_rate_names(self):
        actual_reaction_rates = self.analysis.reaction_rate_names
        assert_list_equal(self.expected_reaction_rates, actual_reaction_rates)

    def test_total_timesteps(self):
        actual_timesteps = self.analysis.total_timesteps
        assert_equals(self.expected_timesteps, actual_timesteps)

    def test_world_dimensions(self):
        actual_dimensions = self.analysis.world_dimensions
        assert_equal(self.expected_dimensions, actual_dimensions)


Add new validators to SPA

Add new validators to SPA

--- lanes/models.py
+++ lanes/models.py
@@ -41,9 +41,17 @@
     pass

+class Period(validators.Period):
+    validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods')
+
+
 class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator):
     pass

 class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator):
     pass
+
+
+class LaneMaxReservationsPerUserValidator(validators.MaxReservationsPerUserValidator):
+    pass

<|original_code|>
from django.db import models
from django.contrib.auth.models import User

from kitabu.models.subjects import VariableSizeSubject, BaseSubject
from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation
from kitabu.models import validators

from pools.models import Pool

class Lane(VariableSizeSubject, BaseSubject):
    name = models.TextField()
    cluster = models.ForeignKey(Pool, related_name='subjects')

    def __unicode__(self):
        return self.name

class LaneReservation(ReservationMaybeExclusive, BaseReservation):
    subject = models.ForeignKey('Lane', related_name='reservations')
    group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True)
    owner = models.ForeignKey(User, null=True)

    def __unicode__(self):
        return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size)

class LaneReservationGroup(ReservationGroup):
    pass

class LaneFullTimeValidator(validators.FullTimeValidator):
    pass

class LaneTimeIntervalValidator(validators.TimeIntervalValidator):
    pass

class LaneWithinPeriodValidator(validators.WithinPeriodValidator):
    pass

class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator):
    pass

class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator):
    pass

<|edits_diff|>
--- lanes/models.py
+++ lanes/models.py
@@ -41,6 +41,10 @@
     pass

+class Period(validators.Period):
+    validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods')
+
+
 class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator):
     pass

<|current_version|>
from django.db import models
from django.contrib.auth.models import User

from kitabu.models.subjects import VariableSizeSubject, BaseSubject
from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation
from kitabu.models import validators

from pools.models import Pool

class Lane(VariableSizeSubject, BaseSubject):
    name = models.TextField()
    cluster = models.ForeignKey(Pool, related_name='subjects')

    def __unicode__(self):
        return self.name

class LaneReservation(ReservationMaybeExclusive, BaseReservation):
    subject = models.ForeignKey('Lane', related_name='reservations')
    group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True)
    owner = models.ForeignKey(User, null=True)

    def __unicode__(self):
        return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size)

class LaneReservationGroup(ReservationGroup):
    pass

class LaneFullTimeValidator(validators.FullTimeValidator):
    pass

class LaneTimeIntervalValidator(validators.TimeIntervalValidator):
    pass

class LaneWithinPeriodValidator(validators.WithinPeriodValidator):
    pass

class Period(validators.Period):
    validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods')

class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator):
    pass

class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator):
    pass

<|next_version|>
from django.db import models
from django.contrib.auth.models import User

from kitabu.models.subjects import VariableSizeSubject, BaseSubject
from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation
from kitabu.models import validators

from pools.models import Pool

class Lane(VariableSizeSubject, BaseSubject):
    name = models.TextField()
    cluster = models.ForeignKey(Pool, related_name='subjects')

    def __unicode__(self):
        return self.name

class LaneReservation(ReservationMaybeExclusive, BaseReservation):
    subject = models.ForeignKey('Lane', related_name='reservations')
    group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True)
    owner = models.ForeignKey(User, null=True)

    def __unicode__(self):
        return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size)

class LaneReservationGroup(ReservationGroup):
    pass

class LaneFullTimeValidator(validators.FullTimeValidator):
    pass

class LaneTimeIntervalValidator(validators.TimeIntervalValidator):
    pass

class LaneWithinPeriodValidator(validators.WithinPeriodValidator):
    pass

class Period(validators.Period):
    validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods')

class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator):
    pass

class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator):
    pass

class LaneMaxReservationsPerUserValidator(validators.MaxReservationsPerUserValidator):
    pass


Add gcsfs, tensorflow-datasets, zarr as dependencies.

PiperOrigin-RevId: 414517642

--- setup.py
+++ setup.py
@@ -24,14 +24,17 @@
         'absl-py',
         'dopamine-rl',
         'flax',
+        'gcsfs',
         'gin-config',
         'gym',
         'opensimplex',
         's2sphere',
         'scikit-learn',
         'tensorflow',
+        'tensorflow-datasets',
         'tensorflow-probability',
         'transitions',
+        'zarr',
     ],
     package_data={
         '': ['*.msgpack', '*.pb'],

<|original_code|>
# coding=utf-8
# Copyright 2021 The Balloon Learning Environment Authors.
#
# 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.

"""Setup file for installing the BLE."""
import setuptools

setuptools.setup(
    name='balloon_learning_environment',
    version='0.0.1',
    packages=setuptools.find_packages(),
    install_requires=[
        'absl-py',
        'dopamine-rl',
        'flax',
        'gin-config',
        'gym',
        'opensimplex',
        's2sphere',
        'scikit-learn',
        'tensorflow',
        'tensorflow-probability',
        'transitions',
    ],
    package_data={
        '': ['*.msgpack', '*.pb'],
    },
    python_requires='>=3.7',
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -24,12 +24,14 @@
         'absl-py',
         'dopamine-rl',
         'flax',
+        'gcsfs',
         'gin-config',
         'gym',
         'opensimplex',
         's2sphere',
         'scikit-learn',
         'tensorflow',
+        'tensorflow-datasets',
         'tensorflow-probability',
         'transitions',
     ],
<|current_version|>
# coding=utf-8
# Copyright 2021 The Balloon Learning Environment Authors.
#
# 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.

"""Setup file for installing the BLE."""
import setuptools

setuptools.setup(
    name='balloon_learning_environment',
    version='0.0.1',
    packages=setuptools.find_packages(),
    install_requires=[
        'absl-py',
        'dopamine-rl',
        'flax',
        'gcsfs',
        'gin-config',
        'gym',
        'opensimplex',
        's2sphere',
        'scikit-learn',
        'tensorflow',
        'tensorflow-datasets',
        'tensorflow-probability',
        'transitions',
    ],
    package_data={
        '': ['*.msgpack', '*.pb'],
    },
    python_requires='>=3.7',
)

<|next_version|>
# coding=utf-8
# Copyright 2021 The Balloon Learning Environment Authors.
#
# 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.

"""Setup file for installing the BLE."""
import setuptools

setuptools.setup(
    name='balloon_learning_environment',
    version='0.0.1',
    packages=setuptools.find_packages(),
    install_requires=[
        'absl-py',
        'dopamine-rl',
        'flax',
        'gcsfs',
        'gin-config',
        'gym',
        'opensimplex',
        's2sphere',
        'scikit-learn',
        'tensorflow',
        'tensorflow-datasets',
        'tensorflow-probability',
        'transitions',
        'zarr',
    ],
    package_data={
        '': ['*.msgpack', '*.pb'],
    },
    python_requires='>=3.7',
)


Add description and test build stage

Add description and test build stage

--- conanfile.py
+++ conanfile.py
@@ -4,6 +4,7 @@
     name = "core8"
     version = "0.1"
     url = "https://github.com/benvenutti/core8.git"
+    description = """A Chip-8 VM implemented in C++"""
     settings = "os", "compiler", "build_type", "arch"
     license = "MIT"
     exports_sources = "*"
@@ -12,6 +13,7 @@
         cmake = CMake(self.settings)
         self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
         self.run("cmake --build . %s" % cmake.build_config)
+        self.run("ctest .")

     def package(self):
         self.copy("*.hpp", dst="include/core8", src="include/core8")

<|original_code|>
from conans import ConanFile, CMake

class Core8(ConanFile):
    name = "core8"
    version = "0.1"
    url = "https://github.com/benvenutti/core8.git"
    settings = "os", "compiler", "build_type", "arch"
    license = "MIT"
    exports_sources = "*"

    def build(self):
        cmake = CMake(self.settings)
        self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
        self.run("cmake --build . %s" % cmake.build_config)

    def package(self):
        self.copy("*.hpp", dst="include/core8", src="include/core8")
        self.copy("*", dst="lib", src="lib")

    def package_info(self):
        self.cpp_info.libs = ["core8"]
<|edits_diff|>
--- conanfile.py
+++ conanfile.py
@@ -4,6 +4,7 @@
     name = "core8"
     version = "0.1"
     url = "https://github.com/benvenutti/core8.git"
+    description = """A Chip-8 VM implemented in C++"""
     settings = "os", "compiler", "build_type", "arch"
     license = "MIT"
     exports_sources = "*"
<|current_version|>
from conans import ConanFile, CMake

class Core8(ConanFile):
    name = "core8"
    version = "0.1"
    url = "https://github.com/benvenutti/core8.git"
    description = """A Chip-8 VM implemented in C++"""
    settings = "os", "compiler", "build_type", "arch"
    license = "MIT"
    exports_sources = "*"

    def build(self):
        cmake = CMake(self.settings)
        self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
        self.run("cmake --build . %s" % cmake.build_config)

    def package(self):
        self.copy("*.hpp", dst="include/core8", src="include/core8")
        self.copy("*", dst="lib", src="lib")

    def package_info(self):
        self.cpp_info.libs = ["core8"]
<|next_version|>
from conans import ConanFile, CMake

class Core8(ConanFile):
    name = "core8"
    version = "0.1"
    url = "https://github.com/benvenutti/core8.git"
    description = """A Chip-8 VM implemented in C++"""
    settings = "os", "compiler", "build_type", "arch"
    license = "MIT"
    exports_sources = "*"

    def build(self):
        cmake = CMake(self.settings)
        self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
        self.run("cmake --build . %s" % cmake.build_config)
        self.run("ctest .")

    def package(self):
        self.copy("*.hpp", dst="include/core8", src="include/core8")
        self.copy("*", dst="lib", src="lib")

    def package_info(self):
        self.cpp_info.libs = ["core8"]


Add extra missing items to the entity

Add extra missing items to the entity

--- mangopaysdk/entities/card.py
+++ mangopaysdk/entities/card.py
@@ -5,6 +5,7 @@
     """Card entity"""

     def __init__(self, id = None):
+        self.UserId = None
         # MMYY
         self.ExpirationDate = None
         # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
@@ -13,6 +14,7 @@
         self.CardProvider = None
         # CardType enum
         self.CardType = None
+        self.Country = None
         self.Product = None
         self.BankCode = None
         # Boolean

<|original_code|>
from mangopaysdk.entities.entitybase import EntityBase

class Card(EntityBase):
    """Card entity"""

    def __init__(self, id = None):
        # MMYY
        self.ExpirationDate = None
        # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
        self.Alias = None
        # The card provider, it could be CB, VISA, MASTERCARD, etc.
        self.CardProvider = None
        # CardType enum
        self.CardType = None
        self.Product = None
        self.BankCode = None
        # Boolean
        self.Active = None
        self.Currency = None
        # UNKNOWN, VALID, INVALID
        self.Validity = None
        return super(Card, self).__init__(id)

<|edits_diff|>
--- mangopaysdk/entities/card.py
+++ mangopaysdk/entities/card.py
@@ -5,6 +5,7 @@
     """Card entity"""

     def __init__(self, id = None):
+        self.UserId = None
         # MMYY
         self.ExpirationDate = None
         # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
<|current_version|>
from mangopaysdk.entities.entitybase import EntityBase

class Card(EntityBase):
    """Card entity"""

    def __init__(self, id = None):
        self.UserId = None
        # MMYY
        self.ExpirationDate = None
        # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
        self.Alias = None
        # The card provider, it could be CB, VISA, MASTERCARD, etc.
        self.CardProvider = None
        # CardType enum
        self.CardType = None
        self.Product = None
        self.BankCode = None
        # Boolean
        self.Active = None
        self.Currency = None
        # UNKNOWN, VALID, INVALID
        self.Validity = None
        return super(Card, self).__init__(id)

<|next_version|>
from mangopaysdk.entities.entitybase import EntityBase

class Card(EntityBase):
    """Card entity"""

    def __init__(self, id = None):
        self.UserId = None
        # MMYY
        self.ExpirationDate = None
        # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414
        self.Alias = None
        # The card provider, it could be CB, VISA, MASTERCARD, etc.
        self.CardProvider = None
        # CardType enum
        self.CardType = None
        self.Country = None
        self.Product = None
        self.BankCode = None
        # Boolean
        self.Active = None
        self.Currency = None
        # UNKNOWN, VALID, INVALID
        self.Validity = None
        return super(Card, self).__init__(id)


Add an RNG to each cog.

Add an RNG to each cog.

--- joku/cogs/_common.py
+++ joku/cogs/_common.py
@@ -3,6 +3,7 @@
 import threading

 import aiohttp
+import random

 from joku.bot import Jokusoramame

@@ -22,6 +23,9 @@
         # A cog-local session that can be used.
         self.session = aiohttp.ClientSession()

+        # A RNG that can be used by each cog.
+        self.rng = random.SystemRandom()
+
     def __unload(self):
         self.session.close()

<|original_code|>
from collections import OrderedDict

import threading

import aiohttp

from joku.bot import Jokusoramame

class _CogMeta(type):
    def __prepare__(*args, **kwargs):
        # Use an OrderedDict for the class body.
        return OrderedDict()

class Cog(metaclass=_CogMeta):
    def __init__(self, bot: Jokusoramame):
        self._bot = bot

        self.logger = self.bot.logger

        # A cog-local session that can be used.
        self.session = aiohttp.ClientSession()

    def __unload(self):
        self.session.close()

    @property
    def bot(self) -> 'Jokusoramame':
        """
        :return: The bot instance associated with this cog.
        """
        return self._bot

    @classmethod
    def setup(cls, bot: Jokusoramame):
        bot.add_cog(cls(bot))

<|edits_diff|>
--- joku/cogs/_common.py
+++ joku/cogs/_common.py
@@ -3,6 +3,7 @@
 import threading

 import aiohttp
+import random

 from joku.bot import Jokusoramame

<|current_version|>
from collections import OrderedDict

import threading

import aiohttp
import random

from joku.bot import Jokusoramame

class _CogMeta(type):
    def __prepare__(*args, **kwargs):
        # Use an OrderedDict for the class body.
        return OrderedDict()

class Cog(metaclass=_CogMeta):
    def __init__(self, bot: Jokusoramame):
        self._bot = bot

        self.logger = self.bot.logger

        # A cog-local session that can be used.
        self.session = aiohttp.ClientSession()

    def __unload(self):
        self.session.close()

    @property
    def bot(self) -> 'Jokusoramame':
        """
        :return: The bot instance associated with this cog.
        """
        return self._bot

    @classmethod
    def setup(cls, bot: Jokusoramame):
        bot.add_cog(cls(bot))

<|next_version|>
from collections import OrderedDict

import threading

import aiohttp
import random

from joku.bot import Jokusoramame

class _CogMeta(type):
    def __prepare__(*args, **kwargs):
        # Use an OrderedDict for the class body.
        return OrderedDict()

class Cog(metaclass=_CogMeta):
    def __init__(self, bot: Jokusoramame):
        self._bot = bot

        self.logger = self.bot.logger

        # A cog-local session that can be used.
        self.session = aiohttp.ClientSession()

        # A RNG that can be used by each cog.
        self.rng = random.SystemRandom()

    def __unload(self):
        self.session.close()

    @property
    def bot(self) -> 'Jokusoramame':
        """
        :return: The bot instance associated with this cog.
        """
        return self._bot

    @classmethod
    def setup(cls, bot: Jokusoramame):
        bot.add_cog(cls(bot))


Add test for new custom landing format

Add test for new custom landing format

--- custom/icds/tests/test_views.py
+++ custom/icds/tests/test_views.py
@@ -1,5 +1,6 @@
 from __future__ import absolute_import
 from __future__ import unicode_literals
+
 from django.test import TestCase
 from django.test.utils import override_settings
 from django.urls import reverse
@@ -7,6 +8,11 @@

 class TestViews(TestCase):
     @override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
+    def test_custom_login_old_format(self):
+        response = self.client.get(reverse("login"), follow=False)
+        self.assertEqual(response.status_code, 200)
+
+    @override_settings(CUSTOM_LANDING_TEMPLATE={"default": 'icds/login.html'})
     def test_custom_login(self):
         response = self.client.get(reverse("login"), follow=False)
         self.assertEqual(response.status_code, 200)

<|original_code|>
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse

class TestViews(TestCase):
    @override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
    def test_custom_login(self):
        response = self.client.get(reverse("login"), follow=False)
        self.assertEqual(response.status_code, 200)

<|edits_diff|>
--- custom/icds/tests/test_views.py
+++ custom/icds/tests/test_views.py
@@ -1,5 +1,6 @@
 from __future__ import absolute_import
 from __future__ import unicode_literals
+
 from django.test import TestCase
 from django.test.utils import override_settings
 from django.urls import reverse
<|current_version|>
from __future__ import absolute_import
from __future__ import unicode_literals

from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse

class TestViews(TestCase):
    @override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
    def test_custom_login(self):
        response = self.client.get(reverse("login"), follow=False)
        self.assertEqual(response.status_code, 200)

<|next_version|>
from __future__ import absolute_import
from __future__ import unicode_literals

from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse

class TestViews(TestCase):
    @override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
    def test_custom_login_old_format(self):
        response = self.client.get(reverse("login"), follow=False)
        self.assertEqual(response.status_code, 200)

    @override_settings(CUSTOM_LANDING_TEMPLATE={"default": 'icds/login.html'})
    def test_custom_login(self):
        response = self.client.get(reverse("login"), follow=False)
        self.assertEqual(response.status_code, 200)


Fix mimetype detection to handle more types.

--- plumeria/util/__init__.py
+++ plumeria/util/__init__.py
@@ -3,9 +3,12 @@
     '.jpg': 'image/jpeg',
     '.jpeg': 'image/jpeg',
     '.gif': 'image/gif',
+    '.txt': 'text/plain',
 }

 def to_mimetype(ext):
     if ext.lower() in MIME_TYPES:
         return MIME_TYPES[ext.lower()]
+    else:
+        return "application/octet-stream"

<|original_code|>
MIME_TYPES = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
}

def to_mimetype(ext):
    if ext.lower() in MIME_TYPES:
        return MIME_TYPES[ext.lower()]

<|edits_diff|>
--- plumeria/util/__init__.py
+++ plumeria/util/__init__.py
@@ -3,6 +3,7 @@
     '.jpg': 'image/jpeg',
     '.jpeg': 'image/jpeg',
     '.gif': 'image/gif',
+    '.txt': 'text/plain',
 }

<|current_version|>
MIME_TYPES = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.txt': 'text/plain',
}

def to_mimetype(ext):
    if ext.lower() in MIME_TYPES:
        return MIME_TYPES[ext.lower()]

<|next_version|>
MIME_TYPES = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.txt': 'text/plain',
}

def to_mimetype(ext):
    if ext.lower() in MIME_TYPES:
        return MIME_TYPES[ext.lower()]
    else:
        return "application/octet-stream"


Add temporary redirect for stories URL

Add temporary redirect for stories URL

--- bedrock/stories/urls.py
+++ bedrock/stories/urls.py
@@ -4,10 +4,13 @@

 from bedrock.mozorg.util import page
+from bedrock.redirects.util import redirect

 urlpatterns = (
     page("", "stories/landing.html"),
     page("art-of-engagement/", "stories/articles/art-of-engagement.html"),
     page("build-together/", "stories/articles/build-together.html"),
     page("community-champion/", "stories/articles/community-champion.html"),
+    # REMOVE WHEN REAL PAGE GOES LIVE
+    redirect(r"^joy-of-color/?$", "https://blog.mozilla.org/en/products/firefox/firefox-news/independent-voices/", permanent=False),
 )

<|original_code|>
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

from bedrock.mozorg.util import page

urlpatterns = (
    page("", "stories/landing.html"),
    page("art-of-engagement/", "stories/articles/art-of-engagement.html"),
    page("build-together/", "stories/articles/build-together.html"),
    page("community-champion/", "stories/articles/community-champion.html"),
)

<|edits_diff|>
--- bedrock/stories/urls.py
+++ bedrock/stories/urls.py
@@ -4,6 +4,7 @@

 from bedrock.mozorg.util import page
+from bedrock.redirects.util import redirect

 urlpatterns = (
     page("", "stories/landing.html"),
<|current_version|>
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

from bedrock.mozorg.util import page
from bedrock.redirects.util import redirect

urlpatterns = (
    page("", "stories/landing.html"),
    page("art-of-engagement/", "stories/articles/art-of-engagement.html"),
    page("build-together/", "stories/articles/build-together.html"),
    page("community-champion/", "stories/articles/community-champion.html"),
)

<|next_version|>
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

from bedrock.mozorg.util import page
from bedrock.redirects.util import redirect

urlpatterns = (
    page("", "stories/landing.html"),
    page("art-of-engagement/", "stories/articles/art-of-engagement.html"),
    page("build-together/", "stories/articles/build-together.html"),
    page("community-champion/", "stories/articles/community-champion.html"),
    # REMOVE WHEN REAL PAGE GOES LIVE
    redirect(r"^joy-of-color/?$", "https://blog.mozilla.org/en/products/firefox/firefox-news/independent-voices/", permanent=False),
)


Allow flier markers in box-and-whisker plots to be modified.

--- BoxAndWhisker.py
+++ BoxAndWhisker.py
@@ -1,5 +1,6 @@
 from matplotlib import pyplot
 from PlotInfo import *
+from Marker import Marker

 class BoxAndWhisker(PlotInfo):
     """
@@ -12,6 +13,9 @@
         self.color="black"
         self.label = None
         self.xSequence = []
+        self.flierMarker = Marker()
+        self.flierMarker.marker = '+'
+        self.flierMarker.color = 'b'

     def draw(self, fig, axis, transform=None):
         # To be compatible with PlotInfo assumptions
@@ -22,6 +26,11 @@

         kwdict = {}

+        if self.flierMarker.marker is not None:
+            kwdict["sym"] = self.flierMarker.marker
+        else:
+            kwdict["sym"] = ''
+
         plotHandles = axis.boxplot(self.xSequence, **kwdict)

         # Picking which part of the plot to use in the legend may

<|original_code|>
from matplotlib import pyplot
from PlotInfo import *

class BoxAndWhisker(PlotInfo):
    """
    Box and whisker plots
    """

    def __init__(self):
        super(BoxAndWhisker,self).__init__("boxplot")
        self.width=None
        self.color="black"
        self.label = None
        self.xSequence = []

    def draw(self, fig, axis, transform=None):
        # To be compatible with PlotInfo assumptions
        self.xValues = range(1,len(self.xSequence)+1)
        self.yValues = [0 for x in self.xValues]

        super(BoxAndWhisker,self).draw(fig, axis)

        kwdict = {}

        plotHandles = axis.boxplot(self.xSequence, **kwdict)

        # Picking which part of the plot to use in the legend may
        # require more thought as there are multiple lines in the
        # boxplot, as well as the possibility for outliers.
        # Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
        return [plotHandles['medians'], [self.label]]

<|edits_diff|>
--- BoxAndWhisker.py
+++ BoxAndWhisker.py
@@ -1,5 +1,6 @@
 from matplotlib import pyplot
 from PlotInfo import *
+from Marker import Marker

 class BoxAndWhisker(PlotInfo):
     """
@@ -12,6 +13,9 @@
         self.color="black"
         self.label = None
         self.xSequence = []
+        self.flierMarker = Marker()
+        self.flierMarker.marker = '+'
+        self.flierMarker.color = 'b'

     def draw(self, fig, axis, transform=None):
         # To be compatible with PlotInfo assumptions
<|current_version|>
from matplotlib import pyplot
from PlotInfo import *
from Marker import Marker

class BoxAndWhisker(PlotInfo):
    """
    Box and whisker plots
    """

    def __init__(self):
        super(BoxAndWhisker,self).__init__("boxplot")
        self.width=None
        self.color="black"
        self.label = None
        self.xSequence = []
        self.flierMarker = Marker()
        self.flierMarker.marker = '+'
        self.flierMarker.color = 'b'

    def draw(self, fig, axis, transform=None):
        # To be compatible with PlotInfo assumptions
        self.xValues = range(1,len(self.xSequence)+1)
        self.yValues = [0 for x in self.xValues]

        super(BoxAndWhisker,self).draw(fig, axis)

        kwdict = {}

        plotHandles = axis.boxplot(self.xSequence, **kwdict)

        # Picking which part of the plot to use in the legend may
        # require more thought as there are multiple lines in the
        # boxplot, as well as the possibility for outliers.
        # Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
        return [plotHandles['medians'], [self.label]]

<|next_version|>
from matplotlib import pyplot
from PlotInfo import *
from Marker import Marker

class BoxAndWhisker(PlotInfo):
    """
    Box and whisker plots
    """

    def __init__(self):
        super(BoxAndWhisker,self).__init__("boxplot")
        self.width=None
        self.color="black"
        self.label = None
        self.xSequence = []
        self.flierMarker = Marker()
        self.flierMarker.marker = '+'
        self.flierMarker.color = 'b'

    def draw(self, fig, axis, transform=None):
        # To be compatible with PlotInfo assumptions
        self.xValues = range(1,len(self.xSequence)+1)
        self.yValues = [0 for x in self.xValues]

        super(BoxAndWhisker,self).draw(fig, axis)

        kwdict = {}

        if self.flierMarker.marker is not None:
            kwdict["sym"] = self.flierMarker.marker
        else:
            kwdict["sym"] = ''

        plotHandles = axis.boxplot(self.xSequence, **kwdict)

        # Picking which part of the plot to use in the legend may
        # require more thought as there are multiple lines in the
        # boxplot, as well as the possibility for outliers.
        # Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
        return [plotHandles['medians'], [self.label]]


Set input type to phone for phone.

Set input type to phone for phone.

--- django_classified/forms.py
+++ django_classified/forms.py
@@ -38,9 +38,16 @@
         )

+class PhoneWidget(forms.TextInput):
+    input_type = 'phone'
+
+
 class ProfileForm(forms.ModelForm):
     class Meta:
         model = Profile
         fields = (
             'phone',
         )
+        widgets = {
+            'phone': PhoneWidget
+        }

<|original_code|>
# -*- coding:utf-8 -*-
from django import forms
from django.utils.translation import ugettext as _

from .models import Item, Group, Profile, Area

class SearchForm(forms.Form):
    area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False)
    group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False)
    q = forms.CharField(required=False, label=_('Query'),)

    def filter_by(self):
        # TODO search using more than one field
        # TODO split query string and make seaprate search by words
        filters = {}
        if self.cleaned_data['group']:
            filters['group'] = self.cleaned_data['group']

        if self.cleaned_data['area']:
            filters['area'] = self.cleaned_data['area']

        filters['description__icontains'] = self.cleaned_data['q']

        return filters

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = (
            'area',
            'group',
            'title',
            'description',
            'price',
            'is_active'
        )

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = (
            'phone',
        )

<|edits_diff|>
--- django_classified/forms.py
+++ django_classified/forms.py
@@ -38,6 +38,10 @@
         )

+class PhoneWidget(forms.TextInput):
+    input_type = 'phone'
+
+
 class ProfileForm(forms.ModelForm):
     class Meta:
         model = Profile
<|current_version|>
# -*- coding:utf-8 -*-
from django import forms
from django.utils.translation import ugettext as _

from .models import Item, Group, Profile, Area

class SearchForm(forms.Form):
    area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False)
    group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False)
    q = forms.CharField(required=False, label=_('Query'),)

    def filter_by(self):
        # TODO search using more than one field
        # TODO split query string and make seaprate search by words
        filters = {}
        if self.cleaned_data['group']:
            filters['group'] = self.cleaned_data['group']

        if self.cleaned_data['area']:
            filters['area'] = self.cleaned_data['area']

        filters['description__icontains'] = self.cleaned_data['q']

        return filters

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = (
            'area',
            'group',
            'title',
            'description',
            'price',
            'is_active'
        )

class PhoneWidget(forms.TextInput):
    input_type = 'phone'

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = (
            'phone',
        )

<|next_version|>
# -*- coding:utf-8 -*-
from django import forms
from django.utils.translation import ugettext as _

from .models import Item, Group, Profile, Area

class SearchForm(forms.Form):
    area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False)
    group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False)
    q = forms.CharField(required=False, label=_('Query'),)

    def filter_by(self):
        # TODO search using more than one field
        # TODO split query string and make seaprate search by words
        filters = {}
        if self.cleaned_data['group']:
            filters['group'] = self.cleaned_data['group']

        if self.cleaned_data['area']:
            filters['area'] = self.cleaned_data['area']

        filters['description__icontains'] = self.cleaned_data['q']

        return filters

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = (
            'area',
            'group',
            'title',
            'description',
            'price',
            'is_active'
        )

class PhoneWidget(forms.TextInput):
    input_type = 'phone'

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = (
            'phone',
        )
        widgets = {
            'phone': PhoneWidget
        }


Add sleeps to test to avoid eutils issues

--- tests/test_basic.py
+++ tests/test_basic.py
@@ -2,16 +2,19 @@
 import pubrunner
 import pubrunner.command_line
 import os
+import time

 def test_countwords():
 	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 	projectPath = os.path.join(parentDir,'examples','CountWords')
 	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
 	pubrunner.command_line.main()
+	time.sleep(1)

 def test_textminingcounter():
 	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 	projectPath = os.path.join(parentDir,'examples','TextMiningCounter')
 	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
 	pubrunner.command_line.main()
+	time.sleep(1)

<|original_code|>
import sys
import pubrunner
import pubrunner.command_line
import os

def test_countwords():
	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	projectPath = os.path.join(parentDir,'examples','CountWords')
	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
	pubrunner.command_line.main()

def test_textminingcounter():
	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	projectPath = os.path.join(parentDir,'examples','TextMiningCounter')
	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
	pubrunner.command_line.main()

<|edits_diff|>
--- tests/test_basic.py
+++ tests/test_basic.py
@@ -2,12 +2,14 @@
 import pubrunner
 import pubrunner.command_line
 import os
+import time

 def test_countwords():
 	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 	projectPath = os.path.join(parentDir,'examples','CountWords')
 	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
 	pubrunner.command_line.main()
+	time.sleep(1)

 def test_textminingcounter():
 	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
<|current_version|>
import sys
import pubrunner
import pubrunner.command_line
import os
import time

def test_countwords():
	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	projectPath = os.path.join(parentDir,'examples','CountWords')
	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
	pubrunner.command_line.main()
	time.sleep(1)

def test_textminingcounter():
	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	projectPath = os.path.join(parentDir,'examples','TextMiningCounter')
	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
	pubrunner.command_line.main()

<|next_version|>
import sys
import pubrunner
import pubrunner.command_line
import os
import time

def test_countwords():
	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	projectPath = os.path.join(parentDir,'examples','CountWords')
	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
	pubrunner.command_line.main()
	time.sleep(1)

def test_textminingcounter():
	parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	projectPath = os.path.join(parentDir,'examples','TextMiningCounter')
	sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath]
	pubrunner.command_line.main()
	time.sleep(1)


Set better defaults for numpy's print function

--- __init__.py
+++ __init__.py
@@ -6,6 +6,8 @@
 from spinsys import state_generators
 from spinsys import tests
 from spinsys import utils
+import shutil
+import numpy

 __all__ = [
     "constructors",
@@ -17,3 +19,7 @@
     "tests",
     "utils"
 ]
+
+# set default print options for better display of data on screen
+term_width = tuple(shutil.get_terminal_size())[0]
+numpy.set_printoptions(precision=5, suppress=True, linewidth=term_width)

<|original_code|>
from spinsys import constructors
from spinsys import exceptions
from spinsys import half
from spinsys import hamiltonians
from spinsys import quantities
from spinsys import state_generators
from spinsys import tests
from spinsys import utils

__all__ = [
    "constructors",
    "exceptions",
    "half",
    "hamiltonians",
    "quantities",
    "state_generators",
    "tests",
    "utils"
]

<|edits_diff|>
--- __init__.py
+++ __init__.py
@@ -6,6 +6,8 @@
 from spinsys import state_generators
 from spinsys import tests
 from spinsys import utils
+import shutil
+import numpy

 __all__ = [
     "constructors",
<|current_version|>
from spinsys import constructors
from spinsys import exceptions
from spinsys import half
from spinsys import hamiltonians
from spinsys import quantities
from spinsys import state_generators
from spinsys import tests
from spinsys import utils
import shutil
import numpy

__all__ = [
    "constructors",
    "exceptions",
    "half",
    "hamiltonians",
    "quantities",
    "state_generators",
    "tests",
    "utils"
]

<|next_version|>
from spinsys import constructors
from spinsys import exceptions
from spinsys import half
from spinsys import hamiltonians
from spinsys import quantities
from spinsys import state_generators
from spinsys import tests
from spinsys import utils
import shutil
import numpy

__all__ = [
    "constructors",
    "exceptions",
    "half",
    "hamiltonians",
    "quantities",
    "state_generators",
    "tests",
    "utils"
]

# set default print options for better display of data on screen
term_width = tuple(shutil.get_terminal_size())[0]
numpy.set_printoptions(precision=5, suppress=True, linewidth=term_width)


Mark ubuntupkg tests as flaky

Mark ubuntupkg tests as flaky

--- tests/test_ubuntupkg.py
+++ tests/test_ubuntupkg.py
@@ -1,17 +1,22 @@
 # MIT licensed
 # Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.

+from flaky import flaky
 import pytest
 pytestmark = pytest.mark.asyncio

+@flaky
 async def test_ubuntupkg(get_version):
     assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"

+@flaky
 async def test_ubuntupkg_strip_release(get_version):
     assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"

+@flaky
 async def test_ubuntupkg_suite(get_version):
     assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"

+@flaky
 async def test_ubuntupkg_suite_with_paging(get_version):
     assert await get_version("ffmpeg", {"ubuntupkg": None, "suite": "vivid"}) == "7:2.5.10-0ubuntu0.15.04.1"

<|original_code|>
# MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.

import pytest
pytestmark = pytest.mark.asyncio

async def test_ubuntupkg(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"

async def test_ubuntupkg_strip_release(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"

async def test_ubuntupkg_suite(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"

async def test_ubuntupkg_suite_with_paging(get_version):
    assert await get_version("ffmpeg", {"ubuntupkg": None, "suite": "vivid"}) == "7:2.5.10-0ubuntu0.15.04.1"

<|edits_diff|>
--- tests/test_ubuntupkg.py
+++ tests/test_ubuntupkg.py
@@ -1,15 +1,19 @@
 # MIT licensed
 # Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.

+from flaky import flaky
 import pytest
 pytestmark = pytest.mark.asyncio

+@flaky
 async def test_ubuntupkg(get_version):
     assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"

+@flaky
 async def test_ubuntupkg_strip_release(get_version):
     assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"

+@flaky
 async def test_ubuntupkg_suite(get_version):
     assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"

<|current_version|>
# MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.

from flaky import flaky
import pytest
pytestmark = pytest.mark.asyncio

@flaky
async def test_ubuntupkg(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"

@flaky
async def test_ubuntupkg_strip_release(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"

@flaky
async def test_ubuntupkg_suite(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"

async def test_ubuntupkg_suite_with_paging(get_version):
    assert await get_version("ffmpeg", {"ubuntupkg": None, "suite": "vivid"}) == "7:2.5.10-0ubuntu0.15.04.1"

<|next_version|>
# MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.

from flaky import flaky
import pytest
pytestmark = pytest.mark.asyncio

@flaky
async def test_ubuntupkg(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"

@flaky
async def test_ubuntupkg_strip_release(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"

@flaky
async def test_ubuntupkg_suite(get_version):
    assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"

@flaky
async def test_ubuntupkg_suite_with_paging(get_version):
    assert await get_version("ffmpeg", {"ubuntupkg": None, "suite": "vivid"}) == "7:2.5.10-0ubuntu0.15.04.1"


Add utility for address change functionality testing

--- utils/addressTest.py
+++ utils/addressTest.py
@@ -1,11 +1,22 @@
 #!/usr/bin/python
+
+"""Looks for sensor with ADDRESS1 and changes it's address to ADDRESS2 then changes it back to ADDRESS1"""
+
 import minimalmodbus
+import serial
 from time import sleep
 ADDRESS1 = 1
 ADDRESS2 = 2

 minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
+minimalmodbus.PARITY=serial.PARITY_NONE
+minimalmodbus.STOPBITS = 2
+minimalmodbus.BAUDRATE=19200
+
+minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
 sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
+sensor.debug=True
+print(("reading address: ") + str(sensor.read_register(0, functioncode=3)))
 print("writing new address: " + str(ADDRESS2))
 sensor.write_register(0, value=ADDRESS2, functioncode=6)

<|original_code|>
#!/usr/bin/python
import minimalmodbus
from time import sleep
ADDRESS1 = 1
ADDRESS2 = 2

minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
print("writing new address: " + str(ADDRESS2))
sensor.write_register(0, value=ADDRESS2, functioncode=6)

sleep(0.2)
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS2)
print("reading address from holding register: ")
print(sensor.read_register(0, functioncode=3))

print("writing new address: " + str(ADDRESS1))
sensor.write_register(0, value=ADDRESS1, functioncode=6)

sleep(0.2)
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
print("reading address from holding register: ")
print(sensor.read_register(0, functioncode=3))

<|edits_diff|>
--- utils/addressTest.py
+++ utils/addressTest.py
@@ -1,8 +1,17 @@
 #!/usr/bin/python
+
+"""Looks for sensor with ADDRESS1 and changes it's address to ADDRESS2 then changes it back to ADDRESS1"""
+
 import minimalmodbus
+import serial
 from time import sleep
 ADDRESS1 = 1
 ADDRESS2 = 2
+
+minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
+minimalmodbus.PARITY=serial.PARITY_NONE
+minimalmodbus.STOPBITS = 2
+minimalmodbus.BAUDRATE=19200

 minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
 sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
<|current_version|>
#!/usr/bin/python

"""Looks for sensor with ADDRESS1 and changes it's address to ADDRESS2 then changes it back to ADDRESS1"""

import minimalmodbus
import serial
from time import sleep
ADDRESS1 = 1
ADDRESS2 = 2

minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
minimalmodbus.PARITY=serial.PARITY_NONE
minimalmodbus.STOPBITS = 2
minimalmodbus.BAUDRATE=19200

minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
print("writing new address: " + str(ADDRESS2))
sensor.write_register(0, value=ADDRESS2, functioncode=6)

sleep(0.2)
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS2)
print("reading address from holding register: ")
print(sensor.read_register(0, functioncode=3))

print("writing new address: " + str(ADDRESS1))
sensor.write_register(0, value=ADDRESS1, functioncode=6)

sleep(0.2)
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
print("reading address from holding register: ")
print(sensor.read_register(0, functioncode=3))

<|next_version|>
#!/usr/bin/python

"""Looks for sensor with ADDRESS1 and changes it's address to ADDRESS2 then changes it back to ADDRESS1"""

import minimalmodbus
import serial
from time import sleep
ADDRESS1 = 1
ADDRESS2 = 2

minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
minimalmodbus.PARITY=serial.PARITY_NONE
minimalmodbus.STOPBITS = 2
minimalmodbus.BAUDRATE=19200

minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = True
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
sensor.debug=True
print(("reading address: ") + str(sensor.read_register(0, functioncode=3)))
print("writing new address: " + str(ADDRESS2))
sensor.write_register(0, value=ADDRESS2, functioncode=6)

sleep(0.2)
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS2)
print("reading address from holding register: ")
print(sensor.read_register(0, functioncode=3))

print("writing new address: " + str(ADDRESS1))
sensor.write_register(0, value=ADDRESS1, functioncode=6)

sleep(0.2)
sensor = minimalmodbus.Instrument('/dev/ttyUSB5', slaveaddress=ADDRESS1)
print("reading address from holding register: ")
print(sensor.read_register(0, functioncode=3))


Change init to add inverse strategy

Change init to add inverse strategy

--- axelrod/strategies/__init__.py
+++ axelrod/strategies/__init__.py
@@ -7,6 +7,7 @@
 from alternator import *
 from averagecopier import *
 from grumpy import *
+from inverse import *

 strategies = [
@@ -19,4 +20,5 @@
         Alternator,
         AverageCopier,
         Grumpy,
+        Inverse
         ]

<|original_code|>
from cooperator import *
from defector import *
from grudger import *
from rand import *
from titfortat import *
from gobymajority import *
from alternator import *
from averagecopier import *
from grumpy import *

strategies = [
        Defector,
        Cooperator,
        TitForTat,
        Grudger,
        GoByMajority,
        Random,
        Alternator,
        AverageCopier,
        Grumpy,
        ]

<|edits_diff|>
--- axelrod/strategies/__init__.py
+++ axelrod/strategies/__init__.py
@@ -7,6 +7,7 @@
 from alternator import *
 from averagecopier import *
 from grumpy import *
+from inverse import *

 strategies = [
<|current_version|>
from cooperator import *
from defector import *
from grudger import *
from rand import *
from titfortat import *
from gobymajority import *
from alternator import *
from averagecopier import *
from grumpy import *
from inverse import *

strategies = [
        Defector,
        Cooperator,
        TitForTat,
        Grudger,
        GoByMajority,
        Random,
        Alternator,
        AverageCopier,
        Grumpy,
        ]

<|next_version|>
from cooperator import *
from defector import *
from grudger import *
from rand import *
from titfortat import *
from gobymajority import *
from alternator import *
from averagecopier import *
from grumpy import *
from inverse import *

strategies = [
        Defector,
        Cooperator,
        TitForTat,
        Grudger,
        GoByMajority,
        Random,
        Alternator,
        AverageCopier,
        Grumpy,
        Inverse
        ]


Modify login view to be a post endpoint

Modify login view to be a post endpoint

--- assassins/assassins/views.py
+++ assassins/assassins/views.py
@@ -1,10 +1,12 @@
 from django.shortcuts import render, redirect
 from django.contrib.auth import views as auth_views
+from django.views.decorators.http import require_POST

 # Create your views here.
 def index(request):
 	pass

+@require_POST
 def login(request, **kwargs):
 	if request.user.is_authenticated():
 		return redirect('index')

<|original_code|>
from django.shortcuts import render, redirect
from django.contrib.auth import views as auth_views

# Create your views here.
def index(request):
	pass

def login(request, **kwargs):
	if request.user.is_authenticated():
		return redirect('index')
	else:
		return auth_views.login(request)

<|edits_diff|>
--- assassins/assassins/views.py
+++ assassins/assassins/views.py
@@ -1,5 +1,6 @@
 from django.shortcuts import render, redirect
 from django.contrib.auth import views as auth_views
+from django.views.decorators.http import require_POST

 # Create your views here.
 def index(request):
<|current_version|>
from django.shortcuts import render, redirect
from django.contrib.auth import views as auth_views
from django.views.decorators.http import require_POST

# Create your views here.
def index(request):
	pass

def login(request, **kwargs):
	if request.user.is_authenticated():
		return redirect('index')
	else:
		return auth_views.login(request)

<|next_version|>
from django.shortcuts import render, redirect
from django.contrib.auth import views as auth_views
from django.views.decorators.http import require_POST

# Create your views here.
def index(request):
	pass

@require_POST
def login(request, **kwargs):
	if request.user.is_authenticated():
		return redirect('index')
	else:
		return auth_views.login(request)


Cover unknown time format case

Cover unknown time format case

--- tests/test_util.py
+++ tests/test_util.py
@@ -1,3 +1,5 @@
+import pytest
+
 from grazer.util import time_convert, grouper

@@ -12,6 +14,10 @@
     def test_hours(self):
         assert time_convert("3h") == 3 * 60 * 60

+    def test_unknown(self):
+        with pytest.raises(RuntimeError):
+            time_convert("5u")
+

 class TestGrouper(object):

<|original_code|>
from grazer.util import time_convert, grouper

class TestTimeConvert(object):

    def test_seconds(self):
        assert time_convert("10s") == 10

    def test_minutes(self):
        assert time_convert("2m") == 120

    def test_hours(self):
        assert time_convert("3h") == 3 * 60 * 60

class TestGrouper(object):

    def test_simple_seq(self):
        seq = range(0, 10)
        result = list(grouper(2, seq))
        assert len(result) == 5

    def test_odd_seq(self):
        seq = range(0, 10)
        result = list(grouper(3, seq))
        assert len(result) == 4
        assert result[-1] == (9, None, None)

<|edits_diff|>
--- tests/test_util.py
+++ tests/test_util.py
@@ -1,3 +1,5 @@
+import pytest
+
 from grazer.util import time_convert, grouper

<|current_version|>
import pytest

from grazer.util import time_convert, grouper

class TestTimeConvert(object):

    def test_seconds(self):
        assert time_convert("10s") == 10

    def test_minutes(self):
        assert time_convert("2m") == 120

    def test_hours(self):
        assert time_convert("3h") == 3 * 60 * 60

class TestGrouper(object):

    def test_simple_seq(self):
        seq = range(0, 10)
        result = list(grouper(2, seq))
        assert len(result) == 5

    def test_odd_seq(self):
        seq = range(0, 10)
        result = list(grouper(3, seq))
        assert len(result) == 4
        assert result[-1] == (9, None, None)

<|next_version|>
import pytest

from grazer.util import time_convert, grouper

class TestTimeConvert(object):

    def test_seconds(self):
        assert time_convert("10s") == 10

    def test_minutes(self):
        assert time_convert("2m") == 120

    def test_hours(self):
        assert time_convert("3h") == 3 * 60 * 60

    def test_unknown(self):
        with pytest.raises(RuntimeError):
            time_convert("5u")

class TestGrouper(object):

    def test_simple_seq(self):
        seq = range(0, 10)
        result = list(grouper(2, seq))
        assert len(result) == 5

    def test_odd_seq(self):
        seq = range(0, 10)
        result = list(grouper(3, seq))
        assert len(result) == 4
        assert result[-1] == (9, None, None)


Add indicator for how many datapoints have been loaded

--- data/load_data.py
+++ data/load_data.py
@@ -9,6 +9,7 @@
     with open(path, "r") as csvfile:
         reader = csv.reader(csvfile, delimiter=',', quotechar='"')
         points = []
+        count = 0
         for row in reader:
             if row == []:
                 continue
@@ -37,6 +38,8 @@
                         decay_feature=decay_feature)
                 point.clean_fields()
                 points.append(point)
+                count += 1
             except Exception as e:
                 pass
         DataPoint.objects.bulk_create(points)
+        print "Added %d datapoints." % count

<|original_code|>
import csv

from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint

def main(path):
    with open(path, "r") as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        points = []
        for row in reader:
            if row == []:
                continue
            try:
                band_gap = row[10]
                if band_gap == '---':
                    band_gap = None
                options = row[4]

                try:
                    exact_name = get_exact_name(row[1])
                    try:
                        decay_feature = get_decay_feature_vector(exact_name)
                    except:
                        decay_feature = None
                except:
                    exact_name = None
                    decay_feature = None

                point = DataPoint(
                        name=row[1], options=row[4],
                        homo=row[5], lumo=row[6],
                        homo_orbital=row[7], dipole=row[8],
                        energy=row[9], band_gap=band_gap,
                        exact_name=exact_name,
                        decay_feature=decay_feature)
                point.clean_fields()
                points.append(point)
            except Exception as e:
                pass
        DataPoint.objects.bulk_create(points)

<|edits_diff|>
--- data/load_data.py
+++ data/load_data.py
@@ -9,6 +9,7 @@
     with open(path, "r") as csvfile:
         reader = csv.reader(csvfile, delimiter=',', quotechar='"')
         points = []
+        count = 0
         for row in reader:
             if row == []:
                 continue
@@ -37,6 +38,7 @@
                         decay_feature=decay_feature)
                 point.clean_fields()
                 points.append(point)
+                count += 1
             except Exception as e:
                 pass
         DataPoint.objects.bulk_create(points)
<|current_version|>
import csv

from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint

def main(path):
    with open(path, "r") as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        points = []
        count = 0
        for row in reader:
            if row == []:
                continue
            try:
                band_gap = row[10]
                if band_gap == '---':
                    band_gap = None
                options = row[4]

                try:
                    exact_name = get_exact_name(row[1])
                    try:
                        decay_feature = get_decay_feature_vector(exact_name)
                    except:
                        decay_feature = None
                except:
                    exact_name = None
                    decay_feature = None

                point = DataPoint(
                        name=row[1], options=row[4],
                        homo=row[5], lumo=row[6],
                        homo_orbital=row[7], dipole=row[8],
                        energy=row[9], band_gap=band_gap,
                        exact_name=exact_name,
                        decay_feature=decay_feature)
                point.clean_fields()
                points.append(point)
                count += 1
            except Exception as e:
                pass
        DataPoint.objects.bulk_create(points)

<|next_version|>
import csv

from chemtools.ml import get_decay_feature_vector
from chemtools.mol_name import get_exact_name
from models import DataPoint

def main(path):
    with open(path, "r") as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        points = []
        count = 0
        for row in reader:
            if row == []:
                continue
            try:
                band_gap = row[10]
                if band_gap == '---':
                    band_gap = None
                options = row[4]

                try:
                    exact_name = get_exact_name(row[1])
                    try:
                        decay_feature = get_decay_feature_vector(exact_name)
                    except:
                        decay_feature = None
                except:
                    exact_name = None
                    decay_feature = None

                point = DataPoint(
                        name=row[1], options=row[4],
                        homo=row[5], lumo=row[6],
                        homo_orbital=row[7], dipole=row[8],
                        energy=row[9], band_gap=band_gap,
                        exact_name=exact_name,
                        decay_feature=decay_feature)
                point.clean_fields()
                points.append(point)
                count += 1
            except Exception as e:
                pass
        DataPoint.objects.bulk_create(points)
        print "Added %d datapoints." % count


Set a user agent for the webhook if not provided

--- awx/main/notifications/webhook_backend.py
+++ awx/main/notifications/webhook_backend.py
@@ -8,6 +8,7 @@
 from django.utils.encoding import smart_text

 from awx.main.notifications.base import TowerBaseEmailBackend
+from awx.main.utils import get_awx_version

 logger = logging.getLogger('awx.main.notifications.webhook_backend')

@@ -27,6 +28,8 @@

     def send_messages(self, messages):
         sent_messages = 0
+        if 'User-Agent' not in self.headers:
+            self.headers['User-Agent'] = "Tower {}".format(get_awx_version())
         for m in messages:
             r = requests.post("{}".format(m.recipients()[0]),
                               data=json.dumps(m.body),

<|original_code|>
# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.

import logging
import requests
import json

from django.utils.encoding import smart_text

from awx.main.notifications.base import TowerBaseEmailBackend

logger = logging.getLogger('awx.main.notifications.webhook_backend')

class WebhookBackend(TowerBaseEmailBackend):

    init_parameters = {"url": {"label": "Target URL", "type": "string"},
                       "headers": {"label": "HTTP Headers", "type": "object"}}
    recipient_parameter = "url"
    sender_parameter = None

    def __init__(self, headers, fail_silently=False, **kwargs):
        self.headers = headers
        super(WebhookBackend, self).__init__(fail_silently=fail_silently)

    def format_body(self, body):
        return body

    def send_messages(self, messages):
        sent_messages = 0
        for m in messages:
            r = requests.post("{}".format(m.recipients()[0]),
                              data=json.dumps(m.body),
                              headers=self.headers)
            if r.status_code >= 400:
                logger.error(smart_text("Error sending notification webhook: {}".format(r.text)))
                if not self.fail_silently:
                    raise Exception(smart_text("Error sending notification webhook: {}".format(r.text)))
            sent_messages += 1
        return sent_messages

<|edits_diff|>
--- awx/main/notifications/webhook_backend.py
+++ awx/main/notifications/webhook_backend.py
@@ -8,6 +8,7 @@
 from django.utils.encoding import smart_text

 from awx.main.notifications.base import TowerBaseEmailBackend
+from awx.main.utils import get_awx_version

 logger = logging.getLogger('awx.main.notifications.webhook_backend')

<|current_version|>
# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.

import logging
import requests
import json

from django.utils.encoding import smart_text

from awx.main.notifications.base import TowerBaseEmailBackend
from awx.main.utils import get_awx_version

logger = logging.getLogger('awx.main.notifications.webhook_backend')

class WebhookBackend(TowerBaseEmailBackend):

    init_parameters = {"url": {"label": "Target URL", "type": "string"},
                       "headers": {"label": "HTTP Headers", "type": "object"}}
    recipient_parameter = "url"
    sender_parameter = None

    def __init__(self, headers, fail_silently=False, **kwargs):
        self.headers = headers
        super(WebhookBackend, self).__init__(fail_silently=fail_silently)

    def format_body(self, body):
        return body

    def send_messages(self, messages):
        sent_messages = 0
        for m in messages:
            r = requests.post("{}".format(m.recipients()[0]),
                              data=json.dumps(m.body),
                              headers=self.headers)
            if r.status_code >= 400:
                logger.error(smart_text("Error sending notification webhook: {}".format(r.text)))
                if not self.fail_silently:
                    raise Exception(smart_text("Error sending notification webhook: {}".format(r.text)))
            sent_messages += 1
        return sent_messages

<|next_version|>
# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.

import logging
import requests
import json

from django.utils.encoding import smart_text

from awx.main.notifications.base import TowerBaseEmailBackend
from awx.main.utils import get_awx_version

logger = logging.getLogger('awx.main.notifications.webhook_backend')

class WebhookBackend(TowerBaseEmailBackend):

    init_parameters = {"url": {"label": "Target URL", "type": "string"},
                       "headers": {"label": "HTTP Headers", "type": "object"}}
    recipient_parameter = "url"
    sender_parameter = None

    def __init__(self, headers, fail_silently=False, **kwargs):
        self.headers = headers
        super(WebhookBackend, self).__init__(fail_silently=fail_silently)

    def format_body(self, body):
        return body

    def send_messages(self, messages):
        sent_messages = 0
        if 'User-Agent' not in self.headers:
            self.headers['User-Agent'] = "Tower {}".format(get_awx_version())
        for m in messages:
            r = requests.post("{}".format(m.recipients()[0]),
                              data=json.dumps(m.body),
                              headers=self.headers)
            if r.status_code >= 400:
                logger.error(smart_text("Error sending notification webhook: {}".format(r.text)))
                if not self.fail_silently:
                    raise Exception(smart_text("Error sending notification webhook: {}".format(r.text)))
            sent_messages += 1
        return sent_messages


Change so that kvsession (server side sessions) is used instead of flask default

--- api/__init__.py
+++ api/__init__.py
@@ -1,6 +1,12 @@
 from flask import Flask
+from simplekv.memory import DictStore
+from flaskext.kvsession import KVSessionExtension

+# Use DictStore until the code is ready for production
+store = DictStore()
 app = Flask(__name__)
 app.secret_key = ''

+KVSessionExtension(store, app)
+
 import api.userview

<|original_code|>
from flask import Flask

app = Flask(__name__)
app.secret_key = ''

import api.userview

<|edits_diff|>
--- api/__init__.py
+++ api/__init__.py
@@ -1,5 +1,9 @@
 from flask import Flask
+from simplekv.memory import DictStore
+from flaskext.kvsession import KVSessionExtension

+# Use DictStore until the code is ready for production
+store = DictStore()
 app = Flask(__name__)
 app.secret_key = ''

<|current_version|>
from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension

# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''

import api.userview

<|next_version|>
from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension

# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''

KVSessionExtension(store, app)

import api.userview


Add tests for the subtraction operator for BCEDate.

--- calexicon/dates/tests/test_bce.py
+++ calexicon/dates/tests/test_bce.py
@@ -1,4 +1,6 @@
 import unittest
+
+from datetime import timedelta

 from calexicon.dates import BCEDate

@@ -11,3 +13,7 @@

     def test_equality(self):
         self.assertEqual(BCEDate(-44, 3, 15), BCEDate(-44, 3, 15))
+
+    def test_subtraction(self):
+        self.assertEqual(timedelta(days=4), BCEDate(-44, 3, 15) - BCEDate(-44, 3, 11))
+        self.assertEqual(timedelta(days=33), BCEDate(-44, 3, 15) - BCEDate(-44, 2, 11))

<|original_code|>
import unittest

from calexicon.dates import BCEDate

class TestBCEDate(unittest.TestCase):

    def test_make_bce_date(self):
        bd = BCEDate(-4713, 1, 1)
        self.assertEqual(bd.julian_representation(), (-4713, 1, 1))

    def test_equality(self):
        self.assertEqual(BCEDate(-44, 3, 15), BCEDate(-44, 3, 15))

<|edits_diff|>
--- calexicon/dates/tests/test_bce.py
+++ calexicon/dates/tests/test_bce.py
@@ -1,4 +1,6 @@
 import unittest
+
+from datetime import timedelta

 from calexicon.dates import BCEDate

<|current_version|>
import unittest

from datetime import timedelta

from calexicon.dates import BCEDate

class TestBCEDate(unittest.TestCase):

    def test_make_bce_date(self):
        bd = BCEDate(-4713, 1, 1)
        self.assertEqual(bd.julian_representation(), (-4713, 1, 1))

    def test_equality(self):
        self.assertEqual(BCEDate(-44, 3, 15), BCEDate(-44, 3, 15))

<|next_version|>
import unittest

from datetime import timedelta

from calexicon.dates import BCEDate

class TestBCEDate(unittest.TestCase):

    def test_make_bce_date(self):
        bd = BCEDate(-4713, 1, 1)
        self.assertEqual(bd.julian_representation(), (-4713, 1, 1))

    def test_equality(self):
        self.assertEqual(BCEDate(-44, 3, 15), BCEDate(-44, 3, 15))

    def test_subtraction(self):
        self.assertEqual(timedelta(days=4), BCEDate(-44, 3, 15) - BCEDate(-44, 3, 11))
        self.assertEqual(timedelta(days=33), BCEDate(-44, 3, 15) - BCEDate(-44, 2, 11))


Add view function for councili arhive

Add view function for councili arhive

--- members/views.py
+++ members/views.py
@@ -6,6 +6,7 @@

 from hackfmi.utils import json_view
 from .models import User
+from protocols.models import Protocol

 def homepage(request):
@@ -32,3 +33,8 @@
         return redirect('members.views.homepage')
     else:
         return auth.views.login(request, template_name='members/login_form.html')
+
+
+def archive_student_council(request):
+    protocols = Protocol.objects.all().order_by('-conducted_at')
+    return render(request, 'members/archive.html', locals())

<|original_code|>
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect

from django.http import HttpResponse
from django.contrib import auth

from hackfmi.utils import json_view
from .models import User

def homepage(request):
    return render(request, "index.html", {})

@json_view
def search(request, name):
    members = User.objects.filter(first_name__icontains=name) or \
        User.objects.filter(last_name__icontains=name) or \
        User.objects.filter(username__icontains=name)

    json_data = [dict(
        id=member.id,
        faculty_number=member.faculty_number,
        full_name=' '.join([member.first_name, member.last_name]))
                for member in members]

    return json_data

def login(request):
    if request.user.is_authenticated():
        return redirect('members.views.homepage')
    else:
        return auth.views.login(request, template_name='members/login_form.html')
<|edits_diff|>
--- members/views.py
+++ members/views.py
@@ -32,3 +32,8 @@
         return redirect('members.views.homepage')
     else:
         return auth.views.login(request, template_name='members/login_form.html')
+
+
+def archive_student_council(request):
+    protocols = Protocol.objects.all().order_by('-conducted_at')
+    return render(request, 'members/archive.html', locals())
<|current_version|>
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect

from django.http import HttpResponse
from django.contrib import auth

from hackfmi.utils import json_view
from .models import User

def homepage(request):
    return render(request, "index.html", {})

@json_view
def search(request, name):
    members = User.objects.filter(first_name__icontains=name) or \
        User.objects.filter(last_name__icontains=name) or \
        User.objects.filter(username__icontains=name)

    json_data = [dict(
        id=member.id,
        faculty_number=member.faculty_number,
        full_name=' '.join([member.first_name, member.last_name]))
                for member in members]

    return json_data

def login(request):
    if request.user.is_authenticated():
        return redirect('members.views.homepage')
    else:
        return auth.views.login(request, template_name='members/login_form.html')

def archive_student_council(request):
    protocols = Protocol.objects.all().order_by('-conducted_at')
    return render(request, 'members/archive.html', locals())

<|next_version|>
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect

from django.http import HttpResponse
from django.contrib import auth

from hackfmi.utils import json_view
from .models import User
from protocols.models import Protocol

def homepage(request):
    return render(request, "index.html", {})

@json_view
def search(request, name):
    members = User.objects.filter(first_name__icontains=name) or \
        User.objects.filter(last_name__icontains=name) or \
        User.objects.filter(username__icontains=name)

    json_data = [dict(
        id=member.id,
        faculty_number=member.faculty_number,
        full_name=' '.join([member.first_name, member.last_name]))
                for member in members]

    return json_data

def login(request):
    if request.user.is_authenticated():
        return redirect('members.views.homepage')
    else:
        return auth.views.login(request, template_name='members/login_form.html')

def archive_student_council(request):
    protocols = Protocol.objects.all().order_by('-conducted_at')
    return render(request, 'members/archive.html', locals())


Add comments to abstract methods.

Add comments to abstract methods.

--- function/univariate_function.py
+++ function/univariate_function.py
@@ -18,14 +18,27 @@

     @abstractmethod
     def eval(self, v):
+        """
+        Evaluate the univariate function with input v, and return that value
+        :param v: Typically some kind of numeric.
+        :return:
+        """
         pass

     @property
     @abstractmethod
     def domain_start(self):
+        """
+        Return the start value of the domain.
+        :return:
+        """
         pass

     @property
     @abstractmethod
     def domain_end(self):
+        """
+        Return the end value of the domain.
+        :return:
+        """
         pass

<|original_code|>
"""

File: univariate_function.py

Purpose: Class that defines a generic (abstract) univariate function.

"""
from abc import ABC, abstractmethod

class UnivariateFunction(ABC):
    """
    Class that defines a generic (abstract) univariate function.
    """

    def __init(self):
        super().__init__()

    @abstractmethod
    def eval(self, v):
        pass

    @property
    @abstractmethod
    def domain_start(self):
        pass

    @property
    @abstractmethod
    def domain_end(self):
        pass

<|edits_diff|>
--- function/univariate_function.py
+++ function/univariate_function.py
@@ -18,11 +18,20 @@

     @abstractmethod
     def eval(self, v):
+        """
+        Evaluate the univariate function with input v, and return that value
+        :param v: Typically some kind of numeric.
+        :return:
+        """
         pass

     @property
     @abstractmethod
     def domain_start(self):
+        """
+        Return the start value of the domain.
+        :return:
+        """
         pass

     @property
<|current_version|>
"""

File: univariate_function.py

Purpose: Class that defines a generic (abstract) univariate function.

"""
from abc import ABC, abstractmethod

class UnivariateFunction(ABC):
    """
    Class that defines a generic (abstract) univariate function.
    """

    def __init(self):
        super().__init__()

    @abstractmethod
    def eval(self, v):
        """
        Evaluate the univariate function with input v, and return that value
        :param v: Typically some kind of numeric.
        :return:
        """
        pass

    @property
    @abstractmethod
    def domain_start(self):
        """
        Return the start value of the domain.
        :return:
        """
        pass

    @property
    @abstractmethod
    def domain_end(self):
        pass

<|next_version|>
"""

File: univariate_function.py

Purpose: Class that defines a generic (abstract) univariate function.

"""
from abc import ABC, abstractmethod

class UnivariateFunction(ABC):
    """
    Class that defines a generic (abstract) univariate function.
    """

    def __init(self):
        super().__init__()

    @abstractmethod
    def eval(self, v):
        """
        Evaluate the univariate function with input v, and return that value
        :param v: Typically some kind of numeric.
        :return:
        """
        pass

    @property
    @abstractmethod
    def domain_start(self):
        """
        Return the start value of the domain.
        :return:
        """
        pass

    @property
    @abstractmethod
    def domain_end(self):
        """
        Return the end value of the domain.
        :return:
        """
        pass


Apply default style on import

Apply default style on import

--- dataviews/__init__.py
+++ dataviews/__init__.py
@@ -13,7 +13,9 @@
 from .dataviews import * # pyflakes:ignore (API import)
 from .sheetviews import * # pyflakes:ignore (API import)
 from .ndmapping import * # pyflakes:ignore (API import)
+from .styles import set_style

+set_style('default')

 def public(obj):
     if not isinstance(obj, type): return False

<|original_code|>
import sys, os

# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))

import param

__version__ = param.Version(release=(0,7), fpath=__file__,
                            commit="$Format:%h$", reponame='dataviews')

from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)

def public(obj):
    if not isinstance(obj, type): return False
    baseclasses = [NdMapping, View, Dimension, Overlay]
    return any([issubclass(obj, bc) for bc in baseclasses])

_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]

<|edits_diff|>
--- dataviews/__init__.py
+++ dataviews/__init__.py
@@ -13,6 +13,7 @@
 from .dataviews import * # pyflakes:ignore (API import)
 from .sheetviews import * # pyflakes:ignore (API import)
 from .ndmapping import * # pyflakes:ignore (API import)
+from .styles import set_style

 def public(obj):
<|current_version|>
import sys, os

# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))

import param

__version__ = param.Version(release=(0,7), fpath=__file__,
                            commit="$Format:%h$", reponame='dataviews')

from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
from .styles import set_style

def public(obj):
    if not isinstance(obj, type): return False
    baseclasses = [NdMapping, View, Dimension, Overlay]
    return any([issubclass(obj, bc) for bc in baseclasses])

_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]

<|next_version|>
import sys, os

# Add param submodule to sys.path
cwd = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(cwd, '..', 'param'))

import param

__version__ = param.Version(release=(0,7), fpath=__file__,
                            commit="$Format:%h$", reponame='dataviews')

from .views import * # pyflakes:ignore (API import)
from .dataviews import * # pyflakes:ignore (API import)
from .sheetviews import * # pyflakes:ignore (API import)
from .ndmapping import * # pyflakes:ignore (API import)
from .styles import set_style

set_style('default')

def public(obj):
    if not isinstance(obj, type): return False
    baseclasses = [NdMapping, View, Dimension, Overlay]
    return any([issubclass(obj, bc) for bc in baseclasses])

_public = list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public + ["boundingregion", "ipython", "plotting", "sheetcoords" ]


Mark export test XFAIL since no chain mockup exists

--- pyethapp/tests/test_export.py
+++ pyethapp/tests/test_export.py
@@ -4,8 +4,10 @@
 from click.testing import CliRunner
 from ethereum.blocks import BlockHeader
 import rlp
+import pytest

+@pytest.mark.xfail  # can not work without mock-up chain
 def test_export():
     # requires a chain with at least 5 blocks
     assert subprocess.call('pyethapp export', shell=True) != 0

<|original_code|>
from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp

def test_export():
    # requires a chain with at least 5 blocks
    assert subprocess.call('pyethapp export', shell=True) != 0
    assert subprocess.call('pyethapp export --from -1 -', shell=True) != 0
    assert subprocess.call('pyethapp export --to -3 -', shell=True) != 0
    assert subprocess.call('pyethapp export --from 4 --to 2 -', shell=True) != 0

    result = subprocess.Popen('pyethapp export --from 2 --to 4 -', shell=True,
                              stdout=subprocess.PIPE)
    result.wait()
    assert result.returncode == 0
    s = result.stdout.read()

    headers = []
    end = 0
    while end < len(s):
        item, end = rlp.codec.consume_item(s, end)
        headers.append(BlockHeader.deserialize(item[0]))
    assert [header.number for header in headers] == [2, 3, 4]

<|edits_diff|>
--- pyethapp/tests/test_export.py
+++ pyethapp/tests/test_export.py
@@ -4,6 +4,7 @@
 from click.testing import CliRunner
 from ethereum.blocks import BlockHeader
 import rlp
+import pytest

 def test_export():
<|current_version|>
from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
import pytest

def test_export():
    # requires a chain with at least 5 blocks
    assert subprocess.call('pyethapp export', shell=True) != 0
    assert subprocess.call('pyethapp export --from -1 -', shell=True) != 0
    assert subprocess.call('pyethapp export --to -3 -', shell=True) != 0
    assert subprocess.call('pyethapp export --from 4 --to 2 -', shell=True) != 0

    result = subprocess.Popen('pyethapp export --from 2 --to 4 -', shell=True,
                              stdout=subprocess.PIPE)
    result.wait()
    assert result.returncode == 0
    s = result.stdout.read()

    headers = []
    end = 0
    while end < len(s):
        item, end = rlp.codec.consume_item(s, end)
        headers.append(BlockHeader.deserialize(item[0]))
    assert [header.number for header in headers] == [2, 3, 4]

<|next_version|>
from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
import pytest

@pytest.mark.xfail  # can not work without mock-up chain
def test_export():
    # requires a chain with at least 5 blocks
    assert subprocess.call('pyethapp export', shell=True) != 0
    assert subprocess.call('pyethapp export --from -1 -', shell=True) != 0
    assert subprocess.call('pyethapp export --to -3 -', shell=True) != 0
    assert subprocess.call('pyethapp export --from 4 --to 2 -', shell=True) != 0

    result = subprocess.Popen('pyethapp export --from 2 --to 4 -', shell=True,
                              stdout=subprocess.PIPE)
    result.wait()
    assert result.returncode == 0
    s = result.stdout.read()

    headers = []
    end = 0
    while end < len(s):
        item, end = rlp.codec.consume_item(s, end)
        headers.append(BlockHeader.deserialize(item[0]))
    assert [header.number for header in headers] == [2, 3, 4]


Add django media file serving in debug mode

--- fp/fp/urls.py
+++ fp/fp/urls.py
@@ -1,7 +1,10 @@
 from __future__ import unicode_literals

+from django.conf import settings
 from django.conf.urls import patterns, include, url
+from django.conf.urls.static import static
 from django.contrib import admin
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns

 admin.autodiscover()
@@ -14,3 +17,8 @@

     url(r'^admin/', include(admin.site.urls)),
 )
+
+
+if settings.DEBUG:
+    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+    urlpatterns += staticfiles_urlpatterns()

<|original_code|>
from __future__ import unicode_literals

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

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'fp.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)

<|edits_diff|>
--- fp/fp/urls.py
+++ fp/fp/urls.py
@@ -1,7 +1,10 @@
 from __future__ import unicode_literals

+from django.conf import settings
 from django.conf.urls import patterns, include, url
+from django.conf.urls.static import static
 from django.contrib import admin
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns

 admin.autodiscover()
<|current_version|>
from __future__ import unicode_literals

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'fp.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)

<|next_version|>
from __future__ import unicode_literals

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'fp.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += staticfiles_urlpatterns()