Fix calling "display" method multiple times

--- k3d/__init__.py
+++ k3d/__init__.py
@@ -21,6 +21,7 @@
         super(K3D, self).__init__()

         self.__objects = Objects(self.__show)
+        self.__display_strategy = self.__display
         self.on_displayed(lambda x: self.__objects.flush())

         self.parameters = {
@@ -34,7 +35,14 @@
         return self

     def display(self):
+        self.__display_strategy()
+
+    def __display(self):
         display(self)
+        self.__display_strategy = self.__pass

     def __show(self, obj):
         self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
+
+    def __pass(self):
+        pass

<|original_code|>
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib

class K3D(DOMWidget, Factory):
    _view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
    _view_name = Unicode('K3DView', sync=True)
    _model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
    _model_name = Unicode('K3DModel', sync=True)

    COMPRESSION_LEVEL = 1

    data = Bytes(sync=True)
    parameters = Dict(sync=True)

    def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
        super(K3D, self).__init__()

        self.__objects = Objects(self.__show)
        self.on_displayed(lambda x: self.__objects.flush())

        self.parameters = {
            'antialias': antialias,
            'backgroundColor': background_color,
            'height': height,
        }

    def __add__(self, obj):
        self.__objects.add(obj)
        return self

    def display(self):
        display(self)

    def __show(self, obj):
        self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))

<|edits_diff|>
--- k3d/__init__.py
+++ k3d/__init__.py
@@ -21,6 +21,7 @@
         super(K3D, self).__init__()

         self.__objects = Objects(self.__show)
+        self.__display_strategy = self.__display
         self.on_displayed(lambda x: self.__objects.flush())

         self.parameters = {
@@ -34,7 +35,11 @@
         return self

     def display(self):
+        self.__display_strategy()
+
+    def __display(self):
         display(self)
+        self.__display_strategy = self.__pass

     def __show(self, obj):
         self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
<|current_version|>
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib

class K3D(DOMWidget, Factory):
    _view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
    _view_name = Unicode('K3DView', sync=True)
    _model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
    _model_name = Unicode('K3DModel', sync=True)

    COMPRESSION_LEVEL = 1

    data = Bytes(sync=True)
    parameters = Dict(sync=True)

    def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
        super(K3D, self).__init__()

        self.__objects = Objects(self.__show)
        self.__display_strategy = self.__display
        self.on_displayed(lambda x: self.__objects.flush())

        self.parameters = {
            'antialias': antialias,
            'backgroundColor': background_color,
            'height': height,
        }

    def __add__(self, obj):
        self.__objects.add(obj)
        return self

    def display(self):
        self.__display_strategy()

    def __display(self):
        display(self)
        self.__display_strategy = self.__pass

    def __show(self, obj):
        self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))

<|next_version|>
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib

class K3D(DOMWidget, Factory):
    _view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
    _view_name = Unicode('K3DView', sync=True)
    _model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
    _model_name = Unicode('K3DModel', sync=True)

    COMPRESSION_LEVEL = 1

    data = Bytes(sync=True)
    parameters = Dict(sync=True)

    def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
        super(K3D, self).__init__()

        self.__objects = Objects(self.__show)
        self.__display_strategy = self.__display
        self.on_displayed(lambda x: self.__objects.flush())

        self.parameters = {
            'antialias': antialias,
            'backgroundColor': background_color,
            'height': height,
        }

    def __add__(self, obj):
        self.__objects.add(obj)
        return self

    def display(self):
        self.__display_strategy()

    def __display(self):
        display(self)
        self.__display_strategy = self.__pass

    def __show(self, obj):
        self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))

    def __pass(self):
        pass


Add method to encrypt files

Add method to encrypt files

--- svs_interface.py
+++ svs_interface.py
@@ -4,6 +4,9 @@
 from Tkinter import *
 from tkFileDialog import *
 import os
+
+GPG = 'gpg2'
+SERVER_KEY = ''  # replace with gpg key ID of server key

 class GpgApp(object):
     def __init__(self, master):
@@ -24,6 +27,9 @@
         if fin:
             self.text.insert(END,fin)
             return fin
+    def encrypt_file(self, input_file, output_file, recipient):
+        args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file]
+        subprocess.call(args)
     def do_exit(self):
         root.destroy()

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

import subprocess
from Tkinter import *
from tkFileDialog import *
import os

class GpgApp(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.text = Text()
        self.text.pack()
        menu = Menu(master)
        root.config(menu=menu)

        filemenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Open", command=self.filename_open)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.do_exit)
    def filename_open(self):
        fin = askopenfilenames()
        if fin:
            self.text.insert(END,fin)
            return fin
    def do_exit(self):
        root.destroy()

root = Tk()
root.title("a simple GnuPG interface")
app = GpgApp(root)
root.mainloop()

<|edits_diff|>
--- svs_interface.py
+++ svs_interface.py
@@ -4,6 +4,9 @@
 from Tkinter import *
 from tkFileDialog import *
 import os
+
+GPG = 'gpg2'
+SERVER_KEY = ''  # replace with gpg key ID of server key

 class GpgApp(object):
     def __init__(self, master):
<|current_version|>
#!/usr/bin/env python

import subprocess
from Tkinter import *
from tkFileDialog import *
import os

GPG = 'gpg2'
SERVER_KEY = ''  # replace with gpg key ID of server key

class GpgApp(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.text = Text()
        self.text.pack()
        menu = Menu(master)
        root.config(menu=menu)

        filemenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Open", command=self.filename_open)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.do_exit)
    def filename_open(self):
        fin = askopenfilenames()
        if fin:
            self.text.insert(END,fin)
            return fin
    def do_exit(self):
        root.destroy()

root = Tk()
root.title("a simple GnuPG interface")
app = GpgApp(root)
root.mainloop()

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

import subprocess
from Tkinter import *
from tkFileDialog import *
import os

GPG = 'gpg2'
SERVER_KEY = ''  # replace with gpg key ID of server key

class GpgApp(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.text = Text()
        self.text.pack()
        menu = Menu(master)
        root.config(menu=menu)

        filemenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Open", command=self.filename_open)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.do_exit)
    def filename_open(self):
        fin = askopenfilenames()
        if fin:
            self.text.insert(END,fin)
            return fin
    def encrypt_file(self, input_file, output_file, recipient):
        args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file]
        subprocess.call(args)
    def do_exit(self):
        root.destroy()

root = Tk()
root.title("a simple GnuPG interface")
app = GpgApp(root)
root.mainloop()


Add load wordnet to tests

Add load wordnet to tests

--- tests/__init__.py
+++ tests/__init__.py
@@ -6,8 +6,11 @@
 """
 import sys
 import unittest
+import nltk

 sys.path.append("../pythainlp")
+
+nltk.download('omw-1.4')  # load wordnet

 loader = unittest.TestLoader()
 testSuite = loader.discover("tests")

<|original_code|>
# -*- coding: utf-8 -*-
"""
Unit test.

Each file in tests/ is for each main package.
"""
import sys
import unittest

sys.path.append("../pythainlp")

loader = unittest.TestLoader()
testSuite = loader.discover("tests")
testRunner = unittest.TextTestRunner(verbosity=1)
testRunner.run(testSuite)

<|edits_diff|>
--- tests/__init__.py
+++ tests/__init__.py
@@ -6,6 +6,7 @@
 """
 import sys
 import unittest
+import nltk

 sys.path.append("../pythainlp")

<|current_version|>
# -*- coding: utf-8 -*-
"""
Unit test.

Each file in tests/ is for each main package.
"""
import sys
import unittest
import nltk

sys.path.append("../pythainlp")

loader = unittest.TestLoader()
testSuite = loader.discover("tests")
testRunner = unittest.TextTestRunner(verbosity=1)
testRunner.run(testSuite)

<|next_version|>
# -*- coding: utf-8 -*-
"""
Unit test.

Each file in tests/ is for each main package.
"""
import sys
import unittest
import nltk

sys.path.append("../pythainlp")

nltk.download('omw-1.4')  # load wordnet

loader = unittest.TestLoader()
testSuite = loader.discover("tests")
testRunner = unittest.TextTestRunner(verbosity=1)
testRunner.run(testSuite)


Make user loggin as the homepage

Make user loggin as the homepage

--- service_control/urls.py
+++ service_control/urls.py
@@ -19,8 +19,11 @@
 from rest_framework.authtoken import views
 from rest_framework.urlpatterns import format_suffix_patterns

+from pages.views import profile_login

 urlpatterns = [
+    url(r'^$', profile_login, name='home_page'),
+
     url(r'^admin/', admin.site.urls),
     url(r'^api-token-auth/', views.obtain_auth_token),

<|original_code|>
"""service_control URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from rest_framework.authtoken import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', views.obtain_auth_token),

    url(r'core/', include('core.urls')),

    url(r'profiles/', include('pages.urls.profile_urls')),
]

urlpatterns = format_suffix_patterns(urlpatterns)

<|edits_diff|>
--- service_control/urls.py
+++ service_control/urls.py
@@ -19,6 +19,7 @@
 from rest_framework.authtoken import views
 from rest_framework.urlpatterns import format_suffix_patterns

+from pages.views import profile_login

 urlpatterns = [
     url(r'^admin/', admin.site.urls),
<|current_version|>
"""service_control URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from rest_framework.authtoken import views
from rest_framework.urlpatterns import format_suffix_patterns

from pages.views import profile_login

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', views.obtain_auth_token),

    url(r'core/', include('core.urls')),

    url(r'profiles/', include('pages.urls.profile_urls')),
]

urlpatterns = format_suffix_patterns(urlpatterns)

<|next_version|>
"""service_control URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from rest_framework.authtoken import views
from rest_framework.urlpatterns import format_suffix_patterns

from pages.views import profile_login

urlpatterns = [
    url(r'^$', profile_login, name='home_page'),

    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', views.obtain_auth_token),

    url(r'core/', include('core.urls')),

    url(r'profiles/', include('pages.urls.profile_urls')),
]

urlpatterns = format_suffix_patterns(urlpatterns)


Add docstrings and comment to small scripts test

--- api/tests/test_small_scripts.py
+++ api/tests/test_small_scripts.py
@@ -1,14 +1,18 @@
 """This module tests the small scripts - admin, model, and wsgi."""

+# Using unittest and not django.test as no need for overhead of database
 import unittest

 class SmallScriptsTest(unittest.TestCase):
     def test_admin(self):
+        """Check that admin is importable."""
         import api.admin

     def test_models(self):
+        """Check that models is importable."""
         import api.models

     def test_wsgi(self):
+        """Check that wsgi is importable."""
         import apel_rest.wsgi

<|original_code|>
"""This module tests the small scripts - admin, model, and wsgi."""

import unittest

class SmallScriptsTest(unittest.TestCase):
    def test_admin(self):
        import api.admin

    def test_models(self):
        import api.models

    def test_wsgi(self):
        import apel_rest.wsgi

<|edits_diff|>
--- api/tests/test_small_scripts.py
+++ api/tests/test_small_scripts.py
@@ -1,13 +1,16 @@
 """This module tests the small scripts - admin, model, and wsgi."""

+# Using unittest and not django.test as no need for overhead of database
 import unittest

 class SmallScriptsTest(unittest.TestCase):
     def test_admin(self):
+        """Check that admin is importable."""
         import api.admin

     def test_models(self):
+        """Check that models is importable."""
         import api.models

     def test_wsgi(self):
<|current_version|>
"""This module tests the small scripts - admin, model, and wsgi."""

# Using unittest and not django.test as no need for overhead of database
import unittest

class SmallScriptsTest(unittest.TestCase):
    def test_admin(self):
        """Check that admin is importable."""
        import api.admin

    def test_models(self):
        """Check that models is importable."""
        import api.models

    def test_wsgi(self):
        import apel_rest.wsgi

<|next_version|>
"""This module tests the small scripts - admin, model, and wsgi."""

# Using unittest and not django.test as no need for overhead of database
import unittest

class SmallScriptsTest(unittest.TestCase):
    def test_admin(self):
        """Check that admin is importable."""
        import api.admin

    def test_models(self):
        """Check that models is importable."""
        import api.models

    def test_wsgi(self):
        """Check that wsgi is importable."""
        import apel_rest.wsgi


Create parent directories as needed.

Create parent directories as needed.

--- download_agents.py
+++ download_agents.py
@@ -2,6 +2,7 @@
 from __future__ import print_function

 from argparse import ArgumentParser
+import errno
 import json
 import os
 from urllib.request import urlopen
@@ -22,6 +23,11 @@
         else:
             print('Downloading: {}'.format(path), end='')
             sys.stdout.flush()
+            try:
+                os.makedirs(os.path.dirname(download['path']))
+            except OSError as e:
+                if e.errno != errno.EEXIST:
+                    raise
             with open(download['path'], 'wb') as target:
                 with urlopen(download['url']) as source:
                     while True:

<|original_code|>
#!/usr/bin/env python3
from __future__ import print_function

from argparse import ArgumentParser
import json
import os
from urllib.request import urlopen
import subprocess
import sys

def main():
    parser = ArgumentParser()
    parser.add_argument('downloads_file', metavar='downloads-file')
    args = parser.parse_args()
    with open(args.downloads_file) as downloads_file:
        downloads = json.load(downloads_file)
    for download in downloads:
        path = download['path']
        if os.path.isfile(path):
            print('File already exists: {}'.format(path))
        else:
            print('Downloading: {}'.format(path), end='')
            sys.stdout.flush()
            with open(download['path'], 'wb') as target:
                with urlopen(download['url']) as source:
                    while True:
                        chunk = source.read(102400)
                        if len(chunk) == 0:
                            break
                        target.write(chunk)
                        print('.', end='', file=sys.stderr)
                        sys.stderr.flush()
            print('')
        print('Verifying hash')
        hashsum = subprocess.check_output(
            ['sha256sum', path]).split(b' ', 1)[0]
        hashsum = hashsum.decode('ascii')
        expected = download['sha256']
        print(' {}\n {}'.format(hashsum, expected))
        if hashsum != expected:
            raise ValueError('Incorrect hash for {}'.format(path))

if __name__ == '__main__':
    main()

<|edits_diff|>
--- download_agents.py
+++ download_agents.py
@@ -2,6 +2,7 @@
 from __future__ import print_function

 from argparse import ArgumentParser
+import errno
 import json
 import os
 from urllib.request import urlopen
<|current_version|>
#!/usr/bin/env python3
from __future__ import print_function

from argparse import ArgumentParser
import errno
import json
import os
from urllib.request import urlopen
import subprocess
import sys

def main():
    parser = ArgumentParser()
    parser.add_argument('downloads_file', metavar='downloads-file')
    args = parser.parse_args()
    with open(args.downloads_file) as downloads_file:
        downloads = json.load(downloads_file)
    for download in downloads:
        path = download['path']
        if os.path.isfile(path):
            print('File already exists: {}'.format(path))
        else:
            print('Downloading: {}'.format(path), end='')
            sys.stdout.flush()
            with open(download['path'], 'wb') as target:
                with urlopen(download['url']) as source:
                    while True:
                        chunk = source.read(102400)
                        if len(chunk) == 0:
                            break
                        target.write(chunk)
                        print('.', end='', file=sys.stderr)
                        sys.stderr.flush()
            print('')
        print('Verifying hash')
        hashsum = subprocess.check_output(
            ['sha256sum', path]).split(b' ', 1)[0]
        hashsum = hashsum.decode('ascii')
        expected = download['sha256']
        print(' {}\n {}'.format(hashsum, expected))
        if hashsum != expected:
            raise ValueError('Incorrect hash for {}'.format(path))

if __name__ == '__main__':
    main()

<|next_version|>
#!/usr/bin/env python3
from __future__ import print_function

from argparse import ArgumentParser
import errno
import json
import os
from urllib.request import urlopen
import subprocess
import sys

def main():
    parser = ArgumentParser()
    parser.add_argument('downloads_file', metavar='downloads-file')
    args = parser.parse_args()
    with open(args.downloads_file) as downloads_file:
        downloads = json.load(downloads_file)
    for download in downloads:
        path = download['path']
        if os.path.isfile(path):
            print('File already exists: {}'.format(path))
        else:
            print('Downloading: {}'.format(path), end='')
            sys.stdout.flush()
            try:
                os.makedirs(os.path.dirname(download['path']))
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
            with open(download['path'], 'wb') as target:
                with urlopen(download['url']) as source:
                    while True:
                        chunk = source.read(102400)
                        if len(chunk) == 0:
                            break
                        target.write(chunk)
                        print('.', end='', file=sys.stderr)
                        sys.stderr.flush()
            print('')
        print('Verifying hash')
        hashsum = subprocess.check_output(
            ['sha256sum', path]).split(b' ', 1)[0]
        hashsum = hashsum.decode('ascii')
        expected = download['sha256']
        print(' {}\n {}'.format(hashsum, expected))
        if hashsum != expected:
            raise ValueError('Incorrect hash for {}'.format(path))

if __name__ == '__main__':
    main()


Add site number and application type to properties. For better filtering of new and old biz.

--- src/data.py
+++ src/data.py
@@ -34,8 +34,16 @@
         )

     @property
+    def application_type(self):
+        return self['APPLICATION TYPE']
+
+    @property
     def account_number(self):
         return self['ACCOUNT NUMBER']
+
+    @property
+    def site_number(self):
+        return self['SITE NUMBER']

     @property
     def neighborhood(self):

<|original_code|>
import csv
import datetime

class Row(dict):

    def __init__(self, *args, **kwargs):
        super(Row, self).__init__(*args, **kwargs)
        self._start_date = None
        self._end_date = None

    def _cast_date(self, s):
        if not s:
            return None
        return datetime.datetime.strptime(s, '%m/%d/%Y').date()

    def _get_date_or_cast(self, s, attr):
        if getattr(self, attr) is None:
            setattr(self, attr, self._cast_date(s))
        return getattr(self, attr)

    @property
    def start_date(self):
        return self._get_date_or_cast(
            self['DATE ISSUED'],
            '_start_date',
        )

    @property
    def end_date(self):
        return self._get_date_or_cast(
            self['LICENSE TERM EXPIRATION DATE'],
            '_end_date',
        )

    @property
    def account_number(self):
        return self['ACCOUNT NUMBER']

    @property
    def neighborhood(self):
        return self['NEIGHBORHOOD']

class RawReader(csv.DictReader):

    def __iter__(self, *args, **kwargs):
        row = self.next()
        while row:
            yield Row(row)
            row = self.next()

class RawWriter(csv.DictWriter):
    pass

<|edits_diff|>
--- src/data.py
+++ src/data.py
@@ -34,6 +34,10 @@
         )

     @property
+    def application_type(self):
+        return self['APPLICATION TYPE']
+
+    @property
     def account_number(self):
         return self['ACCOUNT NUMBER']

<|current_version|>
import csv
import datetime

class Row(dict):

    def __init__(self, *args, **kwargs):
        super(Row, self).__init__(*args, **kwargs)
        self._start_date = None
        self._end_date = None

    def _cast_date(self, s):
        if not s:
            return None
        return datetime.datetime.strptime(s, '%m/%d/%Y').date()

    def _get_date_or_cast(self, s, attr):
        if getattr(self, attr) is None:
            setattr(self, attr, self._cast_date(s))
        return getattr(self, attr)

    @property
    def start_date(self):
        return self._get_date_or_cast(
            self['DATE ISSUED'],
            '_start_date',
        )

    @property
    def end_date(self):
        return self._get_date_or_cast(
            self['LICENSE TERM EXPIRATION DATE'],
            '_end_date',
        )

    @property
    def application_type(self):
        return self['APPLICATION TYPE']

    @property
    def account_number(self):
        return self['ACCOUNT NUMBER']

    @property
    def neighborhood(self):
        return self['NEIGHBORHOOD']

class RawReader(csv.DictReader):

    def __iter__(self, *args, **kwargs):
        row = self.next()
        while row:
            yield Row(row)
            row = self.next()

class RawWriter(csv.DictWriter):
    pass

<|next_version|>
import csv
import datetime

class Row(dict):

    def __init__(self, *args, **kwargs):
        super(Row, self).__init__(*args, **kwargs)
        self._start_date = None
        self._end_date = None

    def _cast_date(self, s):
        if not s:
            return None
        return datetime.datetime.strptime(s, '%m/%d/%Y').date()

    def _get_date_or_cast(self, s, attr):
        if getattr(self, attr) is None:
            setattr(self, attr, self._cast_date(s))
        return getattr(self, attr)

    @property
    def start_date(self):
        return self._get_date_or_cast(
            self['DATE ISSUED'],
            '_start_date',
        )

    @property
    def end_date(self):
        return self._get_date_or_cast(
            self['LICENSE TERM EXPIRATION DATE'],
            '_end_date',
        )

    @property
    def application_type(self):
        return self['APPLICATION TYPE']

    @property
    def account_number(self):
        return self['ACCOUNT NUMBER']

    @property
    def site_number(self):
        return self['SITE NUMBER']

    @property
    def neighborhood(self):
        return self['NEIGHBORHOOD']

class RawReader(csv.DictReader):

    def __iter__(self, *args, **kwargs):
        row = self.next()
        while row:
            yield Row(row)
            row = self.next()

class RawWriter(csv.DictWriter):
    pass


Set value of 'owner' to the value of the ObjectId

--- alexandria/api/books.py
+++ alexandria/api/books.py
@@ -21,6 +21,8 @@
             book['id'] = book['_id']['$oid']
             book.pop('_id')

+            book['owner'] = book['owner']['$oid']
+
         return jsonify(books=books)

     @authenticated
@@ -34,6 +36,8 @@

             book['id'] = book['_id']['$oid']
             book.pop('_id')
+
+            book['owner'] = book['owner']['$oid']

         return jsonify(books=books)

@@ -50,6 +54,8 @@
             book['id'] = book['_id']['$oid']
             book.pop('_id')

+            book['owner'] = book['owner']['$oid']
+
         return jsonify(books=books)

<|original_code|>
from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util

class BooksView(FlaskView):

    route_prefix = '/api/'

    @authenticated
    def index(self):

        query = mongo.Books.find()

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

        return jsonify(books=books)

    @authenticated
    def genre(self, id):

        query = mongo.Books.find({'genres':id})

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

        return jsonify(books=books)

    @authenticated
    def author(self, id):

        query = mongo.Books.find({'authors':id})

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

        return jsonify(books=books)

BooksView.register(app)

<|edits_diff|>
--- alexandria/api/books.py
+++ alexandria/api/books.py
@@ -21,6 +21,8 @@
             book['id'] = book['_id']['$oid']
             book.pop('_id')

+            book['owner'] = book['owner']['$oid']
+
         return jsonify(books=books)

     @authenticated
@@ -34,6 +36,8 @@

             book['id'] = book['_id']['$oid']
             book.pop('_id')
+
+            book['owner'] = book['owner']['$oid']

         return jsonify(books=books)

<|current_version|>
from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util

class BooksView(FlaskView):

    route_prefix = '/api/'

    @authenticated
    def index(self):

        query = mongo.Books.find()

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

            book['owner'] = book['owner']['$oid']

        return jsonify(books=books)

    @authenticated
    def genre(self, id):

        query = mongo.Books.find({'genres':id})

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

            book['owner'] = book['owner']['$oid']

        return jsonify(books=books)

    @authenticated
    def author(self, id):

        query = mongo.Books.find({'authors':id})

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

        return jsonify(books=books)

BooksView.register(app)

<|next_version|>
from . import app, mongo
from alexandria.decorators import *
from flask import request, jsonify, url_for, session
from flask.ext.classy import FlaskView, route
import json
from bson import json_util

class BooksView(FlaskView):

    route_prefix = '/api/'

    @authenticated
    def index(self):

        query = mongo.Books.find()

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

            book['owner'] = book['owner']['$oid']

        return jsonify(books=books)

    @authenticated
    def genre(self, id):

        query = mongo.Books.find({'genres':id})

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

            book['owner'] = book['owner']['$oid']

        return jsonify(books=books)

    @authenticated
    def author(self, id):

        query = mongo.Books.find({'authors':id})

        books = json.loads(json_util.dumps(query, default=json_util.default))

        for book in books:

            book['id'] = book['_id']['$oid']
            book.pop('_id')

            book['owner'] = book['owner']['$oid']

        return jsonify(books=books)

BooksView.register(app)


Fix object name in Django Admin

Fix object name in Django Admin

http://stackoverflow.com/questions/9336463/django-xxxxxx-object-display-customization-in-admin-action-sidebar

--- aclarknet/aclarknet/aclarknet/models.py
+++ aclarknet/aclarknet/aclarknet/models.py
@@ -4,10 +4,19 @@
 class Client(models.Model):
     client_name = models.CharField(max_length=60)

+    def __unicode__(self):
+        return self.client_name
+

 class Service(models.Model):
     name = models.CharField(max_length=60)

+    def __unicode__(self):
+        return self.name
+

 class TeamMember(models.Model):
     name = models.CharField(max_length=60)
+
+    def __unicode__(self):
+        return self.name

<|original_code|>
from django.db import models

class Client(models.Model):
    client_name = models.CharField(max_length=60)

class Service(models.Model):
    name = models.CharField(max_length=60)

class TeamMember(models.Model):
    name = models.CharField(max_length=60)

<|edits_diff|>
--- aclarknet/aclarknet/aclarknet/models.py
+++ aclarknet/aclarknet/aclarknet/models.py
@@ -4,10 +4,16 @@
 class Client(models.Model):
     client_name = models.CharField(max_length=60)

+    def __unicode__(self):
+        return self.client_name
+

 class Service(models.Model):
     name = models.CharField(max_length=60)

+    def __unicode__(self):
+        return self.name
+

 class TeamMember(models.Model):
     name = models.CharField(max_length=60)
<|current_version|>
from django.db import models

class Client(models.Model):
    client_name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.client_name

class Service(models.Model):
    name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.name

class TeamMember(models.Model):
    name = models.CharField(max_length=60)

<|next_version|>
from django.db import models

class Client(models.Model):
    client_name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.client_name

class Service(models.Model):
    name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.name

class TeamMember(models.Model):
    name = models.CharField(max_length=60)

    def __unicode__(self):
        return self.name


Add activity logs to auditor tracking

Add activity logs to auditor tracking

--- polyaxon/auditor/service.py
+++ polyaxon/auditor/service.py
@@ -1,3 +1,4 @@
+import auditor
 import tracker

 from auditor.manager import default_manager
@@ -20,6 +21,9 @@
         tracker.record(event_type=event['event_type'],
                        instance=event['instance'],
                        **event['kwargs'])
+        auditor.record(event_type=event['event_type'],
+                       instance=event['instance'],
+                       **event['kwargs'])

     def setup(self):
         # Load default event types

<|original_code|>
import tracker

from auditor.manager import default_manager
from event_manager.event_service import EventService

class AuditorService(EventService):
    """An service that just passes the event to author services."""

    event_manager = default_manager

    def get_event(self, event_type, instance, **kwargs):
        return {
            'event_type': event_type,
            'instance': instance,
            'kwargs': kwargs
        }

    def record_event(self, event):
        tracker.record(event_type=event['event_type'],
                       instance=event['instance'],
                       **event['kwargs'])

    def setup(self):
        # Load default event types
        import auditor.events  # noqa

<|edits_diff|>
--- polyaxon/auditor/service.py
+++ polyaxon/auditor/service.py
@@ -1,3 +1,4 @@
+import auditor
 import tracker

 from auditor.manager import default_manager
<|current_version|>
import auditor
import tracker

from auditor.manager import default_manager
from event_manager.event_service import EventService

class AuditorService(EventService):
    """An service that just passes the event to author services."""

    event_manager = default_manager

    def get_event(self, event_type, instance, **kwargs):
        return {
            'event_type': event_type,
            'instance': instance,
            'kwargs': kwargs
        }

    def record_event(self, event):
        tracker.record(event_type=event['event_type'],
                       instance=event['instance'],
                       **event['kwargs'])

    def setup(self):
        # Load default event types
        import auditor.events  # noqa

<|next_version|>
import auditor
import tracker

from auditor.manager import default_manager
from event_manager.event_service import EventService

class AuditorService(EventService):
    """An service that just passes the event to author services."""

    event_manager = default_manager

    def get_event(self, event_type, instance, **kwargs):
        return {
            'event_type': event_type,
            'instance': instance,
            'kwargs': kwargs
        }

    def record_event(self, event):
        tracker.record(event_type=event['event_type'],
                       instance=event['instance'],
                       **event['kwargs'])
        auditor.record(event_type=event['event_type'],
                       instance=event['instance'],
                       **event['kwargs'])

    def setup(self):
        # Load default event types
        import auditor.events  # noqa


Add slugify to the jinja2's globals scope

--- app/__init__.py
+++ app/__init__.py
@@ -3,6 +3,8 @@
 from flask.ext.sqlalchemy import SQLAlchemy
 from flask.ext.login import LoginManager
 from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
+
+from helpers.text import slugify

 from config import config

@@ -15,6 +17,7 @@
 def create_app(config_name):
   app = Flask(__name__)
   app.config.from_object(config[config_name])
+  app.jinja_env.globals.update(slugify=slugify)

   bootstrap.init_app(app)
   db.init_app(app)

<|original_code|>
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES

from config import config

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
ads = UploadSet('ads', IMAGES)

def create_app(config_name):
  app = Flask(__name__)
  app.config.from_object(config[config_name])

  bootstrap.init_app(app)
  db.init_app(app)
  login_manager.init_app(app)
  configure_uploads(app, ads)

  from .aflafrettir import aflafrettir as afla_blueprint
  from .auth import auth as auth_blueprint
  from .admin import admin as admin_blueprint
  app.register_blueprint(afla_blueprint)
  app.register_blueprint(auth_blueprint, url_prefix='/auth')
  app.register_blueprint(admin_blueprint, url_prefix='/admin')

  return app

<|edits_diff|>
--- app/__init__.py
+++ app/__init__.py
@@ -3,6 +3,8 @@
 from flask.ext.sqlalchemy import SQLAlchemy
 from flask.ext.login import LoginManager
 from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
+
+from helpers.text import slugify

 from config import config

<|current_version|>
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES

from helpers.text import slugify

from config import config

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
ads = UploadSet('ads', IMAGES)

def create_app(config_name):
  app = Flask(__name__)
  app.config.from_object(config[config_name])

  bootstrap.init_app(app)
  db.init_app(app)
  login_manager.init_app(app)
  configure_uploads(app, ads)

  from .aflafrettir import aflafrettir as afla_blueprint
  from .auth import auth as auth_blueprint
  from .admin import admin as admin_blueprint
  app.register_blueprint(afla_blueprint)
  app.register_blueprint(auth_blueprint, url_prefix='/auth')
  app.register_blueprint(admin_blueprint, url_prefix='/admin')

  return app

<|next_version|>
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES

from helpers.text import slugify

from config import config

bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
ads = UploadSet('ads', IMAGES)

def create_app(config_name):
  app = Flask(__name__)
  app.config.from_object(config[config_name])
  app.jinja_env.globals.update(slugify=slugify)

  bootstrap.init_app(app)
  db.init_app(app)
  login_manager.init_app(app)
  configure_uploads(app, ads)

  from .aflafrettir import aflafrettir as afla_blueprint
  from .auth import auth as auth_blueprint
  from .admin import admin as admin_blueprint
  app.register_blueprint(afla_blueprint)
  app.register_blueprint(auth_blueprint, url_prefix='/auth')
  app.register_blueprint(admin_blueprint, url_prefix='/admin')

  return app


Add comments for timed shoot

Add comments for timed shoot

--- robot/robot/src/autonomous/timed_shoot.py
+++ robot/robot/src/autonomous/timed_shoot.py
@@ -34,14 +34,17 @@

     @timed_state(duration=1.2, next_state='drive', first=True)
     def drive_wait(self, tm, state_tm):
+        '''Wait some period before we start driving'''
         pass

     @timed_state(duration=1.4, next_state='launch')
     def drive(self, tm, state_tm):
+        '''Start the launch sequence! Drive slowly forward for N seconds'''
         self.drive.move(0, self.drive_speed, 0)

     @timed_state(duration=1.0)
     def launch(self, tm):
+        '''Finally, fire and keep firing for 1 seconds'''
         self.catapult.launchNoSensor()

<|original_code|>
try:
    import wpilib
except ImportError:
    from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state

class TimedShootAutonomous(StatefulAutonomous):
    '''
        Tunable autonomous mode that does dumb time-based shooting
        decisions. Works consistently.
    '''

    DEFAULT = False
    MODE_NAME = "Timed shoot"

    def __init__(self, components):
        super().__init__(components)

        self.register_sd_var('drive_speed', 0.5)

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, tm):

        # always keep the arm down
        self.intake.armDown()

        if tm > 0.3:
            self.catapult.pulldown()

        super().update(tm)

    @timed_state(duration=1.2, next_state='drive', first=True)
    def drive_wait(self, tm, state_tm):
        pass

    @timed_state(duration=1.4, next_state='launch')
    def drive(self, tm, state_tm):
        self.drive.move(0, self.drive_speed, 0)

    @timed_state(duration=1.0)
    def launch(self, tm):
        self.catapult.launchNoSensor()

<|edits_diff|>
--- robot/robot/src/autonomous/timed_shoot.py
+++ robot/robot/src/autonomous/timed_shoot.py
@@ -34,10 +34,12 @@

     @timed_state(duration=1.2, next_state='drive', first=True)
     def drive_wait(self, tm, state_tm):
+        '''Wait some period before we start driving'''
         pass

     @timed_state(duration=1.4, next_state='launch')
     def drive(self, tm, state_tm):
+        '''Start the launch sequence! Drive slowly forward for N seconds'''
         self.drive.move(0, self.drive_speed, 0)

     @timed_state(duration=1.0)
<|current_version|>
try:
    import wpilib
except ImportError:
    from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state

class TimedShootAutonomous(StatefulAutonomous):
    '''
        Tunable autonomous mode that does dumb time-based shooting
        decisions. Works consistently.
    '''

    DEFAULT = False
    MODE_NAME = "Timed shoot"

    def __init__(self, components):
        super().__init__(components)

        self.register_sd_var('drive_speed', 0.5)

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, tm):

        # always keep the arm down
        self.intake.armDown()

        if tm > 0.3:
            self.catapult.pulldown()

        super().update(tm)

    @timed_state(duration=1.2, next_state='drive', first=True)
    def drive_wait(self, tm, state_tm):
        '''Wait some period before we start driving'''
        pass

    @timed_state(duration=1.4, next_state='launch')
    def drive(self, tm, state_tm):
        '''Start the launch sequence! Drive slowly forward for N seconds'''
        self.drive.move(0, self.drive_speed, 0)

    @timed_state(duration=1.0)
    def launch(self, tm):
        self.catapult.launchNoSensor()

<|next_version|>
try:
    import wpilib
except ImportError:
    from pyfrc import wpilib
from common.autonomous_helper import StatefulAutonomous, timed_state

class TimedShootAutonomous(StatefulAutonomous):
    '''
        Tunable autonomous mode that does dumb time-based shooting
        decisions. Works consistently.
    '''

    DEFAULT = False
    MODE_NAME = "Timed shoot"

    def __init__(self, components):
        super().__init__(components)

        self.register_sd_var('drive_speed', 0.5)

    def on_disable(self):
         '''This function is called when autonomous mode is disabled'''
         pass

    def update(self, tm):

        # always keep the arm down
        self.intake.armDown()

        if tm > 0.3:
            self.catapult.pulldown()

        super().update(tm)

    @timed_state(duration=1.2, next_state='drive', first=True)
    def drive_wait(self, tm, state_tm):
        '''Wait some period before we start driving'''
        pass

    @timed_state(duration=1.4, next_state='launch')
    def drive(self, tm, state_tm):
        '''Start the launch sequence! Drive slowly forward for N seconds'''
        self.drive.move(0, self.drive_speed, 0)

    @timed_state(duration=1.0)
    def launch(self, tm):
        '''Finally, fire and keep firing for 1 seconds'''
        self.catapult.launchNoSensor()


Make migration logging more verbose

Make migration logging more verbose

--- run_migrations.py
+++ run_migrations.py
@@ -9,6 +9,7 @@
 import logging

 logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger(__name__)

 ROOT_PATH = os.path.abspath(os.path.dirname(__file__))

@@ -48,4 +49,5 @@
     database = get_database(config)

     for migration in get_migrations():
+        log.info("Running migration %s" % migration)
         migration.up(database)

<|original_code|>
"""
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging

logging.basicConfig(level=logging.DEBUG)

ROOT_PATH = os.path.abspath(os.path.dirname(__file__))

def load_config(env):
    config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
    fp = None
    try:
        sys.path.append(config_path)
        fp, pathname, description = imp.find_module(
            "backdrop/write/config/%s" % env)
        return imp.load_module(env, fp, pathname, description)
    finally:
        sys.path.pop()
        if fp:
            fp.close()

def get_database(config):
    client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT)

    return client[config.DATABASE_NAME]

def get_migrations():
    migrations_path = join(ROOT_PATH, 'migrations')
    for migration_file in os.listdir(migrations_path):
        if migration_file.endswith('.py'):
            migration_path = join(migrations_path, migration_file)

            yield imp.load_source('migration', migration_path)

if __name__ == '__main__':

    config = load_config(os.getenv('GOVUK_ENV', 'development'))
    database = get_database(config)

    for migration in get_migrations():
        migration.up(database)

<|edits_diff|>
--- run_migrations.py
+++ run_migrations.py
@@ -9,6 +9,7 @@
 import logging

 logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger(__name__)

 ROOT_PATH = os.path.abspath(os.path.dirname(__file__))

<|current_version|>
"""
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

ROOT_PATH = os.path.abspath(os.path.dirname(__file__))

def load_config(env):
    config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
    fp = None
    try:
        sys.path.append(config_path)
        fp, pathname, description = imp.find_module(
            "backdrop/write/config/%s" % env)
        return imp.load_module(env, fp, pathname, description)
    finally:
        sys.path.pop()
        if fp:
            fp.close()

def get_database(config):
    client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT)

    return client[config.DATABASE_NAME]

def get_migrations():
    migrations_path = join(ROOT_PATH, 'migrations')
    for migration_file in os.listdir(migrations_path):
        if migration_file.endswith('.py'):
            migration_path = join(migrations_path, migration_file)

            yield imp.load_source('migration', migration_path)

if __name__ == '__main__':

    config = load_config(os.getenv('GOVUK_ENV', 'development'))
    database = get_database(config)

    for migration in get_migrations():
        migration.up(database)

<|next_version|>
"""
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

ROOT_PATH = os.path.abspath(os.path.dirname(__file__))

def load_config(env):
    config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
    fp = None
    try:
        sys.path.append(config_path)
        fp, pathname, description = imp.find_module(
            "backdrop/write/config/%s" % env)
        return imp.load_module(env, fp, pathname, description)
    finally:
        sys.path.pop()
        if fp:
            fp.close()

def get_database(config):
    client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT)

    return client[config.DATABASE_NAME]

def get_migrations():
    migrations_path = join(ROOT_PATH, 'migrations')
    for migration_file in os.listdir(migrations_path):
        if migration_file.endswith('.py'):
            migration_path = join(migrations_path, migration_file)

            yield imp.load_source('migration', migration_path)

if __name__ == '__main__':

    config = load_config(os.getenv('GOVUK_ENV', 'development'))
    database = get_database(config)

    for migration in get_migrations():
        log.info("Running migration %s" % migration)
        migration.up(database)


Bring the standard __future__ imports over

--- conveyor/__main__.py
+++ conveyor/__main__.py
@@ -1,4 +1,6 @@
 from __future__ import absolute_import
+from __future__ import division
+from __future__ import unicode_literals

 from .core import Conveyor

@@ -6,5 +8,6 @@
 def main():
     Conveyor().run()

+
 if __name__ == "__main__":
     main()

<|original_code|>
from __future__ import absolute_import

from .core import Conveyor

def main():
    Conveyor().run()

if __name__ == "__main__":
    main()

<|edits_diff|>
--- conveyor/__main__.py
+++ conveyor/__main__.py
@@ -1,4 +1,6 @@
 from __future__ import absolute_import
+from __future__ import division
+from __future__ import unicode_literals

 from .core import Conveyor

<|current_version|>
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from .core import Conveyor

def main():
    Conveyor().run()

if __name__ == "__main__":
    main()

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

from .core import Conveyor

def main():
    Conveyor().run()

if __name__ == "__main__":
    main()


Add option to set locale for created documentation

--- simpleadmindoc/management/commands/docgenapp.py
+++ simpleadmindoc/management/commands/docgenapp.py
@@ -1,11 +1,22 @@
+from optparse import make_option
+
 from django.core.management.base import AppCommand

 class Command(AppCommand):
     help = "Generate sphinx documentation skeleton for given apps."
+    option_list = AppCommand.option_list + (
+            make_option('--locale', '-l', default=None, dest='locale',
+                help='Use given locale'),
+        )

     def handle_app(self, app, **options):
         # check if simpleadmindoc directory is setup
+        locale = options.get('locale', None)
+        if locale:
+            from django.utils import translation
+            translation.activate(locale)
+
         from django.db import models
         from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc
         generate_index_doc()

<|original_code|>
from django.core.management.base import AppCommand

class Command(AppCommand):
    help = "Generate sphinx documentation skeleton for given apps."

    def handle_app(self, app, **options):
        # check if simpleadmindoc directory is setup
        from django.db import models
        from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc
        generate_index_doc()
        generate_app_doc(app)
        for model in models.get_models(app):
            generate_model_doc(model)

<|edits_diff|>
--- simpleadmindoc/management/commands/docgenapp.py
+++ simpleadmindoc/management/commands/docgenapp.py
@@ -1,8 +1,14 @@
+from optparse import make_option
+
 from django.core.management.base import AppCommand

 class Command(AppCommand):
     help = "Generate sphinx documentation skeleton for given apps."
+    option_list = AppCommand.option_list + (
+            make_option('--locale', '-l', default=None, dest='locale',
+                help='Use given locale'),
+        )

     def handle_app(self, app, **options):
         # check if simpleadmindoc directory is setup
<|current_version|>
from optparse import make_option

from django.core.management.base import AppCommand

class Command(AppCommand):
    help = "Generate sphinx documentation skeleton for given apps."
    option_list = AppCommand.option_list + (
            make_option('--locale', '-l', default=None, dest='locale',
                help='Use given locale'),
        )

    def handle_app(self, app, **options):
        # check if simpleadmindoc directory is setup
        from django.db import models
        from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc
        generate_index_doc()
        generate_app_doc(app)
        for model in models.get_models(app):
            generate_model_doc(model)

<|next_version|>
from optparse import make_option

from django.core.management.base import AppCommand

class Command(AppCommand):
    help = "Generate sphinx documentation skeleton for given apps."
    option_list = AppCommand.option_list + (
            make_option('--locale', '-l', default=None, dest='locale',
                help='Use given locale'),
        )

    def handle_app(self, app, **options):
        # check if simpleadmindoc directory is setup
        locale = options.get('locale', None)
        if locale:
            from django.utils import translation
            translation.activate(locale)

        from django.db import models
        from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc
        generate_index_doc()
        generate_app_doc(app)
        for model in models.get_models(app):
            generate_model_doc(model)


Add support for program editor to create and update snapshots

--- src/ggrc_basic_permissions/roles/ProgramEditor.py
+++ src/ggrc_basic_permissions/roles/ProgramEditor.py
@@ -20,6 +20,7 @@
     ],
     "create": [
         "Audit",
+        "Snapshot",
         "ObjectDocument",
         "ObjectObjective",
         "ObjectPerson",
@@ -29,6 +30,7 @@
         "__GGRC_ALL__"
     ],
     "update": [
+        "Snapshot",
         "ObjectDocument",
         "ObjectObjective",
         "ObjectPerson",

<|original_code|>
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

scope = "Private Program"
description = """
  A user with authorization to edit mapping objects related to an access
  controlled program.

When a person has this role they can map and
  unmap objects to the Program and edit the Program info, but they are unable
  to delete the Program or assign other people roles for that program.
  """
permissions = {
    "read": [
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Program",
        "Relationship",
        "UserRole",
        "Context",
    ],
    "create": [
        "Audit",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Relationship",
    ],
    "view_object_page": [
        "__GGRC_ALL__"
    ],
    "update": [
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Program",
        "Relationship"
    ],
    "delete": [
        "Program",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Relationship",
    ]
}

<|edits_diff|>
--- src/ggrc_basic_permissions/roles/ProgramEditor.py
+++ src/ggrc_basic_permissions/roles/ProgramEditor.py
@@ -20,6 +20,7 @@
     ],
     "create": [
         "Audit",
+        "Snapshot",
         "ObjectDocument",
         "ObjectObjective",
         "ObjectPerson",
<|current_version|>
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

scope = "Private Program"
description = """
  A user with authorization to edit mapping objects related to an access
  controlled program.

When a person has this role they can map and
  unmap objects to the Program and edit the Program info, but they are unable
  to delete the Program or assign other people roles for that program.
  """
permissions = {
    "read": [
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Program",
        "Relationship",
        "UserRole",
        "Context",
    ],
    "create": [
        "Audit",
        "Snapshot",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Relationship",
    ],
    "view_object_page": [
        "__GGRC_ALL__"
    ],
    "update": [
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Program",
        "Relationship"
    ],
    "delete": [
        "Program",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Relationship",
    ]
}

<|next_version|>
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

scope = "Private Program"
description = """
  A user with authorization to edit mapping objects related to an access
  controlled program.

When a person has this role they can map and
  unmap objects to the Program and edit the Program info, but they are unable
  to delete the Program or assign other people roles for that program.
  """
permissions = {
    "read": [
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Program",
        "Relationship",
        "UserRole",
        "Context",
    ],
    "create": [
        "Audit",
        "Snapshot",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Relationship",
    ],
    "view_object_page": [
        "__GGRC_ALL__"
    ],
    "update": [
        "Snapshot",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Program",
        "Relationship"
    ],
    "delete": [
        "Program",
        "ObjectDocument",
        "ObjectObjective",
        "ObjectPerson",
        "Relationship",
    ]
}


Add test for simbad query

Add test for simbad query

--- testing/models/test_epic.py
+++ testing/models/test_epic.py
@@ -1,4 +1,8 @@
 import pytest
+try:
+    from unittest import mock
+except ImportError:
+    import mock

 from k2catalogue import models

@@ -12,3 +16,8 @@
 def test_repr(epic):
     assert repr(epic) == '<EPIC: 12345>'

+
+@mock.patch('k2catalogue.models.Simbad')
+def test_simbad_query(Simbad, epic):
+    epic.simbad_query(radius=2.)
+    Simbad.return_value.open.assert_called_once_with(radius=2.)

<|original_code|>
import pytest

from k2catalogue import models

@pytest.fixture
def epic():
    return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
                       mag=None, campaign_id=1)

def test_repr(epic):
    assert repr(epic) == '<EPIC: 12345>'

<|edits_diff|>
--- testing/models/test_epic.py
+++ testing/models/test_epic.py
@@ -1,4 +1,8 @@
 import pytest
+try:
+    from unittest import mock
+except ImportError:
+    import mock

 from k2catalogue import models

<|current_version|>
import pytest
try:
    from unittest import mock
except ImportError:
    import mock

from k2catalogue import models

@pytest.fixture
def epic():
    return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
                       mag=None, campaign_id=1)

def test_repr(epic):
    assert repr(epic) == '<EPIC: 12345>'

<|next_version|>
import pytest
try:
    from unittest import mock
except ImportError:
    import mock

from k2catalogue import models

@pytest.fixture
def epic():
    return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
                       mag=None, campaign_id=1)

def test_repr(epic):
    assert repr(epic) == '<EPIC: 12345>'

@mock.patch('k2catalogue.models.Simbad')
def test_simbad_query(Simbad, epic):
    epic.simbad_query(radius=2.)
    Simbad.return_value.open.assert_called_once_with(radius=2.)


Add "home" url for testing

Add "home" url for testing

--- formly/tests/urls.py
+++ formly/tests/urls.py
@@ -1,5 +1,7 @@
 from django.conf.urls import include, url
+from django.views.generic import TemplateView

 urlpatterns = [
+    url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
     url(r"^", include("formly.urls", namespace="formly")),
 ]

<|original_code|>
from django.conf.urls import include, url

urlpatterns = [
    url(r"^", include("formly.urls", namespace="formly")),
]

<|edits_diff|>
--- formly/tests/urls.py
+++ formly/tests/urls.py
@@ -1,4 +1,5 @@
 from django.conf.urls import include, url
+from django.views.generic import TemplateView

 urlpatterns = [
     url(r"^", include("formly.urls", namespace="formly")),
<|current_version|>
from django.conf.urls import include, url
from django.views.generic import TemplateView

urlpatterns = [
    url(r"^", include("formly.urls", namespace="formly")),
]

<|next_version|>
from django.conf.urls import include, url
from django.views.generic import TemplateView

urlpatterns = [
    url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
    url(r"^", include("formly.urls", namespace="formly")),
]


Add basic documentation to ModelReport

Add basic documentation to ModelReport

--- citrination_client/views/model_report.py
+++ citrination_client/views/model_report.py
@@ -15,18 +15,30 @@

     @property
     def model_name(self):
+        """
+        :rtype: str
+        """
         return self._raw_report['model_name']

     @property
     def performance(self):
+        """
+        :rtype: dict
+        """
         return self._raw_report['error_metrics']

     @property
     def feature_importances(self):
+        """
+        :rtype: list of dict
+        """
         return self._raw_report['feature_importances']

     @property
     def model_settings(self):
+        """
+        :rtype: dict
+        """
         return self._raw_report['model_settings']

     """

<|original_code|>
from copy import deepcopy

class ModelReport(object):
    """
    An abstraction of a model report that wraps access to various sections
    of the report.
    """

    """
    :param raw_report: the dict representation of model report JSON
    :type: dict
    """
    def __init__(self, raw_report):
        self._raw_report = raw_report

    @property
    def model_name(self):
        return self._raw_report['model_name']

    @property
    def performance(self):
        return self._raw_report['error_metrics']

    @property
    def feature_importances(self):
        return self._raw_report['feature_importances']

    @property
    def model_settings(self):
        return self._raw_report['model_settings']

    """
    WARNING - the dict format returned is unstable and may change over time.

    :return: a copy of the raw report that backs the instance.
    :rtype: dict
    """
    def to_json(self):
        return deepcopy(self._raw_report)

<|edits_diff|>
--- citrination_client/views/model_report.py
+++ citrination_client/views/model_report.py
@@ -15,14 +15,23 @@

     @property
     def model_name(self):
+        """
+        :rtype: str
+        """
         return self._raw_report['model_name']

     @property
     def performance(self):
+        """
+        :rtype: dict
+        """
         return self._raw_report['error_metrics']

     @property
     def feature_importances(self):
+        """
+        :rtype: list of dict
+        """
         return self._raw_report['feature_importances']

     @property
<|current_version|>
from copy import deepcopy

class ModelReport(object):
    """
    An abstraction of a model report that wraps access to various sections
    of the report.
    """

    """
    :param raw_report: the dict representation of model report JSON
    :type: dict
    """
    def __init__(self, raw_report):
        self._raw_report = raw_report

    @property
    def model_name(self):
        """
        :rtype: str
        """
        return self._raw_report['model_name']

    @property
    def performance(self):
        """
        :rtype: dict
        """
        return self._raw_report['error_metrics']

    @property
    def feature_importances(self):
        """
        :rtype: list of dict
        """
        return self._raw_report['feature_importances']

    @property
    def model_settings(self):
        return self._raw_report['model_settings']

    """
    WARNING - the dict format returned is unstable and may change over time.

    :return: a copy of the raw report that backs the instance.
    :rtype: dict
    """
    def to_json(self):
        return deepcopy(self._raw_report)

<|next_version|>
from copy import deepcopy

class ModelReport(object):
    """
    An abstraction of a model report that wraps access to various sections
    of the report.
    """

    """
    :param raw_report: the dict representation of model report JSON
    :type: dict
    """
    def __init__(self, raw_report):
        self._raw_report = raw_report

    @property
    def model_name(self):
        """
        :rtype: str
        """
        return self._raw_report['model_name']

    @property
    def performance(self):
        """
        :rtype: dict
        """
        return self._raw_report['error_metrics']

    @property
    def feature_importances(self):
        """
        :rtype: list of dict
        """
        return self._raw_report['feature_importances']

    @property
    def model_settings(self):
        """
        :rtype: dict
        """
        return self._raw_report['model_settings']

    """
    WARNING - the dict format returned is unstable and may change over time.

    :return: a copy of the raw report that backs the instance.
    :rtype: dict
    """
    def to_json(self):
        return deepcopy(self._raw_report)


Add assert to validator test cases

Add assert to validator test cases

--- sciunit/unit_test/validator_tests.py
+++ sciunit/unit_test/validator_tests.py
@@ -1,12 +1,26 @@
 import unittest
 import quantities as pq
+
 class ValidatorTestCase(unittest.TestCase):
+
+    def test1(self):
+        self.assertEqual(1, 1)
+
     def register_test(self):
+
         class TestClass():
             intValue = 0
             def getIntValue(self):
                 return self.intValue
+
         from sciunit.validators import register_quantity, register_type
+        from cerberus import TypeDefinition, Validator
+
         register_type(TestClass, "TestType1")
         q = pq.Quantity([1,2,3], 'J')
         register_quantity(q, "TestType2")
+        self.assertTrue(isinstance(Validator.types_mapping['TestType1'], TypeDefinition))
+        self.assertTrue(isinstance(Validator.types_mapping['TestType2'], TypeDefinition))
+
+if __name__ == '__main__':
+    unittest.main()

<|original_code|>
import unittest
import quantities as pq
class ValidatorTestCase(unittest.TestCase):
    def register_test(self):
        class TestClass():
            intValue = 0
            def getIntValue(self):
                return self.intValue
        from sciunit.validators import register_quantity, register_type
        register_type(TestClass, "TestType1")
        q = pq.Quantity([1,2,3], 'J')
        register_quantity(q, "TestType2")
<|edits_diff|>
--- sciunit/unit_test/validator_tests.py
+++ sciunit/unit_test/validator_tests.py
@@ -1,12 +1,24 @@
 import unittest
 import quantities as pq
+
 class ValidatorTestCase(unittest.TestCase):
+
+    def test1(self):
+        self.assertEqual(1, 1)
+
     def register_test(self):
+
         class TestClass():
             intValue = 0
             def getIntValue(self):
                 return self.intValue
+
         from sciunit.validators import register_quantity, register_type
         register_type(TestClass, "TestType1")
         q = pq.Quantity([1,2,3], 'J')
         register_quantity(q, "TestType2")
+        self.assertTrue(isinstance(Validator.types_mapping['TestType1'], TypeDefinition))
+        self.assertTrue(isinstance(Validator.types_mapping['TestType2'], TypeDefinition))
+
+if __name__ == '__main__':
+    unittest.main()
<|current_version|>
import unittest
import quantities as pq

class ValidatorTestCase(unittest.TestCase):

    def test1(self):
        self.assertEqual(1, 1)

    def register_test(self):

        class TestClass():
            intValue = 0
            def getIntValue(self):
                return self.intValue

        from sciunit.validators import register_quantity, register_type
        register_type(TestClass, "TestType1")
        q = pq.Quantity([1,2,3], 'J')
        register_quantity(q, "TestType2")
        self.assertTrue(isinstance(Validator.types_mapping['TestType1'], TypeDefinition))
        self.assertTrue(isinstance(Validator.types_mapping['TestType2'], TypeDefinition))

if __name__ == '__main__':
    unittest.main()
<|next_version|>
import unittest
import quantities as pq

class ValidatorTestCase(unittest.TestCase):

    def test1(self):
        self.assertEqual(1, 1)

    def register_test(self):

        class TestClass():
            intValue = 0
            def getIntValue(self):
                return self.intValue

        from sciunit.validators import register_quantity, register_type
        from cerberus import TypeDefinition, Validator

        register_type(TestClass, "TestType1")
        q = pq.Quantity([1,2,3], 'J')
        register_quantity(q, "TestType2")
        self.assertTrue(isinstance(Validator.types_mapping['TestType1'], TypeDefinition))
        self.assertTrue(isinstance(Validator.types_mapping['TestType2'], TypeDefinition))

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


Add typing module as dependencies for python versions older than 3.5

--- setup.py
+++ setup.py
@@ -1,8 +1,10 @@
 from setuptools import setup, find_packages
 import os.path
 import re
+import sys

 package_name = 'sqlalchemy_dict'
+py_version = sys.version_info[:2]

 # reading package's version (same way sqlalchemy does)
 with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
@@ -11,6 +13,9 @@
 dependencies = [
   'sqlalchemy'
 ]
+
+if py_version < (3, 5):
+    dependencies.append('typing')

 setup(
     name=package_name,

<|original_code|>
from setuptools import setup, find_packages
import os.path
import re

package_name = 'sqlalchemy_dict'

# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
    package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)

dependencies = [
  'sqlalchemy'
]

setup(
    name=package_name,
    version=package_version,
    author='Mahdi Ghane.g',
    description='sqlalchemy extension for interacting models with python dictionary.',
    long_description=open('README.rst').read(),
    url='https://github.com/meyt/sqlalchemy-dict',
    packages=find_packages(),
    install_requires=dependencies,
    license='MIT License',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Operating System :: OS Independent',
        'Topic :: Software Development :: Libraries',
    ]
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,8 +1,10 @@
 from setuptools import setup, find_packages
 import os.path
 import re
+import sys

 package_name = 'sqlalchemy_dict'
+py_version = sys.version_info[:2]

 # reading package's version (same way sqlalchemy does)
 with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
<|current_version|>
from setuptools import setup, find_packages
import os.path
import re
import sys

package_name = 'sqlalchemy_dict'
py_version = sys.version_info[:2]

# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
    package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)

dependencies = [
  'sqlalchemy'
]

setup(
    name=package_name,
    version=package_version,
    author='Mahdi Ghane.g',
    description='sqlalchemy extension for interacting models with python dictionary.',
    long_description=open('README.rst').read(),
    url='https://github.com/meyt/sqlalchemy-dict',
    packages=find_packages(),
    install_requires=dependencies,
    license='MIT License',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Operating System :: OS Independent',
        'Topic :: Software Development :: Libraries',
    ]
)

<|next_version|>
from setuptools import setup, find_packages
import os.path
import re
import sys

package_name = 'sqlalchemy_dict'
py_version = sys.version_info[:2]

# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
    package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)

dependencies = [
  'sqlalchemy'
]

if py_version < (3, 5):
    dependencies.append('typing')

setup(
    name=package_name,
    version=package_version,
    author='Mahdi Ghane.g',
    description='sqlalchemy extension for interacting models with python dictionary.',
    long_description=open('README.rst').read(),
    url='https://github.com/meyt/sqlalchemy-dict',
    packages=find_packages(),
    install_requires=dependencies,
    license='MIT License',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Operating System :: OS Independent',
        'Topic :: Software Development :: Libraries',
    ]
)


Add feedback to global settings

Add feedback to global settings

--- src/pretix/control/views/global_settings.py
+++ src/pretix/control/views/global_settings.py
@@ -1,4 +1,6 @@
+from django.contrib import messages
 from django.shortcuts import reverse
+from django.utils.translation import ugettext_lazy as _
 from django.views.generic import FormView

 from pretix.control.forms.global_settings import GlobalSettingsForm
@@ -11,7 +13,12 @@

     def form_valid(self, form):
         form.save()
+        messages.success(self.request, _('Your changes have been saved.'))
         return super().form_valid(form)
+
+    def form_invalid(self, form):
+        messages.error(self.request, _('Your changes have not been saved, see below for errors.'))
+        return super().form_invalid(form)

     def get_success_url(self):
         return reverse('control:global-settings')

<|original_code|>
from django.shortcuts import reverse
from django.views.generic import FormView

from pretix.control.forms.global_settings import GlobalSettingsForm
from pretix.control.permissions import AdministratorPermissionRequiredMixin

class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView):
    template_name = 'pretixcontrol/global_settings.html'
    form_class = GlobalSettingsForm

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('control:global-settings')

<|edits_diff|>
--- src/pretix/control/views/global_settings.py
+++ src/pretix/control/views/global_settings.py
@@ -1,4 +1,6 @@
+from django.contrib import messages
 from django.shortcuts import reverse
+from django.utils.translation import ugettext_lazy as _
 from django.views.generic import FormView

 from pretix.control.forms.global_settings import GlobalSettingsForm
@@ -11,6 +13,7 @@

     def form_valid(self, form):
         form.save()
+        messages.success(self.request, _('Your changes have been saved.'))
         return super().form_valid(form)

     def get_success_url(self):
<|current_version|>
from django.contrib import messages
from django.shortcuts import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView

from pretix.control.forms.global_settings import GlobalSettingsForm
from pretix.control.permissions import AdministratorPermissionRequiredMixin

class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView):
    template_name = 'pretixcontrol/global_settings.html'
    form_class = GlobalSettingsForm

    def form_valid(self, form):
        form.save()
        messages.success(self.request, _('Your changes have been saved.'))
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('control:global-settings')

<|next_version|>
from django.contrib import messages
from django.shortcuts import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView

from pretix.control.forms.global_settings import GlobalSettingsForm
from pretix.control.permissions import AdministratorPermissionRequiredMixin

class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView):
    template_name = 'pretixcontrol/global_settings.html'
    form_class = GlobalSettingsForm

    def form_valid(self, form):
        form.save()
        messages.success(self.request, _('Your changes have been saved.'))
        return super().form_valid(form)

    def form_invalid(self, form):
        messages.error(self.request, _('Your changes have not been saved, see below for errors.'))
        return super().form_invalid(form)

    def get_success_url(self):
        return reverse('control:global-settings')


Add files to the exported names.

Add files to the exported names.

--- importlib_resources/__init__.py
+++ importlib_resources/__init__.py
@@ -8,6 +8,7 @@
     'Resource',
     'ResourceReader',
     'contents',
+    'files',
     'is_resource',
     'open_binary',
     'open_text',
@@ -22,6 +23,7 @@
         Package,
         Resource,
         contents,
+        files,
         is_resource,
         open_binary,
         open_text,
@@ -33,6 +35,7 @@
 else:
     from importlib_resources._py2 import (
         contents,
+        files,
         is_resource,
         open_binary,
         open_text,

<|original_code|>
"""Read resources contained within a package."""

import sys

__all__ = [
    'Package',
    'Resource',
    'ResourceReader',
    'contents',
    'is_resource',
    'open_binary',
    'open_text',
    'path',
    'read_binary',
    'read_text',
    ]

if sys.version_info >= (3,):
    from importlib_resources._py3 import (
        Package,
        Resource,
        contents,
        is_resource,
        open_binary,
        open_text,
        path,
        read_binary,
        read_text,
        )
    from importlib_resources.abc import ResourceReader
else:
    from importlib_resources._py2 import (
        contents,
        is_resource,
        open_binary,
        open_text,
        path,
        read_binary,
        read_text,
        )
    del __all__[:3]

__version__ = read_text('importlib_resources', 'version.txt').strip()

<|edits_diff|>
--- importlib_resources/__init__.py
+++ importlib_resources/__init__.py
@@ -8,6 +8,7 @@
     'Resource',
     'ResourceReader',
     'contents',
+    'files',
     'is_resource',
     'open_binary',
     'open_text',
@@ -22,6 +23,7 @@
         Package,
         Resource,
         contents,
+        files,
         is_resource,
         open_binary,
         open_text,
<|current_version|>
"""Read resources contained within a package."""

import sys

__all__ = [
    'Package',
    'Resource',
    'ResourceReader',
    'contents',
    'files',
    'is_resource',
    'open_binary',
    'open_text',
    'path',
    'read_binary',
    'read_text',
    ]

if sys.version_info >= (3,):
    from importlib_resources._py3 import (
        Package,
        Resource,
        contents,
        files,
        is_resource,
        open_binary,
        open_text,
        path,
        read_binary,
        read_text,
        )
    from importlib_resources.abc import ResourceReader
else:
    from importlib_resources._py2 import (
        contents,
        is_resource,
        open_binary,
        open_text,
        path,
        read_binary,
        read_text,
        )
    del __all__[:3]

__version__ = read_text('importlib_resources', 'version.txt').strip()

<|next_version|>
"""Read resources contained within a package."""

import sys

__all__ = [
    'Package',
    'Resource',
    'ResourceReader',
    'contents',
    'files',
    'is_resource',
    'open_binary',
    'open_text',
    'path',
    'read_binary',
    'read_text',
    ]

if sys.version_info >= (3,):
    from importlib_resources._py3 import (
        Package,
        Resource,
        contents,
        files,
        is_resource,
        open_binary,
        open_text,
        path,
        read_binary,
        read_text,
        )
    from importlib_resources.abc import ResourceReader
else:
    from importlib_resources._py2 import (
        contents,
        files,
        is_resource,
        open_binary,
        open_text,
        path,
        read_binary,
        read_text,
        )
    del __all__[:3]

__version__ = read_text('importlib_resources', 'version.txt').strip()


Change the motionactivity formatter to match the new version of the google play library

We bumped up the play version number in
https://github.com/e-mission/e-mission-data-collection/commit/a93bc993ddcc1e78ab7fc15e6c9a588ce28a5e45
which will change the fields that show up in the android messages.

We really need to resolve
https://github.com/e-mission/e-mission-data-collection/issues/80

--- emission/net/usercache/formatters/android/motion_activity.py
+++ emission/net/usercache/formatters/android/motion_activity.py
@@ -20,6 +20,8 @@
         data.type = ecwa.MotionTypes(entry.data.agb).value
     elif 'zzaEg' in entry.data:
         data.type = ecwa.MotionTypes(entry.data.zzaEg).value
+    elif 'ajO' in entry.data:
+        data.type = ecwa.MotionTypes(entry.data.ajO).value
     else:
         data.type = ecwa.MotionTypes(entry.data.zzaKM).value

@@ -28,6 +30,8 @@
         data.confidence = entry.data.agc
     elif 'zzaEh' in entry.data:
         data.confidence = entry.data.zzaEh
+    elif 'ajP' in entry.data:
+        data.confidence = entry.data.ajP
     else:
         data.confidence = entry.data.zzaKN

<|original_code|>
import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    elif 'zzaEg' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaKM).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    elif 'zzaEh' in entry.data:
        data.confidence = entry.data.zzaEh
    else:
        data.confidence = entry.data.zzaKN

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry

<|edits_diff|>
--- emission/net/usercache/formatters/android/motion_activity.py
+++ emission/net/usercache/formatters/android/motion_activity.py
@@ -20,6 +20,8 @@
         data.type = ecwa.MotionTypes(entry.data.agb).value
     elif 'zzaEg' in entry.data:
         data.type = ecwa.MotionTypes(entry.data.zzaEg).value
+    elif 'ajO' in entry.data:
+        data.type = ecwa.MotionTypes(entry.data.ajO).value
     else:
         data.type = ecwa.MotionTypes(entry.data.zzaKM).value

<|current_version|>
import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    elif 'zzaEg' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value
    elif 'ajO' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.ajO).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaKM).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    elif 'zzaEh' in entry.data:
        data.confidence = entry.data.zzaEh
    else:
        data.confidence = entry.data.zzaKN

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry

<|next_version|>
import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    elif 'zzaEg' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value
    elif 'ajO' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.ajO).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaKM).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    elif 'zzaEh' in entry.data:
        data.confidence = entry.data.zzaEh
    elif 'ajP' in entry.data:
        data.confidence = entry.data.ajP
    else:
        data.confidence = entry.data.zzaKN

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry


Save record in migrations file

Save record in migrations file

--- corehq/apps/accounting/migrations/0026_auto_20180508_1956.py
+++ corehq/apps/accounting/migrations/0026_auto_20180508_1956.py
@@ -16,11 +16,13 @@
     for record in BillingRecord.objects.all():
         if record.emailed_to != '':
             record.emailed_to_list = record.emailed_to.split(',')
+            record.save()

     WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
     for wirerecord in WireBillingRecord.objects.all():
         if wirerecord.emailed_to != '':
             wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')
+            wirerecord.save()

 class Migration(migrations.Migration):

<|original_code|>
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import migrations
from corehq.sql_db.operations import HqRunPython

def noop(*args, **kwargs):
    pass

def _convert_emailed_to_array_field(apps, schema_editor):
    BillingRecord = apps.get_model('accounting', 'BillingRecord')
    for record in BillingRecord.objects.all():
        if record.emailed_to != '':
            record.emailed_to_list = record.emailed_to.split(',')

    WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
    for wirerecord in WireBillingRecord.objects.all():
        if wirerecord.emailed_to != '':
            wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')

class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0025_auto_20180508_1952'),
    ]

    operations = [
        HqRunPython(_convert_emailed_to_array_field, reverse_code=noop)
    ]

<|edits_diff|>
--- corehq/apps/accounting/migrations/0026_auto_20180508_1956.py
+++ corehq/apps/accounting/migrations/0026_auto_20180508_1956.py
@@ -16,6 +16,7 @@
     for record in BillingRecord.objects.all():
         if record.emailed_to != '':
             record.emailed_to_list = record.emailed_to.split(',')
+            record.save()

     WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
     for wirerecord in WireBillingRecord.objects.all():
<|current_version|>
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import migrations
from corehq.sql_db.operations import HqRunPython

def noop(*args, **kwargs):
    pass

def _convert_emailed_to_array_field(apps, schema_editor):
    BillingRecord = apps.get_model('accounting', 'BillingRecord')
    for record in BillingRecord.objects.all():
        if record.emailed_to != '':
            record.emailed_to_list = record.emailed_to.split(',')
            record.save()

    WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
    for wirerecord in WireBillingRecord.objects.all():
        if wirerecord.emailed_to != '':
            wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')

class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0025_auto_20180508_1952'),
    ]

    operations = [
        HqRunPython(_convert_emailed_to_array_field, reverse_code=noop)
    ]

<|next_version|>
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import

from django.db import migrations
from corehq.sql_db.operations import HqRunPython

def noop(*args, **kwargs):
    pass

def _convert_emailed_to_array_field(apps, schema_editor):
    BillingRecord = apps.get_model('accounting', 'BillingRecord')
    for record in BillingRecord.objects.all():
        if record.emailed_to != '':
            record.emailed_to_list = record.emailed_to.split(',')
            record.save()

    WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
    for wirerecord in WireBillingRecord.objects.all():
        if wirerecord.emailed_to != '':
            wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')
            wirerecord.save()

class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0025_auto_20180508_1952'),
    ]

    operations = [
        HqRunPython(_convert_emailed_to_array_field, reverse_code=noop)
    ]


Fix testing on update_game_info management command

--- game_info/tests/test_commands.py
+++ game_info/tests/test_commands.py
@@ -1,7 +1,12 @@
 from django.core.management import call_command
 from django.test import TestCase
+from game_info.models import Server

 class ServerTest(TestCase):
+    def create_server(self, title="Test Server", host="example.org", port=27015):
+        return Server.objects.create(title=title, host=host, port=port)
+
     def test_update_game_info(self):
+        self.create_server().save()
         call_command('update_game_info')

<|original_code|>
from django.core.management import call_command
from django.test import TestCase

class ServerTest(TestCase):
    def test_update_game_info(self):
        call_command('update_game_info')

<|edits_diff|>
--- game_info/tests/test_commands.py
+++ game_info/tests/test_commands.py
@@ -1,7 +1,11 @@
 from django.core.management import call_command
 from django.test import TestCase
+from game_info.models import Server

 class ServerTest(TestCase):
+    def create_server(self, title="Test Server", host="example.org", port=27015):
+        return Server.objects.create(title=title, host=host, port=port)
+
     def test_update_game_info(self):
         call_command('update_game_info')
<|current_version|>
from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server

class ServerTest(TestCase):
    def create_server(self, title="Test Server", host="example.org", port=27015):
        return Server.objects.create(title=title, host=host, port=port)

    def test_update_game_info(self):
        call_command('update_game_info')

<|next_version|>
from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server

class ServerTest(TestCase):
    def create_server(self, title="Test Server", host="example.org", port=27015):
        return Server.objects.create(title=title, host=host, port=port)

    def test_update_game_info(self):
        self.create_server().save()
        call_command('update_game_info')