#!/usr/bin/env python2
from testlib import *

set_port("80")
set_server("us.bittoll.com")

def test_page_error():
    r = apicall("nonexistant", "hi")
    assert "error" in r
    assert r["error"] != ""
    assert int(r["error_code"]) == 0

def test_login(login):
    info = login
    assert 'username' in info
    assert 'secret' in info

def pytest_funcarg__login(request):
    info = register()
    assert 'username' in info
    assert 'secret' in info
    return info

def test_balance(login):
    info = balance(login['username'], login['secret'])
    assert 'balance' in info
    assert int(info["error_code"]) == 0

def test_request(login):
    info = request(login['username'], login['secret'], amount=1)
    assert 'payment' in info
    assert int(info["error_code"]) == 0

def test_mine(login):
    info = mine(login['username'], login['secret'])
    assert 'result' in info
    assert 'id' in info
    assert 'error' in info

#!/usr/bin/env python2
from testlib import *

set_port("80")
set_server("us.bittoll.com")

def test_page_error():
    r = apicall("nonexistant", "hi")
    assert "error" in r
    assert r["error"] != ""
    assert int(r["error_code"]) == 1

def test_login(login):
    info = login
    assert 'username' in info
    assert 'secret' in info

def pytest_funcarg__login(request):
    info = register()
    assert 'username' in info
    assert 'secret' in info
    return info

def test_balance(login):
    info = balance(login['username'], login['secret'])
    assert 'balance' in info
    assert int(info["error_code"]) == 0

def test_request(login):
    info = request(login['username'], login['secret'], amount=1)
    assert 'payment' in info
    assert int(info["error_code"]) == 0

def test_mine(login):
    info = mine(login['username'], login['secret'])
    assert 'result' in info
    assert 'id' in info
    assert 'error' in info

Fix error code on non existent page

Fix error code on non existent page


#!/usr/bin/env python
import argparse
from bioblend import galaxy
import json

def main():
    """
        This script uses bioblend to import .ga workflow files into a running instance of Galaxy
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
    parser.add_argument("-g", "--galaxy",
                        dest="galaxy_url",
                        help="Target Galaxy instance URL/IP address (required "
                             "if not defined in the tools list file)",)
    parser.add_argument("-a", "--apikey",
                        dest="api_key",
                        help="Galaxy admin user API key (required if not "
                             "defined in the tools list file)",)
    args = parser.parse_args()

    gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)

    import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid')
    existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
    if import_uuid not in existing_uuids:
        gi.workflows.import_workflow_from_local_path(args.workflow_path)

if __name__ == '__main__':
    main()

#!/usr/bin/env python
import argparse
from bioblend import galaxy
import json

def main():
    """
        This script uses bioblend to import .ga workflow files into a running instance of Galaxy
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--workflow_path", help='Path to workflow file')
    parser.add_argument("-g", "--galaxy",
                        dest="galaxy_url",
                        help="Target Galaxy instance URL/IP address (required "
                             "if not defined in the tools list file)",)
    parser.add_argument("-a", "--apikey",
                        dest="api_key",
                        help="Galaxy admin user API key (required if not "
                             "defined in the tools list file)",)
    args = parser.parse_args()

    gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key)

    with open(args.workflow_path, 'r') as wf_file:
        import_uuid = json.load(wf_file).get('uuid')
    existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()]
    if import_uuid not in existing_uuids:
        gi.workflows.import_workflow_from_local_path(args.workflow_path)

if __name__ == '__main__':
    main()

Make sure the opened workflow file gets closed after it's been loaded


from firecares.settings.base import *

INSTALLED_APPS = (
    'django_statsd',
) + INSTALLED_APPS

STATSD_HOST = 'stats.garnertb.com'
STATSD_PREFIX = 'firecares'

STATSD_PATCHES = [
    'django_statsd.patches.db',
    'django_statsd.patches.cache',
]

MIDDLEWARE_CLASSES = (
    'django_statsd.middleware.GraphiteRequestTimingMiddleware',
    'django_statsd.middleware.GraphiteMiddleware',
    'django_statsd.middleware.TastyPieRequestTimingMiddleware'
) + MIDDLEWARE_CLASSES

STATSD_PATCHES = [
        'django_statsd.patches.db',
        'django_statsd.patches.cache',
]

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

AWS_STORAGE_BUCKET_NAME = 'firecares-static'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = "https://s3.amazonaws.com/firecares-static/"
COMPRESS_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATICFILES_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATIC_URL = COMPRESS_URL
DEBUG = False

try:
    from local_settings import *  # noqa
except ImportError:
    pass

from firecares.settings.base import *

INSTALLED_APPS = (
    'django_statsd',
) + INSTALLED_APPS

STATSD_HOST = 'stats.garnertb.com'
STATSD_PREFIX = 'firecares'

STATSD_PATCHES = [
    'django_statsd.patches.db',
    'django_statsd.patches.cache',
]

MIDDLEWARE_CLASSES = (
    'django_statsd.middleware.GraphiteRequestTimingMiddleware',
    'django_statsd.middleware.GraphiteMiddleware',
    'django_statsd.middleware.TastyPieRequestTimingMiddleware'
) + MIDDLEWARE_CLASSES

STATSD_PATCHES = [
        'django_statsd.patches.db',
        'django_statsd.patches.cache',
]

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

AWS_STORAGE_BUCKET_NAME = 'firecares-static'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = "https://s3.amazonaws.com/firecares-static/"
COMPRESS_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATICFILES_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATIC_URL = COMPRESS_URL
DEBUG = False
AWS_QUERYSTRING_AUTH = False

try:
    from local_settings import *  # noqa
except ImportError:
    pass

Disable query string auth for django compressor.


import gi
import time

gi.require_version('Unity', '7.0')
from gi.repository import Unity, GObject

def update_counter(count):
    launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop")
    launcher.set_property("count", count)
    launcher.set_property("count_visible", True)

import gi

gi.require_version('Unity', '7.0')
from gi.repository import Unity

def update_counter(count):
    launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop")
    launcher.set_property("count", count)
    launcher.set_property("count_visible", True)

Remove unnecessary imports for Unity module


import unittest

from storage.api import getByID
from hecuba.hdict import StorageDict

class ApiTestSDict(StorageDict):
    '''
    @TypeSpec <<key:int>, value:double>
    '''

class StorageApi_Tests(unittest.TestCase):
    def setUp(self):
        pass

    def class_type_test(self):
        base_dict = ApiTestSDict('test.api_sdict')
        storage_id = base_dict.getID()
        del base_dict

        rebuild_dict = getByID(storage_id)
        self.assertTrue(isinstance(rebuild_dict, ApiTestSDict))

import unittest

from storage.api import getByID
from hecuba import config, StorageDict

class ApiTestSDict(StorageDict):
    '''
    @TypeSpec <<key:int>, value:double>
    '''

class StorageApi_Tests(unittest.TestCase):
    def setUp(self):
        config.reset(mock_cassandra=False)

    def class_type_test(self):
        base_dict = ApiTestSDict('test.api_sdict')
        storage_id = base_dict.getID()
        del base_dict

        rebuild_dict = getByID(storage_id)
        self.assertTrue(isinstance(rebuild_dict, ApiTestSDict))

Reset Hecuba config when setUp a test

Reset Hecuba config when setUp a test


#!/usr/bin/python

import os.path
import re
import subprocess
import sys

### CONFIGURE THESE PATHS ###
binaryPath = "/home/opensim/opensim/opensim-current/bin"
pidPath = "/tmp/OpenSim.pid"
### END OF CONFIG ###

if os.path.exists(pidPath):
  print >> sys.stderr, "ERROR: OpenSim PID file %s still present.  Assuming OpenSim has been started already." % pidPath
  sys.exit(1)

# If PID isn't set then we'll check the screen list.
# However, this is a much less perfect mechanism since OpenSimulator may have been started outside screen
screenList = ""

try:
  screenList = subprocess.check_output("screen -list", shell=True)
except:
  None

if re.match("\s+\d+\.OpenSim", screenList):
  print >> sys.stderr, "ERROR: Screen session for OpenSim already started."
  sys.exit(1)

#!/usr/bin/python

import os.path
import re
import subprocess
import sys

### CONFIGURE THESE PATHS ###
binaryPath = "/home/opensim/opensim/opensim-current/bin"
pidPath = "/tmp/OpenSim.pid"
### END OF CONFIG ###

### FUNCTIONS ###
def execCmd(cmd):
  print "Executing command: %s" % cmd
  return subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)

### SCRIPT ###
if os.path.exists(pidPath):
  print >> sys.stderr, "ERROR: OpenSim PID file %s still present.  Assuming OpenSim has been started already." % pidPath
  sys.exit(1)

# If PID isn't set then we'll check the screen list.
# However, this is a much less perfect mechanism since OpenSimulator may have been started outside screen
screenList = ""

try:
  screenList = execCmd("screen -list")
except:
  None

if re.match("\s+\d+\.OpenSim", screenList):
  print >> sys.stderr, "ERROR: Screen session for OpenSim already started."
  sys.exit(1)

os.chdir(binaryPath)

Create execCmd function and use

Create execCmd function and use


#! /usr/bin/env python
"""
Aragog Router Decorator
-----------------------

Convert any function into a WSGI endpoint with a simple decorator.
"""

from aragog.wsgi import get_url
from aragog.routing.client_error import HTTP404

class Router(object):
    """
    Router holds the mapping of routes to callables.
    """

    def __init__(self):
        """
        Instance level route mapping
        """
        self.mapping = {}

    def __call__(self, environ, start_response):
        """
        Get a WSGI request, and pass it on to the correct callable.
        """
        routing = self.mapping.get(get_url(environ), HTTP404())
        return routing(environ, start_response)

    def add_route(self, url, func):
        """
        Adds a route to the mapping
        """
        if url not in self.mapping:
            self.mapping[url] = func
        else:
            raise KeyError("Route already exists: {}".format(url))

    def route(self, uri):
        """
        Route a request to a function

        :param: uri
        :param_type: string
        """
        def app_wrapper(f):
            self.add_route(uri, f)
            return f
        return app_wrapper

#! /usr/bin/env python
"""
Aragog Router Decorator
-----------------------

Convert any function into a WSGI endpoint with a simple decorator.
"""

from aragog.wsgi import get_url
from aragog.routing.client_error import HTTP404

class Router(object):
    """
    Router holds the mapping of routes to callables.
    """

    def __init__(self):
        """
        Instance level route mapping
        """
        self.mapping = {}

    def __call__(self, environ, start_response):
        """
        Get a WSGI request, and pass it on to the correct callable.
        """
        routing = self.mapping.get(get_url(environ), HTTP404)
        return routing(environ, start_response)

    def add_route(self, url, func):
        """
        Adds a route to the mapping
        """
        if url not in self.mapping:
            self.mapping[url] = func
        else:
            raise KeyError("Route already exists: {}".format(url))

    def route(self, uri):
        """
        Route a request to a function

        :param: uri
        :param_type: string
        """
        def app_wrapper(f):
            self.add_route(uri, f)
            return f
        return app_wrapper

Fix call to HTTP404 now it is a function.


#!/usr/bin/env python
#
# Copyright 2016 BMC Software, Inc.
#
# 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 tspapi

api = tspapi.API()

source = tspapi.Source(ref='myhost')
api.event_create(title="bar", fingerprint_fields=['@title'], source=source)

#!/usr/bin/env python
#
# Copyright 2016 BMC Software, Inc.
#
# 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 tspapi

api = tspapi.API()

source = tspapi.Source(ref='myhost', _type='host')
api.event_create(title="bar", fingerprint_fields=['@title'], source=source)

Add type field to source

Add type field to source


from bitHopper.Website import app, flask
import btcnet_info
import bitHopper.Configuration.Workers

@app.route("/worker", methods=['POST', 'GET'])
def worker():

    #Check if this is a form submission
    handle_worker_post(flask.request.form)

    #Get a list of currently configured workers
    pools_workers = {}
    for pool in btcnet_info.get_pools():
        if not pool.name:
            continue
        pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name)

    return flask.render_template('worker.html', pools = pools_workers)

def handle_worker_post(post):
    for item in ['method','username','password', 'pool']:
        if item not in post:
            return

    if post['method'] == 'remove':
        bitHopper.Configuration.Workers.remove(
                post['pool'], post['username'], post['password'])

    elif post['method'] == 'add':
        bitHopper.Configuration.Workers.add(
                post['pool'], post['username'], post['password'])

from bitHopper.Website import app, flask
import btcnet_info
import bitHopper.Configuration.Workers

@app.route("/worker", methods=['POST', 'GET'])
def worker():

    #Check if this is a form submission
    handle_worker_post(flask.request.form)

    #Get a list of currently configured workers
    pools_workers = {}
    for pool in btcnet_info.get_pools():
        if pool.name is None:
            logging.debug('Ignoring %s', pool)
            continue
        pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name)

    return flask.render_template('worker.html', pools = pools_workers)

def handle_worker_post(post):
    for item in ['method','username','password', 'pool']:
        if item not in post:
            return

    if post['method'] == 'remove':
        bitHopper.Configuration.Workers.remove(
                post['pool'], post['username'], post['password'])

    elif post['method'] == 'add':
        bitHopper.Configuration.Workers.add(
                post['pool'], post['username'], post['password'])

Add some debugging for the worker generation


# Copyright 2013 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.

from measurements import rasterize_and_record_micro
from telemetry import test

@test.Disabled('android', 'linux')
class RasterizeAndRecordMicroTop25(test.Test):
  """Measures rasterize and record performance on the top 25 web pages.

  http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
  test = rasterize_and_record_micro.RasterizeAndRecordMicro
  page_set = 'page_sets/top_25.json'

class RasterizeAndRecordMicroKeyMobileSites(test.Test):
  """Measures rasterize and record performance on the key mobile sites.

  http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
  test = rasterize_and_record_micro.RasterizeAndRecordMicro
  page_set = 'page_sets/key_mobile_sites.json'

class RasterizeAndRecordMicroKeySilkCases(test.Test):
  """Measures rasterize and record performance on the silk sites.

  http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
  test = rasterize_and_record_micro.RasterizeAndRecordMicro
  page_set = 'page_sets/key_silk_cases.json'

Add rasterization microbenchmark for silk

Add rasterize_and_record_micro_key_silk_cases for keeping track of
rasterization and recording performance of silk content. This mirrors
the existing rasterize_and_record_key_silk_cases benchmark and will
potentially allow us to remove it if this microbenchmark produces less
noisy data.

BUG=339517

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

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


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

from setuptools import setup

setup(
    name='clash',
    version='0.16',
    author='GigaSpaces',
    author_email='cosmo-admin@gigaspaces.com',
    packages=['clash'],
    description='Framework to wrap Cloudify local based blueprints as CLIs',
    license='Apache License, Version 2.0',
    zip_safe=False,
    install_requires=[
        'argcomplete',
        'ansicolors',
        'argh',
        'path.py',
        'cloudify-plugins-common==3.3.1',
        'cloudify-dsl-parser==3.3.1',
        'cloudify-script-plugin==1.3.1'
    ]
)

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

from setuptools import setup

setup(
    name='clash',
    version='0.16',
    author='GigaSpaces',
    author_email='cosmo-admin@gigaspaces.com',
    packages=['clash'],
    description='Framework to wrap Cloudify local based blueprints as CLIs',
    license='Apache License, Version 2.0',
    zip_safe=False,
    install_requires=[
        'argcomplete',
        'ansicolors',
        'argh',
        'path.py==8.1.2',
        'cloudify-plugins-common==3.3.1',
        'cloudify-dsl-parser==3.3.1',
        'cloudify-script-plugin==1.3.1'
    ]
)

Set path.py to a fixed version

Set path.py to a fixed version


import setuptools

from valohai_yaml import __version__

dev_dependencies = [
    'flake8',
    'isort',
    'pydocstyle',
    'pytest-cov',
]

if __name__ == '__main__':
    setuptools.setup(
        name='valohai-yaml',
        description='Valohai.yaml validation and parsing',
        version=__version__,
        url='https://github.com/valohai/valohai-yaml',
        author='Valohai',
        author_email='info@valohai.com',
        maintainer='Aarni Koskela',
        maintainer_email='akx@iki.fi',
        license='MIT',
        install_requires=['jsonschema', 'PyYAML', 'six'],
        tests_require=dev_dependencies,
        extras_require={'dev': dev_dependencies},
        packages=setuptools.find_packages('.', exclude=('*tests*',)),
        include_package_data=True,
        entry_points={
            'console_scripts': [
                'valohai-yaml = valohai_yaml.__main__:main',
            ],
        },
    )

import ast
import os
import re
import setuptools

with open(os.path.join(os.path.dirname(__file__), 'valohai_yaml', '__init__.py')) as infp:
    version = ast.literal_eval(re.search('__version__ = (.+?)$', infp.read(), re.M).group(1))

dev_dependencies = [
    'flake8',
    'isort',
    'pydocstyle',
    'pytest-cov',
]

if __name__ == '__main__':
    setuptools.setup(
        name='valohai-yaml',
        description='Valohai.yaml validation and parsing',
        version=version,
        url='https://github.com/valohai/valohai-yaml',
        author='Valohai',
        author_email='info@valohai.com',
        maintainer='Aarni Koskela',
        maintainer_email='akx@iki.fi',
        license='MIT',
        install_requires=['jsonschema', 'PyYAML', 'six'],
        tests_require=dev_dependencies,
        extras_require={'dev': dev_dependencies},
        packages=setuptools.find_packages('.', exclude=('*tests*',)),
        include_package_data=True,
        entry_points={
            'console_scripts': [
                'valohai-yaml = valohai_yaml.__main__:main',
            ],
        },
    )

Read version without importing package

Read version without importing package


import matplotlib.pyplot as plt
import numpy as np

def display_result(vectors, clusters):
    colors = [np.random.rand(3, 1) for i in range(len(clusters))]
    for cluster_index, (centroid, cluster) in enumerate(clusters.items()):
        current_cluster = [vectors[i] for i in cluster]
        xs = list(map(lambda x: x[0], current_cluster))
        ys = list(map(lambda x: x[1], current_cluster))
        plt.scatter(xs, ys, c=colors[cluster_index])
        plt.scatter(centroid[0], centroid[1], c=colors[cluster_index], marker='x')
    plt.show()

import matplotlib.pyplot as plt
import numpy as np

def display_result(vectors, clusters):
    colors = [np.random.rand(3, 1) for i in range(len(clusters))]
    centroids_colors = [[1-x for x in color] for color in colors]
    for cluster_index, (centroid, cluster) in enumerate(clusters.items()):
        current_cluster = [vectors[i] for i in cluster]
        xs = list(map(lambda x: x[0], current_cluster))
        ys = list(map(lambda x: x[1], current_cluster))
        plt.scatter(xs, ys, c=colors[cluster_index])
        plt.scatter(centroid[0], centroid[1], c=centroids_colors[cluster_index], marker='x')
    plt.show()

Add drawing centroids with inverted colors


#!/usr/bin/env python
# coding=utf8
#
# (C) 2015-2016, MIT License

'''
Installation configuration.
'''
from setuptools import setup

setup(
    name='kanaconv',
    version='1.0.0',
    description=(
        'Converts hiragana and katakana to rōmaji according to '
        'Modified Hepburn transliteration rules'
    ),
    url='https://github.com/msikma/kanaconv',
    author='Michiel Sikma',
    author_email='michiel@sikma.org',
    license='MIT',
    test_suite='kanaconv.tests.test_kanaconv',
    packages=['kanaconv'],
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: Education',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Japanese',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Text Processing :: Linguistic',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4'
    ],
    entry_points={
        'console_scripts': [
            'kanaconv=kanaconv.cli.kanaconv:main'
        ]
    },
    zip_safe=True
)

#!/usr/bin/env python
# coding=utf8
#
# (C) 2015-2016, MIT License

'''
Installation configuration.
'''
from setuptools import setup

setup(
    name='kanaconv',
    version='1.0.1',
    description=(
        'Converts hiragana and katakana to rōmaji according to '
        'Modified Hepburn transliteration rules'
    ),
    url='https://github.com/msikma/kanaconv',
    author='Michiel Sikma',
    author_email='michiel@sikma.org',
    license='MIT',
    test_suite='kanaconv.tests.test_kanaconv',
    packages=['kanaconv'],
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: Education',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Japanese',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Text Processing :: Linguistic',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4'
    ],
    entry_points={
        'console_scripts': [
            'kanaconv=kanaconv.cli.kanaconv:main'
        ]
    },
    zip_safe=True
)

Bump to 1.0.1 - Python 2 support fixed

Bump to 1.0.1 - Python 2 support fixed


Remove some cruft that was accidentally pushed

Change-Id: If75577316398c9d02230882766463f00aa13efd9


#!/usr/bin/env python

from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError

def get_link_status_code(link):
    headers = {'User-agent':'Mozilla/5.0'}
    try:
        r = requests.head(link, headers=headers, allow_redirects=True)
        return r.status_code
    except (SSLError, InvalidSchema, ConnectionError):
        return 409

def is_valid_link(status_code):
    if status_code == 200:
        return True
    else:
        return False

def process_links(links):
    bad_links = 0
    try:
        for link in links:
            status_code = get_link_status_code(link['href'])
            if not is_valid_link(status_code):
                print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href'])
                bad_links += 1
    except KeyboardInterrupt:
        pass

    linkrot = int(bad_links/len(links)*100)
    print '\n%s%% linkrot\n' % linkrot

def process_bookmarks_file(filename):
    with open(filename) as f:
        bookmarks = json.load(f)
        process_links(bookmarks)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'Usage: pinboard_linkrot.py <bookmarks.json>'
        exit(1)
    process_bookmarks_file(sys.argv[1])

#!/usr/bin/env python

from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError

def get_link_status_code(link):
    headers = {'User-agent':'Mozilla/5.0'}
    try:
        r = requests.head(link, headers=headers, allow_redirects=True)
        return r.status_code
    except (Exception) as e:
        return '%s: %s' % (type(e).__name__, str(e))

def is_valid_link(status_code):
    if status_code == 200:
        return True
    else:
        return False

def process_links(links):
    bad_links = 0
    try:
        for link in links:
            status_code = get_link_status_code(link['href'])
            if not is_valid_link(status_code):
                print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href'])
                bad_links += 1
    except KeyboardInterrupt:
        pass

    linkrot = int(bad_links/len(links)*100)
    print '\n%s%% linkrot\n' % linkrot

def process_bookmarks_file(filename):
    with open(filename) as f:
        bookmarks = json.load(f)
        process_links(bookmarks)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'Usage: pinboard_linkrot.py <bookmarks.json>'
        exit(1)
    process_bookmarks_file(sys.argv[1])

Return exception details when failing to load link


import unittest

from bermann.spark_context import SparkContext

class TestSparkContext(unittest.TestCase):

    def test_parallelize_with_list_input(self):
        sc = SparkContext()

        self.assertEqual([1, 2, 3], sc.parallelize([1, 2, 3]).collect())

    def test_parallelize_with_generator_input(self):
        sc = SparkContext()

        def gen_range(i):
            for i in range(i):
                yield i

        self.assertEqual([0, 1, 2, 3], sc.parallelize(gen_range(4)).collect())

import unittest

from bermann.spark_context import SparkContext
import bermann.rdd

class TestSparkContext(unittest.TestCase):

    def test_parallelize_with_list_input(self):
        sc = SparkContext()

        self.assertEqual([1, 2, 3], sc.parallelize([1, 2, 3]).collect())

    def test_parallelize_with_generator_input(self):
        sc = SparkContext()

        def gen_range(i):
            for i in range(i):
                yield i

        self.assertEqual([0, 1, 2, 3], sc.parallelize(gen_range(4)).collect())

    def test_empty_rdd_returns_empty_rdd(self):
        sc = SparkContext()

        empty = sc.emptyRDD()
        self.assertTrue(isinstance(empty, bermann.rdd.RDD))
        self.assertEqual(0, empty.count())

Add test case for SparkContext.emptyRDD()


#!/usr/bin/env python
from setuptools import setup, find_packages

setup(name='django-oscar-datacash',
      version='0.3.5',
      url='https://github.com/tangentlabs/django-oscar-datacash',
      author="David Winterbottom",
      author_email="david.winterbottom@tangentlabs.co.uk",
      description="Datacash payment module for django-oscar",
      long_description=open('README.rst').read(),
      keywords="Payment, Datacash",
      license='BSD',
      packages=find_packages(exclude=['sandbox*', 'tests*']),
      include_package_data=True,
      install_requires=['django-oscar==0.2',],
      # See http://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=['Environment :: Web Environment',
                   'Framework :: Django',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: Unix',
                   'Programming Language :: Python']
      )

#!/usr/bin/env python
from setuptools import setup, find_packages

setup(name='django-oscar-datacash',
      version='0.4',
      url='https://github.com/tangentlabs/django-oscar-datacash',
      author="David Winterbottom",
      author_email="david.winterbottom@tangentlabs.co.uk",
      description="Datacash payment module for django-oscar",
      long_description=open('README.rst').read(),
      keywords="Payment, Datacash",
      license='BSD',
      packages=find_packages(exclude=['sandbox*', 'tests*']),
      include_package_data=True,
      install_requires=['django-oscar>=0.4'],
      # See http://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=['Environment :: Web Environment',
                   'Framework :: Django',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: Unix',
                   'Programming Language :: Python']
      )

Bump version and support django oscar version


from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush

class FlashingBox(QOpenGLWidget):

  def __init__(self, parent, freq, color):
    super(FlashingBox, self).__init__(parent)
    self.freq = freq
    self.brushes = [QBrush(Qt.black), QBrush(color)]
    self.index = 0
    self.enabled = False

  def timerEvent(self, event):
    if self.enabled:
        self.index = (self.index + 1) % 2
    else:
        self.index = 0
    self.update()

  def paintEvent(self, event):
    painter = QPainter(self)
    painter.fillRect(event.rect(), self.brushes[self.index])

  def suspendFlashing(self):
    self.killTimer(self._timer)
    self.enabled=False
    self.index = 0
    self.update()

  def startFlashing(self):
    self.index = 0
    self.enabled = True
    delay = int(1000/(2 * self.freq))  #in mSec
    self._timer = self.startTimer(delay, Qt.PreciseTimer)

from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush

class FlashingBox(QOpenGLWidget):
  def __init__(self, parent, freq=1, color=Qt.black):
    super(FlashingBox, self).__init__(parent)
    self.freq = freq
    self.brushes = [QBrush(Qt.black), QBrush(color)]
    self.index = 0
    self.enabled = False

  def setFreq(self, freq):
    self.freq = freq

  def setColor(self, color):
    self.brushes[1] = QBrush(color)

  def timerEvent(self, event):
    if self.enabled:
      self.index = (self.index + 1) % 2
    else:
      self.index = 0
    self.update()

  def paintEvent(self, event):
    painter = QPainter(self)
    painter.fillRect(event.rect(), self.brushes[self.index])

  def startFlashing(self):
    self.index = 0
    self.enabled = True
    delay = int(1000/(2 * self.freq))  #in mSec
    self._timer = self.startTimer(delay, Qt.PreciseTimer)

  def stopFlashing(self):
    self.killTimer(self._timer)
    self.enabled=False
    self.index = 0
    self.update()

Add setFreq/setColor methods for FlashingBox


#!/usr/bin/env python
# encoding: utf-8
"""
tempodb/setup.py

Copyright (c) 2012 TempoDB Inc. All rights reserved.
"""

import os
from setuptools import setup

import tempodb

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name="python-tempodb",
    version=tempodb.__version__,
    author="TempoDB Inc",
    author_email="dev@tempo-db.com",
    description="A client for the TempoDB API",
    packages=["tempodb"],
    long_description=read('README'),
    install_requires=[
        'python-dateutil==1.5',
        'requests',
        'simplejson',
    ]
)

#!/usr/bin/env python
# encoding: utf-8
"""
tempodb/setup.py

Copyright (c) 2012 TempoDB Inc. All rights reserved.
"""

import os
from setuptools import setup

import tempodb

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name="tempodb",
    version=tempodb.__version__,
    author="TempoDB Inc",
    author_email="dev@tempo-db.com",
    description="A client for the TempoDB API",
    packages=["tempodb"],
    long_description=read('README'),
    install_requires=[
        'python-dateutil==1.5',
        'requests',
        'simplejson',
    ]
)

Change package name to tempodb

Change package name to tempodb


"""
Flask-Babel
-----------

Adds i18n/l10n support to Flask applications with the help of the
`Babel`_ library.

Links
`````

* `documentation <http://packages.python.org/Flask-Babel>`_
* `development version
  <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_

.. _Babel: http://babel.edgewall.org/

"""
from setuptools import setup

setup(
    name='Flask-Babel',
    version='0.9',
    url='http://github.com/mitsuhiko/flask-babel',
    license='BSD',
    author='Armin Ronacher',
    author_email='armin.ronacher@active-4.com',
    description='Adds i18n/l10n support to Flask applications',
    long_description=__doc__,
    packages=['flask_babel'],
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask',
        'Babel>=1.0',
        'speaklater>=1.2',
        'Jinja2>=2.5'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)

"""
Flask-Babel
-----------

Adds i18n/l10n support to Flask applications with the help of the
`Babel`_ library.

Links
`````

* `documentation <http://packages.python.org/Flask-Babel>`_
* `development version
  <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_

.. _Babel: http://babel.edgewall.org/

"""
from setuptools import setup

setup(
    name='Flask-Babel',
    version='0.9',
    url='http://github.com/mitsuhiko/flask-babel',
    license='BSD',
    author='Armin Ronacher',
    author_email='armin.ronacher@active-4.com',
    description='Adds i18n/l10n support to Flask applications',
    long_description=__doc__,
    packages=['flask_babel'],
    zip_safe=False,
    platforms='any',
    install_requires=[
        'Flask',
        'Babel>=2.3',
        'speaklater>=1.2',
        'Jinja2>=2.5'
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ]
)

Update minimum babel version to >=2.3.

Update minimum babel version to >=2.3.

Babel 1.0 is now 3 years obsolete. Numerous critical bug fixes are
included in the 1.0 - 2.3 range.


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

requirements = [
    'furl==0.5.6',
    'six==1.10.0'
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='surveymonkey',
    version='0.4.2',
    description="Python wrapper for the Survey Monkey v3 API",
    long_description=readme,
    author="Aaron Bassett",
    author_email='engineering@getadministrate.com',
    url='https://github.com/Administrate/surveymonkey',
    packages=[
        'surveymonkey',
        'surveymonkey.collectors',
        'surveymonkey.webhooks',
        'surveymonkey.messages'
    ],
    package_dir={'surveymonkey':
                 'surveymonkey'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='surveymonkey',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

requirements = [
    'furl==0.5.6',
    'six==1.10.0',
    'pytest==3.0.3'
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='surveymonkey',
    version='0.4.2',
    description="Python wrapper for the Survey Monkey v3 API",
    long_description=readme,
    author="Aaron Bassett",
    author_email='engineering@getadministrate.com',
    url='https://github.com/Administrate/surveymonkey',
    packages=[
        'surveymonkey',
        'surveymonkey.collectors',
        'surveymonkey.webhooks',
        'surveymonkey.messages'
    ],
    package_dir={'surveymonkey':
                 'surveymonkey'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='surveymonkey',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)

Add pytest to surveymonkey dependencies

Add pytest to surveymonkey dependencies


# -*- coding: utf-8 -*-
from setuptools import setup

VERSION = '0.5'

setup(
    name='conllu',
    packages=["conllu"],
    version=VERSION,
    description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
    author=u'Emil Stenström',
    author_email='em@kth.se',
    url='https://github.com/EmilStenstrom/conllu/',
    download_url='https://github.com/EmilStenstrom/conllu/archive/%s.zip' % VERSION,
    install_requires=[],
    tests_require=["nose>=1.3.7", "flake8>=3.0.4"],
    test_suite="nose.collector",
    keywords=['conllu', 'conll', 'conllu-u', 'parser', 'nlp'],
    classifiers=[
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Operating System :: OS Independent",
    ],
)

# -*- coding: utf-8 -*-
from setuptools import setup

VERSION = '0.6'

setup(
    name='conllu',
    packages=["conllu"],
    version=VERSION,
    description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
    author=u'Emil Stenström',
    author_email='em@kth.se',
    url='https://github.com/EmilStenstrom/conllu/',
    download_url='https://github.com/EmilStenstrom/conllu/archive/%s.zip' % VERSION,
    install_requires=[],
    tests_require=["nose>=1.3.7", "flake8>=3.0.4"],
    test_suite="nose.collector",
    keywords=['conllu', 'conll', 'conllu-u', 'parser', 'nlp'],
    classifiers=[
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
)

Declare Python 3 support, bump version.

Declare Python 3 support, bump version.


import os
from distutils.core import setup

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
LICENSE = open(os.path.join(here, 'LICENSE')).read()

setup(
    name='saferedisqueue',
    version='1.1.0',
    description='A small wrapper around Redis that provides access to a FIFO queue.',
    long_description=README + '\n\n' + CHANGES,
    license=LICENSE,
    author="Fabian Neumann, ferret go GmbH",
    author_email="neumann@ferret-go.com",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Topic :: Internet",
    ],
    keywords='Redis, key-value store, queue, queueing, Storm',
    url='https://github.com/hellp/saferedisqueue',
    py_modules=['saferedisqueue'],
    install_requires=[
        'redis >= 2.4.10, < 2.5',
    ],
    zip_safe=False,
)

import os
from distutils.core import setup

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
LICENSE = open(os.path.join(here, 'LICENSE')).read()

setup(
    name='saferedisqueue',
    version='1.1.0',
    description='A small wrapper around Redis that provides access to a FIFO queue.',
    long_description=README + '\n\n' + CHANGES,
    license=LICENSE,
    author="Fabian Neumann, ferret go GmbH",
    author_email="neumann@ferret-go.com",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Topic :: Internet",
    ],
    keywords='Redis, key-value store, queue, queueing, Storm',
    url='https://github.com/hellp/saferedisqueue',
    py_modules=['saferedisqueue'],
    install_requires=[
        'redis >= 2.4.10, < 2.7',
    ],
    zip_safe=False,
)

Mark this version as compatible with redis.py up to 2.6.x


import os

from setuptools import setup

def get_version():
    """Get the version info from the mpld3 package without importing it"""
    import ast

    with open(os.path.join("geneimpacts", "__init__.py"), "r") as init_file:
        module = ast.parse(init_file.read())

    version = (ast.literal_eval(node.value) for node in ast.walk(module)
               if isinstance(node, ast.Assign)
               and node.targets[0].id == "__version__")
    try:
        return next(version)
    except StopIteration:
        raise ValueError("version could not be located")

setup(version=get_version(),
      name='geneimpacts',
      description="normalize effects from variant annotation tools (snpEff, VEP)",
      packages=['geneimpacts', 'geneimpacts.tests'],
      long_description=open('README.md').read(),
      long_description_content_type="text/markdown",
      author="Brent Pedersen",
      author_email="bpederse@gmail.com",
      zip_safe=False,
      test_suite='nose.collector',
      include_package_data=True,
      tests_require=['nose'],
      classifiers=[
    'Development Status :: 4 - Beta',
    'Intended Audience :: Science/Research',
    'License :: OSI Approved :: MIT License',
    'Topic :: Scientific/Engineering :: Bio-Informatics'
  ])

import os

from setuptools import setup

def get_version():
    """Get the version info from the mpld3 package without importing it"""
    import ast

    with open(os.path.join("geneimpacts", "__init__.py"), "r") as init_file:
        module = ast.parse(init_file.read())

    version = (ast.literal_eval(node.value) for node in ast.walk(module)
               if isinstance(node, ast.Assign)
               and node.targets[0].id == "__version__")
    try:
        return next(version)
    except StopIteration:
        raise ValueError("version could not be located")

setup(version=get_version(),
      name='geneimpacts',
      description="normalize effects from variant annotation tools (snpEff, VEP)",
      packages=['geneimpacts', 'geneimpacts.tests'],
      long_description=open('README.md').read(),
      long_description_content_type="text/markdown",
      author="Brent Pedersen",
      author_email="bpederse@gmail.com",
      zip_safe=False,
      test_suite='pytest',
      include_package_data=True,
      tests_require=['pytest'],
      classifiers=[
    'Development Status :: 4 - Beta',
    'Intended Audience :: Science/Research',
    'License :: OSI Approved :: MIT License',
    'Topic :: Scientific/Engineering :: Bio-Informatics'
  ])

Switch from nosetest -> pytest

Switch from nosetest -> pytest


#-*- coding: utf-8 -*-
#
#  setup.py
#  anytop
#
#  Created by Lars Yencken on 2011-10-09.
#  Copyright 2011 Lars Yencken. All rights reserved.
#

from distutils.core import setup

setup(
    name='anytop',
    version='0.1.2',
    description='Streaming frequency distribution viewer.',
    long_description=open('README.rst').read(),
    author='Lars Yencken',
    author_email='lars@yencken.org',
    url='http://bitbucket.org/larsyencken/anytop',
    scripts=['anytop'],
    packages=['anyutil'],
    license='ISC',
)

#-*- coding: utf-8 -*-
#
#  setup.py
#  anytop
#
#  Created by Lars Yencken on 2011-10-09.
#  Copyright 2011 Lars Yencken. All rights reserved.
#

from distutils.core import setup

setup(
    name='anytop',
    version='0.1.2',
    description='Streaming frequency distribution viewer.',
    long_description=open('README.rst').read(),
    author='Lars Yencken',
    author_email='lars@yencken.org',
    url='http://bitbucket.org/larsyencken/anytop',
    scripts=['anytop', 'anyhist'],
    packages=['anyutil'],
    license='ISC',
)

Add anyhist as an installed script.

Add anyhist as an installed script.


import io

from setuptools import find_packages, setup

def read(fname):
    with io.open(fname, encoding='utf-8') as f:
        return f.read()

setup(
    name='wagtail-pg-search-backend',
    version='1.0.0.dev0',
    packages=find_packages(exclude=['tests']),
    include_package_data=True,
    zip_safe=False,
    url='https://github.com/leukeleu/wagtail-pg-search-backend',
    description='PostgreSQL full text search backend for Wagtail CMS',
    long_description=read('README.rst'),
    keywords=['wagtail', 'postgres', 'fulltext', 'search'],
    classifiers=[
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'License :: OSI Approved :: MIT License'
    ],
    license='MIT',
    install_requires=[
        'Django>=1.10',
        'psycopg2',
        'six',
        'wagtail'
    ],
    test_suite='runtests.runtests'
)

import io

from setuptools import find_packages, setup

def read(fname):
    with io.open(fname, encoding='utf-8') as f:
        return f.read()

setup(
    name='wagtail-pg-search-backend',
    version='1.0.0.dev0',
    author='Bertrand Bordage',
    author_email='bordage.bertrand@gmail.com',
    packages=find_packages(exclude=['tests']),
    include_package_data=True,
    zip_safe=False,
    url='https://github.com/leukeleu/wagtail-pg-search-backend',
    description='PostgreSQL full text search backend for Wagtail CMS',
    long_description=read('README.rst'),
    keywords=['wagtail', 'postgres', 'fulltext', 'search'],
    classifiers=[
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'License :: OSI Approved :: MIT License'
    ],
    license='MIT',
    install_requires=[
        'Django>=1.10',
        'psycopg2',
        'six',
        'wagtail'
    ],
    test_suite='runtests.runtests'
)

Set package author to Bertrand Bordage

Set package author to Bertrand Bordage


# Copyright 2012 Kevin Goodsell
#
# This software is licensed under the Eclipse Public License (EPL) V1.0.

'''
Interface to the STAF API.
'''

# Using __all__ makes pydoc work properly. Otherwise it looks at the modules the
# items actually come from and assumes they don't belong in the docs for
# __init__.
__all__ = [
    'Handle', 'wrap_data', 'add_privacy_delimiters',
    'remove_privacy_delimiters', 'mask_private_data',
    'escape_privacy_delimiters', 'errors', 'strerror', 'STAFError',
    'STAFResultError', 'unmarshal', 'STAFUnmarshalError', 'MapClassDefinition',
    'MapClass', 'unmarshal_recursive', 'unmarshal_non_recursive',
    'unmarshal_none',
]

from ._staf import (
    Handle,
    wrap_data,
    add_privacy_delimiters,
    remove_privacy_delimiters,
    mask_private_data,
    escape_privacy_delimiters,
)

from ._errors import (
    errors,
    strerror,
    STAFError,
    STAFResultError,
)

from ._marshal import (
    unmarshal,
    unmarshal_force,
    STAFUnmarshalError,
    MapClassDefinition,
    MapClass,
    unmarshal_recursive,
    unmarshal_non_recursive,
    unmarshal_none,
)

# Copyright 2012 Kevin Goodsell
#
# This software is licensed under the Eclipse Public License (EPL) V1.0.

'''
Interface to the STAF API.
'''

# Using __all__ makes pydoc work properly. Otherwise it looks at the modules the
# items actually come from and assumes they don't belong in the docs for
# __init__.
__all__ = [
    'Handle', 'wrap_data', 'add_privacy_delimiters',
    'remove_privacy_delimiters', 'mask_private_data',
    'escape_privacy_delimiters', 'errors', 'strerror', 'STAFError',
    'STAFResultError', 'unmarshal', 'unmarshal_force', 'STAFUnmarshalError',
    'MapClassDefinition', 'MapClass', 'unmarshal_recursive',
    'unmarshal_non_recursive', 'unmarshal_none',
]

from ._staf import (
    Handle,
    wrap_data,
    add_privacy_delimiters,
    remove_privacy_delimiters,
    mask_private_data,
    escape_privacy_delimiters,
)

from ._errors import (
    errors,
    strerror,
    STAFError,
    STAFResultError,
)

from ._marshal import (
    unmarshal,
    unmarshal_force,
    STAFUnmarshalError,
    MapClassDefinition,
    MapClass,
    unmarshal_recursive,
    unmarshal_non_recursive,
    unmarshal_none,
)

Add missing function in __all__.

Add missing function in __all__.


"""Setuptools configuration for rpmvenv."""

from setuptools import setup
from setuptools import find_packages

with open('README.rst', 'r') as readmefile:

    README = readmefile.read()

setup(
    name='rpmvenv',
    version='0.23.0',
    url='https://github.com/kevinconway/rpmvenv',
    description='RPM packager for Python virtualenv.',
    author="Kevin Conway",
    author_email="kevinjacobconway@gmail.com",
    long_description=README,
    license='MIT',
    packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
    install_requires=[
        'jinja2',
        'venvctrl',
        'argparse',
        'confpy',
        'ordereddict',
        'semver',
    ],
    entry_points={
        'console_scripts': [
            'rpmvenv = rpmvenv.cli:main',
        ],
        'rpmvenv.extensions': [
            'core = rpmvenv.extensions.core:Extension',
            'file_permissions = rpmvenv.extensions.files.permissions:Extension',
            'file_extras = rpmvenv.extensions.files.extras:Extension',
            'python_venv = rpmvenv.extensions.python.venv:Extension',
            'blocks = rpmvenv.extensions.blocks.generic:Extension',
        ]
    },
    package_data={
        "rpmvenv": ["templates/*"],
    },
)

"""Setuptools configuration for rpmvenv."""

from setuptools import setup
from setuptools import find_packages

with open('README.rst', 'r') as readmefile:

    README = readmefile.read()

setup(
    name='rpmvenv',
    version='0.23.0',
    url='https://github.com/kevinconway/rpmvenv',
    description='RPM packager for Python virtualenv.',
    author="Kevin Conway",
    author_email="kevinjacobconway@gmail.com",
    long_description=README,
    license='MIT',
    packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),
    install_requires=[
        'jinja2',
        'venvctrl',
        'argparse',
        'confpy',
        'ordereddict',
        'semver<2.10', # semver dropped support for legacy Python at 2.10.
    ],
    entry_points={
        'console_scripts': [
            'rpmvenv = rpmvenv.cli:main',
        ],
        'rpmvenv.extensions': [
            'core = rpmvenv.extensions.core:Extension',
            'file_permissions = rpmvenv.extensions.files.permissions:Extension',
            'file_extras = rpmvenv.extensions.files.extras:Extension',
            'python_venv = rpmvenv.extensions.python.venv:Extension',
            'blocks = rpmvenv.extensions.blocks.generic:Extension',
        ]
    },
    package_data={
        "rpmvenv": ["templates/*"],
    },
)

Add semver version limit due to compat changes

The semver library stopped working for legacy Python versions after the
2.9.1 release. This adds a less than 2.10 restriction to the abstract
dependency requirements so that folks don't need to all add a pin to
their requirements.txt.


from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='yarntf',
    version='0.0.1.dev15',
    description='TensorFlow on YARN',
    long_description=long_description,
    url='https://github.com/tobiajo/yarntf',
    author='Tobias Johansson',
    author_email='tobias@johansson.xyz',
    license='Apache License 2.0',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Libraries',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.7',
    ],
    keywords='yarn tf hadoop tensorflow',
    packages=find_packages(exclude=['tests']),
    install_requires=['grpc', 'tensorflow'],
)

from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='yarntf',
    version='0.0.1.dev16',
    description='TensorFlow on YARN',
    long_description=long_description,
    url='https://github.com/tobiajo/yarntf',
    author='Tobias Johansson',
    author_email='tobias@johansson.xyz',
    license='Apache License 2.0',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Libraries',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.7',
    ],
    keywords='yarn tf hadoop tensorflow',
    packages=find_packages(exclude=['tests']),
    install_requires=['grpcio', 'tensorflow'],
)

Change require from grpc to grpcio

Change require from grpc to grpcio


# -*- coding: utf-8 -*-
from os import path, chdir, pardir
from setuptools import setup, find_packages

README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# requirements.txt must be included in MANIFEST.in and include_package_data must be True
# in order for this to work; ensures that tox can use the setup to enforce requirements
REQUIREMENTS = '\n'.join(open(path.join(path.dirname(__file__), 'requirements.txt')).readlines())  # noqa

# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))

setup(
    name="elasticsearch-django",
    version="0.4.0-dev",
    packages=find_packages(),
    install_requires=REQUIREMENTS,
    include_package_data=True,
    description='Elasticsearch Django app',
    long_description=README,
    url='https://github.com/yunojuno/elasticsearch-django',
    author='Hugo Rodger-Brown',
    author_email='code@yunojuno.com',
    maintainer='Hugo Rodger-Brown',
    maintainer_email='hugo@yunojuno.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

# -*- coding: utf-8 -*-
from os import path, chdir, pardir
from setuptools import setup, find_packages

README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# requirements.txt must be included in MANIFEST.in and include_package_data must be True
# in order for this to work; ensures that tox can use the setup to enforce requirements
REQUIREMENTS = '\n'.join(open(path.join(path.dirname(__file__), 'requirements.txt')).readlines())  # noqa

# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))

setup(
    name="elasticsearch-django",
    version="0.4.0",
    packages=find_packages(),
    install_requires=REQUIREMENTS,
    include_package_data=True,
    description='Elasticsearch Django app',
    long_description=README,
    url='https://github.com/yunojuno/elasticsearch-django',
    author='Hugo Rodger-Brown',
    author_email='code@yunojuno.com',
    maintainer='Hugo Rodger-Brown',
    maintainer_email='hugo@yunojuno.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)

Bump version to v0.4.0 (Django 1.9)

Bump version to v0.4.0 (Django 1.9)


#!/usr/bin/env python
# coding: utf-8

import os
import sys

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

def publish():
    """
    Publish this package to PyPI (aka "the Cheeseshop").

    """
    os.system('python setup.py sdist upload')

if sys.argv[-1] == 'publish':
    publish()
    sys.exit()

setup(name='pystache',
      version='0.3.1',
      description='Mustache for Python',
      long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(),
      author='Chris Wanstrath',
      author_email='chris@ozmm.org',
      url='http://github.com/defunkt/pystache',
      packages=['pystache'],
      license='MIT',
      entry_points = {
        'console_scripts': ['pystache=pystache.commands:main'],
      },
      classifiers = (
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.5',
        'Programming Language :: Python :: 2.6',
      )
)

#!/usr/bin/env python
# coding: utf-8

import os
import sys

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

def publish():
    """
    Publish this package to PyPI (aka "the Cheeseshop").

    """
    os.system('python setup.py sdist upload')

def make_long_description():
    """
    Return the long description for the package.

    """
    long_description = open('README.rst').read() + '\n\n' + open('HISTORY.rst').read()

    return long_description

if sys.argv[-1] == 'publish':
    publish()
    sys.exit()

long_description = make_long_description()

setup(name='pystache',
      version='0.3.1',
      description='Mustache for Python',
      long_description=long_description,
      author='Chris Wanstrath',
      author_email='chris@ozmm.org',
      url='http://github.com/defunkt/pystache',
      packages=['pystache'],
      license='MIT',
      entry_points = {
        'console_scripts': ['pystache=pystache.commands:main'],
      },
      classifiers = (
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.5',
        'Programming Language :: Python :: 2.6',
      )
)

Put the code to create the package's long_description into a function.


from setuptools import setup, find_packages

setup(
    name="vantage",
    version="3.0.0",
    packages=find_packages(),
    include_package_data=True,
    install_requires=["Click", "sh", "pyyaml"],
    entry_points="""
        [console_scripts]
        vantage=vantage.entry:vantage
        vg=vantage.entry:vantage
    """,
)

from setuptools import setup, find_packages

setup(
    name="vantage",
    version="3.0.2",
    packages=find_packages(),
    include_package_data=True,
    install_requires=["Click", "sh", "pyyaml", "certifi"],
    entry_points="""
        [console_scripts]
        vantage=vantage.entry:vantage
        vg=vantage.entry:vantage
    """,
)

Bump version and insclude certifi

Bump version and insclude certifi


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

from setuptools import setup

setup(
    name='fontreport',
    version='1.0',
    packages=['fontreport'],
    package_data = {'fontreport': ['*.json']},
    entry_points = {
        'console_scripts': [
            'fontreport = fontreport.fontreport:main'
        ],
    },
    install_requires=[
        'fonttools>=3.0',
    ]
)

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

from setuptools import setup

setup(
    name='fontreport',
    version='1.0',
    packages=['fontreport'],
    package_data = {'fontreport': ['*.json']},
    entry_points = {
        'console_scripts': [
            'fontreport = fontreport.fontreport:main'
        ],
    },
    install_requires=[
        'fonttools>=3.0',
    ],
    dependency_links=[
        'https://github.com/behdad/fonttools/tarball/master#egg=fonttools-3.0'
    ]
)

Add dependency on github version of fonttools


#!/usr/bin/env python

from __future__ import absolute_import
from __future__ import unicode_literals
from setuptools import setup, find_packages
from milestones import __version__ as VERSION

setup(
    name='edx-milestones',
    version=VERSION,
    description='Significant events module for Open edX',
    long_description=open('README.md').read(),
    author='edX',
    url='https://github.com/edx/edx-milestones',
    license='AGPL',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU Affero General Public License v3',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
    packages=find_packages(exclude=["tests"]),
    install_requires=[
        "django>=1.8,<2.0",
        "django-model-utils",
        "edx-opaque-keys>=0.2.1,<1.0.0",
    ],
    tests_require=[
        "coverage==4.5.3",
        "nose==1.3.3",
        "httpretty==0.8.0",
        "pep8==1.5.7",
        "pylint==1.2.1",
        "pep257==0.3.2"
    ]
)

#!/usr/bin/env python

from __future__ import absolute_import
from __future__ import unicode_literals
from setuptools import setup, find_packages
from milestones import __version__ as VERSION

setup(
    name='edx-milestones',
    version=VERSION,
    description='Significant events module for Open edX',
    long_description=open('README.md').read(),
    author='edX',
    url='https://github.com/edx/edx-milestones',
    license='AGPL',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU Affero General Public License v3',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
    packages=find_packages(exclude=["tests"]),
    install_requires=[
        "django>=1.8,<2.0",
        "django-model-utils",
        "edx-opaque-keys>=0.2.1,<1.0.0",
        "six",
    ],
    tests_require=[
        "coverage==4.5.3",
        "nose==1.3.3",
        "httpretty==0.8.0",
        "pep8==1.5.7",
        "pylint==1.2.1",
        "pep257==0.3.2"
    ]
)

Add six as a requirement.

Add six as a requirement.


from setuptools import setup, find_packages

setup(
    name='formal',
    version='0.8.2',
    description='HTML forms framework for Nevow',
    author='Matt Goodall',
    author_email='matt@pollenation.net',
    packages=find_packages(),
    package_data={
        'formal': ['formal.css', 'html/*', 'js/*'],
        },
    zip_safe = True,
    )

from setuptools import setup, find_packages

setup(
    name='formal',
    version='0.8.2',
    description='HTML forms framework for Nevow',
    author='Matt Goodall',
    author_email='matt@pollenation.net',
    packages=find_packages(),
    package_data={
        '': ['*.css', '*.html', '*.js'],
        },
    zip_safe = True,
    )

Make the package_data globs less specific to pick up examples.css too and (hopefully) not miss resource files added in future.


import os
from setuptools import find_packages
from setuptools import setup
import sys

sys.path.insert(0, os.path.abspath('lib'))

exec(open('lib/ansiblereview/version.py').read())

setup(
    name='ansible-review',
    version=__version__,
    description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
    keywords='ansible, code review',
    author='Will Thames',
    author_email='will@thames.id.au',
    url='https://github.com/willthames/ansible-review',
    package_dir={'': 'lib'},
    packages=find_packages('lib'),
    zip_safe=False,
    install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff'],
    scripts=['bin/ansible-review'],
    classifiers=[
        'License :: OSI Approved :: MIT License',
    ],
    test_suite="test"
)

import os
from setuptools import find_packages
from setuptools import setup
import sys

sys.path.insert(0, os.path.abspath('lib'))

exec(open('lib/ansiblereview/version.py').read())

setup(
    name='ansible-review',
    version=__version__,
    description=('reviews ansible playbooks, roles and inventory and suggests improvements'),
    keywords='ansible, code review',
    author='Will Thames',
    author_email='will@thames.id.au',
    url='https://github.com/willthames/ansible-review',
    package_dir={'': 'lib'},
    packages=find_packages('lib'),
    zip_safe=False,
    install_requires=['ansible-lint>=3.0.0', 'pyyaml', 'appdirs', 'unidiff', 'flake8'],
    scripts=['bin/ansible-review'],
    classifiers=[
        'License :: OSI Approved :: MIT License',
    ],
    test_suite="test"
)

Add flake8 to installation dependencies

Add flake8 to installation dependencies


from setuptools import setup

setup(
    name='EasyEuler',
    version='0.1',
    py_modules=['EasyEuler'],
    install_requires=[
        'Click',
        'Jinja2'
    ],
    entry_points='''
        [console_scripts]
        easyeuler=EasyEuler.cli:cli
    '''
)

import sys

from setuptools import setup

requirements = ['Click', 'Jinja2']

if 'win32' in sys.platform.lower():
    # Windows needs colorama for the terminal colors to work.
    requirements.append('colorama')

setup(
    name='EasyEuler',
    version='0.1',
    py_modules=['EasyEuler'],
    install_requires=requirements,
    entry_points='''
        [console_scripts]
        easyeuler=EasyEuler.cli:cli
    '''
)

Add colorama to requirements for Windows


from mock import patch

from django.test import TestCase
from breach.sniffer import Sniffer

class SnifferTest(TestCase):
    def setUp(self):
        self.endpoint = 'http://localhost'
        self.sniffer = Sniffer(self.endpoint)

        self.source_ip = '147.102.239.229'
        self.destination_host = 'dionyziz.com'

    @patch('breach.sniffer.requests')
    def test_sniffer_start(self, requests):
        self.sniffer.start(self.source_ip, self.destination_host)
        self.assertTrue(requests.post.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_read(self, requests):
        self.sniffer.read(self.source_ip, self.destination_host)
        self.assertTrue(requests.get.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_stop(self, requests):
        self.sniffer.stop(self.source_ip, self.destination_host)
        self.assertTrue(requests.post.called)

from mock import patch

from django.test import TestCase
from breach.sniffer import Sniffer

class SnifferTest(TestCase):
    def setUp(self):
        self.endpoint = 'http://localhost'
        self.sniffer = Sniffer(self.endpoint)

        self.source_ip = '147.102.239.229'
        self.destination_host = 'dionyziz.com'

    @patch('breach.sniffer.requests')
    def test_sniffer_start(self, requests):
        self.sniffer.start(self.source_ip, self.destination_host)
        self.assertTrue(requests.post.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_read(self, requests):
        self.sniffer.read(self.source_ip, self.destination_host)
        self.assertTrue(requests.get.called)

    @patch('breach.sniffer.requests')
    def test_sniffer_delete(self, requests):
        self.sniffer.delete(self.source_ip, self.destination_host)
        self.assertTrue(requests.post.called)

Fix sniffer test, rename stop to delete

Fix sniffer test, rename stop to delete


import os
import pytest

from subprocess import Popen, PIPE

def has_installed(program):
    """Checks to see if a program is installed using ``which``.

    :param str program: the name of the program we're looking for

    :rtype bool:

    :return: True if it's installed, otherwise False.

    """
    proc = Popen(["which", program], stdout=PIPE, stderr=PIPE)
    exit_code = proc.wait()
    return exit_code == 0

hasdocker = pytest.mark.skipif(not has_installed("docker"),
                               reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""

@hasdocker
def test_build(parse_and_run):
    """Test vanilla assignment build
    """
    path = parse_and_run(["init", "cpl"])
    parse_and_run(["new", "a1"])

    dockerfile_path = os.path.join(path, "assignments", "a1",
                                   "gradesheet", "Dockerfile")
    with open(dockerfile_path, 'w') as dockerfile:
        dockerfile.write("FROM ubuntu:12.04")

    parse_and_run(["build", "a1"])

import os
import pytest
import shutil

hasdocker = pytest.mark.skipif(shutil.which("docker") is None,
                               reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""

@hasdocker
def test_build(parse_and_run):
    """Test vanilla assignment build
    """
    path = parse_and_run(["init", "cpl"])
    parse_and_run(["new", "a1"])

    dockerfile_path = os.path.join(path, "assignments", "a1",
                                   "gradesheet", "Dockerfile")
    with open(dockerfile_path, 'w') as dockerfile:
        dockerfile.write("FROM ubuntu:12.04")

    parse_and_run(["build", "a1"])

Use shutil for 'which docker'

Use shutil for 'which docker'


# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: Emanuel Cino <ecino@compassion.ch>
#
#    The licence is in the file __manifest__.py
#
##############################################################################

from odoo import api, models, fields

class HrExpense(models.Model):
    _inherit = "hr.expense"

    # Make product editable when expense is submitted
    product_id = fields.Many2one(
        states={
            'draft': [('readonly', False)],
            'submit': [('readonly', False)]
        }
    )

    @api.onchange('product_id')
    def _onchange_product_id(self):
        """
        Prevent changing amounts if expense is submitted.
        """
        if self.state == 'draft':
            super(HrExpense, self)._onchange_product_id()

class HrExpenseSheet(models.Model):
    _inherit = 'hr.expense.sheet'

    # Adding a user_id field for the assign notification to work
    user_id = fields.Many2one(related='employee_id.user_id')

    @api.model
    def create(self, vals):
        """Notify managers when expense is created."""
        sheet = super(HrExpenseSheet, self).create(vals)
        users = sheet._get_users_to_subscribe() - self.env.user
        sheet._message_auto_subscribe_notify(users.mapped('partner_id').ids)
        return sheet

    def _add_followers(self):
        """Notify managers when employee is changed."""
        super(HrExpenseSheet, self)._add_followers()
        users = self._get_users_to_subscribe() - self.env.user
        self._message_auto_subscribe_notify(users.mapped('partner_id').ids)

Add notification to manager at expense creation


import os
from dbcollection.utils.file_load import load_json

def load_data_test(set_name, image_dir, annotation_path, verbose=True):
    """
    Load test data annotations.
    """
    data = {}

    # load annotation file
    if verbose:
        print('> Loading annotation file: ' + annotation_path)
    annotations = load_json(annotation_path)

    # parse annotations
    # images
    if verbose:
        print('> Processing image annotations... ')
    for i, annot in enumerate(annotations['images']):
        data[annot['id']] = {
            "width" : annot['width'],
            "height" : annot['height'],
            "filename" : os.path.join(image_dir, annot['file_name'])
        }

    # categories
    if verbose:
        print('> Processing category annotations... ')
    categories = {}
    category_list, supercategory_list = [], []
    for i, annot in enumerate(annotations['categories']):
        categories[annot['id']] = {
            "name" : annot['name'],
            "supercategory" : annot['supercategory']
        }
        category_list.append(annot['name'])
        supercategory_list.append(annot['supercategory'])
    supercategory_list = list(set(supercategory_list))

    return {set_name : [data, category_list, supercategory_list]}

import os
from dbcollection.utils.file_load import load_json

def load_data_test(set_name, image_dir, annotation_path, verbose=True):
    """
    Load test data annotations.
    """
    data = {}

    # load annotation file
    if verbose:
        print('> Loading annotation file: ' + annotation_path)
    annotations = load_json(annotation_path)

    # parse annotations
    # images
    if verbose:
        print('> Processing image annotations... ')
    for i, annot in enumerate(annotations['images']):
        data[annot['file_name']] = {
            "file_name" : os.path.join(image_dir, annot['file_name']),
            "width" : annot['width'],
            "height" : annot['height'],
            "id" : annot['id'],
            "coco_url" : annot['coco_url'],
        }

    # categories
    if verbose:
        print('> Processing category annotations... ')
    categories = {}
    category_list, supercategory_list = [], []
    for i, annot in enumerate(annotations['categories']):
        categories[annot['id']] = {
            "name" : annot['name'],
            "supercategory" : annot['supercategory'],
            "id" : annot['id']
        }
        category_list.append(annot['name'])
        supercategory_list.append(annot['supercategory'])
    supercategory_list = list(set(supercategory_list))

    return {set_name : [sorted(data), annotations, category_list, supercategory_list]}

Add annotations var to returned data

db: Add annotations var to returned data


import json

if __name__ == "__main__":
    input = sys.argv[1]
    output = sys.argv[2]
    processor = fix_changeline_budget_titles().process(input,output,[])

class fix_changeline_budget_titles(object):

    def process(self,inputs,output):

        out = []

        budgets = {}

        changes_jsons, budget_jsons = inputs

        for line in file(budget_jsons):
            line = json.loads(line.strip())
            budgets["%(year)s/%(code)s" % line] = line['title']

        outfile = file(output,"w")
        changed_num = 0
        for line in file(changes_jsons):
            line = json.loads(line.strip())
            title = budgets.get("%(year)s/%(budget_code)s" % line)
            if title != None and title != line['budget_title']:
                line['budget_title'] = title
                changed_num += 1
                outfile.write(json.dumps(line,sort_keys=True)+"\n")
        print "updated %d entries" % changed_num

import json
import logging

if __name__ == "__main__":
    input = sys.argv[1]
    output = sys.argv[2]
    processor = fix_changeline_budget_titles().process(input,output,[])

class fix_changeline_budget_titles(object):

    def process(self,inputs,output):

        out = []

        budgets = {}

        changes_jsons, budget_jsons = inputs

        for line in file(budget_jsons):
            line = json.loads(line.strip())
            budgets["%(year)s/%(code)s" % line] = line['title']

        outfile = file(output,"w")
        changed_num = 0
        for line in file(changes_jsons):
            line = json.loads(line.strip())
            key = "%(year)s/%(budget_code)s" % line
            title = budgets.get(key)
            if title != None and title != line['budget_title']:
                line['budget_title'] = title
                changed_num += 1
            else:
                logging.error("Failed to find title for change with key %s" % key)
            outfile.write(json.dumps(line,sort_keys=True)+"\n")
        print "updated %d entries" % changed_num

Fix bug in changeling title fix - it used to remove some lines on the way...


import random
from ...card import *

# Ragnaros the Firelord
class EX1_298(Card):
	cantAttack = True
	def onTurnEnd(self, player):
		self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8)

# Harrison Jones
class EX1_558(Card):
	def action(self):
		weapon = self.controller.opponent.hero.weapon
		if weapon:
			weapon.destroy()
			self.controller.draw(weapon.durability)

# Deathwing
class NEW1_030(Card):
	def action(self):
		for target in self.controller.getTargets(TARGET_ALL_MINIONS):
			# Let's not kill ourselves in the process
			if target is not self:
				target.destroy()
		self.controller.discardHand()

import random
from ...card import *

# Cairne Bloodhoof
class EX1_110(Card):
	deathrattle = summonMinion("EX1_110t")

# Baron Geddon
class EX1_249(Card):
	def action(self):
		for target in self.controller.getTargets(TARGET_ALL_MINIONS):
			if target is not self:
				self.hit(target, 2)

# Ragnaros the Firelord
class EX1_298(Card):
	cantAttack = True
	def onTurnEnd(self, player):
		self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8)

# Harrison Jones
class EX1_558(Card):
	def action(self):
		weapon = self.controller.opponent.hero.weapon
		if weapon:
			weapon.destroy()
			self.controller.draw(weapon.durability)

# Malygos
class EX1_563(Card):
	spellpower = 5

# Deathwing
class NEW1_030(Card):
	def action(self):
		for target in self.controller.getTargets(TARGET_ALL_MINIONS):
			# Let's not kill ourselves in the process
			if target is not self:
				target.destroy()
		self.controller.discardHand()

Implement Baron Geddon, Cairne Bloodhoof and Malygos


import changes
import urlparse

from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView

class IndexView(MethodView):
    def get(self, path=''):
        # require auth
        if not session.get('email'):
            return redirect(url_for('login'))

        if current_app.config['SENTRY_DSN']:
            parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
            dsn = '%s://%s@%s/%s' % (
                parsed.scheme,
                parsed.username,
                parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
                parsed.path,
            )
        else:
            dsn = None

        return render_template('index.html', **{
            'SENTRY_PUBLIC_DSN': dsn,
            'VERSION': changes.get_version(),
        })

import changes
import urlparse

from flask import render_template, current_app, redirect, url_for, session
from flask.views import MethodView

class IndexView(MethodView):
    def get(self, path=''):
        # require auth
        if not session.get('email'):
            return redirect(url_for('login'))

        if current_app.config['SENTRY_DSN'] and False:
            parsed = urlparse.urlparse(current_app.config['SENTRY_DSN'])
            dsn = '%s://%s@%s/%s' % (
                parsed.scheme,
                parsed.username,
                parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''),
                parsed.path,
            )
        else:
            dsn = None

        return render_template('index.html', **{
            'SENTRY_PUBLIC_DSN': dsn,
            'VERSION': changes.get_version(),
        })

Disable Sentry due to sync behavior

Disable Sentry due to sync behavior


import sys
import platform
import llvm

from llvm.core import Module
from llvm.ee import EngineBuilder
from llvm.utils import check_intrinsics

m = Module.new('fjoidajfa')
eb = EngineBuilder.new(m)
target = eb.select_target()

print('target.triple=%r' % target.triple)
if sys.platform == 'darwin':
    s = {'64bit': 'x86_64', '32bit': 'x86'}[platform.architecture()[0]]
    assert target.triple.startswith(s + '-apple-darwin')

assert llvm.test(verbosity=2, run_isolated=False) == 0
#check_intrinsics.main()

print('llvm.__version__: %s' % llvm.__version__)
#assert llvm.__version__ == '0.12.0'

import sys
import platform
import llvm
from llvm.ee import TargetMachine
target = TargetMachine.new()

print('target.triple=%r' % target.triple)
if sys.platform == 'darwin':
    s = {'64bit': 'x86_64', '32bit': 'x86'}[platform.architecture()[0]]
    assert target.triple.startswith(s + '-apple-darwin')

assert llvm.test(verbosity=2, run_isolated=False) == 0
print('llvm.__version__: %s' % llvm.__version__)

Fix buildscript for Python2 on OSX

Fix buildscript for Python2 on OSX


import networkx as nx
from ClusterUtility import ClusterUtility

class ConnectedComponents:
    """This is a class for connected component detection method to cluster event logs [1]_.

    References
    ----------
    .. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log
           clustering, The 2nd International Seminar on Science and Technology, 2016, pp. 495-496.
    """
    def __init__(self, graph):
        """This is a constructor for ConnectedComponent class.

        Parameters
        ----------
        graph : graph
            A graph to be clustered.
        """
        self.graph = graph

    def get_clusters(self):
        """This method find any connected component in a graph.

        A component represents a cluster and each component will be given a cluster identifier.
        This method heavily rely on the cosine similarity threshold to build an edge in a graph.

        Returns
        -------
        clusters : dict[list]
            Dictionary of cluster list, where each list contains index (line number) of event log.
        """
        clusters = {}
        cluster_id = 0
        for components in nx.connected_components(self.graph):
            clusters[cluster_id] = components
            cluster_id += 1

        ClusterUtility.set_cluster_id(self.graph, clusters)

        return clusters

import networkx as nx
from ClusterUtility import ClusterUtility

class ConnectedComponents:
    """This is a class for connected component detection method to cluster event logs [Studiawan2016a]_.

    References
    ----------
    .. [Studiawan2016a] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log
                        clustering, The 2nd International Seminar on Science and Technology, 2016, pp. 495-496.
    """
    def __init__(self, graph):
        """This is a constructor for ConnectedComponent class.

        Parameters
        ----------
        graph : graph
            A graph to be clustered.
        """
        self.graph = graph

    def get_clusters(self):
        """This method find any connected component in a graph.

        A component represents a cluster and each component will be given a cluster identifier.
        This method heavily rely on the cosine similarity threshold to build an edge in a graph.

        Returns
        -------
        clusters : dict[list]
            Dictionary of cluster list, where each list contains index (line number) of event log.
        """
        clusters = {}
        cluster_id = 0
        for components in nx.connected_components(self.graph):
            clusters[cluster_id] = components
            cluster_id += 1

        ClusterUtility.set_cluster_id(self.graph, clusters)

        return clusters

Fix bug in docstring references Studiawan2016a


import networkx as nx

class ConnectedComponents:
    """This is a class for connected component detection method to cluster event logs [1]_.

    .. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log
       clustering, in Proceedings of the International Seminar on Science and Technology, 2016, pp. 495-496.
    """
    def __init__(self, g):
        """This is a constructor for ConnectedComponent class

        Parameters
        ----------
        g : graph
            a graph to be clustered
        """
        self.g = g

    def get_clusters(self):
        """This method find any connected component in a graph.

        A component represents a cluster and each component will be given a cluster identifier.

        Returns
        -------
        clusters : list[list]
            List of cluster list, where each list contains index (line number) of event log.
        """
        clusters = []
        for components in nx.connected_components(self.g):
            clusters.append(components)

        cluster_id = 0
        for cluster in clusters:
            for node in cluster:
                self.g.node[node]['cluster'] = cluster_id
            cluster_id += 1

        return clusters

Add new line in the end of the file

Add new line in the end of the file


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

class Vertex(object):
	"""Vertex class.

    It uses a dict to keep track of the vertices which it's connected.
	"""

class Graph(object):
    """Graph class.

    It contains a dict to map vertex name to vertex objects.
    """
    pass

def main():
    pass

if __name__ == '__main__':
    main()

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

class Vertex(object):
	"""Vertex class.

    It uses a dict to keep track of the vertices which it's connected.
	"""
	def __init__(self, key):
		self.id = key
		self.connected_to_dict = {}

	def add_neighnor(self, new_nb, weight=0):
		pass

	def __str__(self):
		pass

	def get_connections(self):
		pass

	def get_id(self):
		pass

	def get_weight(self, new_nb):
		pass

class Graph(object):
    """Graph class.

    It contains a dict to map vertex name to vertex objects.
    """
    pass

def main():
    pass

if __name__ == '__main__':
    main()

Implement Vertex class’s __init__ and helper functions


# Copyright 2017 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import fields, models

class AccountMoveLine(models.Model):

    _inherit = 'account.move.line'

    date_range_fy_id = fields.Many2one(
        related='move_id.date_range_fy_id',
        store=True, copy=False)

# Copyright 2017 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import fields, models

class AccountMoveLine(models.Model):

    _inherit = 'account.move.line'

    date_range_fy_id = fields.Many2one(
        related='move_id.date_range_fy_id',
    )

[FIX] Remove unneeded and inefficient "store=True"


# coding: utf-8
import requests

def test_forbidden_get(live_server):

    r = requests.get(live_server.url + '/all-rpc/')
    assert r.status_code == 405

    r2 = requests.post(live_server.url + '/all-rpc/')
    assert r2.status_code == 200

def test_allowed_get(live_server):

    r = requests.get(live_server.url + '/all-rpc-doc/')
    assert r.status_code == 200

    r2 = requests.post(live_server.url + '/all-rpc-doc/')
    assert r2.status_code == 405

# coding: utf-8
import requests
from django.core.exceptions import ImproperlyConfigured
from pytest import raises

from modernrpc.views import RPCEntryPoint

def test_forbidden_get(live_server):

    r = requests.get(live_server.url + '/all-rpc/')
    assert r.status_code == 405

    r2 = requests.post(live_server.url + '/all-rpc/')
    assert r2.status_code == 200

def test_allowed_get(live_server):

    r = requests.get(live_server.url + '/all-rpc-doc/')
    assert r.status_code == 200

    r2 = requests.post(live_server.url + '/all-rpc-doc/')
    assert r2.status_code == 405

def test_invalid_entry_point(settings, rf):
    settings.MODERNRPC_HANDLERS = []

    entry_point = RPCEntryPoint.as_view()
    with raises(ImproperlyConfigured) as e:
        entry_point(rf.post('xxx'))

    assert 'handler' in str(e.value)

Test for bad setting value

Test for bad setting value


import logging.config

def configure_logging(filename):
    time_format = '[%(asctime)s] :: %(name)s - %(levelname)s - %(message)s'
    simple_format = '%(name)s - %(message)s'

    logging_config = {
        'version': 1,
        'formatters': {
            'time': {'format': time_format},
            'simple': {'format': simple_format},
            },
        'handlers': {
            # This is what gets printed out to the console
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
                'level': 'DEBUG',
                },
            # This is what gets saved to the file
            'file': {
                'class': 'logging.FileHandler',
                'formatter': 'time',
                'filename': filename,
                'level': 'DEBUG',
                }
            },
        'loggers': {
            '__main__': {'level': 'DEBUG'},
            'cochlear': {'level': 'DEBUG'},
            'cochlear.nidaqmx': {'level': 'ERROR'},
            },
        'root': {
            'handlers': ['console'],
            },
        }
    logging.config.dictConfig(logging_config)

import logging.config

def configure_logging(filename=None):
    time_format = '[%(asctime)s] :: %(name)s - %(levelname)s - %(message)s'
    simple_format = '%(name)s - %(message)s'

    logging_config = {
        'version': 1,
        'formatters': {
            'time': {'format': time_format},
            'simple': {'format': simple_format},
            },
        'handlers': {
            # This is what gets printed out to the console
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'simple',
                'level': 'DEBUG',
                },
            },
        'loggers': {
            '__main__': {'level': 'DEBUG'},
            'cochlear': {'level': 'DEBUG'},
            'cochlear.nidaqmx': {'level': 'ERROR'},
            },
        'root': {
            'handlers': ['console'],
            },
        }
    if filename is not None:
        logging_config['handlers']['file'] = {
            'class': 'logging.FileHandler',
            'formatter': 'time',
            'filename': filename,
            'level': 'DEBUG',
        }
        logging_config['root']['handlers'].append('file')
    logging.config.dictConfig(logging_config)

Allow logging to be config w/o filename

ENH: Allow logging to be config w/o filename


import redis_collections
import threading
import time
import __main__

class RedisDict(redis_collections.Dict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.die = False
        self.thread = threading.Thread(target=self.update_loop)
        self.thread.start()
        self.prev = None

    def update_loop(self):
        time.sleep(2)
        while not (__main__.liara.stopped or self.die):
            if self.prev != repr(self):
                self.prev = repr(self)
                self.sync()
                time.sleep(0.1)
            else:
                self.cache.clear()
                time.sleep(0.1)

class dataIO:
    @staticmethod
    def save_json(filename, content):
        pass  # "oops"

    @staticmethod
    def load_json(filename):
        return RedisDict(key=filename, redis=__main__.redis_conn, writeback=True)

import redis_collections
import threading
import time
import __main__

class RedisDict(redis_collections.Dict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.die = False
        self.thread = threading.Thread(target=self.update_loop, daemon=True)
        self.thread.start()
        self.prev = None

    def update_loop(self):
        time.sleep(2)
        while not (__main__.liara.stopped or self.die):
            if self.prev != repr(self):
                self.prev = repr(self)
                self.sync()
                time.sleep(0.1)
            else:
                self.cache.clear()
                time.sleep(0.1)

class dataIO:
    @staticmethod
    def save_json(filename, content):
        pass  # "oops"

    @staticmethod
    def load_json(filename):
        return RedisDict(key=filename, redis=__main__.redis_conn, writeback=True)

Make threads run in daemon mode

Make threads run in daemon mode