Add URL enter in dynamic process

Add URL enter in dynamic process

--- mining/urls.py
+++ mining/urls.py
@@ -1,9 +1,12 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 from .views import MainHandler, ProcessHandler, DashboardHandler
+from .views import ProcessWebSocketHandler

 INCLUDE_URLS = [
+    (r"/process/(?P<slug>[\w-]+).ws", ProcessWebSocketHandler),
+    (r"/process/(?P<slug>[\w-]+).json", ProcessHandler),
     (r"/process/(?P<slug>[\w-]+).json", ProcessHandler),
     (r"/(?P<slug>[\w-]+)", DashboardHandler),
     (r"/", MainHandler),

<|original_code|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import MainHandler, ProcessHandler, DashboardHandler

INCLUDE_URLS = [
    (r"/process/(?P<slug>[\w-]+).json", ProcessHandler),
    (r"/(?P<slug>[\w-]+)", DashboardHandler),
    (r"/", MainHandler),
]

<|edits_diff|>
--- mining/urls.py
+++ mining/urls.py
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 from .views import MainHandler, ProcessHandler, DashboardHandler
+from .views import ProcessWebSocketHandler

 INCLUDE_URLS = [
<|current_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import MainHandler, ProcessHandler, DashboardHandler
from .views import ProcessWebSocketHandler

INCLUDE_URLS = [
    (r"/process/(?P<slug>[\w-]+).json", ProcessHandler),
    (r"/(?P<slug>[\w-]+)", DashboardHandler),
    (r"/", MainHandler),
]

<|next_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .views import MainHandler, ProcessHandler, DashboardHandler
from .views import ProcessWebSocketHandler

INCLUDE_URLS = [
    (r"/process/(?P<slug>[\w-]+).ws", ProcessWebSocketHandler),
    (r"/process/(?P<slug>[\w-]+).json", ProcessHandler),
    (r"/process/(?P<slug>[\w-]+).json", ProcessHandler),
    (r"/(?P<slug>[\w-]+)", DashboardHandler),
    (r"/", MainHandler),
]


Add bbox to parking area statistics view set

--- parkings/api/public/parking_area_statistics.py
+++ parkings/api/public/parking_area_statistics.py
@@ -2,6 +2,8 @@
 from rest_framework import serializers, viewsets

 from parkings.models import Parking, ParkingArea
+
+from ..common import WGS84InBBoxFilter

 class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
@@ -36,3 +38,6 @@
 class PublicAPIParkingAreaStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
     queryset = ParkingArea.objects.all()
     serializer_class = ParkingAreaStatisticsSerializer
+    bbox_filter_field = 'areas'
+    filter_backends = (WGS84InBBoxFilter,)
+    bbox_filter_include_overlapping = True

<|original_code|>
from django.utils import timezone
from rest_framework import serializers, viewsets

from parkings.models import Parking, ParkingArea

class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
    current_parking_count = serializers.SerializerMethodField()

    def get_current_parking_count(self, area):
        count = Parking.objects.filter(
            parking_area=area,
            time_end__gte=timezone.now(),
            time_start__lte=timezone.now(),
        ).count()
        return self.blur_count(count)

    def blur_count(self, count):
        """
        Returns a blurred count, which is supposed to hide individual
        parkings.
        """
        if count <= 3:
            return 0
        else:
            return count

    class Meta:
        model = ParkingArea
        fields = (
            'id',
            'current_parking_count',
        )

class PublicAPIParkingAreaStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = ParkingArea.objects.all()
    serializer_class = ParkingAreaStatisticsSerializer

<|edits_diff|>
--- parkings/api/public/parking_area_statistics.py
+++ parkings/api/public/parking_area_statistics.py
@@ -2,6 +2,8 @@
 from rest_framework import serializers, viewsets

 from parkings.models import Parking, ParkingArea
+
+from ..common import WGS84InBBoxFilter

 class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
<|current_version|>
from django.utils import timezone
from rest_framework import serializers, viewsets

from parkings.models import Parking, ParkingArea

from ..common import WGS84InBBoxFilter

class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
    current_parking_count = serializers.SerializerMethodField()

    def get_current_parking_count(self, area):
        count = Parking.objects.filter(
            parking_area=area,
            time_end__gte=timezone.now(),
            time_start__lte=timezone.now(),
        ).count()
        return self.blur_count(count)

    def blur_count(self, count):
        """
        Returns a blurred count, which is supposed to hide individual
        parkings.
        """
        if count <= 3:
            return 0
        else:
            return count

    class Meta:
        model = ParkingArea
        fields = (
            'id',
            'current_parking_count',
        )

class PublicAPIParkingAreaStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = ParkingArea.objects.all()
    serializer_class = ParkingAreaStatisticsSerializer

<|next_version|>
from django.utils import timezone
from rest_framework import serializers, viewsets

from parkings.models import Parking, ParkingArea

from ..common import WGS84InBBoxFilter

class ParkingAreaStatisticsSerializer(serializers.ModelSerializer):
    current_parking_count = serializers.SerializerMethodField()

    def get_current_parking_count(self, area):
        count = Parking.objects.filter(
            parking_area=area,
            time_end__gte=timezone.now(),
            time_start__lte=timezone.now(),
        ).count()
        return self.blur_count(count)

    def blur_count(self, count):
        """
        Returns a blurred count, which is supposed to hide individual
        parkings.
        """
        if count <= 3:
            return 0
        else:
            return count

    class Meta:
        model = ParkingArea
        fields = (
            'id',
            'current_parking_count',
        )

class PublicAPIParkingAreaStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = ParkingArea.objects.all()
    serializer_class = ParkingAreaStatisticsSerializer
    bbox_filter_field = 'areas'
    filter_backends = (WGS84InBBoxFilter,)
    bbox_filter_include_overlapping = True


Add stem test for spanish stemmer

Add stem test for spanish stemmer

--- nltk/test/unit/test_stem.py
+++ nltk/test/unit/test_stem.py
@@ -2,6 +2,7 @@
 from __future__ import print_function, unicode_literals
 import unittest
 from nltk.stem.snowball import SnowballStemmer
+

 class SnowballTest(unittest.TestCase):

@@ -22,6 +23,11 @@
         assert stemmer_german.stem("keinen") == 'kein'
         assert stemmer_german2.stem("keinen") == 'keinen'

+    def test_spanish(self):
+        stemmer = SnowballStemmer('spanish')
+
+        assert stemmer.stem("Visionado") == 'vision'
+
     def test_short_strings_bug(self):
         stemmer = SnowballStemmer('english')
         assert stemmer.stem("y's") == 'y'

<|original_code|>
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.stem.snowball import SnowballStemmer

class SnowballTest(unittest.TestCase):

    def test_russian(self):
        # Russian words both consisting of Cyrillic
        # and Roman letters can be stemmed.
        stemmer_russian = SnowballStemmer("russian")
        assert stemmer_russian.stem("авантненькая") == "авантненьк"
        assert stemmer_russian.stem("avenantnen'kai^a") == "avenantnen'k"

    def test_german(self):
        stemmer_german = SnowballStemmer("german")
        stemmer_german2 = SnowballStemmer("german", ignore_stopwords=True)

        assert stemmer_german.stem("Schr\xe4nke") == 'schrank'
        assert stemmer_german2.stem("Schr\xe4nke") == 'schrank'

        assert stemmer_german.stem("keinen") == 'kein'
        assert stemmer_german2.stem("keinen") == 'keinen'

    def test_short_strings_bug(self):
        stemmer = SnowballStemmer('english')
        assert stemmer.stem("y's") == 'y'

<|edits_diff|>
--- nltk/test/unit/test_stem.py
+++ nltk/test/unit/test_stem.py
@@ -2,6 +2,7 @@
 from __future__ import print_function, unicode_literals
 import unittest
 from nltk.stem.snowball import SnowballStemmer
+

 class SnowballTest(unittest.TestCase):

<|current_version|>
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.stem.snowball import SnowballStemmer

class SnowballTest(unittest.TestCase):

    def test_russian(self):
        # Russian words both consisting of Cyrillic
        # and Roman letters can be stemmed.
        stemmer_russian = SnowballStemmer("russian")
        assert stemmer_russian.stem("авантненькая") == "авантненьк"
        assert stemmer_russian.stem("avenantnen'kai^a") == "avenantnen'k"

    def test_german(self):
        stemmer_german = SnowballStemmer("german")
        stemmer_german2 = SnowballStemmer("german", ignore_stopwords=True)

        assert stemmer_german.stem("Schr\xe4nke") == 'schrank'
        assert stemmer_german2.stem("Schr\xe4nke") == 'schrank'

        assert stemmer_german.stem("keinen") == 'kein'
        assert stemmer_german2.stem("keinen") == 'keinen'

    def test_short_strings_bug(self):
        stemmer = SnowballStemmer('english')
        assert stemmer.stem("y's") == 'y'

<|next_version|>
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.stem.snowball import SnowballStemmer

class SnowballTest(unittest.TestCase):

    def test_russian(self):
        # Russian words both consisting of Cyrillic
        # and Roman letters can be stemmed.
        stemmer_russian = SnowballStemmer("russian")
        assert stemmer_russian.stem("авантненькая") == "авантненьк"
        assert stemmer_russian.stem("avenantnen'kai^a") == "avenantnen'k"

    def test_german(self):
        stemmer_german = SnowballStemmer("german")
        stemmer_german2 = SnowballStemmer("german", ignore_stopwords=True)

        assert stemmer_german.stem("Schr\xe4nke") == 'schrank'
        assert stemmer_german2.stem("Schr\xe4nke") == 'schrank'

        assert stemmer_german.stem("keinen") == 'kein'
        assert stemmer_german2.stem("keinen") == 'keinen'

    def test_spanish(self):
        stemmer = SnowballStemmer('spanish')

        assert stemmer.stem("Visionado") == 'vision'

    def test_short_strings_bug(self):
        stemmer = SnowballStemmer('english')
        assert stemmer.stem("y's") == 'y'


Allow direct SPPF generation from interactive script

--- viper.py
+++ viper.py
@@ -1,6 +1,8 @@
 #!/usr/bin/env python3

 from viper.interactive import *
+from viper.lexer import lex_file
+from viper.grammar import GRAMMAR

 if __name__ == '__main__':
@@ -8,6 +10,7 @@
     parser = argparse.ArgumentParser()
     parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input')
     parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF')
+    parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input')
     parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing')
     args = parser.parse_args()

@@ -15,3 +18,7 @@
         InteractiveLexer().cmdloop()
     elif args.interactive_sppf:
         InteractiveSPPF(args.grammar_rule).cmdloop()
+    elif args.file_sppf:
+        lexemes = lex_file(args.file_sppf)
+        sppf = GRAMMAR.parse_multiple(lexemes)
+        print(sppf)

<|original_code|>
#!/usr/bin/env python3

from viper.interactive import *

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input')
    parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF')
    parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing')
    args = parser.parse_args()

    if args.interactive_lexer:
        InteractiveLexer().cmdloop()
    elif args.interactive_sppf:
        InteractiveSPPF(args.grammar_rule).cmdloop()

<|edits_diff|>
--- viper.py
+++ viper.py
@@ -1,6 +1,8 @@
 #!/usr/bin/env python3

 from viper.interactive import *
+from viper.lexer import lex_file
+from viper.grammar import GRAMMAR

 if __name__ == '__main__':
@@ -8,6 +10,7 @@
     parser = argparse.ArgumentParser()
     parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input')
     parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF')
+    parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input')
     parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing')
     args = parser.parse_args()

<|current_version|>
#!/usr/bin/env python3

from viper.interactive import *
from viper.lexer import lex_file
from viper.grammar import GRAMMAR

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input')
    parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF')
    parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input')
    parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing')
    args = parser.parse_args()

    if args.interactive_lexer:
        InteractiveLexer().cmdloop()
    elif args.interactive_sppf:
        InteractiveSPPF(args.grammar_rule).cmdloop()

<|next_version|>
#!/usr/bin/env python3

from viper.interactive import *
from viper.lexer import lex_file
from viper.grammar import GRAMMAR

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input')
    parser.add_argument('-S', '--interactive-sppf', action='store_true', help='lexes input and produces SPPF')
    parser.add_argument('-s', '--file-sppf', help='produces SPPF for given input')
    parser.add_argument('-r', '--grammar-rule', default='single_line', help='grammar rule from which to start parsing')
    args = parser.parse_args()

    if args.interactive_lexer:
        InteractiveLexer().cmdloop()
    elif args.interactive_sppf:
        InteractiveSPPF(args.grammar_rule).cmdloop()
    elif args.file_sppf:
        lexemes = lex_file(args.file_sppf)
        sppf = GRAMMAR.parse_multiple(lexemes)
        print(sppf)


Remove config files from filesystem on teardown

[DEV-13843]

--- blueprints/multi_node_kubernetes_cluster/teardown_kubernetes_cluster/teardown_kubernetes_cluster.py
+++ blueprints/multi_node_kubernetes_cluster/teardown_kubernetes_cluster/teardown_kubernetes_cluster.py
@@ -4,6 +4,7 @@
 """
 from common.methods import set_progress
 from containerorchestrators.kuberneteshandler.models import Kubernetes
+from utilities.run_command import execute_command

 def run(job, *args, **kwargs):
@@ -14,3 +15,6 @@

     container_orchestrator.delete()
     environment.delete()
+
+    resource_dir = '/var/opt/cloudbolt/kubernetes/resource-{}'.format(resource_id)
+    execute_command('rm -rf {}'.format(RESOURCE_LOCATION))

<|original_code|>
"""
Teardown the CloudBolt resources (container_orchestrator, environment)
associated with this Kubernetes cluster.
"""
from common.methods import set_progress
from containerorchestrators.kuberneteshandler.models import Kubernetes

def run(job, *args, **kwargs):
    resource = job.resource_set.first()

    container_orchestrator = Kubernetes.objects.get(id=resource.container_orchestrator_id)
    environment = container_orchestrator.environment_set.first()

    container_orchestrator.delete()
    environment.delete()
<|edits_diff|>
--- blueprints/multi_node_kubernetes_cluster/teardown_kubernetes_cluster/teardown_kubernetes_cluster.py
+++ blueprints/multi_node_kubernetes_cluster/teardown_kubernetes_cluster/teardown_kubernetes_cluster.py
@@ -14,3 +14,6 @@

     container_orchestrator.delete()
     environment.delete()
+
+    resource_dir = '/var/opt/cloudbolt/kubernetes/resource-{}'.format(resource_id)
+    execute_command('rm -rf {}'.format(RESOURCE_LOCATION))
<|current_version|>
"""
Teardown the CloudBolt resources (container_orchestrator, environment)
associated with this Kubernetes cluster.
"""
from common.methods import set_progress
from containerorchestrators.kuberneteshandler.models import Kubernetes

def run(job, *args, **kwargs):
    resource = job.resource_set.first()

    container_orchestrator = Kubernetes.objects.get(id=resource.container_orchestrator_id)
    environment = container_orchestrator.environment_set.first()

    container_orchestrator.delete()
    environment.delete()

    resource_dir = '/var/opt/cloudbolt/kubernetes/resource-{}'.format(resource_id)
    execute_command('rm -rf {}'.format(RESOURCE_LOCATION))

<|next_version|>
"""
Teardown the CloudBolt resources (container_orchestrator, environment)
associated with this Kubernetes cluster.
"""
from common.methods import set_progress
from containerorchestrators.kuberneteshandler.models import Kubernetes
from utilities.run_command import execute_command

def run(job, *args, **kwargs):
    resource = job.resource_set.first()

    container_orchestrator = Kubernetes.objects.get(id=resource.container_orchestrator_id)
    environment = container_orchestrator.environment_set.first()

    container_orchestrator.delete()
    environment.delete()

    resource_dir = '/var/opt/cloudbolt/kubernetes/resource-{}'.format(resource_id)
    execute_command('rm -rf {}'.format(RESOURCE_LOCATION))


Add description column to Restaurant

feat: Add description column to Restaurant

--- database_setup.py
+++ database_setup.py
@@ -12,12 +12,14 @@
     __tablename__ = 'restaurant'

     name = Column(String(80), nullable = False)
+    description = Column(String(250))
     id = Column(Integer, primary_key = True)

     @property
     def serialize(self):
         return {
             'name': self.name,
+            'description': self.description,
             'id': self.id,
         }

<|original_code|>
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Restaurant(Base):

    __tablename__ = 'restaurant'

    name = Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'id': self.id,
        }

class MenuItem(Base):

    __tablename__ = 'menu_item'

    name = Column(String(80), nullable = False)
    id = Column(Integer,primary_key = True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(8))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.create_all(engine)

<|edits_diff|>
--- database_setup.py
+++ database_setup.py
@@ -12,6 +12,7 @@
     __tablename__ = 'restaurant'

     name = Column(String(80), nullable = False)
+    description = Column(String(250))
     id = Column(Integer, primary_key = True)

     @property
<|current_version|>
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Restaurant(Base):

    __tablename__ = 'restaurant'

    name = Column(String(80), nullable = False)
    description = Column(String(250))
    id = Column(Integer, primary_key = True)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'id': self.id,
        }

class MenuItem(Base):

    __tablename__ = 'menu_item'

    name = Column(String(80), nullable = False)
    id = Column(Integer,primary_key = True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(8))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.create_all(engine)

<|next_version|>
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Restaurant(Base):

    __tablename__ = 'restaurant'

    name = Column(String(80), nullable = False)
    description = Column(String(250))
    id = Column(Integer, primary_key = True)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
        }

class MenuItem(Base):

    __tablename__ = 'menu_item'

    name = Column(String(80), nullable = False)
    id = Column(Integer,primary_key = True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(8))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.create_all(engine)


Test for property ten as well

Test for property ten as well

--- tests/unit/util/test_cache.py
+++ tests/unit/util/test_cache.py
@@ -22,6 +22,9 @@
         assert "nine" not in klass.__dict__
         assert klass.nine == 9
         assert "nine" in klass.__dict__
+        assert "ten" not in klass.__dict__
+        assert klass.ten == 10
+        assert "ten" in klass.__dict__

     def test_repr(self):
         klass = self.Klass()
@@ -30,6 +33,11 @@
         property_repr = repr(self.Klass.nine)
         assert property_repr.startswith("<cachedproperty <function")

+        assert repr(klass.ten) == "10"
+
+        property_repr = repr(self.Klass.ten)
+        assert property_repr.startswith("<cachedproperty <function")
+
     def test_doc(self):
         assert self.Klass.nine.__doc__ == "Return 9."
         assert self.Klass.ten.__doc__ == "Return 10."

<|original_code|>
"""Test praw.util.cache."""

from .. import UnitTest

from praw.util.cache import cachedproperty

class TestCachedProperty(UnitTest):
    class Klass:
        @cachedproperty
        def nine(self):
            """Return 9."""
            return 9

        def ten(self):
            return 10

        ten = cachedproperty(ten, doc="Return 10.")

    def test_get(self):
        klass = self.Klass()
        assert "nine" not in klass.__dict__
        assert klass.nine == 9
        assert "nine" in klass.__dict__

    def test_repr(self):
        klass = self.Klass()
        assert repr(klass.nine) == "9"

        property_repr = repr(self.Klass.nine)
        assert property_repr.startswith("<cachedproperty <function")

    def test_doc(self):
        assert self.Klass.nine.__doc__ == "Return 9."
        assert self.Klass.ten.__doc__ == "Return 10."

<|edits_diff|>
--- tests/unit/util/test_cache.py
+++ tests/unit/util/test_cache.py
@@ -22,6 +22,9 @@
         assert "nine" not in klass.__dict__
         assert klass.nine == 9
         assert "nine" in klass.__dict__
+        assert "ten" not in klass.__dict__
+        assert klass.ten == 10
+        assert "ten" in klass.__dict__

     def test_repr(self):
         klass = self.Klass()
<|current_version|>
"""Test praw.util.cache."""

from .. import UnitTest

from praw.util.cache import cachedproperty

class TestCachedProperty(UnitTest):
    class Klass:
        @cachedproperty
        def nine(self):
            """Return 9."""
            return 9

        def ten(self):
            return 10

        ten = cachedproperty(ten, doc="Return 10.")

    def test_get(self):
        klass = self.Klass()
        assert "nine" not in klass.__dict__
        assert klass.nine == 9
        assert "nine" in klass.__dict__
        assert "ten" not in klass.__dict__
        assert klass.ten == 10
        assert "ten" in klass.__dict__

    def test_repr(self):
        klass = self.Klass()
        assert repr(klass.nine) == "9"

        property_repr = repr(self.Klass.nine)
        assert property_repr.startswith("<cachedproperty <function")

    def test_doc(self):
        assert self.Klass.nine.__doc__ == "Return 9."
        assert self.Klass.ten.__doc__ == "Return 10."

<|next_version|>
"""Test praw.util.cache."""

from .. import UnitTest

from praw.util.cache import cachedproperty

class TestCachedProperty(UnitTest):
    class Klass:
        @cachedproperty
        def nine(self):
            """Return 9."""
            return 9

        def ten(self):
            return 10

        ten = cachedproperty(ten, doc="Return 10.")

    def test_get(self):
        klass = self.Klass()
        assert "nine" not in klass.__dict__
        assert klass.nine == 9
        assert "nine" in klass.__dict__
        assert "ten" not in klass.__dict__
        assert klass.ten == 10
        assert "ten" in klass.__dict__

    def test_repr(self):
        klass = self.Klass()
        assert repr(klass.nine) == "9"

        property_repr = repr(self.Klass.nine)
        assert property_repr.startswith("<cachedproperty <function")

        assert repr(klass.ten) == "10"

        property_repr = repr(self.Klass.ten)
        assert property_repr.startswith("<cachedproperty <function")

    def test_doc(self):
        assert self.Klass.nine.__doc__ == "Return 9."
        assert self.Klass.ten.__doc__ == "Return 10."


Add permission check to slide urls.

Add permission check to slide urls.

--- waliki/slides/views.py
+++ waliki/slides/views.py
@@ -5,8 +5,10 @@
 from django.shortcuts import get_object_or_404
 from django.http import HttpResponse
 from waliki.models import Page
+from waliki.acl import permission_required

+@permission_required('view_page')
 def slides(request, slug):
     page = get_object_or_404(Page, slug=slug)
     outpath = tempfile.mkdtemp()

<|original_code|>
from os import path
import shutil
import tempfile
from sh import hovercraft
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from waliki.models import Page

def slides(request, slug):
    page = get_object_or_404(Page, slug=slug)
    outpath = tempfile.mkdtemp()
    try:
        infile = page.abspath
        template = path.join(path.dirname(path.realpath(__file__)), 'template')
        hovercraft('-t', template, infile, outpath)
        with open(path.join(outpath, 'index.html')) as f:
            content = f.read()
    finally:
        shutil.rmtree(outpath)
    return HttpResponse(content)

<|edits_diff|>
--- waliki/slides/views.py
+++ waliki/slides/views.py
@@ -5,6 +5,7 @@
 from django.shortcuts import get_object_or_404
 from django.http import HttpResponse
 from waliki.models import Page
+from waliki.acl import permission_required

 def slides(request, slug):
<|current_version|>
from os import path
import shutil
import tempfile
from sh import hovercraft
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from waliki.models import Page
from waliki.acl import permission_required

def slides(request, slug):
    page = get_object_or_404(Page, slug=slug)
    outpath = tempfile.mkdtemp()
    try:
        infile = page.abspath
        template = path.join(path.dirname(path.realpath(__file__)), 'template')
        hovercraft('-t', template, infile, outpath)
        with open(path.join(outpath, 'index.html')) as f:
            content = f.read()
    finally:
        shutil.rmtree(outpath)
    return HttpResponse(content)

<|next_version|>
from os import path
import shutil
import tempfile
from sh import hovercraft
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from waliki.models import Page
from waliki.acl import permission_required

@permission_required('view_page')
def slides(request, slug):
    page = get_object_or_404(Page, slug=slug)
    outpath = tempfile.mkdtemp()
    try:
        infile = page.abspath
        template = path.join(path.dirname(path.realpath(__file__)), 'template')
        hovercraft('-t', template, infile, outpath)
        with open(path.join(outpath, 'index.html')) as f:
            content = f.read()
    finally:
        shutil.rmtree(outpath)
    return HttpResponse(content)


Fix NOT NULL constraint on Setting name not being removed

--- migrations/versions/1f9c61031fa_.py
+++ migrations/versions/1f9c61031fa_.py
@@ -17,6 +17,9 @@
 def upgrade():
     ### commands auto generated by Alembic - please adjust! ###
     op.add_column('setting', sa.Column('key', sa.String(length=100)))
+    op.alter_column('setting', 'name',
+        existing_type=sa.VARCHAR(length=100),
+        nullable=True)
     op.drop_column('setting', 'id')
     ### end Alembic commands ###

@@ -24,5 +27,8 @@
 def downgrade():
     ### commands auto generated by Alembic - please adjust! ###
     op.add_column('setting', sa.Column('id', sa.INTEGER(), nullable=False))
+    op.alter_column('setting', 'name',
+        existing_type=sa.VARCHAR(length=100),
+        nullable=False)
     op.drop_column('setting', 'key')
     ### end Alembic commands ###

<|original_code|>
"""empty message

Revision ID: 1f9c61031fa
Revises: 1f872d11bbf
Create Date: 2016-01-24 17:46:54.879784

"""

# revision identifiers, used by Alembic.
revision = '1f9c61031fa'
down_revision = '1f872d11bbf'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('setting', sa.Column('key', sa.String(length=100)))
    op.drop_column('setting', 'id')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('setting', sa.Column('id', sa.INTEGER(), nullable=False))
    op.drop_column('setting', 'key')
    ### end Alembic commands ###

<|edits_diff|>
--- migrations/versions/1f9c61031fa_.py
+++ migrations/versions/1f9c61031fa_.py
@@ -17,6 +17,9 @@
 def upgrade():
     ### commands auto generated by Alembic - please adjust! ###
     op.add_column('setting', sa.Column('key', sa.String(length=100)))
+    op.alter_column('setting', 'name',
+        existing_type=sa.VARCHAR(length=100),
+        nullable=True)
     op.drop_column('setting', 'id')
     ### end Alembic commands ###

<|current_version|>
"""empty message

Revision ID: 1f9c61031fa
Revises: 1f872d11bbf
Create Date: 2016-01-24 17:46:54.879784

"""

# revision identifiers, used by Alembic.
revision = '1f9c61031fa'
down_revision = '1f872d11bbf'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('setting', sa.Column('key', sa.String(length=100)))
    op.alter_column('setting', 'name',
        existing_type=sa.VARCHAR(length=100),
        nullable=True)
    op.drop_column('setting', 'id')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('setting', sa.Column('id', sa.INTEGER(), nullable=False))
    op.drop_column('setting', 'key')
    ### end Alembic commands ###

<|next_version|>
"""empty message

Revision ID: 1f9c61031fa
Revises: 1f872d11bbf
Create Date: 2016-01-24 17:46:54.879784

"""

# revision identifiers, used by Alembic.
revision = '1f9c61031fa'
down_revision = '1f872d11bbf'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('setting', sa.Column('key', sa.String(length=100)))
    op.alter_column('setting', 'name',
        existing_type=sa.VARCHAR(length=100),
        nullable=True)
    op.drop_column('setting', 'id')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('setting', sa.Column('id', sa.INTEGER(), nullable=False))
    op.alter_column('setting', 'name',
        existing_type=sa.VARCHAR(length=100),
        nullable=False)
    op.drop_column('setting', 'key')
    ### end Alembic commands ###


Add some debug for debian box

Add some debug for debian box

--- gitcd/Cli/Command.py
+++ gitcd/Cli/Command.py
@@ -1,10 +1,14 @@
 import subprocess
 import string
+
+from pprint import pprint

 class Command(object):

   def execute(self, command: str):
     cliArgs = self.parseCliArgs(command)
+
+    pprint(cliArgs)

     process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     output, err = process.communicate()

<|original_code|>
import subprocess
import string

class Command(object):

  def execute(self, command: str):
    cliArgs = self.parseCliArgs(command)

    process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = process.communicate()
    if process.returncode != 0:
      return False

    return output.decode("utf-8").strip()

  def parseCliArgs(self, command: str):
    rawArgs = command.split(" ")

    parsedArgs = []
    tmpString = False
    isSingle = False
    isDouble = False
    for arg in rawArgs:
      # handle  strings in single quotes
      if arg.startswith("'") and isSingle == False and isDouble == False:
        isSingle = True
        tmpString = arg

      elif arg.endswith("'") and isSingle == True:
        arg = "%s %s" % (tmpString, arg)
        parsedArgs.append(arg)
        isSingle = False
        tmpString = False

      # handle strings in double quotes
      elif arg.startswith('"') and isDouble == False and isSingle == False:
        isDouble = True
        tmpString = arg

      elif arg.endswith('"') and isDouble == True:
        arg = "%s %s" % (tmpString, arg)
        parsedArgs.append(arg)
        isDouble = False
        tmpString = False

      # extend current string
      elif tmpString != False:
        tmpString = "%s %s" % (tmpString, arg)

      else:
        parsedArgs.append(arg)

    return parsedArgs
<|edits_diff|>
--- gitcd/Cli/Command.py
+++ gitcd/Cli/Command.py
@@ -1,5 +1,7 @@
 import subprocess
 import string
+
+from pprint import pprint

 class Command(object):

<|current_version|>
import subprocess
import string

from pprint import pprint

class Command(object):

  def execute(self, command: str):
    cliArgs = self.parseCliArgs(command)

    process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = process.communicate()
    if process.returncode != 0:
      return False

    return output.decode("utf-8").strip()

  def parseCliArgs(self, command: str):
    rawArgs = command.split(" ")

    parsedArgs = []
    tmpString = False
    isSingle = False
    isDouble = False
    for arg in rawArgs:
      # handle  strings in single quotes
      if arg.startswith("'") and isSingle == False and isDouble == False:
        isSingle = True
        tmpString = arg

      elif arg.endswith("'") and isSingle == True:
        arg = "%s %s" % (tmpString, arg)
        parsedArgs.append(arg)
        isSingle = False
        tmpString = False

      # handle strings in double quotes
      elif arg.startswith('"') and isDouble == False and isSingle == False:
        isDouble = True
        tmpString = arg

      elif arg.endswith('"') and isDouble == True:
        arg = "%s %s" % (tmpString, arg)
        parsedArgs.append(arg)
        isDouble = False
        tmpString = False

      # extend current string
      elif tmpString != False:
        tmpString = "%s %s" % (tmpString, arg)

      else:
        parsedArgs.append(arg)

    return parsedArgs
<|next_version|>
import subprocess
import string

from pprint import pprint

class Command(object):

  def execute(self, command: str):
    cliArgs = self.parseCliArgs(command)

    pprint(cliArgs)

    process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = process.communicate()
    if process.returncode != 0:
      return False

    return output.decode("utf-8").strip()

  def parseCliArgs(self, command: str):
    rawArgs = command.split(" ")

    parsedArgs = []
    tmpString = False
    isSingle = False
    isDouble = False
    for arg in rawArgs:
      # handle  strings in single quotes
      if arg.startswith("'") and isSingle == False and isDouble == False:
        isSingle = True
        tmpString = arg

      elif arg.endswith("'") and isSingle == True:
        arg = "%s %s" % (tmpString, arg)
        parsedArgs.append(arg)
        isSingle = False
        tmpString = False

      # handle strings in double quotes
      elif arg.startswith('"') and isDouble == False and isSingle == False:
        isDouble = True
        tmpString = arg

      elif arg.endswith('"') and isDouble == True:
        arg = "%s %s" % (tmpString, arg)
        parsedArgs.append(arg)
        isDouble = False
        tmpString = False

      # extend current string
      elif tmpString != False:
        tmpString = "%s %s" % (tmpString, arg)

      else:
        parsedArgs.append(arg)

    return parsedArgs


Add utility methods for yesterday's date

--- etl_framework/utilities/DatetimeConverter.py
+++ etl_framework/utilities/DatetimeConverter.py
@@ -18,6 +18,11 @@

         return datetime.datetime.today() + datetime.timedelta(days=1)

+    @staticmethod
+    def get_yesterday():
+
+        return datetime.datetime.today() - datetime.timedelta(days=1)
+
     @classmethod
     def get_timestamp(cls, datetime_obj):
         """helper method to return timestamp fo datetime object"""
@@ -29,3 +34,8 @@
         """stuff"""

         return cls.get_timestamp(cls.get_tomorrow())
+
+    @classmethod
+    def get_yesterday_timestamp(cls):
+
+        return cls.get_timestamp(cls.get_yesterday())

<|original_code|>
"""class to convert datetime values"""

import datetime

class DatetimeConverter(object):
    """stuff"""

    _EPOCH_0 = datetime.datetime(1970, 1, 1)

    def __init__(self):
        """stuff"""

        pass

    @staticmethod
    def get_tomorrow():
        """stuff"""

        return datetime.datetime.today() + datetime.timedelta(days=1)

    @classmethod
    def get_timestamp(cls, datetime_obj):
        """helper method to return timestamp fo datetime object"""

        return (datetime_obj - cls._EPOCH_0).total_seconds()

    @classmethod
    def get_tomorrow_timestamp(cls):
        """stuff"""

        return cls.get_timestamp(cls.get_tomorrow())

<|edits_diff|>
--- etl_framework/utilities/DatetimeConverter.py
+++ etl_framework/utilities/DatetimeConverter.py
@@ -18,6 +18,11 @@

         return datetime.datetime.today() + datetime.timedelta(days=1)

+    @staticmethod
+    def get_yesterday():
+
+        return datetime.datetime.today() - datetime.timedelta(days=1)
+
     @classmethod
     def get_timestamp(cls, datetime_obj):
         """helper method to return timestamp fo datetime object"""
<|current_version|>
"""class to convert datetime values"""

import datetime

class DatetimeConverter(object):
    """stuff"""

    _EPOCH_0 = datetime.datetime(1970, 1, 1)

    def __init__(self):
        """stuff"""

        pass

    @staticmethod
    def get_tomorrow():
        """stuff"""

        return datetime.datetime.today() + datetime.timedelta(days=1)

    @staticmethod
    def get_yesterday():

        return datetime.datetime.today() - datetime.timedelta(days=1)

    @classmethod
    def get_timestamp(cls, datetime_obj):
        """helper method to return timestamp fo datetime object"""

        return (datetime_obj - cls._EPOCH_0).total_seconds()

    @classmethod
    def get_tomorrow_timestamp(cls):
        """stuff"""

        return cls.get_timestamp(cls.get_tomorrow())

<|next_version|>
"""class to convert datetime values"""

import datetime

class DatetimeConverter(object):
    """stuff"""

    _EPOCH_0 = datetime.datetime(1970, 1, 1)

    def __init__(self):
        """stuff"""

        pass

    @staticmethod
    def get_tomorrow():
        """stuff"""

        return datetime.datetime.today() + datetime.timedelta(days=1)

    @staticmethod
    def get_yesterday():

        return datetime.datetime.today() - datetime.timedelta(days=1)

    @classmethod
    def get_timestamp(cls, datetime_obj):
        """helper method to return timestamp fo datetime object"""

        return (datetime_obj - cls._EPOCH_0).total_seconds()

    @classmethod
    def get_tomorrow_timestamp(cls):
        """stuff"""

        return cls.get_timestamp(cls.get_tomorrow())

    @classmethod
    def get_yesterday_timestamp(cls):

        return cls.get_timestamp(cls.get_yesterday())


Add comments and docstring to OSMDataModel

--- cosmo/monitors/osm_data_models.py
+++ cosmo/monitors/osm_data_models.py
@@ -8,6 +8,7 @@

 class OSMDataModel(BaseDataModel):
+    """Data model for all OSM Shift monitors."""

     def get_data(self):
         header_keys = (
@@ -18,6 +19,7 @@
         data_keys = ('TIME', 'SHIFT_DISP', 'SHIFT_XDISP', 'SEGMENT')
         data_extensions = (1, 1, 1, 1)

+        # Find data from lampflash files
         finder = FileDataFinder(
             FILES_SOURCE,
             '*lampflash*',

<|original_code|>
import pandas as pd

from monitorframe.monitor import BaseDataModel

from cosmo.filesystem import FileDataFinder
from cosmo import FILES_SOURCE
from cosmo.monitor_helpers import explode_df

class OSMDataModel(BaseDataModel):

    def get_data(self):
        header_keys = (
            'ROOTNAME', 'EXPSTART', 'DETECTOR', 'LIFE_ADJ', 'OPT_ELEM', 'CENWAVE', 'FPPOS', 'PROPOSID', 'OBSET_ID'
        )
        header_extensions = (0, 1, 0, 0, 0, 0, 0, 0, 0)

        data_keys = ('TIME', 'SHIFT_DISP', 'SHIFT_XDISP', 'SEGMENT')
        data_extensions = (1, 1, 1, 1)

        finder = FileDataFinder(
            FILES_SOURCE,
            '*lampflash*',
            header_keys,
            header_extensions,
            data_keys=data_keys,
            data_extensions=data_extensions
        )

        df = pd.DataFrame(finder.data_from_files())

        return explode_df(df, list(data_keys))

<|edits_diff|>
--- cosmo/monitors/osm_data_models.py
+++ cosmo/monitors/osm_data_models.py
@@ -8,6 +8,7 @@

 class OSMDataModel(BaseDataModel):
+    """Data model for all OSM Shift monitors."""

     def get_data(self):
         header_keys = (
<|current_version|>
import pandas as pd

from monitorframe.monitor import BaseDataModel

from cosmo.filesystem import FileDataFinder
from cosmo import FILES_SOURCE
from cosmo.monitor_helpers import explode_df

class OSMDataModel(BaseDataModel):
    """Data model for all OSM Shift monitors."""

    def get_data(self):
        header_keys = (
            'ROOTNAME', 'EXPSTART', 'DETECTOR', 'LIFE_ADJ', 'OPT_ELEM', 'CENWAVE', 'FPPOS', 'PROPOSID', 'OBSET_ID'
        )
        header_extensions = (0, 1, 0, 0, 0, 0, 0, 0, 0)

        data_keys = ('TIME', 'SHIFT_DISP', 'SHIFT_XDISP', 'SEGMENT')
        data_extensions = (1, 1, 1, 1)

        finder = FileDataFinder(
            FILES_SOURCE,
            '*lampflash*',
            header_keys,
            header_extensions,
            data_keys=data_keys,
            data_extensions=data_extensions
        )

        df = pd.DataFrame(finder.data_from_files())

        return explode_df(df, list(data_keys))

<|next_version|>
import pandas as pd

from monitorframe.monitor import BaseDataModel

from cosmo.filesystem import FileDataFinder
from cosmo import FILES_SOURCE
from cosmo.monitor_helpers import explode_df

class OSMDataModel(BaseDataModel):
    """Data model for all OSM Shift monitors."""

    def get_data(self):
        header_keys = (
            'ROOTNAME', 'EXPSTART', 'DETECTOR', 'LIFE_ADJ', 'OPT_ELEM', 'CENWAVE', 'FPPOS', 'PROPOSID', 'OBSET_ID'
        )
        header_extensions = (0, 1, 0, 0, 0, 0, 0, 0, 0)

        data_keys = ('TIME', 'SHIFT_DISP', 'SHIFT_XDISP', 'SEGMENT')
        data_extensions = (1, 1, 1, 1)

        # Find data from lampflash files
        finder = FileDataFinder(
            FILES_SOURCE,
            '*lampflash*',
            header_keys,
            header_extensions,
            data_keys=data_keys,
            data_extensions=data_extensions
        )

        df = pd.DataFrame(finder.data_from_files())

        return explode_df(df, list(data_keys))


Save a few SQL queries.

Save a few SQL queries.

--- webapp/byceps/blueprints/ticket/service.py
+++ webapp/byceps/blueprints/ticket/service.py
@@ -6,6 +6,8 @@

 :Copyright: 2006-2015 Jochen Kupperschmidt
 """
+
+from ...database import db

 from ..party.models import Party
 from ..seating.models import Category
@@ -22,6 +24,9 @@

     return Ticket.query \
         .filter(Ticket.used_by == user) \
+        .options(
+            db.joinedload_all('occupied_seat.area'),
+        ) \
         .for_party(party) \
         .first()

<|original_code|>
# -*- coding: utf-8 -*-

"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2015 Jochen Kupperschmidt
"""

from ..party.models import Party
from ..seating.models import Category

from .models import Ticket

def find_ticket_for_user(user, party):
    """Return the ticket used by the user for the party, or `None` if not
    found.
    """
    if user.is_anonymous:
        return None

    return Ticket.query \
        .filter(Ticket.used_by == user) \
        .for_party(party) \
        .first()

def get_attended_parties(user):
    """Return the parties the user has attended."""
    return Party.query \
        .join(Category).join(Ticket).filter(Ticket.used_by == user) \
        .all()

<|edits_diff|>
--- webapp/byceps/blueprints/ticket/service.py
+++ webapp/byceps/blueprints/ticket/service.py
@@ -6,6 +6,8 @@

 :Copyright: 2006-2015 Jochen Kupperschmidt
 """
+
+from ...database import db

 from ..party.models import Party
 from ..seating.models import Category
<|current_version|>
# -*- coding: utf-8 -*-

"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2015 Jochen Kupperschmidt
"""

from ...database import db

from ..party.models import Party
from ..seating.models import Category

from .models import Ticket

def find_ticket_for_user(user, party):
    """Return the ticket used by the user for the party, or `None` if not
    found.
    """
    if user.is_anonymous:
        return None

    return Ticket.query \
        .filter(Ticket.used_by == user) \
        .for_party(party) \
        .first()

def get_attended_parties(user):
    """Return the parties the user has attended."""
    return Party.query \
        .join(Category).join(Ticket).filter(Ticket.used_by == user) \
        .all()

<|next_version|>
# -*- coding: utf-8 -*-

"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2015 Jochen Kupperschmidt
"""

from ...database import db

from ..party.models import Party
from ..seating.models import Category

from .models import Ticket

def find_ticket_for_user(user, party):
    """Return the ticket used by the user for the party, or `None` if not
    found.
    """
    if user.is_anonymous:
        return None

    return Ticket.query \
        .filter(Ticket.used_by == user) \
        .options(
            db.joinedload_all('occupied_seat.area'),
        ) \
        .for_party(party) \
        .first()

def get_attended_parties(user):
    """Return the parties the user has attended."""
    return Party.query \
        .join(Category).join(Ticket).filter(Ticket.used_by == user) \
        .all()


Add warning about outdated pymongo versions.

signac currently only supports pymongo versions 3.x.

--- signac/db/__init__.py
+++ signac/db/__init__.py
@@ -1,3 +1,4 @@
+import logging
 import warnings
 try:
     import pymongo  # noqa
@@ -12,6 +13,10 @@
         raise ImportError(
             "You need to install pymongo to use `get_database()`.")
 else:
+    if pymongo.version_tuple[0] < 3:
+        logging.getLogger(__name__).warn(
+            "Your pymongo installation (version {}) is no longer "
+            "supported by signac. Consider updating.".format(pymongo.version))
     from .database import get_database

<|original_code|>
import warnings
try:
    import pymongo  # noqa
except ImportError:
    warnings.warn("Failed to import pymongo. "
                  "get_database will not be available.", ImportWarning)

    def get_database(*args, **kwargs):
        """Get a database handle.

        This function is only available if pymongo is installed."""
        raise ImportError(
            "You need to install pymongo to use `get_database()`.")
else:
    from .database import get_database

__all__ = ['get_database']

<|edits_diff|>
--- signac/db/__init__.py
+++ signac/db/__init__.py
@@ -1,3 +1,4 @@
+import logging
 import warnings
 try:
     import pymongo  # noqa
<|current_version|>
import logging
import warnings
try:
    import pymongo  # noqa
except ImportError:
    warnings.warn("Failed to import pymongo. "
                  "get_database will not be available.", ImportWarning)

    def get_database(*args, **kwargs):
        """Get a database handle.

        This function is only available if pymongo is installed."""
        raise ImportError(
            "You need to install pymongo to use `get_database()`.")
else:
    from .database import get_database

__all__ = ['get_database']

<|next_version|>
import logging
import warnings
try:
    import pymongo  # noqa
except ImportError:
    warnings.warn("Failed to import pymongo. "
                  "get_database will not be available.", ImportWarning)

    def get_database(*args, **kwargs):
        """Get a database handle.

        This function is only available if pymongo is installed."""
        raise ImportError(
            "You need to install pymongo to use `get_database()`.")
else:
    if pymongo.version_tuple[0] < 3:
        logging.getLogger(__name__).warn(
            "Your pymongo installation (version {}) is no longer "
            "supported by signac. Consider updating.".format(pymongo.version))
    from .database import get_database

__all__ = ['get_database']


Deploy Travis CI build 834 to GitHub

Deploy Travis CI build 834 to GitHub

--- demo/tests/conftest.py
+++ demo/tests/conftest.py
@@ -1,8 +1,12 @@
 """Unit tests configuration file."""
+
+import logging

 def pytest_configure(config):
     """Disable verbose output when running tests."""
+    logging.basicConfig(level=logging.DEBUG)
+
     terminal = config.pluginmanager.getplugin('terminal')
     base = terminal.TerminalReporter

<|original_code|>
"""Unit tests configuration file."""

def pytest_configure(config):
    """Disable verbose output when running tests."""
    terminal = config.pluginmanager.getplugin('terminal')
    base = terminal.TerminalReporter

    class QuietReporter(base):
        """A py.test reporting that only shows dots when running tests."""

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.verbosity = 0
            self.showlongtestinfo = False
            self.showfspath = False

    terminal.TerminalReporter = QuietReporter

<|edits_diff|>
--- demo/tests/conftest.py
+++ demo/tests/conftest.py
@@ -1,4 +1,6 @@
 """Unit tests configuration file."""
+
+import logging

 def pytest_configure(config):
<|current_version|>
"""Unit tests configuration file."""

import logging

def pytest_configure(config):
    """Disable verbose output when running tests."""
    terminal = config.pluginmanager.getplugin('terminal')
    base = terminal.TerminalReporter

    class QuietReporter(base):
        """A py.test reporting that only shows dots when running tests."""

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.verbosity = 0
            self.showlongtestinfo = False
            self.showfspath = False

    terminal.TerminalReporter = QuietReporter

<|next_version|>
"""Unit tests configuration file."""

import logging

def pytest_configure(config):
    """Disable verbose output when running tests."""
    logging.basicConfig(level=logging.DEBUG)

    terminal = config.pluginmanager.getplugin('terminal')
    base = terminal.TerminalReporter

    class QuietReporter(base):
        """A py.test reporting that only shows dots when running tests."""

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.verbosity = 0
            self.showlongtestinfo = False
            self.showfspath = False

    terminal.TerminalReporter = QuietReporter


Use logging levels to suppress non-error output with --quiet on the CLI.

--- src/markdoc/cli/main.py
+++ src/markdoc/cli/main.py
@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-

+import logging
 import os
 import argparse

@@ -31,6 +32,9 @@
     else:
         config = None

+    if args.quiet:
+        logging.getLogger('markdoc').setLevel(logging.ERROR)
+
     command = getattr(commands, args.command.replace('-', '_'))
     return command(config, args)

<|original_code|>
# -*- coding: utf-8 -*-

import os
import argparse

from markdoc.cli import commands
from markdoc.cli.parser import parser
from markdoc.config import Config, ConfigNotFound

def main(cmd_args=None):
    """The main entry point for running the Markdoc CLI."""

    if cmd_args is not None:
        args = parser.parse_args(cmd_args)
    else:
        args = parser.parse_args()

    if args.command != 'init':
        try:
            args.config = os.path.abspath(args.config)

            if os.path.isdir(args.config):
                config = Config.for_directory(args.config)
            elif os.path.isfile(args.config):
                config = Config.for_file(args.config)
            else:
                raise ConfigNotFound("Couldn't locate Markdoc config.")
        except ConfigNotFound, exc:
            parser.error(str(exc))
    else:
        config = None

    command = getattr(commands, args.command.replace('-', '_'))
    return command(config, args)

if __name__ == '__main__':
    main()

<|edits_diff|>
--- src/markdoc/cli/main.py
+++ src/markdoc/cli/main.py
@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-

+import logging
 import os
 import argparse

<|current_version|>
# -*- coding: utf-8 -*-

import logging
import os
import argparse

from markdoc.cli import commands
from markdoc.cli.parser import parser
from markdoc.config import Config, ConfigNotFound

def main(cmd_args=None):
    """The main entry point for running the Markdoc CLI."""

    if cmd_args is not None:
        args = parser.parse_args(cmd_args)
    else:
        args = parser.parse_args()

    if args.command != 'init':
        try:
            args.config = os.path.abspath(args.config)

            if os.path.isdir(args.config):
                config = Config.for_directory(args.config)
            elif os.path.isfile(args.config):
                config = Config.for_file(args.config)
            else:
                raise ConfigNotFound("Couldn't locate Markdoc config.")
        except ConfigNotFound, exc:
            parser.error(str(exc))
    else:
        config = None

    command = getattr(commands, args.command.replace('-', '_'))
    return command(config, args)

if __name__ == '__main__':
    main()

<|next_version|>
# -*- coding: utf-8 -*-

import logging
import os
import argparse

from markdoc.cli import commands
from markdoc.cli.parser import parser
from markdoc.config import Config, ConfigNotFound

def main(cmd_args=None):
    """The main entry point for running the Markdoc CLI."""

    if cmd_args is not None:
        args = parser.parse_args(cmd_args)
    else:
        args = parser.parse_args()

    if args.command != 'init':
        try:
            args.config = os.path.abspath(args.config)

            if os.path.isdir(args.config):
                config = Config.for_directory(args.config)
            elif os.path.isfile(args.config):
                config = Config.for_file(args.config)
            else:
                raise ConfigNotFound("Couldn't locate Markdoc config.")
        except ConfigNotFound, exc:
            parser.error(str(exc))
    else:
        config = None

    if args.quiet:
        logging.getLogger('markdoc').setLevel(logging.ERROR)

    command = getattr(commands, args.command.replace('-', '_'))
    return command(config, args)

if __name__ == '__main__':
    main()


Print each bpmx pv name along with the associated value to stdout

--- pytac/mini_project.py
+++ pytac/mini_project.py
@@ -2,6 +2,7 @@
 import pytac.epics

 def main():
+    # First task: print the number of bpm y elements in the ring.
     lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem())
     bpms = lattice.get_elements('BPM')
     bpms_n = 0
@@ -13,6 +14,11 @@
     except:
         print 'Warning! There exists a bpm with no y field.'

+    # Second task: Print each bpmx pv along with the associated value.
+    for bpm in bpms:
+        print bpm.get_pv_name('x', 'readback')
+        print bpm.get_pv_value('x', 'readback')
+

 if __name__=='__main__':
     main()

<|original_code|>
import pytac.load_csv
import pytac.epics

def main():
    lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem())
    bpms = lattice.get_elements('BPM')
    bpms_n = 0
    try:
        for bpm in bpms:
            bpm.get_pv_name('y')
            bpms_n += 1
        print 'There exist {0} BPMy elements in the ring.'.format(bpms_n)
    except:
        print 'Warning! There exists a bpm with no y field.'

if __name__=='__main__':
    main()

<|edits_diff|>
--- pytac/mini_project.py
+++ pytac/mini_project.py
@@ -2,6 +2,7 @@
 import pytac.epics

 def main():
+    # First task: print the number of bpm y elements in the ring.
     lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem())
     bpms = lattice.get_elements('BPM')
     bpms_n = 0
<|current_version|>
import pytac.load_csv
import pytac.epics

def main():
    # First task: print the number of bpm y elements in the ring.
    lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem())
    bpms = lattice.get_elements('BPM')
    bpms_n = 0
    try:
        for bpm in bpms:
            bpm.get_pv_name('y')
            bpms_n += 1
        print 'There exist {0} BPMy elements in the ring.'.format(bpms_n)
    except:
        print 'Warning! There exists a bpm with no y field.'

if __name__=='__main__':
    main()

<|next_version|>
import pytac.load_csv
import pytac.epics

def main():
    # First task: print the number of bpm y elements in the ring.
    lattice = pytac.load_csv.load('VMX', pytac.epics.EpicsControlSystem())
    bpms = lattice.get_elements('BPM')
    bpms_n = 0
    try:
        for bpm in bpms:
            bpm.get_pv_name('y')
            bpms_n += 1
        print 'There exist {0} BPMy elements in the ring.'.format(bpms_n)
    except:
        print 'Warning! There exists a bpm with no y field.'

    # Second task: Print each bpmx pv along with the associated value.
    for bpm in bpms:
        print bpm.get_pv_name('x', 'readback')
        print bpm.get_pv_value('x', 'readback')

if __name__=='__main__':
    main()


Add venues to site export

Add venues to site export

--- wafer/schedule/renderers.py
+++ wafer/schedule/renderers.py
@@ -1,9 +1,15 @@
 from django_medusa.renderers import StaticSiteRenderer
+from wafer.schedule.models import Venue

 class ScheduleRenderer(StaticSiteRenderer):
     def get_paths(self):
         paths = ["/schedule/", ]
+
+        # Add the venues
+        items = Venue.objects.all()
+        for item in items:
+            paths.append(item.get_absolute_url())
         return paths

 renderers = [ScheduleRenderer, ]

<|original_code|>
from django_medusa.renderers import StaticSiteRenderer

class ScheduleRenderer(StaticSiteRenderer):
    def get_paths(self):
        paths = ["/schedule/", ]
        return paths

renderers = [ScheduleRenderer, ]

<|edits_diff|>
--- wafer/schedule/renderers.py
+++ wafer/schedule/renderers.py
@@ -1,4 +1,5 @@
 from django_medusa.renderers import StaticSiteRenderer
+from wafer.schedule.models import Venue

 class ScheduleRenderer(StaticSiteRenderer):
<|current_version|>
from django_medusa.renderers import StaticSiteRenderer
from wafer.schedule.models import Venue

class ScheduleRenderer(StaticSiteRenderer):
    def get_paths(self):
        paths = ["/schedule/", ]
        return paths

renderers = [ScheduleRenderer, ]

<|next_version|>
from django_medusa.renderers import StaticSiteRenderer
from wafer.schedule.models import Venue

class ScheduleRenderer(StaticSiteRenderer):
    def get_paths(self):
        paths = ["/schedule/", ]

        # Add the venues
        items = Venue.objects.all()
        for item in items:
            paths.append(item.get_absolute_url())
        return paths

renderers = [ScheduleRenderer, ]


Make command-keyword compatible with DFW implementation

--- Cauldron/ext/commandkeywords/__init__.py
+++ Cauldron/ext/commandkeywords/__init__.py
@@ -6,6 +6,7 @@

 from Cauldron.types import Boolean, DispatcherKeywordType
 from Cauldron.exc import NoWriteNecessary
+from Cauldron.utils.callbacks import Callbacks

 class CommandKeyword(Boolean, DispatcherKeywordType):
     """This keyword will receive boolean writes as 1, and will always be set to 0.
@@ -20,6 +21,11 @@
     def __init__(self, *args, **kwargs):
         kwargs['initial'] = '0'
         super(CommandKeyword, self).__init__(*args, **kwargs)
+        self._cbs = Callbacks()
+
+    def command(self, func):
+        """Add command items."""
+        self._cbs.add(func)

     def prewrite(self, value):
         """Before writing, trigger no-write-necssary if value is False"""
@@ -27,6 +33,11 @@
             raise NoWriteNecessary("No write needed, command not triggered.")
         return super(CommandKeyword, self).prewrite(value)

+    def write(self, value):
+        """Write to the commands."""
+        if str(value) == '1':
+            self._cbs(self)
+
     def postwrite(self, value):
         """Special postwrite that always sets the value to '0'."""
         self.set('0', force=True)

<|original_code|>
# -*- coding: utf-8 -*-
"""
An extension for a command-based keyword.
"""
from __future__ import absolute_import

from Cauldron.types import Boolean, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary

class CommandKeyword(Boolean, DispatcherKeywordType):
    """This keyword will receive boolean writes as 1, and will always be set to 0.

        Actions can then be performed in callbacks, etc., every time this keyword is triggered.
    """

    KTL_REGISTERED = False

    KTL_TYPE = 'boolean'

    def __init__(self, *args, **kwargs):
        kwargs['initial'] = '0'
        super(CommandKeyword, self).__init__(*args, **kwargs)

    def prewrite(self, value):
        """Before writing, trigger no-write-necssary if value is False"""
        if self.translate(value) == '0':
            raise NoWriteNecessary("No write needed, command not triggered.")
        return super(CommandKeyword, self).prewrite(value)

    def postwrite(self, value):
        """Special postwrite that always sets the value to '0'."""
        self.set('0', force=True)

    # We don't have to do anything else here.

<|edits_diff|>
--- Cauldron/ext/commandkeywords/__init__.py
+++ Cauldron/ext/commandkeywords/__init__.py
@@ -6,6 +6,7 @@

 from Cauldron.types import Boolean, DispatcherKeywordType
 from Cauldron.exc import NoWriteNecessary
+from Cauldron.utils.callbacks import Callbacks

 class CommandKeyword(Boolean, DispatcherKeywordType):
     """This keyword will receive boolean writes as 1, and will always be set to 0.
@@ -20,6 +21,11 @@
     def __init__(self, *args, **kwargs):
         kwargs['initial'] = '0'
         super(CommandKeyword, self).__init__(*args, **kwargs)
+        self._cbs = Callbacks()
+
+    def command(self, func):
+        """Add command items."""
+        self._cbs.add(func)

     def prewrite(self, value):
         """Before writing, trigger no-write-necssary if value is False"""
<|current_version|>
# -*- coding: utf-8 -*-
"""
An extension for a command-based keyword.
"""
from __future__ import absolute_import

from Cauldron.types import Boolean, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary
from Cauldron.utils.callbacks import Callbacks

class CommandKeyword(Boolean, DispatcherKeywordType):
    """This keyword will receive boolean writes as 1, and will always be set to 0.

        Actions can then be performed in callbacks, etc., every time this keyword is triggered.
    """

    KTL_REGISTERED = False

    KTL_TYPE = 'boolean'

    def __init__(self, *args, **kwargs):
        kwargs['initial'] = '0'
        super(CommandKeyword, self).__init__(*args, **kwargs)
        self._cbs = Callbacks()

    def command(self, func):
        """Add command items."""
        self._cbs.add(func)

    def prewrite(self, value):
        """Before writing, trigger no-write-necssary if value is False"""
        if self.translate(value) == '0':
            raise NoWriteNecessary("No write needed, command not triggered.")
        return super(CommandKeyword, self).prewrite(value)

    def postwrite(self, value):
        """Special postwrite that always sets the value to '0'."""
        self.set('0', force=True)

    # We don't have to do anything else here.

<|next_version|>
# -*- coding: utf-8 -*-
"""
An extension for a command-based keyword.
"""
from __future__ import absolute_import

from Cauldron.types import Boolean, DispatcherKeywordType
from Cauldron.exc import NoWriteNecessary
from Cauldron.utils.callbacks import Callbacks

class CommandKeyword(Boolean, DispatcherKeywordType):
    """This keyword will receive boolean writes as 1, and will always be set to 0.

        Actions can then be performed in callbacks, etc., every time this keyword is triggered.
    """

    KTL_REGISTERED = False

    KTL_TYPE = 'boolean'

    def __init__(self, *args, **kwargs):
        kwargs['initial'] = '0'
        super(CommandKeyword, self).__init__(*args, **kwargs)
        self._cbs = Callbacks()

    def command(self, func):
        """Add command items."""
        self._cbs.add(func)

    def prewrite(self, value):
        """Before writing, trigger no-write-necssary if value is False"""
        if self.translate(value) == '0':
            raise NoWriteNecessary("No write needed, command not triggered.")
        return super(CommandKeyword, self).prewrite(value)

    def write(self, value):
        """Write to the commands."""
        if str(value) == '1':
            self._cbs(self)

    def postwrite(self, value):
        """Special postwrite that always sets the value to '0'."""
        self.set('0', force=True)

    # We don't have to do anything else here.


Add a detection of a function definition.

--- micro.py
+++ micro.py
@@ -16,9 +16,17 @@
 def get_tokens(code):
 	return code.split(' ')

+def parse_function(tokens):
+	return 'test', (23, None), tokens[-1:]
+
 def evaluate(tokens):
 	name = tokens[0]
 	tokens = tokens[1:]
+	if name == 'fn':
+		name, function, tokens = parse_function(tokens)
+		functions[name] = function
+
+		return 0, tokens
 	if name not in functions:
 		return int(name), tokens

@@ -36,3 +44,4 @@
 	tokens = get_tokens(code)
 	value, _ = evaluate(tokens)
 	print(value)
+	print(functions)

<|original_code|>
#!/usr/bin/env python

from sys import argv
from operator import add, sub, mul, div

functions = { \
	'+': (2, add), \
	'-': (2, sub), \
	'*': (2, mul), \
	'/': (2, div) \
}

def get_code():
	return argv[1]

def get_tokens(code):
	return code.split(' ')

def evaluate(tokens):
	name = tokens[0]
	tokens = tokens[1:]
	if name not in functions:
		return int(name), tokens

	function = functions[name]
	arguments = []
	for _ in xrange(function[0]):
		value, tokens = evaluate(tokens)
		arguments.append(value)

	value = function[1](*arguments)
	return value, tokens

if __name__ == '__main__':
	code = get_code()
	tokens = get_tokens(code)
	value, _ = evaluate(tokens)
	print(value)

<|edits_diff|>
--- micro.py
+++ micro.py
@@ -16,9 +16,17 @@
 def get_tokens(code):
 	return code.split(' ')

+def parse_function(tokens):
+	return 'test', (23, None), tokens[-1:]
+
 def evaluate(tokens):
 	name = tokens[0]
 	tokens = tokens[1:]
+	if name == 'fn':
+		name, function, tokens = parse_function(tokens)
+		functions[name] = function
+
+		return 0, tokens
 	if name not in functions:
 		return int(name), tokens

<|current_version|>
#!/usr/bin/env python

from sys import argv
from operator import add, sub, mul, div

functions = { \
	'+': (2, add), \
	'-': (2, sub), \
	'*': (2, mul), \
	'/': (2, div) \
}

def get_code():
	return argv[1]

def get_tokens(code):
	return code.split(' ')

def parse_function(tokens):
	return 'test', (23, None), tokens[-1:]

def evaluate(tokens):
	name = tokens[0]
	tokens = tokens[1:]
	if name == 'fn':
		name, function, tokens = parse_function(tokens)
		functions[name] = function

		return 0, tokens
	if name not in functions:
		return int(name), tokens

	function = functions[name]
	arguments = []
	for _ in xrange(function[0]):
		value, tokens = evaluate(tokens)
		arguments.append(value)

	value = function[1](*arguments)
	return value, tokens

if __name__ == '__main__':
	code = get_code()
	tokens = get_tokens(code)
	value, _ = evaluate(tokens)
	print(value)

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

from sys import argv
from operator import add, sub, mul, div

functions = { \
	'+': (2, add), \
	'-': (2, sub), \
	'*': (2, mul), \
	'/': (2, div) \
}

def get_code():
	return argv[1]

def get_tokens(code):
	return code.split(' ')

def parse_function(tokens):
	return 'test', (23, None), tokens[-1:]

def evaluate(tokens):
	name = tokens[0]
	tokens = tokens[1:]
	if name == 'fn':
		name, function, tokens = parse_function(tokens)
		functions[name] = function

		return 0, tokens
	if name not in functions:
		return int(name), tokens

	function = functions[name]
	arguments = []
	for _ in xrange(function[0]):
		value, tokens = evaluate(tokens)
		arguments.append(value)

	value = function[1](*arguments)
	return value, tokens

if __name__ == '__main__':
	code = get_code()
	tokens = get_tokens(code)
	value, _ = evaluate(tokens)
	print(value)
	print(functions)


Delete non-digit characters in ISBN in server side

--- sell/views.py
+++ sell/views.py
@@ -1,4 +1,5 @@
 from decimal import Decimal
+import re

 from django.shortcuts import render
 from django.utils.translation import ugettext_lazy as _
@@ -34,6 +35,7 @@
             if 'pk' in book:
                 dbbook.book_type_id = book['pk']
             else:
+                book['isbn'] = re.sub(r'[^\d.]+', '', book['isbn'])
                 book['price'] = Decimal(book['price'])
                 if book['publication_year'] == "":
                     book['publication_year'] = 1970

<|original_code|>
from decimal import Decimal

from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _

from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard

class SellWizard(BookChooserWizard):
    @property
    def page_title(self):
        return _("Sell books")

    @property
    def url_namespace(self):
        return "sell"

    @property
    def session_var_name(self):
        return "sell_chosen_books"

    @property
    def feature_add_new(self):
        return True

    def process_books_summary(self, session, user, book_list):
        for book in book_list:
            amount = book['amount']
            del book['amount']

            user.save()
            dbbook = Book(owner=user, accepted=False, sold=False)
            if 'pk' in book:
                dbbook.book_type_id = book['pk']
            else:
                book['price'] = Decimal(book['price'])
                if book['publication_year'] == "":
                    book['publication_year'] = 1970

                book_type = BookType(**book)
                book_type.save()
                dbbook.book_type = book_type

            for i in range(0, amount):
                dbbook.pk = None
                dbbook.save()

        return True, None

    def success(self, request):
        return render(request, 'sell/success.html')
<|edits_diff|>
--- sell/views.py
+++ sell/views.py
@@ -1,4 +1,5 @@
 from decimal import Decimal
+import re

 from django.shortcuts import render
 from django.utils.translation import ugettext_lazy as _
<|current_version|>
from decimal import Decimal
import re

from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _

from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard

class SellWizard(BookChooserWizard):
    @property
    def page_title(self):
        return _("Sell books")

    @property
    def url_namespace(self):
        return "sell"

    @property
    def session_var_name(self):
        return "sell_chosen_books"

    @property
    def feature_add_new(self):
        return True

    def process_books_summary(self, session, user, book_list):
        for book in book_list:
            amount = book['amount']
            del book['amount']

            user.save()
            dbbook = Book(owner=user, accepted=False, sold=False)
            if 'pk' in book:
                dbbook.book_type_id = book['pk']
            else:
                book['price'] = Decimal(book['price'])
                if book['publication_year'] == "":
                    book['publication_year'] = 1970

                book_type = BookType(**book)
                book_type.save()
                dbbook.book_type = book_type

            for i in range(0, amount):
                dbbook.pk = None
                dbbook.save()

        return True, None

    def success(self, request):
        return render(request, 'sell/success.html')
<|next_version|>
from decimal import Decimal
import re

from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _

from books.models import BookType, Book
from common.bookchooserwizard import BookChooserWizard

class SellWizard(BookChooserWizard):
    @property
    def page_title(self):
        return _("Sell books")

    @property
    def url_namespace(self):
        return "sell"

    @property
    def session_var_name(self):
        return "sell_chosen_books"

    @property
    def feature_add_new(self):
        return True

    def process_books_summary(self, session, user, book_list):
        for book in book_list:
            amount = book['amount']
            del book['amount']

            user.save()
            dbbook = Book(owner=user, accepted=False, sold=False)
            if 'pk' in book:
                dbbook.book_type_id = book['pk']
            else:
                book['isbn'] = re.sub(r'[^\d.]+', '', book['isbn'])
                book['price'] = Decimal(book['price'])
                if book['publication_year'] == "":
                    book['publication_year'] = 1970

                book_type = BookType(**book)
                book_type.save()
                dbbook.book_type = book_type

            for i in range(0, amount):
                dbbook.pk = None
                dbbook.save()

        return True, None

    def success(self, request):
        return render(request, 'sell/success.html')


Include README.md in package metadata

Include README.md in package metadata

--- setup.py
+++ setup.py
@@ -3,6 +3,9 @@
 import sys
 from setuptools import setup, find_packages
 from pkg_resources import resource_filename
+
+with open("README.md", "r") as fh:
+    long_description = fh.read()

 # depending on your execution context the version file
 # may be located in a different place!
@@ -17,6 +20,8 @@
     name='hvac',
     version=open(vsn_path, 'r').read(),
     description='HashiCorp Vault API client',
+    long_description=long_description,
+    long_description_content_type="text/markdown",
     author='Ian Unruh',
     author_email='ianunruh@gmail.com',
     url='https://github.com/ianunruh/hvac',

<|original_code|>
#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from pkg_resources import resource_filename

# depending on your execution context the version file
# may be located in a different place!
vsn_path = resource_filename(__name__, 'hvac/version')
if not os.path.exists(vsn_path):
    vsn_path = resource_filename(__name__, 'version')
    if not os.path.exists(vsn_path):
        print("%s is missing" % vsn_path)
        sys.exit(1)

setup(
    name='hvac',
    version=open(vsn_path, 'r').read(),
    description='HashiCorp Vault API client',
    author='Ian Unruh',
    author_email='ianunruh@gmail.com',
    url='https://github.com/ianunruh/hvac',
    keywords=['hashicorp', 'vault'],
    classifiers=['License :: OSI Approved :: Apache Software License'],
    packages=find_packages(),
    install_requires=[
        'requests>=2.7.0',
    ],
    include_package_data=True,
    package_data={'hvac': ['version']},
    extras_require={
        'parser': ['pyhcl>=0.2.1,<0.3.0']
    }
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -3,6 +3,9 @@
 import sys
 from setuptools import setup, find_packages
 from pkg_resources import resource_filename
+
+with open("README.md", "r") as fh:
+    long_description = fh.read()

 # depending on your execution context the version file
 # may be located in a different place!
<|current_version|>
#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from pkg_resources import resource_filename

with open("README.md", "r") as fh:
    long_description = fh.read()

# depending on your execution context the version file
# may be located in a different place!
vsn_path = resource_filename(__name__, 'hvac/version')
if not os.path.exists(vsn_path):
    vsn_path = resource_filename(__name__, 'version')
    if not os.path.exists(vsn_path):
        print("%s is missing" % vsn_path)
        sys.exit(1)

setup(
    name='hvac',
    version=open(vsn_path, 'r').read(),
    description='HashiCorp Vault API client',
    author='Ian Unruh',
    author_email='ianunruh@gmail.com',
    url='https://github.com/ianunruh/hvac',
    keywords=['hashicorp', 'vault'],
    classifiers=['License :: OSI Approved :: Apache Software License'],
    packages=find_packages(),
    install_requires=[
        'requests>=2.7.0',
    ],
    include_package_data=True,
    package_data={'hvac': ['version']},
    extras_require={
        'parser': ['pyhcl>=0.2.1,<0.3.0']
    }
)

<|next_version|>
#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from pkg_resources import resource_filename

with open("README.md", "r") as fh:
    long_description = fh.read()

# depending on your execution context the version file
# may be located in a different place!
vsn_path = resource_filename(__name__, 'hvac/version')
if not os.path.exists(vsn_path):
    vsn_path = resource_filename(__name__, 'version')
    if not os.path.exists(vsn_path):
        print("%s is missing" % vsn_path)
        sys.exit(1)

setup(
    name='hvac',
    version=open(vsn_path, 'r').read(),
    description='HashiCorp Vault API client',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author='Ian Unruh',
    author_email='ianunruh@gmail.com',
    url='https://github.com/ianunruh/hvac',
    keywords=['hashicorp', 'vault'],
    classifiers=['License :: OSI Approved :: Apache Software License'],
    packages=find_packages(),
    install_requires=[
        'requests>=2.7.0',
    ],
    include_package_data=True,
    package_data={'hvac': ['version']},
    extras_require={
        'parser': ['pyhcl>=0.2.1,<0.3.0']
    }
)


Make other API classes available from base module.

--- lib/__init__.py
+++ lib/__init__.py
@@ -1,3 +1,5 @@
+from errors import WebHDFSError
 from client import WebHDFSClient
+from attrib import WebHDFSObject

 __version__ = '1.0'

<|original_code|>
from client import WebHDFSClient

__version__ = '1.0'

<|edits_diff|>
--- lib/__init__.py
+++ lib/__init__.py
@@ -1,3 +1,4 @@
+from errors import WebHDFSError
 from client import WebHDFSClient

 __version__ = '1.0'
<|current_version|>
from errors import WebHDFSError
from client import WebHDFSClient

__version__ = '1.0'

<|next_version|>
from errors import WebHDFSError
from client import WebHDFSClient
from attrib import WebHDFSObject

__version__ = '1.0'


Add KDE show & hide logging

Add KDE show & hide logging

--- stdup/kde.py
+++ stdup/kde.py
@@ -30,12 +30,14 @@
         self.workspace = 6

     def show(self):
+        logger.info('kde show')
         envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6',
                   timeout=2)
         # envoy.run('killall firefox', timeout=2)
         # envoy.connect('firefox http://standup-backend.herokuapp.com/?room=12')

     def hide(self):
+        logger.info('kde hide')
         envoy.run(('qdbus org.kde.kwin /KWin '
                   'org.kde.KWin.setCurrentDesktop {}')
                       .format(self.prev_workspace),

<|original_code|>
# -*- coding: utf-8 -*-

# Copyright 2013 Jacek Mitręga

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

import envoy
import logging

logger = logging.getLogger(__name__)

class KdeWindowManager(object):

    def __init__(self, workspace=6):
        self.prev_workspace = 1
        self.workspace = 6

    def show(self):
        envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6',
                  timeout=2)
        # envoy.run('killall firefox', timeout=2)
        # envoy.connect('firefox http://standup-backend.herokuapp.com/?room=12')

    def hide(self):
        envoy.run(('qdbus org.kde.kwin /KWin '
                  'org.kde.KWin.setCurrentDesktop {}')
                      .format(self.prev_workspace),
                  timeout=2)
        # envoy.run('killall firefox', timeout=2)

<|edits_diff|>
--- stdup/kde.py
+++ stdup/kde.py
@@ -30,6 +30,7 @@
         self.workspace = 6

     def show(self):
+        logger.info('kde show')
         envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6',
                   timeout=2)
         # envoy.run('killall firefox', timeout=2)
<|current_version|>
# -*- coding: utf-8 -*-

# Copyright 2013 Jacek Mitręga

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

import envoy
import logging

logger = logging.getLogger(__name__)

class KdeWindowManager(object):

    def __init__(self, workspace=6):
        self.prev_workspace = 1
        self.workspace = 6

    def show(self):
        logger.info('kde show')
        envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6',
                  timeout=2)
        # envoy.run('killall firefox', timeout=2)
        # envoy.connect('firefox http://standup-backend.herokuapp.com/?room=12')

    def hide(self):
        envoy.run(('qdbus org.kde.kwin /KWin '
                  'org.kde.KWin.setCurrentDesktop {}')
                      .format(self.prev_workspace),
                  timeout=2)
        # envoy.run('killall firefox', timeout=2)

<|next_version|>
# -*- coding: utf-8 -*-

# Copyright 2013 Jacek Mitręga

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import unicode_literals

import envoy
import logging

logger = logging.getLogger(__name__)

class KdeWindowManager(object):

    def __init__(self, workspace=6):
        self.prev_workspace = 1
        self.workspace = 6

    def show(self):
        logger.info('kde show')
        envoy.run('qdbus org.kde.kwin /KWin org.kde.KWin.setCurrentDesktop 6',
                  timeout=2)
        # envoy.run('killall firefox', timeout=2)
        # envoy.connect('firefox http://standup-backend.herokuapp.com/?room=12')

    def hide(self):
        logger.info('kde hide')
        envoy.run(('qdbus org.kde.kwin /KWin '
                  'org.kde.KWin.setCurrentDesktop {}')
                      .format(self.prev_workspace),
                  timeout=2)
        # envoy.run('killall firefox', timeout=2)


Add `owner` filter to CaseES

Add `owner` filter to CaseES

--- corehq/apps/es/cases.py
+++ corehq/apps/es/cases.py
@@ -12,6 +12,7 @@
             closed_range,
             is_closed,
             case_type,
+            owner,
         ] + super(CaseES, self).builtin_filters

@@ -29,3 +30,7 @@

 def case_type(type_):
     return filters.term('type.exact', type_)
+
+
+def owner(owner_id):
+    return filters.term('owner_id', owner_id)

<|original_code|>
from .es_query import HQESQuery
from . import filters

class CaseES(HQESQuery):
    index = 'cases'

    @property
    def builtin_filters(self):
        return [
            opened_range,
            closed_range,
            is_closed,
            case_type,
        ] + super(CaseES, self).builtin_filters

def opened_range(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('opened_on', gt, gte, lt, lte)

def closed_range(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('closed_on', gt, gte, lt, lte)

def is_closed(closed=True):
    return filters.term('closed', closed)

def case_type(type_):
    return filters.term('type.exact', type_)

<|edits_diff|>
--- corehq/apps/es/cases.py
+++ corehq/apps/es/cases.py
@@ -12,6 +12,7 @@
             closed_range,
             is_closed,
             case_type,
+            owner,
         ] + super(CaseES, self).builtin_filters

<|current_version|>
from .es_query import HQESQuery
from . import filters

class CaseES(HQESQuery):
    index = 'cases'

    @property
    def builtin_filters(self):
        return [
            opened_range,
            closed_range,
            is_closed,
            case_type,
            owner,
        ] + super(CaseES, self).builtin_filters

def opened_range(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('opened_on', gt, gte, lt, lte)

def closed_range(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('closed_on', gt, gte, lt, lte)

def is_closed(closed=True):
    return filters.term('closed', closed)

def case_type(type_):
    return filters.term('type.exact', type_)

<|next_version|>
from .es_query import HQESQuery
from . import filters

class CaseES(HQESQuery):
    index = 'cases'

    @property
    def builtin_filters(self):
        return [
            opened_range,
            closed_range,
            is_closed,
            case_type,
            owner,
        ] + super(CaseES, self).builtin_filters

def opened_range(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('opened_on', gt, gte, lt, lte)

def closed_range(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('closed_on', gt, gte, lt, lte)

def is_closed(closed=True):
    return filters.term('closed', closed)

def case_type(type_):
    return filters.term('type.exact', type_)

def owner(owner_id):
    return filters.term('owner_id', owner_id)


Fix django 1.5 warning - provide debug filter

--- wheelcms_project/settings/base/settings_logging.py
+++ wheelcms_project/settings/base/settings_logging.py
@@ -6,9 +6,15 @@
 LOGGING = {
     'version': 1,
     'disable_existing_loggers': False,
+    'filters': {
+     'require_debug_false': {
+         '()': 'django.utils.log.RequireDebugFalse'
+     }
+     },
     'handlers': {
         'mail_admins': {
             'level': 'ERROR',
+            'filters': ['require_debug_false'],
             'class': 'django.utils.log.AdminEmailHandler'
         },
         'console': {

<|original_code|>
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.db.backends': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': False,
        },
    }
}

<|edits_diff|>
--- wheelcms_project/settings/base/settings_logging.py
+++ wheelcms_project/settings/base/settings_logging.py
@@ -6,6 +6,11 @@
 LOGGING = {
     'version': 1,
     'disable_existing_loggers': False,
+    'filters': {
+     'require_debug_false': {
+         '()': 'django.utils.log.RequireDebugFalse'
+     }
+     },
     'handlers': {
         'mail_admins': {
             'level': 'ERROR',
<|current_version|>
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
     'require_debug_false': {
         '()': 'django.utils.log.RequireDebugFalse'
     }
     },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.db.backends': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': False,
        },
    }
}

<|next_version|>
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
     'require_debug_false': {
         '()': 'django.utils.log.RequireDebugFalse'
     }
     },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.db.backends': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': False,
        },
    }
}


Add comments to permission utils

Add comments to permission utils

--- zou/app/utils/permissions.py
+++ zou/app/utils/permissions.py
@@ -10,10 +10,17 @@

 def has_manager_permissions():
+    """
+    Return True if user is admin or manager.
+    """
     return admin_permission.can() or manager_permission.can()

 def check_manager_permissions():
+    """
+    Return True if user is admin or manager. It raises a PermissionDenied
+    exception in case of failure.
+    """
     if has_manager_permissions():
         return True
     else:
@@ -21,6 +28,10 @@

 def check_admin_permissions():
+    """
+    Return True if user is admin. It raises a PermissionDenied exception in case
+    of failure.
+    """
     if admin_permission.can():
         return True
     else:

<|original_code|>
from flask_principal import RoleNeed, Permission
from werkzeug.exceptions import Forbidden

admin_permission = Permission(RoleNeed('admin'))
manager_permission = Permission(RoleNeed('manager'))

class PermissionDenied(Forbidden):
    pass

def has_manager_permissions():
    return admin_permission.can() or manager_permission.can()

def check_manager_permissions():
    if has_manager_permissions():
        return True
    else:
        raise PermissionDenied

def check_admin_permissions():
    if admin_permission.can():
        return True
    else:
        raise PermissionDenied

<|edits_diff|>
--- zou/app/utils/permissions.py
+++ zou/app/utils/permissions.py
@@ -10,10 +10,17 @@

 def has_manager_permissions():
+    """
+    Return True if user is admin or manager.
+    """
     return admin_permission.can() or manager_permission.can()

 def check_manager_permissions():
+    """
+    Return True if user is admin or manager. It raises a PermissionDenied
+    exception in case of failure.
+    """
     if has_manager_permissions():
         return True
     else:
<|current_version|>
from flask_principal import RoleNeed, Permission
from werkzeug.exceptions import Forbidden

admin_permission = Permission(RoleNeed('admin'))
manager_permission = Permission(RoleNeed('manager'))

class PermissionDenied(Forbidden):
    pass

def has_manager_permissions():
    """
    Return True if user is admin or manager.
    """
    return admin_permission.can() or manager_permission.can()

def check_manager_permissions():
    """
    Return True if user is admin or manager. It raises a PermissionDenied
    exception in case of failure.
    """
    if has_manager_permissions():
        return True
    else:
        raise PermissionDenied

def check_admin_permissions():
    if admin_permission.can():
        return True
    else:
        raise PermissionDenied

<|next_version|>
from flask_principal import RoleNeed, Permission
from werkzeug.exceptions import Forbidden

admin_permission = Permission(RoleNeed('admin'))
manager_permission = Permission(RoleNeed('manager'))

class PermissionDenied(Forbidden):
    pass

def has_manager_permissions():
    """
    Return True if user is admin or manager.
    """
    return admin_permission.can() or manager_permission.can()

def check_manager_permissions():
    """
    Return True if user is admin or manager. It raises a PermissionDenied
    exception in case of failure.
    """
    if has_manager_permissions():
        return True
    else:
        raise PermissionDenied

def check_admin_permissions():
    """
    Return True if user is admin. It raises a PermissionDenied exception in case
    of failure.
    """
    if admin_permission.can():
        return True
    else:
        raise PermissionDenied