Fix not imported os and format code

Fix not imported os and format code

--- example-flask-python3.6-index/app/main.py
+++ example-flask-python3.6-index/app/main.py
@@ -1,14 +1,19 @@
+import os
+
 from flask import Flask, send_file
 app = Flask(__name__)
+

 @app.route("/hello")
 def hello():
     return "Hello World from Flask in a uWSGI Nginx Docker container with \
      Python 3.6 (from the example template)"

+
 @app.route("/")
 def main():
     return send_file('./static/index.html')
+

 # Everything not declared before (not a Flask route / API endpoint)...
 @app.route('/<path:path>')
@@ -22,5 +27,6 @@
     else:
         return send_file('./static/index.html')

+
 if __name__ == "__main__":
     app.run(host='0.0.0.0', debug=True, port=80)

<|original_code|>
from flask import Flask, send_file
app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World from Flask in a uWSGI Nginx Docker container with \
     Python 3.6 (from the example template)"

@app.route("/")
def main():
    return send_file('./static/index.html')

# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = './static/' + path
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        return send_file('./static/index.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, port=80)

<|edits_diff|>
--- example-flask-python3.6-index/app/main.py
+++ example-flask-python3.6-index/app/main.py
@@ -1,14 +1,19 @@
+import os
+
 from flask import Flask, send_file
 app = Flask(__name__)
+

 @app.route("/hello")
 def hello():
     return "Hello World from Flask in a uWSGI Nginx Docker container with \
      Python 3.6 (from the example template)"

+
 @app.route("/")
 def main():
     return send_file('./static/index.html')
+

 # Everything not declared before (not a Flask route / API endpoint)...
 @app.route('/<path:path>')
<|current_version|>
import os

from flask import Flask, send_file
app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World from Flask in a uWSGI Nginx Docker container with \
     Python 3.6 (from the example template)"

@app.route("/")
def main():
    return send_file('./static/index.html')

# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = './static/' + path
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        return send_file('./static/index.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, port=80)

<|next_version|>
import os

from flask import Flask, send_file
app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World from Flask in a uWSGI Nginx Docker container with \
     Python 3.6 (from the example template)"

@app.route("/")
def main():
    return send_file('./static/index.html')

# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
    # ...could be a static file needed by the front end that
    # doesn't use the `static` path (like in `<script src="bundle.js">`)
    file_path = './static/' + path
    if os.path.isfile(file_path):
        return send_file(file_path)
    # ...or should be handled by the SPA's "router" in front end
    else:
        return send_file('./static/index.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, port=80)


Add some logging to the EVE API task

Add some logging to the EVE API task

--- eve_api/tasks.py
+++ eve_api/tasks.py
@@ -1,3 +1,4 @@
+import logging
 from celery.decorators import task
 from eve_api.api_puller.accounts import import_eve_account
 from eve_api.app_defines import *
@@ -5,6 +6,8 @@

 @task()
 def import_apikey(api_userid, api_key, user=None, force_cache=False):
+    l = logging.getLogger('import_apikey')
+    l.info("Importing %s/%s" % (api_userid, api_key))
     acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
     donecorps = []
     if acc and acc.api_status == API_STATUS_OK:

<|original_code|>
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access

@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
    acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
    donecorps = []
    if acc and acc.api_status == API_STATUS_OK:
        if user and not acc.user:
            acc.user = user
        if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
            donecorps = []
            for char in acc.characters.filter(director=1):
                if not char.corporation.id in donecorps:
                    #pull_corp_members(acc.api_key, acc.api_user_id, char.id)
                    char.corporation.query_and_update_corp()
                    donecorps.append(char.corporation.id)

        for char in acc.characters.all():
            try:
                if char.corporation.id not in donecorps:
                    char.corporation.query_and_update_corp()
                    donecorps.append(char.corporation.id)
            except:
                continue

        acc.save()
        if acc.user:
             update_user_access.delay(user=acc.user)

    return acc

<|edits_diff|>
--- eve_api/tasks.py
+++ eve_api/tasks.py
@@ -1,3 +1,4 @@
+import logging
 from celery.decorators import task
 from eve_api.api_puller.accounts import import_eve_account
 from eve_api.app_defines import *
<|current_version|>
import logging
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access

@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
    acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
    donecorps = []
    if acc and acc.api_status == API_STATUS_OK:
        if user and not acc.user:
            acc.user = user
        if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
            donecorps = []
            for char in acc.characters.filter(director=1):
                if not char.corporation.id in donecorps:
                    #pull_corp_members(acc.api_key, acc.api_user_id, char.id)
                    char.corporation.query_and_update_corp()
                    donecorps.append(char.corporation.id)

        for char in acc.characters.all():
            try:
                if char.corporation.id not in donecorps:
                    char.corporation.query_and_update_corp()
                    donecorps.append(char.corporation.id)
            except:
                continue

        acc.save()
        if acc.user:
             update_user_access.delay(user=acc.user)

    return acc

<|next_version|>
import logging
from celery.decorators import task
from eve_api.api_puller.accounts import import_eve_account
from eve_api.app_defines import *
from sso.tasks import update_user_access

@task()
def import_apikey(api_userid, api_key, user=None, force_cache=False):
    l = logging.getLogger('import_apikey')
    l.info("Importing %s/%s" % (api_userid, api_key))
    acc = import_eve_account(api_key, api_userid, force_cache=force_cache)
    donecorps = []
    if acc and acc.api_status == API_STATUS_OK:
        if user and not acc.user:
            acc.user = user
        if acc.api_keytype == API_KEYTYPE_FULL and acc.characters.filter(director=1).count():
            donecorps = []
            for char in acc.characters.filter(director=1):
                if not char.corporation.id in donecorps:
                    #pull_corp_members(acc.api_key, acc.api_user_id, char.id)
                    char.corporation.query_and_update_corp()
                    donecorps.append(char.corporation.id)

        for char in acc.characters.all():
            try:
                if char.corporation.id not in donecorps:
                    char.corporation.query_and_update_corp()
                    donecorps.append(char.corporation.id)
            except:
                continue

        acc.save()
        if acc.user:
             update_user_access.delay(user=acc.user)

    return acc


Revert "remove unecessary sys.exit call"

This reverts commit 50b79fec1e96c1e5e5cc17f58f2c4ccfba16d6d6.

--- project/commands/main.py
+++ project/commands/main.py
@@ -1,6 +1,7 @@
 """The ``main`` function chooses and runs a subcommand."""
 from __future__ import absolute_import, print_function

+import sys
 from argparse import ArgumentParser, RawDescriptionHelpFormatter

 import project.commands.launch as launch
@@ -35,3 +36,6 @@
 def main(argv):
     """Start the launch command."""
     _run_parser(argv)
+    # the various sub-mains exit(0) if they succeed, if we get here
+    # we must not have called one of them
+    sys.exit(1)

<|original_code|>
"""The ``main`` function chooses and runs a subcommand."""
from __future__ import absolute_import, print_function

from argparse import ArgumentParser, RawDescriptionHelpFormatter

import project.commands.launch as launch
import project.commands.prepare as prepare
import project.commands.activate as activate

def _run_parser(args):
    """Internal function to run the parsing of params and run the commands. Allows mocking."""
    parser = ArgumentParser("Anaconda project tool", epilog=__doc__, formatter_class=RawDescriptionHelpFormatter)

    subparsers = parser.add_subparsers()

    preset = subparsers.add_parser('launch', description="Runs the project")
    preset.add_argument('project_dir', default='.')
    # preset.add_argument('ui_mode')
    preset.set_defaults(main=launch.main)

    preset = subparsers.add_parser('prepare', description="Configure the project to run.")
    preset.add_argument('project_dir', default='.')
    preset.set_defaults(main=prepare.main)

    preset = subparsers.add_parser('activate', description="Prepare project and outputs lines to be sourced.")
    preset.add_argument('project_dir', default='.')
    preset.set_defaults(main=activate.main)

    args = parser.parse_args(args)

    args.main(args.project_dir)

def main(argv):
    """Start the launch command."""
    _run_parser(argv)

<|edits_diff|>
--- project/commands/main.py
+++ project/commands/main.py
@@ -1,6 +1,7 @@
 """The ``main`` function chooses and runs a subcommand."""
 from __future__ import absolute_import, print_function

+import sys
 from argparse import ArgumentParser, RawDescriptionHelpFormatter

 import project.commands.launch as launch
<|current_version|>
"""The ``main`` function chooses and runs a subcommand."""
from __future__ import absolute_import, print_function

import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter

import project.commands.launch as launch
import project.commands.prepare as prepare
import project.commands.activate as activate

def _run_parser(args):
    """Internal function to run the parsing of params and run the commands. Allows mocking."""
    parser = ArgumentParser("Anaconda project tool", epilog=__doc__, formatter_class=RawDescriptionHelpFormatter)

    subparsers = parser.add_subparsers()

    preset = subparsers.add_parser('launch', description="Runs the project")
    preset.add_argument('project_dir', default='.')
    # preset.add_argument('ui_mode')
    preset.set_defaults(main=launch.main)

    preset = subparsers.add_parser('prepare', description="Configure the project to run.")
    preset.add_argument('project_dir', default='.')
    preset.set_defaults(main=prepare.main)

    preset = subparsers.add_parser('activate', description="Prepare project and outputs lines to be sourced.")
    preset.add_argument('project_dir', default='.')
    preset.set_defaults(main=activate.main)

    args = parser.parse_args(args)

    args.main(args.project_dir)

def main(argv):
    """Start the launch command."""
    _run_parser(argv)

<|next_version|>
"""The ``main`` function chooses and runs a subcommand."""
from __future__ import absolute_import, print_function

import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter

import project.commands.launch as launch
import project.commands.prepare as prepare
import project.commands.activate as activate

def _run_parser(args):
    """Internal function to run the parsing of params and run the commands. Allows mocking."""
    parser = ArgumentParser("Anaconda project tool", epilog=__doc__, formatter_class=RawDescriptionHelpFormatter)

    subparsers = parser.add_subparsers()

    preset = subparsers.add_parser('launch', description="Runs the project")
    preset.add_argument('project_dir', default='.')
    # preset.add_argument('ui_mode')
    preset.set_defaults(main=launch.main)

    preset = subparsers.add_parser('prepare', description="Configure the project to run.")
    preset.add_argument('project_dir', default='.')
    preset.set_defaults(main=prepare.main)

    preset = subparsers.add_parser('activate', description="Prepare project and outputs lines to be sourced.")
    preset.add_argument('project_dir', default='.')
    preset.set_defaults(main=activate.main)

    args = parser.parse_args(args)

    args.main(args.project_dir)

def main(argv):
    """Start the launch command."""
    _run_parser(argv)
    # the various sub-mains exit(0) if they succeed, if we get here
    # we must not have called one of them
    sys.exit(1)


Disable tests that don't work on travis

Tests: Disable tests that don't work on travis

--- touchdown/tests/test_ssh_client.py
+++ touchdown/tests/test_ssh_client.py
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.

+import unittest
+
 import mock

 from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture
@@ -20,6 +22,7 @@

 class TestSshClient(WorkspaceTestCase):

+    @unittest.skip('test doesn\'t work on CI')
     def test_ssh_client(self):
         goal = self.create_goal('ssh')
         ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace))

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

import mock

from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture
from touchdown.tests.testcases import WorkspaceTestCase

class TestSshClient(WorkspaceTestCase):

    def test_ssh_client(self):
        goal = self.create_goal('ssh')
        ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace))
        connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe')

        self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport'))
        self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding'))

        connection_plan.get_client()

        # FIXME: How to make the dummy server run stuff? Or fake run stuff.

<|edits_diff|>
--- touchdown/tests/test_ssh_client.py
+++ touchdown/tests/test_ssh_client.py
@@ -11,6 +11,8 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+
+import unittest

 import mock

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

import unittest

import mock

from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture
from touchdown.tests.testcases import WorkspaceTestCase

class TestSshClient(WorkspaceTestCase):

    def test_ssh_client(self):
        goal = self.create_goal('ssh')
        ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace))
        connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe')

        self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport'))
        self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding'))

        connection_plan.get_client()

        # FIXME: How to make the dummy server run stuff? Or fake run stuff.

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

import unittest

import mock

from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture
from touchdown.tests.testcases import WorkspaceTestCase

class TestSshClient(WorkspaceTestCase):

    @unittest.skip('test doesn\'t work on CI')
    def test_ssh_client(self):
        goal = self.create_goal('ssh')
        ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace))
        connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe')

        self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport'))
        self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding'))

        connection_plan.get_client()

        # FIXME: How to make the dummy server run stuff? Or fake run stuff.


Add fpp k/d data to the model.

Add fpp k/d data to the model.

--- websaver/parsed_data/models.py
+++ websaver/parsed_data/models.py
@@ -3,15 +3,23 @@
 # Create your models here.
 class RatingData(models.Model):
     userName = models.CharField(max_length=30)
+
     solofpp = models.CharField(max_length=5, null=True)
     duofpp = models.CharField(max_length=5, null=True)
     squadfpp = models.CharField(max_length=5, null=True)
+
     solo = models.CharField(max_length=5, null=True)
     duo = models.CharField(max_length=5, null=True)
     squad = models.CharField(max_length=5, null=True)
+
     solokd = models.CharField(max_length=5, null=True)
     duokd = models.CharField(max_length=5, null=True)
     squadkd = models.CharField(max_length=5, null=True)
+
+    solofppkd = models.CharField(max_length=5, null=True)
+    duofppkd = models.CharField(max_length=5, null=True)
+    squadfppkd = models.CharField(max_length=5, null=True)
+
     created_at = models.DateTimeField(auto_now_add=True)

     class Meta:

<|original_code|>
from django.db import models

# Create your models here.
class RatingData(models.Model):
    userName = models.CharField(max_length=30)
    solofpp = models.CharField(max_length=5, null=True)
    duofpp = models.CharField(max_length=5, null=True)
    squadfpp = models.CharField(max_length=5, null=True)
    solo = models.CharField(max_length=5, null=True)
    duo = models.CharField(max_length=5, null=True)
    squad = models.CharField(max_length=5, null=True)
    solokd = models.CharField(max_length=5, null=True)
    duokd = models.CharField(max_length=5, null=True)
    squadkd = models.CharField(max_length=5, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('created_at',)

    def __str__(self):
        return self.userName
<|edits_diff|>
--- websaver/parsed_data/models.py
+++ websaver/parsed_data/models.py
@@ -3,12 +3,15 @@
 # Create your models here.
 class RatingData(models.Model):
     userName = models.CharField(max_length=30)
+
     solofpp = models.CharField(max_length=5, null=True)
     duofpp = models.CharField(max_length=5, null=True)
     squadfpp = models.CharField(max_length=5, null=True)
+
     solo = models.CharField(max_length=5, null=True)
     duo = models.CharField(max_length=5, null=True)
     squad = models.CharField(max_length=5, null=True)
+
     solokd = models.CharField(max_length=5, null=True)
     duokd = models.CharField(max_length=5, null=True)
     squadkd = models.CharField(max_length=5, null=True)
<|current_version|>
from django.db import models

# Create your models here.
class RatingData(models.Model):
    userName = models.CharField(max_length=30)

    solofpp = models.CharField(max_length=5, null=True)
    duofpp = models.CharField(max_length=5, null=True)
    squadfpp = models.CharField(max_length=5, null=True)

    solo = models.CharField(max_length=5, null=True)
    duo = models.CharField(max_length=5, null=True)
    squad = models.CharField(max_length=5, null=True)

    solokd = models.CharField(max_length=5, null=True)
    duokd = models.CharField(max_length=5, null=True)
    squadkd = models.CharField(max_length=5, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('created_at',)

    def __str__(self):
        return self.userName
<|next_version|>
from django.db import models

# Create your models here.
class RatingData(models.Model):
    userName = models.CharField(max_length=30)

    solofpp = models.CharField(max_length=5, null=True)
    duofpp = models.CharField(max_length=5, null=True)
    squadfpp = models.CharField(max_length=5, null=True)

    solo = models.CharField(max_length=5, null=True)
    duo = models.CharField(max_length=5, null=True)
    squad = models.CharField(max_length=5, null=True)

    solokd = models.CharField(max_length=5, null=True)
    duokd = models.CharField(max_length=5, null=True)
    squadkd = models.CharField(max_length=5, null=True)

    solofppkd = models.CharField(max_length=5, null=True)
    duofppkd = models.CharField(max_length=5, null=True)
    squadfppkd = models.CharField(max_length=5, null=True)

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('created_at',)

    def __str__(self):
        return self.userName


Add a few more cases of "not value"

Add a few more cases of "not value"

--- testsuite/test_util.py
+++ testsuite/test_util.py
@@ -11,9 +11,12 @@
         cwd = os.getcwd()

         self.assertEquals(pep8.normalize_paths(''), [])
+        self.assertEquals(pep8.normalize_paths([]), [])
+        self.assertEquals(pep8.normalize_paths(None), [])
         self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
         self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
         self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
+        self.assertEquals(pep8.normalize_paths('foo,  bar  '), ['foo', 'bar'])
         self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'),
                           ['/foo/bar', cwd + '/bat'])
         self.assertEquals(pep8.normalize_paths(".pyc,\n   build/*"),

<|original_code|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest

import pep8

class UtilTestCase(unittest.TestCase):
    def test_normalize_paths(self):
        cwd = os.getcwd()

        self.assertEquals(pep8.normalize_paths(''), [])
        self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
        self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
        self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
        self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'),
                          ['/foo/bar', cwd + '/bat'])
        self.assertEquals(pep8.normalize_paths(".pyc,\n   build/*"),
                          ['.pyc', cwd + '/build/*'])

<|edits_diff|>
--- testsuite/test_util.py
+++ testsuite/test_util.py
@@ -11,6 +11,8 @@
         cwd = os.getcwd()

         self.assertEquals(pep8.normalize_paths(''), [])
+        self.assertEquals(pep8.normalize_paths([]), [])
+        self.assertEquals(pep8.normalize_paths(None), [])
         self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
         self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
         self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
<|current_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest

import pep8

class UtilTestCase(unittest.TestCase):
    def test_normalize_paths(self):
        cwd = os.getcwd()

        self.assertEquals(pep8.normalize_paths(''), [])
        self.assertEquals(pep8.normalize_paths([]), [])
        self.assertEquals(pep8.normalize_paths(None), [])
        self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
        self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
        self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
        self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'),
                          ['/foo/bar', cwd + '/bat'])
        self.assertEquals(pep8.normalize_paths(".pyc,\n   build/*"),
                          ['.pyc', cwd + '/build/*'])

<|next_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest

import pep8

class UtilTestCase(unittest.TestCase):
    def test_normalize_paths(self):
        cwd = os.getcwd()

        self.assertEquals(pep8.normalize_paths(''), [])
        self.assertEquals(pep8.normalize_paths([]), [])
        self.assertEquals(pep8.normalize_paths(None), [])
        self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
        self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
        self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
        self.assertEquals(pep8.normalize_paths('foo,  bar  '), ['foo', 'bar'])
        self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'),
                          ['/foo/bar', cwd + '/bat'])
        self.assertEquals(pep8.normalize_paths(".pyc,\n   build/*"),
                          ['.pyc', cwd + '/build/*'])


Create mongoengine connection when taking phantom snapshots

--- html_snapshots/utils.py
+++ html_snapshots/utils.py
@@ -1,10 +1,14 @@
 import os
+
+import mongoengine as me

 import rmc.shared.constants as c
 import rmc.models as m

 FILE_DIR = os.path.dirname(os.path.realpath(__file__))
 HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots')
+
+me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT)

 def write(file_path, content):

<|original_code|>
import os

import rmc.shared.constants as c
import rmc.models as m

FILE_DIR = os.path.dirname(os.path.realpath(__file__))
HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots')

def write(file_path, content):
    ensure_dir(file_path)
    with open(file_path, 'w') as f:
        f.write(content)

def ensure_dir(file_path):
    d = os.path.dirname(file_path)
    if not os.path.exists(d):
        os.makedirs(d)

def generate_urls():
    urls = []
    # Home page
    urls.append('')
    # Course pages
    for course in m.Course.objects:
        course_id = course.id
        urls.append('course/' + course_id)
    return urls

<|edits_diff|>
--- html_snapshots/utils.py
+++ html_snapshots/utils.py
@@ -1,4 +1,6 @@
 import os
+
+import mongoengine as me

 import rmc.shared.constants as c
 import rmc.models as m
<|current_version|>
import os

import mongoengine as me

import rmc.shared.constants as c
import rmc.models as m

FILE_DIR = os.path.dirname(os.path.realpath(__file__))
HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots')

def write(file_path, content):
    ensure_dir(file_path)
    with open(file_path, 'w') as f:
        f.write(content)

def ensure_dir(file_path):
    d = os.path.dirname(file_path)
    if not os.path.exists(d):
        os.makedirs(d)

def generate_urls():
    urls = []
    # Home page
    urls.append('')
    # Course pages
    for course in m.Course.objects:
        course_id = course.id
        urls.append('course/' + course_id)
    return urls

<|next_version|>
import os

import mongoengine as me

import rmc.shared.constants as c
import rmc.models as m

FILE_DIR = os.path.dirname(os.path.realpath(__file__))
HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots')

me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT)

def write(file_path, content):
    ensure_dir(file_path)
    with open(file_path, 'w') as f:
        f.write(content)

def ensure_dir(file_path):
    d = os.path.dirname(file_path)
    if not os.path.exists(d):
        os.makedirs(d)

def generate_urls():
    urls = []
    # Home page
    urls.append('')
    # Course pages
    for course in m.Course.objects:
        course_id = course.id
        urls.append('course/' + course_id)
    return urls


Create a simple Index view

Create a simple Index view

--- tutorial/polls/views.py
+++ tutorial/polls/views.py
@@ -1,3 +1,7 @@
 from django.shortcuts import render

+from django.http import HttpResponse
+
 # Create your views here.
+def index(request):
+    return HttpResponse("Hello world you are at the index")

<|original_code|>
from django.shortcuts import render

# Create your views here.

<|edits_diff|>
--- tutorial/polls/views.py
+++ tutorial/polls/views.py
@@ -1,3 +1,5 @@
 from django.shortcuts import render

+from django.http import HttpResponse
+
 # Create your views here.
<|current_version|>
from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

<|next_version|>
from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("Hello world you are at the index")


Add redirect from / to /polls

Add redirect from / to /polls

--- mysite/urls.py
+++ mysite/urls.py
@@ -15,8 +15,10 @@
 """
 from django.conf.urls import include, url
 from django.contrib import admin
+from django.http.response import HttpResponseRedirect

 urlpatterns = [
     url(r'^polls/', include('polls.urls')),
     url(r'^admin/', admin.site.urls),
+    url(r'^$', lambda r: HttpResponseRedirect('polls/')),
 ]

<|original_code|>
"""vote 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 include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

<|edits_diff|>
--- mysite/urls.py
+++ mysite/urls.py
@@ -15,6 +15,7 @@
 """
 from django.conf.urls import include, url
 from django.contrib import admin
+from django.http.response import HttpResponseRedirect

 urlpatterns = [
     url(r'^polls/', include('polls.urls')),
<|current_version|>
"""vote 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 include, url
from django.contrib import admin
from django.http.response import HttpResponseRedirect

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

<|next_version|>
"""vote 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 include, url
from django.contrib import admin
from django.http.response import HttpResponseRedirect

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^$', lambda r: HttpResponseRedirect('polls/')),
]


Add helpful message for users trying to install with Python < 3.5

--- setup.py
+++ setup.py
@@ -1,6 +1,15 @@
+from __future__ import print_function
+
+import sys
+
 from setuptools import setup

+if sys.version_info[:2] < (3, 5):
+    print('Mikla only runs on Python 3.5 or later', file=sys.stderr)
+    sys.exit(1)
+
 import mikla
+

 setup(
     name='mikla',

<|original_code|>
from setuptools import setup

import mikla

setup(
    name='mikla',
    version=mikla.__version__.strip(),
    url='http://dirtymonkey.co.uk/mikla',
    license='MIT',
    author=mikla.__author__.strip(),
    author_email='matt@dirtymonkey.co.uk',
    description=mikla.__doc__.strip().replace('\n', ' '),
    long_description=open('README.rst').read(),
    keywords='encryption security gnupg gpg',
    packages=['mikla'],
    include_package_data=True,
    entry_points={
        'console_scripts': [
            'mikla = mikla.main:main',
        ],
    },
    install_requires=[
        'docopt>=0.6.2',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Operating System :: POSIX :: BSD',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Security :: Cryptography',
        'Topic :: Communications',
        'Topic :: Utilities',
    ],
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,4 +1,12 @@
+from __future__ import print_function
+
+import sys
+
 from setuptools import setup
+
+if sys.version_info[:2] < (3, 5):
+    print('Mikla only runs on Python 3.5 or later', file=sys.stderr)
+    sys.exit(1)

 import mikla

<|current_version|>
from __future__ import print_function

import sys

from setuptools import setup

if sys.version_info[:2] < (3, 5):
    print('Mikla only runs on Python 3.5 or later', file=sys.stderr)
    sys.exit(1)

import mikla

setup(
    name='mikla',
    version=mikla.__version__.strip(),
    url='http://dirtymonkey.co.uk/mikla',
    license='MIT',
    author=mikla.__author__.strip(),
    author_email='matt@dirtymonkey.co.uk',
    description=mikla.__doc__.strip().replace('\n', ' '),
    long_description=open('README.rst').read(),
    keywords='encryption security gnupg gpg',
    packages=['mikla'],
    include_package_data=True,
    entry_points={
        'console_scripts': [
            'mikla = mikla.main:main',
        ],
    },
    install_requires=[
        'docopt>=0.6.2',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Operating System :: POSIX :: BSD',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Security :: Cryptography',
        'Topic :: Communications',
        'Topic :: Utilities',
    ],
)

<|next_version|>
from __future__ import print_function

import sys

from setuptools import setup

if sys.version_info[:2] < (3, 5):
    print('Mikla only runs on Python 3.5 or later', file=sys.stderr)
    sys.exit(1)

import mikla

setup(
    name='mikla',
    version=mikla.__version__.strip(),
    url='http://dirtymonkey.co.uk/mikla',
    license='MIT',
    author=mikla.__author__.strip(),
    author_email='matt@dirtymonkey.co.uk',
    description=mikla.__doc__.strip().replace('\n', ' '),
    long_description=open('README.rst').read(),
    keywords='encryption security gnupg gpg',
    packages=['mikla'],
    include_package_data=True,
    entry_points={
        'console_scripts': [
            'mikla = mikla.main:main',
        ],
    },
    install_requires=[
        'docopt>=0.6.2',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Operating System :: POSIX :: BSD',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Security :: Cryptography',
        'Topic :: Communications',
        'Topic :: Utilities',
    ],
)


Convert README.md to rst for pypi using pandoc.

Closes #11

Thanks for the tips/help Marc :)

--- setup.py
+++ setup.py
@@ -5,10 +5,14 @@
 except ImportError:
     from distutils.core import setup

+import pypandoc
+readme = pypandoc.convert('README.md', 'rst')
+
 setup(name='chevron',
       version='0.7.1',
       license='MIT',
       description='Mustache templating language renderer',
+      long_description=readme,
       author='noah morrison',
       author_email='noah@morrison.ph',
       url='https://github.com/noahmorrison/chevron',

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

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

setup(name='chevron',
      version='0.7.1',
      license='MIT',
      description='Mustache templating language renderer',
      author='noah morrison',
      author_email='noah@morrison.ph',
      url='https://github.com/noahmorrison/chevron',
      packages=['chevron'],
      entry_points={
          'console_scripts': ['chevron=chevron:cli_main']
      },
      classifiers=[
          'Development Status :: 4 - Beta',

          'License :: OSI Approved :: MIT License',

          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.2',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',

          'Topic :: Text Processing :: Markup'
      ]
      )

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -4,6 +4,9 @@
     from setuptools import setup
 except ImportError:
     from distutils.core import setup
+
+import pypandoc
+readme = pypandoc.convert('README.md', 'rst')

 setup(name='chevron',
       version='0.7.1',
<|current_version|>
#!/usr/bin/env python

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

import pypandoc
readme = pypandoc.convert('README.md', 'rst')

setup(name='chevron',
      version='0.7.1',
      license='MIT',
      description='Mustache templating language renderer',
      author='noah morrison',
      author_email='noah@morrison.ph',
      url='https://github.com/noahmorrison/chevron',
      packages=['chevron'],
      entry_points={
          'console_scripts': ['chevron=chevron:cli_main']
      },
      classifiers=[
          'Development Status :: 4 - Beta',

          'License :: OSI Approved :: MIT License',

          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.2',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',

          'Topic :: Text Processing :: Markup'
      ]
      )

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

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

import pypandoc
readme = pypandoc.convert('README.md', 'rst')

setup(name='chevron',
      version='0.7.1',
      license='MIT',
      description='Mustache templating language renderer',
      long_description=readme,
      author='noah morrison',
      author_email='noah@morrison.ph',
      url='https://github.com/noahmorrison/chevron',
      packages=['chevron'],
      entry_points={
          'console_scripts': ['chevron=chevron:cli_main']
      },
      classifiers=[
          'Development Status :: 4 - Beta',

          'License :: OSI Approved :: MIT License',

          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.2',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',

          'Topic :: Text Processing :: Markup'
      ]
      )


Add __active property to rule

Add __active property to rule

--- grammpy/Rule.py
+++ grammpy/Rule.py
@@ -11,10 +11,13 @@

 class Rule:
+    #TODO rules -> rule -> left/right -> rules
     right = [EPSILON]
     left = [EPSILON]
     rule = ([EPSILON], [EPSILON])
     rules = [([EPSILON], [EPSILON])]
+
+    __active = True

     @staticmethod
     def is_regular():

<|original_code|>
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

from .Constants import EPSILON

class Rule:
    right = [EPSILON]
    left = [EPSILON]
    rule = ([EPSILON], [EPSILON])
    rules = [([EPSILON], [EPSILON])]

    @staticmethod
    def is_regular():
        return False

    @staticmethod
    def is_contextfree():
        return False

    @staticmethod
    def is_context():
        return False

    @staticmethod
    def is_unrestricted():
        return False

<|edits_diff|>
--- grammpy/Rule.py
+++ grammpy/Rule.py
@@ -11,6 +11,7 @@

 class Rule:
+    #TODO rules -> rule -> left/right -> rules
     right = [EPSILON]
     left = [EPSILON]
     rule = ([EPSILON], [EPSILON])
<|current_version|>
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

from .Constants import EPSILON

class Rule:
    #TODO rules -> rule -> left/right -> rules
    right = [EPSILON]
    left = [EPSILON]
    rule = ([EPSILON], [EPSILON])
    rules = [([EPSILON], [EPSILON])]

    @staticmethod
    def is_regular():
        return False

    @staticmethod
    def is_contextfree():
        return False

    @staticmethod
    def is_context():
        return False

    @staticmethod
    def is_unrestricted():
        return False

<|next_version|>
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

from .Constants import EPSILON

class Rule:
    #TODO rules -> rule -> left/right -> rules
    right = [EPSILON]
    left = [EPSILON]
    rule = ([EPSILON], [EPSILON])
    rules = [([EPSILON], [EPSILON])]

    __active = True

    @staticmethod
    def is_regular():
        return False

    @staticmethod
    def is_contextfree():
        return False

    @staticmethod
    def is_context():
        return False

    @staticmethod
    def is_unrestricted():
        return False


Add more specific Python version classifiers

--- setup.py
+++ setup.py
@@ -28,6 +28,10 @@
         'Intended Audience :: Developers',
         'License :: OSI Approved :: Apache Software License',
         'Programming Language :: Python :: 2',
+        'Programming Language :: Python :: 2.6',
+        'Programming Language :: Python :: 2.7',
         'Programming Language :: Python :: 3',
+        'Programming Language :: Python :: 3.2',
+        'Programming Language :: Python :: 3.3',
     ],
 )

<|original_code|>
import setuptools
import sys
import os.path
import subprocess

# Build README.txt from README.md if not present, and if we are actually building for distribution to pypi
if not os.path.exists('README.txt') and 'sdist' in sys.argv:
    subprocess.call(['pandoc', '--to=rst', '--smart', '--output=README.txt', 'README.md'])

# But use the best README around
readme = 'README.txt' if os.path.exists('README.txt') else 'README.md'

setuptools.setup(
    name='jsonpath-rw',
    version='0.9',
    description='A robust and significantly extended implementation of JSONPath for Python, with a clear AST for metaprogramming.',
    author='Kenneth Knowles',
    author_email='kenn.knowles@gmail.com',
    url='https://github.com/kennknowles/python-jsonpath-rw',
    license='Apache 2.0',
    long_description=open(readme).read(),
    packages = ['jsonpath_rw'],
    test_suite = 'tests',
    install_requires = [ 'ply', 'decorator', 'six' ],
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -28,6 +28,8 @@
         'Intended Audience :: Developers',
         'License :: OSI Approved :: Apache Software License',
         'Programming Language :: Python :: 2',
+        'Programming Language :: Python :: 2.6',
+        'Programming Language :: Python :: 2.7',
         'Programming Language :: Python :: 3',
     ],
 )
<|current_version|>
import setuptools
import sys
import os.path
import subprocess

# Build README.txt from README.md if not present, and if we are actually building for distribution to pypi
if not os.path.exists('README.txt') and 'sdist' in sys.argv:
    subprocess.call(['pandoc', '--to=rst', '--smart', '--output=README.txt', 'README.md'])

# But use the best README around
readme = 'README.txt' if os.path.exists('README.txt') else 'README.md'

setuptools.setup(
    name='jsonpath-rw',
    version='0.9',
    description='A robust and significantly extended implementation of JSONPath for Python, with a clear AST for metaprogramming.',
    author='Kenneth Knowles',
    author_email='kenn.knowles@gmail.com',
    url='https://github.com/kennknowles/python-jsonpath-rw',
    license='Apache 2.0',
    long_description=open(readme).read(),
    packages = ['jsonpath_rw'],
    test_suite = 'tests',
    install_requires = [ 'ply', 'decorator', 'six' ],
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
    ],
)

<|next_version|>
import setuptools
import sys
import os.path
import subprocess

# Build README.txt from README.md if not present, and if we are actually building for distribution to pypi
if not os.path.exists('README.txt') and 'sdist' in sys.argv:
    subprocess.call(['pandoc', '--to=rst', '--smart', '--output=README.txt', 'README.md'])

# But use the best README around
readme = 'README.txt' if os.path.exists('README.txt') else 'README.md'

setuptools.setup(
    name='jsonpath-rw',
    version='0.9',
    description='A robust and significantly extended implementation of JSONPath for Python, with a clear AST for metaprogramming.',
    author='Kenneth Knowles',
    author_email='kenn.knowles@gmail.com',
    url='https://github.com/kennknowles/python-jsonpath-rw',
    license='Apache 2.0',
    long_description=open(readme).read(),
    packages = ['jsonpath_rw'],
    test_suite = 'tests',
    install_requires = [ 'ply', 'decorator', 'six' ],
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
    ],
)


Add static files to data_files

Add static files to data_files

--- setup.py
+++ setup.py
@@ -1,4 +1,5 @@
 import setuptools
+from glob import glob

 setuptools.setup(
     name="nbresuse",
@@ -10,5 +11,8 @@
     install_requires=[
         'psutil',
         'notebook',
+    ],
+    data_files=[
+        ('share/jupyter/nbextensions/nbresuse', glob('nbresuse/static/*'))
     ]
 )

<|original_code|>
import setuptools

setuptools.setup(
    name="nbresuse",
    version='0.1.0',
    url="https://github.com/yuvipanda/nbresuse",
    author="Yuvi Panda",
    description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
    packages=setuptools.find_packages(),
    install_requires=[
        'psutil',
        'notebook',
    ]
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,4 +1,5 @@
 import setuptools
+from glob import glob

 setuptools.setup(
     name="nbresuse",
<|current_version|>
import setuptools
from glob import glob

setuptools.setup(
    name="nbresuse",
    version='0.1.0',
    url="https://github.com/yuvipanda/nbresuse",
    author="Yuvi Panda",
    description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
    packages=setuptools.find_packages(),
    install_requires=[
        'psutil',
        'notebook',
    ]
)

<|next_version|>
import setuptools
from glob import glob

setuptools.setup(
    name="nbresuse",
    version='0.1.0',
    url="https://github.com/yuvipanda/nbresuse",
    author="Yuvi Panda",
    description="Simple Jupyter extension to show how much resources (RAM) your notebook is using",
    packages=setuptools.find_packages(),
    install_requires=[
        'psutil',
        'notebook',
    ],
    data_files=[
        ('share/jupyter/nbextensions/nbresuse', glob('nbresuse/static/*'))
    ]
)


Use C ordering for npy format

Use C ordering for npy format

This appears to save and and load files correctly, but when
loading, it prints this message:

Warning, array does not have Fortran order,
making deep copy and fixing...
...done.

I'm looking into this...

Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>

--- tomviz/python/tomviz/io/formats/numpy.py
+++ tomviz/python/tomviz/io/formats/numpy.py
@@ -24,6 +24,10 @@

     def write(self, path, data_object):
         data = tomviz.utils.get_array(data_object)
+
+        # Switch to row major order for NPY stores
+        data = data.reshape(data.shape[::-1])
+
         with open(path, "wb") as f:
             np.save(f, data)

@@ -37,6 +41,9 @@
         if len(data.shape) != 3:
             return vtkImageData()

+        # NPY stores data as row major order. VTK expects column major order.
+        data = data.reshape(data.shape[::-1])
+
         image_data = vtkImageData()
         (x, y, z) = data.shape

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

###############################################################################
# This source file is part of the Tomviz project, https://tomviz.org/.
# It is released under the 3-Clause BSD License, see "LICENSE".
###############################################################################
import numpy as np

from tomviz.io import FileType, IOBase, Reader, Writer

import tomviz.utils

from vtk import vtkImageData

class NumpyBase(IOBase):

    @staticmethod
    def file_type():
        return FileType('NumPy binary format', ['npy'])

class NumpyWriter(Writer, NumpyBase):

    def write(self, path, data_object):
        data = tomviz.utils.get_array(data_object)
        with open(path, "wb") as f:
            np.save(f, data)

class NumpyReader(Reader, NumpyBase):

    def read(self, path):
        with open(path, "rb") as f:
            data = np.load(f)

        if len(data.shape) != 3:
            return vtkImageData()

        image_data = vtkImageData()
        (x, y, z) = data.shape

        image_data.SetOrigin(0, 0, 0)
        image_data.SetSpacing(1, 1, 1)
        image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1)
        tomviz.utils.set_array(image_data, data)

        return image_data

<|edits_diff|>
--- tomviz/python/tomviz/io/formats/numpy.py
+++ tomviz/python/tomviz/io/formats/numpy.py
@@ -24,6 +24,10 @@

     def write(self, path, data_object):
         data = tomviz.utils.get_array(data_object)
+
+        # Switch to row major order for NPY stores
+        data = data.reshape(data.shape[::-1])
+
         with open(path, "wb") as f:
             np.save(f, data)

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

###############################################################################
# This source file is part of the Tomviz project, https://tomviz.org/.
# It is released under the 3-Clause BSD License, see "LICENSE".
###############################################################################
import numpy as np

from tomviz.io import FileType, IOBase, Reader, Writer

import tomviz.utils

from vtk import vtkImageData

class NumpyBase(IOBase):

    @staticmethod
    def file_type():
        return FileType('NumPy binary format', ['npy'])

class NumpyWriter(Writer, NumpyBase):

    def write(self, path, data_object):
        data = tomviz.utils.get_array(data_object)

        # Switch to row major order for NPY stores
        data = data.reshape(data.shape[::-1])

        with open(path, "wb") as f:
            np.save(f, data)

class NumpyReader(Reader, NumpyBase):

    def read(self, path):
        with open(path, "rb") as f:
            data = np.load(f)

        if len(data.shape) != 3:
            return vtkImageData()

        image_data = vtkImageData()
        (x, y, z) = data.shape

        image_data.SetOrigin(0, 0, 0)
        image_data.SetSpacing(1, 1, 1)
        image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1)
        tomviz.utils.set_array(image_data, data)

        return image_data

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

###############################################################################
# This source file is part of the Tomviz project, https://tomviz.org/.
# It is released under the 3-Clause BSD License, see "LICENSE".
###############################################################################
import numpy as np

from tomviz.io import FileType, IOBase, Reader, Writer

import tomviz.utils

from vtk import vtkImageData

class NumpyBase(IOBase):

    @staticmethod
    def file_type():
        return FileType('NumPy binary format', ['npy'])

class NumpyWriter(Writer, NumpyBase):

    def write(self, path, data_object):
        data = tomviz.utils.get_array(data_object)

        # Switch to row major order for NPY stores
        data = data.reshape(data.shape[::-1])

        with open(path, "wb") as f:
            np.save(f, data)

class NumpyReader(Reader, NumpyBase):

    def read(self, path):
        with open(path, "rb") as f:
            data = np.load(f)

        if len(data.shape) != 3:
            return vtkImageData()

        # NPY stores data as row major order. VTK expects column major order.
        data = data.reshape(data.shape[::-1])

        image_data = vtkImageData()
        (x, y, z) = data.shape

        image_data.SetOrigin(0, 0, 0)
        image_data.SetSpacing(1, 1, 1)
        image_data.SetExtent(0, x - 1, 0, y - 1, 0, z - 1)
        tomviz.utils.set_array(image_data, data)

        return image_data


Update schoalrsbank to grab second description if there are two

--- scrapi/harvesters/scholarsbank.py
+++ scrapi/harvesters/scholarsbank.py
@@ -8,7 +8,12 @@
 from __future__ import unicode_literals

 from scrapi.base import OAIHarvester
+from scrapi.base.schemas import OAISCHEMA
 from scrapi.base.helpers import updated_schema
+
+
+def second_result(des):
+    return des[1] if len(des) > 1 else des[0] if des else ''

 class ScholarsbankHarvester(OAIHarvester):
@@ -22,3 +27,7 @@
         'type', 'source', 'format', 'relation',
         'date', 'description', 'setSpec', 'identifier'
     ]
+
+    schema = updated_schema(OAISCHEMA, {
+        'description': ('//dc:description/node()', second_result)
+    })

<|original_code|>
"""
Harvester for Scholars Bank University of Oregon for the SHARE project

Example API call: http://scholarsbank.uoregon.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc
"""

from __future__ import unicode_literals

from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema

class ScholarsbankHarvester(OAIHarvester):
    short_name = 'scholarsbank'
    long_name = 'Scholars Bank University of Oregon'
    url = 'http://scholarsbank.uoregon.edu'
    timezone_granularity = True

    base_url = 'http://scholarsbank.uoregon.edu/oai/request'
    property_list = [
        'type', 'source', 'format', 'relation',
        'date', 'description', 'setSpec', 'identifier'
    ]

<|edits_diff|>
--- scrapi/harvesters/scholarsbank.py
+++ scrapi/harvesters/scholarsbank.py
@@ -8,7 +8,12 @@
 from __future__ import unicode_literals

 from scrapi.base import OAIHarvester
+from scrapi.base.schemas import OAISCHEMA
 from scrapi.base.helpers import updated_schema
+
+
+def second_result(des):
+    return des[1] if len(des) > 1 else des[0] if des else ''

 class ScholarsbankHarvester(OAIHarvester):
<|current_version|>
"""
Harvester for Scholars Bank University of Oregon for the SHARE project

Example API call: http://scholarsbank.uoregon.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc
"""

from __future__ import unicode_literals

from scrapi.base import OAIHarvester
from scrapi.base.schemas import OAISCHEMA
from scrapi.base.helpers import updated_schema

def second_result(des):
    return des[1] if len(des) > 1 else des[0] if des else ''

class ScholarsbankHarvester(OAIHarvester):
    short_name = 'scholarsbank'
    long_name = 'Scholars Bank University of Oregon'
    url = 'http://scholarsbank.uoregon.edu'
    timezone_granularity = True

    base_url = 'http://scholarsbank.uoregon.edu/oai/request'
    property_list = [
        'type', 'source', 'format', 'relation',
        'date', 'description', 'setSpec', 'identifier'
    ]

<|next_version|>
"""
Harvester for Scholars Bank University of Oregon for the SHARE project

Example API call: http://scholarsbank.uoregon.edu/oai/request?verb=ListRecords&metadataPrefix=oai_dc
"""

from __future__ import unicode_literals

from scrapi.base import OAIHarvester
from scrapi.base.schemas import OAISCHEMA
from scrapi.base.helpers import updated_schema

def second_result(des):
    return des[1] if len(des) > 1 else des[0] if des else ''

class ScholarsbankHarvester(OAIHarvester):
    short_name = 'scholarsbank'
    long_name = 'Scholars Bank University of Oregon'
    url = 'http://scholarsbank.uoregon.edu'
    timezone_granularity = True

    base_url = 'http://scholarsbank.uoregon.edu/oai/request'
    property_list = [
        'type', 'source', 'format', 'relation',
        'date', 'description', 'setSpec', 'identifier'
    ]

    schema = updated_schema(OAISCHEMA, {
        'description': ('//dc:description/node()', second_result)
    })


Add sphinx autosection label plugin.

Add sphinx autosection label plugin.

--- docs/conf.py
+++ docs/conf.py
@@ -14,7 +14,9 @@
     # Official
     'sphinx.ext.autodoc',
     'sphinx.ext.napoleon',
+    'sphinx.ext.autosectionlabel',
 ]
+autosectionlabel_prefix_document = True

 extensions.append('guzzle_sphinx_theme')

<|original_code|>
from datetime import date

import guzzle_sphinx_theme

from pyinfra import __version__

copyright = 'Nick Barrett {0} — pyinfra v{1}'.format(
    date.today().year,
    __version__,
)

extensions = [
    # Official
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
]

extensions.append('guzzle_sphinx_theme')

source_suffix = ['.rst', '.md']
source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}

master_doc = 'index'
project = 'pyinfra'
author = 'Fizzadar'
version = 'develop'
pygments_style = 'sphinx'

# Theme style override
html_short_title = 'Home'
html_theme = 'guzzle_sphinx_theme'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_static_path = ['static']

templates_path = ['templates']

html_favicon = 'static/logo_small.png'

html_sidebars = {
    '**': ['pyinfra_sidebar.html', 'searchbox.html'],
}

<|edits_diff|>
--- docs/conf.py
+++ docs/conf.py
@@ -14,6 +14,7 @@
     # Official
     'sphinx.ext.autodoc',
     'sphinx.ext.napoleon',
+    'sphinx.ext.autosectionlabel',
 ]

 extensions.append('guzzle_sphinx_theme')
<|current_version|>
from datetime import date

import guzzle_sphinx_theme

from pyinfra import __version__

copyright = 'Nick Barrett {0} — pyinfra v{1}'.format(
    date.today().year,
    __version__,
)

extensions = [
    # Official
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx.ext.autosectionlabel',
]

extensions.append('guzzle_sphinx_theme')

source_suffix = ['.rst', '.md']
source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}

master_doc = 'index'
project = 'pyinfra'
author = 'Fizzadar'
version = 'develop'
pygments_style = 'sphinx'

# Theme style override
html_short_title = 'Home'
html_theme = 'guzzle_sphinx_theme'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_static_path = ['static']

templates_path = ['templates']

html_favicon = 'static/logo_small.png'

html_sidebars = {
    '**': ['pyinfra_sidebar.html', 'searchbox.html'],
}

<|next_version|>
from datetime import date

import guzzle_sphinx_theme

from pyinfra import __version__

copyright = 'Nick Barrett {0} — pyinfra v{1}'.format(
    date.today().year,
    __version__,
)

extensions = [
    # Official
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx.ext.autosectionlabel',
]
autosectionlabel_prefix_document = True

extensions.append('guzzle_sphinx_theme')

source_suffix = ['.rst', '.md']
source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}

master_doc = 'index'
project = 'pyinfra'
author = 'Fizzadar'
version = 'develop'
pygments_style = 'sphinx'

# Theme style override
html_short_title = 'Home'
html_theme = 'guzzle_sphinx_theme'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_static_path = ['static']

templates_path = ['templates']

html_favicon = 'static/logo_small.png'

html_sidebars = {
    '**': ['pyinfra_sidebar.html', 'searchbox.html'],
}


Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17

--- app/__init__.py
+++ app/__init__.py
@@ -1,9 +1,12 @@
+from werkzeug.contrib.fixers import ProxyFix
 from flask import Flask
 from flask.ext.login import LoginManager
 from flask.ext.sqlalchemy import SQLAlchemy

 app = Flask(__name__)
 app.config.from_object('config')
+app.wsgi_app = ProxyFix(app.wsgi_app)
+
 login_manager = LoginManager()
 login_manager.init_app(app)
 db = SQLAlchemy(app)

<|original_code|>
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlchemy(app)

from app import views, models
<|edits_diff|>
--- app/__init__.py
+++ app/__init__.py
@@ -1,3 +1,4 @@
+from werkzeug.contrib.fixers import ProxyFix
 from flask import Flask
 from flask.ext.login import LoginManager
 from flask.ext.sqlalchemy import SQLAlchemy
<|current_version|>
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlchemy(app)

from app import views, models

<|next_version|>
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
app.wsgi_app = ProxyFix(app.wsgi_app)

login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlchemy(app)

from app import views, models


Add a property to an exception class

Add a property to an exception class

--- subprocrunner/error.py
+++ subprocrunner/error.py
@@ -9,10 +9,15 @@

 class CommandError(Exception):
     @property
+    def cmd(self):
+        return self.__cmd
+
+    @property
     def errno(self):
         return self.__errno

     def __init__(self, *args, **kwargs):
+        self.__cmd = kwargs.pop("cmd", None)
         self.__errno = kwargs.pop("errno", None)

         super(CommandError, self).__init__(*args, **kwargs)

<|original_code|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import, unicode_literals

class CommandError(Exception):
    @property
    def errno(self):
        return self.__errno

    def __init__(self, *args, **kwargs):
        self.__errno = kwargs.pop("errno", None)

        super(CommandError, self).__init__(*args, **kwargs)

class InvalidCommandError(CommandError):
    # Deprecate in the future
    pass

class CommandNotFoundError(CommandError):
    # Deprecate in the future
    pass

<|edits_diff|>
--- subprocrunner/error.py
+++ subprocrunner/error.py
@@ -8,6 +8,10 @@

 class CommandError(Exception):
+    @property
+    def cmd(self):
+        return self.__cmd
+
     @property
     def errno(self):
         return self.__errno
<|current_version|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import, unicode_literals

class CommandError(Exception):
    @property
    def cmd(self):
        return self.__cmd

    @property
    def errno(self):
        return self.__errno

    def __init__(self, *args, **kwargs):
        self.__errno = kwargs.pop("errno", None)

        super(CommandError, self).__init__(*args, **kwargs)

class InvalidCommandError(CommandError):
    # Deprecate in the future
    pass

class CommandNotFoundError(CommandError):
    # Deprecate in the future
    pass

<|next_version|>
# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from __future__ import absolute_import, unicode_literals

class CommandError(Exception):
    @property
    def cmd(self):
        return self.__cmd

    @property
    def errno(self):
        return self.__errno

    def __init__(self, *args, **kwargs):
        self.__cmd = kwargs.pop("cmd", None)
        self.__errno = kwargs.pop("errno", None)

        super(CommandError, self).__init__(*args, **kwargs)

class InvalidCommandError(CommandError):
    # Deprecate in the future
    pass

class CommandNotFoundError(CommandError):
    # Deprecate in the future
    pass


Fix tests on Django 1.8.

Fix tests on Django 1.8.

--- tests/test_settings.py
+++ tests/test_settings.py
@@ -1,3 +1,5 @@
+import django
+
 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
@@ -19,6 +21,9 @@
     'django.contrib.auth.middleware.AuthenticationMiddleware',
 ]

+if django.VERSION < (1, 10):
+    MIDDLEWARE_CLASSES = MIDDLEWARE
+
 USE_TZ = True

 ROOT_URLCONF = 'tests.urls'

<|original_code|>
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'csv_export',
    'tests',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
]

USE_TZ = True

ROOT_URLCONF = 'tests.urls'

<|edits_diff|>
--- tests/test_settings.py
+++ tests/test_settings.py
@@ -1,3 +1,5 @@
+import django
+
 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3',
<|current_version|>
import django

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'csv_export',
    'tests',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
]

USE_TZ = True

ROOT_URLCONF = 'tests.urls'

<|next_version|>
import django

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'csv_export',
    'tests',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
]

if django.VERSION < (1, 10):
    MIDDLEWARE_CLASSES = MIDDLEWARE

USE_TZ = True

ROOT_URLCONF = 'tests.urls'


from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob

register = template.Library()

@register.filter
def get_priority_select(current):
    select = ""
    val = TestJob.PRIORITY_CHOICES
    for priority, label in val:
        check = " checked" if priority == current else ""
        default = " [default]" if current != 50 and priority == 50 else ""
        select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
                  (label.lower(), priority, check, label, default)
    return mark_safe(select)

Use inline radio buttons for priority changes.

Change-Id: Ifb9a685bca654c5139aef3ca78e800b66ce77eb9

--- lava_scheduler_app/templatetags/utils.py
+++ lava_scheduler_app/templatetags/utils.py
@@ -12,6 +12,8 @@
     for priority, label in val:
         check = " checked" if priority == current else ""
         default = " [default]" if current != 50 and priority == 50 else ""
+        select += ''
         select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input>
' %\
                   (label.lower(), priority, check, label, default)
+        select += ''
     return mark_safe(select)

from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob

register = template.Library()

@register.filter
def get_priority_select(current):
    select = ""
    val = TestJob.PRIORITY_CHOICES
    for priority, label in val:
        check = " checked" if priority == current else ""
        default = " [default]" if current != 50 and priority == 50 else ""
        select += '<label class="checkbox-inline">'
        select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
                  (label.lower(), priority, check, label, default)
    return mark_safe(select)

<|original_code|>
from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob

register = template.Library()

@register.filter
def get_priority_select(current):
    select = ""
    val = TestJob.PRIORITY_CHOICES
    for priority, label in val:
        check = " checked" if priority == current else ""
        default = " [default]" if current != 50 and priority == 50 else ""
        select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input>
' %\
                  (label.lower(), priority, check, label, default)
    return mark_safe(select)

<|edits_diff|>
--- lava_scheduler_app/templatetags/utils.py
+++ lava_scheduler_app/templatetags/utils.py
@@ -12,6 +12,7 @@
     for priority, label in val:
         check = " checked" if priority == current else ""
         default = " [default]" if current != 50 and priority == 50 else ""
+        select += ''
         select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input>
' %\
                   (label.lower(), priority, check, label, default)
     return mark_safe(select)
<|current_version|>
from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob

register = template.Library()

@register.filter
def get_priority_select(current):
    select = ""
    val = TestJob.PRIORITY_CHOICES
    for priority, label in val:
        check = " checked" if priority == current else ""
        default = " [default]" if current != 50 and priority == 50 else ""
        select += ''
        select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input>
' %\
                  (label.lower(), priority, check, label, default)
    return mark_safe(select)

<|next_version|>
from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob

register = template.Library()

@register.filter
def get_priority_select(current):
    select = ""
    val = TestJob.PRIORITY_CHOICES
    for priority, label in val:
        check = " checked" if priority == current else ""
        default = " [default]" if current != 50 and priority == 50 else ""
        select += ''
        select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input>
' %\
                  (label.lower(), priority, check, label, default)
        select += ''
    return mark_safe(select)


Establish basic JSON API capability.

Establish basic JSON API capability.

--- badgecheck/server/app.py
+++ badgecheck/server/app.py
@@ -9,9 +9,19 @@
 app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024  # 4mb file upload limit

+def request_wants_json():
+    best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
+    return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']
+
+
 @app.route("/")
 def home():
     return render_template('index.html')
+
+
+@app.route("/results", methods=['GET'])
+def resultGetRedirect():
+    return redirect('/')

 @app.route("/results", methods=['POST'])
@@ -21,6 +31,9 @@
         if 'image' in request.files and len(request.files['image'].filename):
             user_input = request.files['image']
         verification_results = verify(user_input)
+
+        if request_wants_json():
+            return (json.dumps(verification_results, indent=4), 200, {'Content-Type': 'application/json'},)
         return render_template(
             'results.html', results=json.dumps(verification_results, indent=4))

<|original_code|>
from flask import Flask, redirect, render_template, request
import json
import six

from badgecheck.verifier import verify

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024  # 4mb file upload limit

@app.route("/")
def home():
    return render_template('index.html')

@app.route("/results", methods=['POST'])
def results():
    if isinstance(request.form['data'], six.string_types) or request.files:
        user_input = request.form['data']
        if 'image' in request.files and len(request.files['image'].filename):
            user_input = request.files['image']
        verification_results = verify(user_input)
        return render_template(
            'results.html', results=json.dumps(verification_results, indent=4))

    return redirect('/')

if __name__ == "__main__":
    app.run()

<|edits_diff|>
--- badgecheck/server/app.py
+++ badgecheck/server/app.py
@@ -9,9 +9,19 @@
 app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024  # 4mb file upload limit

+def request_wants_json():
+    best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
+    return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']
+
+
 @app.route("/")
 def home():
     return render_template('index.html')
+
+
+@app.route("/results", methods=['GET'])
+def resultGetRedirect():
+    return redirect('/')

 @app.route("/results", methods=['POST'])
<|current_version|>
from flask import Flask, redirect, render_template, request
import json
import six

from badgecheck.verifier import verify

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024  # 4mb file upload limit

def request_wants_json():
    best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
    return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']

@app.route("/")
def home():
    return render_template('index.html')

@app.route("/results", methods=['GET'])
def resultGetRedirect():
    return redirect('/')

@app.route("/results", methods=['POST'])
def results():
    if isinstance(request.form['data'], six.string_types) or request.files:
        user_input = request.form['data']
        if 'image' in request.files and len(request.files['image'].filename):
            user_input = request.files['image']
        verification_results = verify(user_input)
        return render_template(
            'results.html', results=json.dumps(verification_results, indent=4))

    return redirect('/')

if __name__ == "__main__":
    app.run()

<|next_version|>
from flask import Flask, redirect, render_template, request
import json
import six

from badgecheck.verifier import verify

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024  # 4mb file upload limit

def request_wants_json():
    best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
    return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']

@app.route("/")
def home():
    return render_template('index.html')

@app.route("/results", methods=['GET'])
def resultGetRedirect():
    return redirect('/')

@app.route("/results", methods=['POST'])
def results():
    if isinstance(request.form['data'], six.string_types) or request.files:
        user_input = request.form['data']
        if 'image' in request.files and len(request.files['image'].filename):
            user_input = request.files['image']
        verification_results = verify(user_input)

        if request_wants_json():
            return (json.dumps(verification_results, indent=4), 200, {'Content-Type': 'application/json'},)
        return render_template(
            'results.html', results=json.dumps(verification_results, indent=4))

    return redirect('/')

if __name__ == "__main__":
    app.run()


Support multi-db for user creation signal

--- src/sentry/receivers/users.py
+++ src/sentry/receivers/users.py
@@ -1,5 +1,6 @@
 from __future__ import absolute_import, print_function

+from django.db import router
 from django.db.models.signals import post_syncdb

 from sentry.models import User
@@ -7,6 +8,8 @@

 def create_first_user(app, created_models, verbosity, db, **kwargs):
     if User not in created_models:
+        return
+    if not router.allow_syncdb(db, User):
         return
     if not kwargs.get('interactive', True):
         return

<|original_code|>
from __future__ import absolute_import, print_function

from django.db.models.signals import post_syncdb

from sentry.models import User

def create_first_user(app, created_models, verbosity, db, **kwargs):
    if User not in created_models:
        return
    if not kwargs.get('interactive', True):
        return

    import click
    if not click.confirm('\nWould you like to create a user account now?', default=True):
        # Not using `abort=1` because we don't want to exit out from further execution
        click.echo('\nRun `sentry createuser` to do this later.\n')
        return

    from sentry.runner import call_command
    call_command('sentry.runner.commands.createuser.createuser')

post_syncdb.connect(
    create_first_user,
    dispatch_uid="create_first_user",
    weak=False,
)

<|edits_diff|>
--- src/sentry/receivers/users.py
+++ src/sentry/receivers/users.py
@@ -1,5 +1,6 @@
 from __future__ import absolute_import, print_function

+from django.db import router
 from django.db.models.signals import post_syncdb

 from sentry.models import User
<|current_version|>
from __future__ import absolute_import, print_function

from django.db import router
from django.db.models.signals import post_syncdb

from sentry.models import User

def create_first_user(app, created_models, verbosity, db, **kwargs):
    if User not in created_models:
        return
    if not kwargs.get('interactive', True):
        return

    import click
    if not click.confirm('\nWould you like to create a user account now?', default=True):
        # Not using `abort=1` because we don't want to exit out from further execution
        click.echo('\nRun `sentry createuser` to do this later.\n')
        return

    from sentry.runner import call_command
    call_command('sentry.runner.commands.createuser.createuser')

post_syncdb.connect(
    create_first_user,
    dispatch_uid="create_first_user",
    weak=False,
)

<|next_version|>
from __future__ import absolute_import, print_function

from django.db import router
from django.db.models.signals import post_syncdb

from sentry.models import User

def create_first_user(app, created_models, verbosity, db, **kwargs):
    if User not in created_models:
        return
    if not router.allow_syncdb(db, User):
        return
    if not kwargs.get('interactive', True):
        return

    import click
    if not click.confirm('\nWould you like to create a user account now?', default=True):
        # Not using `abort=1` because we don't want to exit out from further execution
        click.echo('\nRun `sentry createuser` to do this later.\n')
        return

    from sentry.runner import call_command
    call_command('sentry.runner.commands.createuser.createuser')

post_syncdb.connect(
    create_first_user,
    dispatch_uid="create_first_user",
    weak=False,
)


Add maintainer and download URL

Add maintainer and download URL

--- setup.py
+++ setup.py
@@ -11,7 +11,10 @@
     description='Email Tracker for Django',
     author='Venelina Yanakieva',
     author_email='vili@magicsolutions.bg',
+    maintainer='Venelin Stoykov',
+    maintainer_email='venelin@magicsolutions.bg',
     url='https://github.com/MagicSolutions/django-email-tracker',
+    download_url='https://github.com/MagicSolutions/django-email-tracker/releases',
     long_description=get_long_description(),
     packages=find_packages(),
     zip_safe=False,

<|original_code|>
from setuptools import setup, find_packages

def get_long_description():
    with open('./README.rst', 'r') as readme:
        return readme.read()

setup(
    name='django-email-tracker',
    version='0.2',
    description='Email Tracker for Django',
    author='Venelina Yanakieva',
    author_email='vili@magicsolutions.bg',
    url='https://github.com/MagicSolutions/django-email-tracker',
    long_description=get_long_description(),
    packages=find_packages(),
    zip_safe=False,
    install_requires=['django>=1.4'],
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ]
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -11,6 +11,8 @@
     description='Email Tracker for Django',
     author='Venelina Yanakieva',
     author_email='vili@magicsolutions.bg',
+    maintainer='Venelin Stoykov',
+    maintainer_email='venelin@magicsolutions.bg',
     url='https://github.com/MagicSolutions/django-email-tracker',
     long_description=get_long_description(),
     packages=find_packages(),
<|current_version|>
from setuptools import setup, find_packages

def get_long_description():
    with open('./README.rst', 'r') as readme:
        return readme.read()

setup(
    name='django-email-tracker',
    version='0.2',
    description='Email Tracker for Django',
    author='Venelina Yanakieva',
    author_email='vili@magicsolutions.bg',
    maintainer='Venelin Stoykov',
    maintainer_email='venelin@magicsolutions.bg',
    url='https://github.com/MagicSolutions/django-email-tracker',
    long_description=get_long_description(),
    packages=find_packages(),
    zip_safe=False,
    install_requires=['django>=1.4'],
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ]
)

<|next_version|>
from setuptools import setup, find_packages

def get_long_description():
    with open('./README.rst', 'r') as readme:
        return readme.read()

setup(
    name='django-email-tracker',
    version='0.2',
    description='Email Tracker for Django',
    author='Venelina Yanakieva',
    author_email='vili@magicsolutions.bg',
    maintainer='Venelin Stoykov',
    maintainer_email='venelin@magicsolutions.bg',
    url='https://github.com/MagicSolutions/django-email-tracker',
    download_url='https://github.com/MagicSolutions/django-email-tracker/releases',
    long_description=get_long_description(),
    packages=find_packages(),
    zip_safe=False,
    install_requires=['django>=1.4'],
    include_package_data=True,
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ]
)


Update email_id cache when user has registered

--- seahub/profile/models.py
+++ seahub/profile/models.py
@@ -1,7 +1,17 @@
 from django.db import models
+from django.core.cache import cache
+from django.dispatch import receiver
+
+from settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT
+from registration.signals import user_registered

 class Profile(models.Model):
     user = models.EmailField(unique=True)
     nickname = models.CharField(max_length=64, blank=True)
     intro = models.TextField(max_length=256, blank=True)

+
+@receiver(user_registered)
+def clean_email_id_cache(sender, **kwargs):
+    user = kwargs['user']
+    cache.set(EMAIL_ID_CACHE_PREFIX+user.email, user.id, EMAIL_ID_CACHE_TIMEOUT)

<|original_code|>
from django.db import models

class Profile(models.Model):
    user = models.EmailField(unique=True)
    nickname = models.CharField(max_length=64, blank=True)
    intro = models.TextField(max_length=256, blank=True)

<|edits_diff|>
--- seahub/profile/models.py
+++ seahub/profile/models.py
@@ -1,4 +1,9 @@
 from django.db import models
+from django.core.cache import cache
+from django.dispatch import receiver
+
+from settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT
+from registration.signals import user_registered

 class Profile(models.Model):
     user = models.EmailField(unique=True)
<|current_version|>
from django.db import models
from django.core.cache import cache
from django.dispatch import receiver

from settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT
from registration.signals import user_registered

class Profile(models.Model):
    user = models.EmailField(unique=True)
    nickname = models.CharField(max_length=64, blank=True)
    intro = models.TextField(max_length=256, blank=True)

<|next_version|>
from django.db import models
from django.core.cache import cache
from django.dispatch import receiver

from settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT
from registration.signals import user_registered

class Profile(models.Model):
    user = models.EmailField(unique=True)
    nickname = models.CharField(max_length=64, blank=True)
    intro = models.TextField(max_length=256, blank=True)

@receiver(user_registered)
def clean_email_id_cache(sender, **kwargs):
    user = kwargs['user']
    cache.set(EMAIL_ID_CACHE_PREFIX+user.email, user.id, EMAIL_ID_CACHE_TIMEOUT)


Disable failing testSmoke on cros.

Disable failing testSmoke on cros.

BUG=386416
TEST=bots

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

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@280661 0039d316-1c4b-4281-b951-d872f2087c98

--- tools/perf/page_sets/page_set_unittest.py
+++ tools/perf/page_sets/page_set_unittest.py
@@ -4,11 +4,14 @@

 import os

+from telemetry import decorators
 from telemetry.unittest import page_set_smoke_test

 class PageSetUnitTest(page_set_smoke_test.PageSetSmokeTest):

+  # TODO(tbarzic): crbug.com/386416.
+  @decorators.Disabled('chromeos')
   def testSmoke(self):
     page_sets_dir = os.path.dirname(os.path.realpath(__file__))
     top_level_dir = os.path.dirname(page_sets_dir)

<|original_code|>
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os

from telemetry.unittest import page_set_smoke_test

class PageSetUnitTest(page_set_smoke_test.PageSetSmokeTest):

  def testSmoke(self):
    page_sets_dir = os.path.dirname(os.path.realpath(__file__))
    top_level_dir = os.path.dirname(page_sets_dir)
    self.RunSmokeTest(page_sets_dir, top_level_dir)

<|edits_diff|>
--- tools/perf/page_sets/page_set_unittest.py
+++ tools/perf/page_sets/page_set_unittest.py
@@ -4,6 +4,7 @@

 import os

+from telemetry import decorators
 from telemetry.unittest import page_set_smoke_test

<|current_version|>
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os

from telemetry import decorators
from telemetry.unittest import page_set_smoke_test

class PageSetUnitTest(page_set_smoke_test.PageSetSmokeTest):

  def testSmoke(self):
    page_sets_dir = os.path.dirname(os.path.realpath(__file__))
    top_level_dir = os.path.dirname(page_sets_dir)
    self.RunSmokeTest(page_sets_dir, top_level_dir)

<|next_version|>
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os

from telemetry import decorators
from telemetry.unittest import page_set_smoke_test

class PageSetUnitTest(page_set_smoke_test.PageSetSmokeTest):

  # TODO(tbarzic): crbug.com/386416.
  @decorators.Disabled('chromeos')
  def testSmoke(self):
    page_sets_dir = os.path.dirname(os.path.realpath(__file__))
    top_level_dir = os.path.dirname(page_sets_dir)
    self.RunSmokeTest(page_sets_dir, top_level_dir)


Add version number to chainer module

Add version number to chainer module

--- chainer/__init__.py
+++ chainer/__init__.py
@@ -1,8 +1,13 @@
+import pkg_resources
+
 from chainer import function
 from chainer import function_set
 from chainer.functions import basic_math
 from chainer import optimizer
 from chainer import variable
+
+
+__version__ = pkg_resources.get_distribution('chainer').version

 Variable = variable.Variable
 Function = function.Function

<|original_code|>
from chainer import function
from chainer import function_set
from chainer.functions import basic_math
from chainer import optimizer
from chainer import variable

Variable = variable.Variable
Function = function.Function
FunctionSet = function_set.FunctionSet
Optimizer = optimizer.Optimizer

basic_math.install_variable_arithmetics()

<|edits_diff|>
--- chainer/__init__.py
+++ chainer/__init__.py
@@ -1,3 +1,5 @@
+import pkg_resources
+
 from chainer import function
 from chainer import function_set
 from chainer.functions import basic_math
<|current_version|>
import pkg_resources

from chainer import function
from chainer import function_set
from chainer.functions import basic_math
from chainer import optimizer
from chainer import variable

Variable = variable.Variable
Function = function.Function
FunctionSet = function_set.FunctionSet
Optimizer = optimizer.Optimizer

basic_math.install_variable_arithmetics()

<|next_version|>
import pkg_resources

from chainer import function
from chainer import function_set
from chainer.functions import basic_math
from chainer import optimizer
from chainer import variable

__version__ = pkg_resources.get_distribution('chainer').version

Variable = variable.Variable
Function = function.Function
FunctionSet = function_set.FunctionSet
Optimizer = optimizer.Optimizer

basic_math.install_variable_arithmetics()


Add add function taking a functor as input to process connected primitives

--- evaluation/packages/relationGraph.py
+++ evaluation/packages/relationGraph.py
@@ -9,10 +9,12 @@
 class RelationGraph(object):
     def __init__(self,primArray, assignArray):
         self.G=nx.Graph()
+        self.indexedPrimArray = {}

         # First create the nodes
         for p in primArray:
             self.G.add_node(p.uid, w=0)
+            self.indexedPrimArray[p.uid] = p

         # Then their relations
         for idx1, p1 in enumerate(primArray):
@@ -30,6 +32,11 @@
         #print "Number of primitives:  ",self.G.number_of_nodes()
         #print "Number of connections: ",self.G.number_of_edges()

+    # Call the functor over the primitives connected by and edge
+    def processConnectedNodes(self, functor):
+        for e in self.G.edges():
+            functor( self.indexedPrimArray[e[0]], self.indexedPrimArray[e[1]])
+
     def draw(self):
         nx.draw_spectral(self.G)
         #nx.draw_networkx_labels(self.G,pos=nx.spectral_layout(self.G))

<|original_code|>
"""@package Primitive
This module provides an abstraction of the relationGraph using networkX

"""

import networkx as nx
import packages.primitive as primitive

class RelationGraph(object):
    def __init__(self,primArray, assignArray):
        self.G=nx.Graph()

        # First create the nodes
        for p in primArray:
            self.G.add_node(p.uid, w=0)

        # Then their relations
        for idx1, p1 in enumerate(primArray):
            for idx2, p2 in enumerate(primArray):
                if (idx2 > idx1):
                    self.G.add_edge(p1.uid, p2.uid)

        # And finaly the node weights (number of samples)
        # assignArray[][0] = point id
        # assignArray[][1] = primitive uid
        for a in assignArray:
            if a[1] in self.G.node:
                self.G.node[a[1]]['w'] += 1

        #print "Number of primitives:  ",self.G.number_of_nodes()
        #print "Number of connections: ",self.G.number_of_edges()

    def draw(self):
        nx.draw_spectral(self.G)
        #nx.draw_networkx_labels(self.G,pos=nx.spectral_layout(self.G))

<|edits_diff|>
--- evaluation/packages/relationGraph.py
+++ evaluation/packages/relationGraph.py
@@ -9,10 +9,12 @@
 class RelationGraph(object):
     def __init__(self,primArray, assignArray):
         self.G=nx.Graph()
+        self.indexedPrimArray = {}

         # First create the nodes
         for p in primArray:
             self.G.add_node(p.uid, w=0)
+            self.indexedPrimArray[p.uid] = p

         # Then their relations
         for idx1, p1 in enumerate(primArray):
<|current_version|>
"""@package Primitive
This module provides an abstraction of the relationGraph using networkX

"""

import networkx as nx
import packages.primitive as primitive

class RelationGraph(object):
    def __init__(self,primArray, assignArray):
        self.G=nx.Graph()
        self.indexedPrimArray = {}

        # First create the nodes
        for p in primArray:
            self.G.add_node(p.uid, w=0)
            self.indexedPrimArray[p.uid] = p

        # Then their relations
        for idx1, p1 in enumerate(primArray):
            for idx2, p2 in enumerate(primArray):
                if (idx2 > idx1):
                    self.G.add_edge(p1.uid, p2.uid)

        # And finaly the node weights (number of samples)
        # assignArray[][0] = point id
        # assignArray[][1] = primitive uid
        for a in assignArray:
            if a[1] in self.G.node:
                self.G.node[a[1]]['w'] += 1

        #print "Number of primitives:  ",self.G.number_of_nodes()
        #print "Number of connections: ",self.G.number_of_edges()

    def draw(self):
        nx.draw_spectral(self.G)
        #nx.draw_networkx_labels(self.G,pos=nx.spectral_layout(self.G))

<|next_version|>
"""@package Primitive
This module provides an abstraction of the relationGraph using networkX

"""

import networkx as nx
import packages.primitive as primitive

class RelationGraph(object):
    def __init__(self,primArray, assignArray):
        self.G=nx.Graph()
        self.indexedPrimArray = {}

        # First create the nodes
        for p in primArray:
            self.G.add_node(p.uid, w=0)
            self.indexedPrimArray[p.uid] = p

        # Then their relations
        for idx1, p1 in enumerate(primArray):
            for idx2, p2 in enumerate(primArray):
                if (idx2 > idx1):
                    self.G.add_edge(p1.uid, p2.uid)

        # And finaly the node weights (number of samples)
        # assignArray[][0] = point id
        # assignArray[][1] = primitive uid
        for a in assignArray:
            if a[1] in self.G.node:
                self.G.node[a[1]]['w'] += 1

        #print "Number of primitives:  ",self.G.number_of_nodes()
        #print "Number of connections: ",self.G.number_of_edges()

    # Call the functor over the primitives connected by and edge
    def processConnectedNodes(self, functor):
        for e in self.G.edges():
            functor( self.indexedPrimArray[e[0]], self.indexedPrimArray[e[1]])

    def draw(self):
        nx.draw_spectral(self.G)
        #nx.draw_networkx_labels(self.G,pos=nx.spectral_layout(self.G))