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

import os
import sys
import logging
import subprocess

from setuptools import setup
from setuptools.command.install import install

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("virtual-node")

class node_install(install):
    env_dir = os.environ['VIRTUAL_ENV']
    default_version = '0.8.11'
    verbose = False

    def run(self):
        versions = self.distribution.get_version().rsplit('-', 1)
        if len(versions) == 2:
            self.version = versions[1]
        else:
            self.version = self.default_version

        self.install_node(self.env_dir)
        self.run_npm(self.env_dir)
        self.run_bower(self.env_dir)

    def get_node_src_url(self, version, postfix=''):
        node_name = 'node-v%s%s' % (version, postfix)
        tar_name = '%s.tar.gz' % (node_name)
        if version > "0.5.0":
            node_url = 'http://nodejs.org/dist/v%s/%s' % (version, tar_name)
        else:
            node_url = 'http://nodejs.org/dist/%s' % (tar_name)
        return node_url

    def run_cmd(self, cmd, cwd=None, extra_env=None):
        """
        Execute cmd line in sub-shell
        """
        all_output = []
        cmd_parts = []

        for part in cmd:
            if len(part) > 45:
                part = part[:20] + "..." + part[-20:]
            if ' ' in part or '\n' in part or '"' in part or "'" in part:
                part = '"%s"' % part.replace('"', '\\"')
            cmd_parts.append(part)
        cmd_desc = ' '.join(cmd_parts)
        logger.debug(" ** Running command %s" % cmd_desc)

        # output
        stdout = subprocess.PIPE

        # env
        if extra_env:
            env = os.environ.copy()
            if extra_env:
                env.update(extra_env)
        else:
            env = None

        # execute
        try:
            proc = subprocess.Popen(
                [' '.join(cmd)], stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
                cwd=cwd, env=env, shell=True)
        except Exception:
            e = sys.exc_info()[1]
            logger.error("Error %s while executing command %s" % (e, cmd_desc))
            raise

        stdout = proc.stdout
        while stdout:
            line = stdout.readline()
            if not line:
                break
            line = line.rstrip()
            all_output.append(line)
            logger.info(line)
        proc.wait()

        # error handler
        if proc.returncode:
            for s in all_output:
                logger.critical(s)
            raise OSError("Command %s failed with error code %s"
                % (cmd_desc, proc.returncode))

        return proc.returncode, all_output

    def run_npm(self, env_dir):
        if os.path.exists("%s%s" % (env_dir, "package.json")):
            self.run_cmd(['npm', 'install'], env_dir)
        else:
            logger.warning("Could not find 'package.json', ignoring NPM dependencies.")

    def run_bower(self, env_dir):
        bower_bin = "%s/bin/bower" % env_dir
        if not os.path.exists(bower_bin):
            logger.warning("Could not find 'bower' executable, ignoring it")
            return

        if os.path.exists("%s%s" % (env_dir, "components.json")):
            self.run_cmd(['bower', 'install'], env_dir)
        else:
            logger.warning("Could not find 'components.json', ignoring bower dependencies.")

    def install_node(self, env_dir, version=None):
        """
        Download source code for node.js, unpack it
        and install it in virtual environment.
        """
        logger.info(
            ' * Install node.js (%s' % self.version,
            extra={'continued': True}
        )

        node_name = 'node-v%s' % (self.version)
        node_url = self.get_node_src_url(self.version)

        src_dir = os.path.join(env_dir, 'src')
        node_src_dir = os.path.join(src_dir, node_name)
        env_dir = os.path.abspath(env_dir)

        if not os.path.exists(node_src_dir):
            os.makedirs(node_src_dir)

        cmd = [
            'curl', '--silent', '-L', node_url, '|',
            'tar', 'xzf', '-', '-C', src_dir,
        ]
        try:
            self.run_cmd(cmd, env_dir)
            logger.info(') ', extra=dict(continued=True))
        except OSError:
            postfix = '-RC1'
            logger.info('%s) ' % postfix, extra=dict(continued=True))
            new_node_url = self.get_node_src_url(self.version, postfix)
            cmd[cmd.index(node_url)] = new_node_url
            self.run_cmd(cmd, env_dir)

        logger.info('.', extra=dict(continued=True))

        conf_cmd = [
            './configure',
            '--prefix=%s' % (env_dir),
        ]

        self.run_cmd(conf_cmd, node_src_dir)
        logger.info('.', extra=dict(continued=True))
        self.run_cmd(['make'], node_src_dir)
        logger.info('.', extra=dict(continued=True))
        self.run_cmd(['make install'], node_src_dir)

        logger.info(' done.')

setup(
    name='virtual-node',
    version='0.0.2-0.8.11',
    description='Install node.js into your virtualenv',
    author='Sebastian Vetter',
    author_email='sebastian@roadside-developer.com',
    url='http://github.com/elbaschid/virtual-node',
    long_description=open('README.rst', 'r').read(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX',
        'Programming Language :: JavaScript',
        'Topic :: Software Development :: Libraries',
    ],
    license='BSD',
    cmdclass={
        'install': node_install,
    }
)
<commit_msg>Clean up source tree after building Branch: cleanup-build-tree<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import logging
import subprocess

from setuptools import setup
from setuptools.command.install import install

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("virtual-node")

class node_install(install):
    env_dir = os.environ['VIRTUAL_ENV']
    default_version = '0.8.11'
    verbose = False

    def run(self):
        versions = self.distribution.get_version().rsplit('-', 1)
        if len(versions) == 2:
            self.version = versions[1]
        else:
            self.version = self.default_version

        self.install_node(self.env_dir)
        self.run_npm(self.env_dir)
        self.run_bower(self.env_dir)

    def get_node_src_url(self, version, postfix=''):
        node_name = 'node-v%s%s' % (version, postfix)
        tar_name = '%s.tar.gz' % (node_name)
        if version > "0.5.0":
            node_url = 'http://nodejs.org/dist/v%s/%s' % (version, tar_name)
        else:
            node_url = 'http://nodejs.org/dist/%s' % (tar_name)
        return node_url

    def run_cmd(self, cmd, cwd=None, extra_env=None):
        """
        Execute cmd line in sub-shell
        """
        all_output = []
        cmd_parts = []

        for part in cmd:
            if len(part) > 45:
                part = part[:20] + "..." + part[-20:]
            if ' ' in part or '\n' in part or '"' in part or "'" in part:
                part = '"%s"' % part.replace('"', '\\"')
            cmd_parts.append(part)
        cmd_desc = ' '.join(cmd_parts)
        logger.debug(" ** Running command %s" % cmd_desc)

        # output
        stdout = subprocess.PIPE

        # env
        if extra_env:
            env = os.environ.copy()
            if extra_env:
                env.update(extra_env)
        else:
            env = None

        # execute
        try:
            proc = subprocess.Popen(
                [' '.join(cmd)], stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
                cwd=cwd, env=env, shell=True)
        except Exception:
            e = sys.exc_info()[1]
            logger.error("Error %s while executing command %s" % (e, cmd_desc))
            raise

        stdout = proc.stdout
        while stdout:
            line = stdout.readline()
            if not line:
                break
            line = line.rstrip()
            all_output.append(line)
            logger.info(line)
        proc.wait()

        # error handler
        if proc.returncode:
            for s in all_output:
                logger.critical(s)
            raise OSError("Command %s failed with error code %s"
                % (cmd_desc, proc.returncode))

        return proc.returncode, all_output

    def run_npm(self, env_dir):
        if os.path.exists("%s%s" % (env_dir, "package.json")):
            self.run_cmd(['npm', 'install'], env_dir)
        else:
            logger.warning("Could not find 'package.json', ignoring NPM dependencies.")

    def run_bower(self, env_dir):
        bower_bin = "%s/bin/bower" % env_dir
        if not os.path.exists(bower_bin):
            logger.warning("Could not find 'bower' executable, ignoring it")
            return

        if os.path.exists("%s%s" % (env_dir, "components.json")):
            self.run_cmd(['bower', 'install'], env_dir)
        else:
            logger.warning("Could not find 'components.json', ignoring bower dependencies.")

    def install_node(self, env_dir, version=None):
        """
        Download source code for node.js, unpack it
        and install it in virtual environment.
        """
        logger.info(
            ' * Install node.js (%s' % self.version,
            extra={'continued': True}
        )

        node_name = 'node-v%s' % (self.version)
        node_url = self.get_node_src_url(self.version)

        src_dir = os.path.join(env_dir, 'src')
        node_src_dir = os.path.join(src_dir, node_name)
        env_dir = os.path.abspath(env_dir)

        if not os.path.exists(node_src_dir):
            os.makedirs(node_src_dir)

        cmd = [
            'curl', '--silent', '-L', node_url, '|',
            'tar', 'xzf', '-', '-C', src_dir,
        ]
        try:
            self.run_cmd(cmd, env_dir)
            logger.info(') ', extra=dict(continued=True))
        except OSError:
            postfix = '-RC1'
            logger.info('%s) ' % postfix, extra=dict(continued=True))
            new_node_url = self.get_node_src_url(self.version, postfix)
            cmd[cmd.index(node_url)] = new_node_url
            self.run_cmd(cmd, env_dir)

        logger.info('.', extra=dict(continued=True))

        conf_cmd = [
            './configure',
            '--prefix=%s' % (env_dir),
        ]

        self.run_cmd(conf_cmd, node_src_dir)
        logger.info('.', extra=dict(continued=True))
        self.run_cmd(['make'], node_src_dir)
        logger.info('.', extra=dict(continued=True))
        self.run_cmd(['make install'], node_src_dir)
        logger.info('.', extra=dict(continued=True))
        self.run_cmd(['rm -rf "%s"' % node_src_dir])

        logger.info(' done.')

setup(
    name='virtual-node',
    version='0.0.2-0.8.11',
    description='Install node.js into your virtualenv',
    author='Sebastian Vetter',
    author_email='sebastian@roadside-developer.com',
    url='http://github.com/elbaschid/virtual-node',
    long_description=open('README.rst', 'r').read(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX',
        'Programming Language :: JavaScript',
        'Topic :: Software Development :: Libraries',
    ],
    license='BSD',
    cmdclass={
        'install': node_install,
    }
)
<|endoftext|>


<commit_before># -*- coding: utf-8  -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys

from distribute_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages

if sys.version_info[0] != 2:
    raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
    raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
    depend = ['httplib2>=0.6.0']

setup(name='Pywikipediabot',
      version ='2.0alpha',
      description ='Python Wikipedia Bot Framework',
      license = 'MIT',
      packages = find_packages(),
      install_requires = depend
     )

# automatically launch generate_user_files.py

import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
<commit_msg>Set tests folder so users can run "$python setup.py test", also PEP8 fixes.<commit_after># -*- coding: utf-8  -*-
"""installer script for pywikibot 2.0 framework"""
#
# (C) Pywikipedia team, 2009-2012
#
__version__ = '$Id$'
#
# Distributed under the terms of the MIT license.
#
import sys

from distribute_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages

if sys.version_info[0] != 2:
    raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2")
if sys.version_info[1] < 6:
    raise RuntimeError("ERROR: Pywikipediabot only runs under Python 2.6 or higher")
else:
    depend = ['httplib2>=0.6.0']

setup(name='Pywikipediabot',
      version='2.0alpha',
      description='Python Wikipedia Bot Framework',
      license='MIT',
      packages=find_packages(),
      install_requires=depend,
      test_suite="tests",
      )

# automatically launch generate_user_files.py

import subprocess
python = sys.executable
python = python.replace("pythonw.exe", "python.exe") # for Windows
ignore = subprocess.call([python, "generate_user_files.py"])
<|endoftext|>


<commit_before>#! /usr/bin/env python2

from distutils.core import setup

setup(name="vy",
      version="2.5.0",
      description="A vim-like in python made from scratch.",
      packages=["vyapp",
                "vyapp.plugins",
                "vyapp.plugins.syntax",
                "vyapp.plugins.syntax.styles",
                "vyapp.plugins.jdb",
                "vyapp.plugins.pdb"],
      scripts=['vy', 'askpass'],
      package_data={'vyapp': ['vyrc'], 'vyapp.plugins':['tern-config']},
      author="Iury O. G. Figueiredo",
      author_email="ioliveira@id.uff.br",
      url='https://github.com/iogf/vy',
      download_url='https://github.com/iogf/vy/releases',
      keywords=['vy', 'vi', 'vim', 'emacs', 'sublime', 'atom', 'nano', 'vim-like'],
      classifiers=[])

<commit_msg>Fixing setup.py version.<commit_after>#! /usr/bin/env python

from distutils.core import setup

setup(name="vy",
      version="3.0.0",
      description="A vim-like in python made from scratch.",
      packages=["vyapp",
                "vyapp.plugins",
                "vyapp.plugins.syntax",
                "vyapp.plugins.syntax.styles",
                "vyapp.plugins.jdb",
                "vyapp.plugins.pdb"],
      scripts=['vy', 'askpass'],
      package_data={'vyapp': ['vyrc'], 'vyapp.plugins':['tern-config']},
      author="Iury O. G. Figueiredo",
      author_email="ioliveira@id.uff.br",
      url='https://github.com/iogf/vy',
      download_url='https://github.com/iogf/vy/releases',
      keywords=['vy', 'vi', 'vim', 'emacs', 'sublime', 'atom', 'nano', 'vim-like'],
      classifiers=[])

<|endoftext|>


<commit_before>from setuptools import setup

setup(
        name='invo',
        version='0.1',
        description='A Generalized Inverse Optimization package.',
        author='Rafid Mahmood',
        author_email='rafid.mahmood@mail.utoronto.ca',
        url='https://github.com/rafidrm/invo',
        download_url='https://github.com/rafidrm/invo/archive/0.1.tar.gz',
        license='MIT',
        packages=['invo',
            'invo.LinearModels',
            'invo.utils'],
        keywords=['optimization','inverse'],
        install_requires=['numpy', 'cvxpy'],
        zip_safe=False)
<commit_msg>updated setup.py<commit_after>from setuptools import setup

setup(
        name='invo',
        version='0.2',
        description='A Generalized Inverse Optimization package.',
        author='Rafid Mahmood',
        author_email='rafid.mahmood@mail.utoronto.ca',
        url='https://github.com/rafidrm/invo',
        download_url='https://github.com/rafidrm/invo/archive/0.1.tar.gz',
        license='MIT',
        packages=['invo',
            'invo.LinearModels',
            'invo.utils'],
        keywords=['optimization','inverse'],
        install_requires=['numpy', 'cvxpy'],
        zip_safe=False)
<|endoftext|>


<commit_before>from setuptools import setup

setup(name='umapi',
      version='0.7.0',
      description='Adobe User Management API Interfaces',
      url='git@git.corp.adobe.com:adorton/cce-umapi.git',
      author='Andrew Dorton',
      author_email='adorton@adobe.com',
      license='Copyright Adobe Systems',
      packages=['umapi'],
      install_requires=[
            'requests',
            'cryptography',
            'PyJWT',
            'mock',
            'nose>=1.0'
      ],
      zip_safe=False)
<commit_msg>version bump<commit_after>from setuptools import setup

setup(name='umapi',
      version='0.9.0',
      description='Adobe User Management API Interfaces',
      url='git@git.corp.adobe.com:adorton/cce-umapi.git',
      author='Andrew Dorton',
      author_email='adorton@adobe.com',
      license='Copyright Adobe Systems',
      packages=['umapi'],
      install_requires=[
            'requests',
            'cryptography',
            'PyJWT',
            'mock',
            'nose>=1.0'
      ],
      zip_safe=False)
<|endoftext|>


<commit_before>#!/usr/bin/env python

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

import os
import sys

# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
    os.environ['C_INCLUDE_PATH'] = '/usr/local/include'

version = '0.1'

setup(  name = 'coi-services',
        version = version,
        description = 'OOI ION COI Services',
        url = 'https://github.com/ooici/coi-services',
        download_url = 'http://ooici.net/releases',
        license = 'Apache 2.0',
        author = 'Michael Meisinger',
        author_email = 'mmeisinger@ucsd.edu',
        keywords = ['ooici','ioncore', 'pyon', 'coi'],
        packages = find_packages(),
        dependency_links = [
            'http://ooici.net/releases'
        ],
        test_suite = 'pyon',
        install_requires = [
            'pyon',
            'Flask==0.8',
            'WebTest',
            'h5py==2.0.1'
        ],
     )
<commit_msg>Removed hdf5 from setup.py. Keeping only the buildout install for hdf5 in coi-services.<commit_after>#!/usr/bin/env python

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

import os
import sys

# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
    os.environ['C_INCLUDE_PATH'] = '/usr/local/include'

version = '0.1'

setup(  name = 'coi-services',
        version = version,
        description = 'OOI ION COI Services',
        url = 'https://github.com/ooici/coi-services',
        download_url = 'http://ooici.net/releases',
        license = 'Apache 2.0',
        author = 'Michael Meisinger',
        author_email = 'mmeisinger@ucsd.edu',
        keywords = ['ooici','ioncore', 'pyon', 'coi'],
        packages = find_packages(),
        dependency_links = [
            'http://ooici.net/releases'
        ],
        test_suite = 'pyon',
        install_requires = [
            'pyon',
            'Flask==0.8',
            'WebTest',
        ],
     )
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from __future__ import absolute_import

from functools import wraps
from flask import session, abort, current_app, request, jsonify
from marshmallow.exceptions import ValidationError
from eduid_userdb.exceptions import UserDoesNotExist, MultipleUsersReturned
from eduid_common.api.utils import retrieve_modified_ts
from eduid_common.api.schemas.base import FluxStandardAction
from eduid_common.api.schemas.models import FluxResponseStatus, FluxSuccessResponse, FluxFailResponse
from eduid_common.api.exceptions import ApiException

__author__ = 'lundberg'

def require_eppn(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        eppn = session.get('user_eppn', None)
        # If the user is logged in and has a session
        # pass on the request to the decorated view
        # together with the eppn of the logged in user.
        if eppn:
            kwargs['eppn'] = eppn
            return f(*args, **kwargs)
        raise ApiException('Not authorized', status_code=401)
    return decorated_function

def _get_user():
    eppn = session.get('user_eppn', None)
    if not eppn:
        raise ApiException('Not authorized', status_code=401)
    # Get user from central database
    try:
        return current_app.central_userdb.get_user_by_eppn(eppn, raise_on_missing=True)
    except UserDoesNotExist as e:
        current_app.logger.error('Could not find user central database.')
        current_app.logger.error(e)
        raise ApiException('Not authorized', status_code=401)
    except MultipleUsersReturned as e:
        current_app.logger.error('Found multiple users in central database.')
        current_app.logger.error(e)
        raise ApiException('Not authorized', status_code=401)

def require_user(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = _get_user()
        kwargs['user'] = user
        return f(*args, **kwargs)
    return decorated_function

def require_dashboard_user(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = _get_user()
        retrieve_modified_ts(user, current_app.dashboard_userdb)
        kwargs['user'] = user
        return f(*args, **kwargs)
    return decorated_function

def require_support_personnel(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        eppn = session.get('user_eppn', None)

        # If the logged in user is whitelisted then we
        # pass on the request to the decorated view
        # together with the eppn of the logged in user.
        if eppn in current_app.config['SUPPORT_PERSONNEL']:
            kwargs['logged_in_user'] = eppn
            return f(*args, **kwargs)
        current_app.logger.warning('{!s} not in support personnel whitelist: {!s}'.format(
            eppn, current_app.config['SUPPORT_PERSONNEL']))
        # Anything else is considered as an unauthorized request
        abort(403)
    return decorated_function

class MarshalWith(object):

    def __init__(self, schema):
        self.schema = schema

    def __call__(self, f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            ret = f(*args, **kwargs)
            response_status = ret.pop('_status', FluxResponseStatus.ok)

            # Handle fail responses
            if response_status != FluxResponseStatus.ok:
                response_data = FluxFailResponse(request, payload=ret)
                return jsonify(FluxStandardAction().dump(response_data.to_dict()).data)

            # Handle success responses
            response_data = FluxSuccessResponse(request, payload=ret)
            return jsonify(self.schema().dump(response_data.to_dict()).data)
        return decorated_function

class UnmarshalWith(object):

    def __init__(self, schema):
        self.schema = schema

    def __call__(self, f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                json_data = request.get_json(force=True)
                if json_data is None:
                    json_data = {}
                unmarshal_result = self.schema().load(json_data)
                kwargs.update(unmarshal_result.data)
                return f(*args, **kwargs)
            except ValidationError as e:
                response_data = FluxFailResponse(request, payload={'error': e.normalized_messages()})
                return jsonify(response_data.to_dict())
        return decorated_function

<commit_msg>Revert "Try to parse json even with wrong content type"<commit_after># -*- coding: utf-8 -*-

from __future__ import absolute_import

from functools import wraps
from flask import session, abort, current_app, request, jsonify
from marshmallow.exceptions import ValidationError
from eduid_userdb.exceptions import UserDoesNotExist, MultipleUsersReturned
from eduid_common.api.utils import retrieve_modified_ts
from eduid_common.api.schemas.base import FluxStandardAction
from eduid_common.api.schemas.models import FluxResponseStatus, FluxSuccessResponse, FluxFailResponse
from eduid_common.api.exceptions import ApiException

__author__ = 'lundberg'

def require_eppn(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        eppn = session.get('user_eppn', None)
        # If the user is logged in and has a session
        # pass on the request to the decorated view
        # together with the eppn of the logged in user.
        if eppn:
            kwargs['eppn'] = eppn
            return f(*args, **kwargs)
        raise ApiException('Not authorized', status_code=401)
    return decorated_function

def _get_user():
    eppn = session.get('user_eppn', None)
    if not eppn:
        raise ApiException('Not authorized', status_code=401)
    # Get user from central database
    try:
        return current_app.central_userdb.get_user_by_eppn(eppn, raise_on_missing=True)
    except UserDoesNotExist as e:
        current_app.logger.error('Could not find user central database.')
        current_app.logger.error(e)
        raise ApiException('Not authorized', status_code=401)
    except MultipleUsersReturned as e:
        current_app.logger.error('Found multiple users in central database.')
        current_app.logger.error(e)
        raise ApiException('Not authorized', status_code=401)

def require_user(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = _get_user()
        kwargs['user'] = user
        return f(*args, **kwargs)
    return decorated_function

def require_dashboard_user(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = _get_user()
        retrieve_modified_ts(user, current_app.dashboard_userdb)
        kwargs['user'] = user
        return f(*args, **kwargs)
    return decorated_function

def require_support_personnel(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        eppn = session.get('user_eppn', None)

        # If the logged in user is whitelisted then we
        # pass on the request to the decorated view
        # together with the eppn of the logged in user.
        if eppn in current_app.config['SUPPORT_PERSONNEL']:
            kwargs['logged_in_user'] = eppn
            return f(*args, **kwargs)
        current_app.logger.warning('{!s} not in support personnel whitelist: {!s}'.format(
            eppn, current_app.config['SUPPORT_PERSONNEL']))
        # Anything else is considered as an unauthorized request
        abort(403)
    return decorated_function

class MarshalWith(object):

    def __init__(self, schema):
        self.schema = schema

    def __call__(self, f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            ret = f(*args, **kwargs)
            response_status = ret.pop('_status', FluxResponseStatus.ok)

            # Handle fail responses
            if response_status != FluxResponseStatus.ok:
                response_data = FluxFailResponse(request, payload=ret)
                return jsonify(FluxStandardAction().dump(response_data.to_dict()).data)

            # Handle success responses
            response_data = FluxSuccessResponse(request, payload=ret)
            return jsonify(self.schema().dump(response_data.to_dict()).data)
        return decorated_function

class UnmarshalWith(object):

    def __init__(self, schema):
        self.schema = schema

    def __call__(self, f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                json_data = request.get_json()
                if json_data is None:
                    json_data = {}
                unmarshal_result = self.schema().load(json_data)
                kwargs.update(unmarshal_result.data)
                return f(*args, **kwargs)
            except ValidationError as e:
                response_data = FluxFailResponse(request, payload={'error': e.normalized_messages()})
                return jsonify(response_data.to_dict())
        return decorated_function

<|endoftext|>


<commit_before>import re
import os

from setuptools import setup, find_packages

with open(
        os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            'aiocache/_version.py')) as fp:
    try:
        version = re.findall(
            r"^__version__ = \"([^']+)\"\r?$", fp.read(), re.M)[0]
    except IndexError:
        raise RuntimeError('Unable to determine version.')

with open('README.rst', 'rt', encoding='utf8') as f:
    readme = f.read()

setup(
    name='aiocache',
    version=version,
    author='Manuel Miranda',
    url='https://github.com/argaen/aiocache',
    author_email='manu.mirandad@gmail.com',
    description='multi backend asyncio cache',
    long_description=readme,
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Framework :: AsyncIO',
    ],
    packages=find_packages(),
    install_requires=None,
    extras_require={
        'redis:python_version<"3.7"': ['aioredis>=0.3.3'],
        'redis:python_version>="3.8"': ['aioredis>=1.3.0'],
        'redis:python_version>="3.7" and python_version<"3.8"': ['aioredis>=1.0.0'],
        'memcached': ['aiomcache>=0.5.2'],
        'msgpack': ['msgpack>=0.5.5'],
        'dev': [
            'asynctest>=0.11.0',
            'black;python_version>="3.6"',
            'codecov',
            'coverage',
            'flake8',
            'ipdb',
            'marshmallow>=3',
            'pystache',
            'pytest',
            'pytest-asyncio',
            'pytest-mock',
            'sphinx',
            'sphinx-autobuild',
            'sphinx-rtd-theme',
        ]
    }
)
<commit_msg>setup.py: Update URL (#521)<commit_after>import re
import os

from setuptools import setup, find_packages

with open(
        os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            'aiocache/_version.py')) as fp:
    try:
        version = re.findall(
            r"^__version__ = \"([^']+)\"\r?$", fp.read(), re.M)[0]
    except IndexError:
        raise RuntimeError('Unable to determine version.')

with open('README.rst', 'rt', encoding='utf8') as f:
    readme = f.read()

setup(
    name='aiocache',
    version=version,
    author='Manuel Miranda',
    url='https://github.com/aio-libs/aiocache',
    author_email='manu.mirandad@gmail.com',
    description='multi backend asyncio cache',
    long_description=readme,
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Framework :: AsyncIO',
    ],
    packages=find_packages(),
    install_requires=None,
    extras_require={
        'redis:python_version<"3.7"': ['aioredis>=0.3.3'],
        'redis:python_version>="3.8"': ['aioredis>=1.3.0'],
        'redis:python_version>="3.7" and python_version<"3.8"': ['aioredis>=1.0.0'],
        'memcached': ['aiomcache>=0.5.2'],
        'msgpack': ['msgpack>=0.5.5'],
        'dev': [
            'asynctest>=0.11.0',
            'black;python_version>="3.6"',
            'codecov',
            'coverage',
            'flake8',
            'ipdb',
            'marshmallow>=3',
            'pystache',
            'pytest',
            'pytest-asyncio',
            'pytest-mock',
            'sphinx',
            'sphinx-autobuild',
            'sphinx-rtd-theme',
        ]
    }
)
<|endoftext|>


<commit_before>#
# Copyright (c) 2016 NORDUnet A/S
# All rights reserved.
#
#   Redistribution and use in source and binary forms, with or
#   without modification, are permitted provided that the following
#   conditions are met:
#
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#     2. Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials provided
#        with the distribution.
#     3. Neither the name of the NORDUnet nor the names of its
#        contributors may be used to endorse or promote products derived
#        from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

from collections import OrderedDict

from eduid_msg.celery import celery, get_message_relay
from eduid_msg.tasks import sendmail

import logging
logger = logging.getLogger(__name__)

class MsgRelay(object):

    class TaskFailed(Exception):
        pass

    def __init__(self, settings):

        config = settings.get('default_celery_conf')
        config.update({
            'BROKER_URL': settings.get('msg_broker_url'),
            'MONGO_URI': settings.get('mongo_uri'),
        })
        celery.conf.update(config)

        self._relay = get_message_relay(celery)
        self.settings = settings
        self._sendmail = sendmail

    def sendmail(self, subject, recipients, text=None, html=None):
        """
        """
        rtask = self._sendmail.apply_async(subject, recipients,
                                           text=None, html=None)
        # XXX this goes in its own thread
        try:
            rtask.wait()
        except Exception as e:
            raise self.TaskFailed('Error sending mail: {!r}'.format(e))

        if rtask.successful():
            result = rtask.get()
            return result
        else:
            raise self.TaskFailed('Something went wrong')
<commit_msg>mail relay, wip<commit_after>#
# Copyright (c) 2016 NORDUnet A/S
# All rights reserved.
#
#   Redistribution and use in source and binary forms, with or
#   without modification, are permitted provided that the following
#   conditions are met:
#
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#     2. Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials provided
#        with the distribution.
#     3. Neither the name of the NORDUnet nor the names of its
#        contributors may be used to endorse or promote products derived
#        from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from flask import current_app
from eduid_msg.celery import celery, get_message_relay
from eduid_msg.tasks import sendmail

import logging
logger = logging.getLogger(__name__)

class MailRelay(object):

    class TaskFailed(Exception):
        pass

    def __init__(self, settings):

        config = settings.get('default_celery_conf', {})
        config.update({
            'BROKER_URL': settings.get('msg_broker_url'),
            'MONGO_URI': settings.get('mongo_uri'),
        })
        celery.conf.update(config)

        self._relay = get_message_relay(celery)
        self.settings = settings
        self._sendmail = sendmail

    def sendmail(self, subject, recipients, text=None, html=None):
        """
        """
        sender = current_app.conf.get("MAIL_DEFAULT_SENDER")
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ', '.join(recipients)
        if text:
            msg.attach(MIMEText(text, 'plain'))
        if html:
            msg.attach(MIMEText(html, 'html'))

        logger.debug('About to send email:\n\n {}'.format(msg.as_string()))

        def wait_for_sendmail():
            rtask = self._sendmail.apply_async(sender, recipients, msg)
            try:
                rtask.wait()
            except Exception as e:
                err = 'Error sending mail: {!r}'.format(e)
                logger.error(err)
                raise self.TaskFailed(err)

            if rtask.successful():
                result = rtask.get()
                logger.info('Success sending mail, {!r}'.format(result))
            else:
                err = 'Something went wrong'
                logger.error(err)
                raise self.TaskFailed(err)

        t = threading.Thread(target=wait_for_sendmail)
        t.daemon = True
        t.start()

def init_relay(app):
    """
    :param app: Flask app
    :type app: flask.Flask
    :return: Flask app
    :rtype: flask.Flask
    """
    app.mail_relay = MailRelay(app.config)
    return app
<|endoftext|>


<commit_before>from os.path import dirname, join
try:
	from setuptools import setup, Extension
except ImportError:
	from distutils.core import setup, Extension

# If you change the version here, also change it in jsonlib2.c and .py.
version = '1.4.1'

setup (
	name = 'jsonlib2',
	version = version,
	description = "JSON serializer/deserializer for Python",
	long_description = open (join (dirname (__file__), 'README.txt')).read (),
	author = "Alec Flett",
	author_email = "alecf@flett.org",
	license = "MIT",
	url = "http://code.google.com/p/jsonlib2/",
	download_url = "http://code.google.com/p/jsonlib2/downloads/list",
	platforms = ["Platform Independent"],
	classifiers = [
		"Development Status :: 5 - Production/Stable",
		"Intended Audience :: Developers",
		"License :: OSI Approved :: MIT License",
		"Operating System :: OS Independent",
		"Programming Language :: Python",
		"Topic :: Software Development :: Libraries :: Python Modules",
	],
	keywords = ["json"],
	ext_modules = [
		Extension ('jsonlib2', ['jsonlib2.c']),
	],
)
<commit_msg>rev the version for next release<commit_after>from os.path import dirname, join
try:
	from setuptools import setup, Extension
except ImportError:
	from distutils.core import setup, Extension

# If you change the version here, also change it in jsonlib2.c and .py.
version = '1.4.2'

setup (
	name = 'jsonlib2',
	version = version,
	description = "JSON serializer/deserializer for Python",
	long_description = open (join (dirname (__file__), 'README.txt')).read (),
	author = "Alec Flett",
	author_email = "alecf@flett.org",
	license = "MIT",
	url = "http://code.google.com/p/jsonlib2/",
	download_url = "http://code.google.com/p/jsonlib2/downloads/list",
	platforms = ["Platform Independent"],
    test_suite = "jsonlib2_simplejson.tests",
	classifiers = [
		"Development Status :: 5 - Production/Stable",
		"Intended Audience :: Developers",
		"License :: OSI Approved :: MIT License",
		"Operating System :: OS Independent",
		"Programming Language :: Python",
		"Topic :: Software Development :: Libraries :: Python Modules",
	],
	keywords = ["json"],
	ext_modules = [
		Extension ('jsonlib2', ['jsonlib2.c']),
	],
)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import os
import os.path
import etcd
import yaml
import json
try:
    import ConfigParser as configparser
except ImportError:
    # Python 3
    import configparser

__author__ = 'lundberg'

class ParserException(Exception):

    def __init__(self, message):
        Exception.__init__(self)
        self.value = message

    def __str__(self):
        return self.value

class IniConfigParser(object):

    section = 'main'

    def __init__(self, config_file_name, config_environment_variable=None):
        """
        :param config_file_name: config files name
        :param config_environment_variable: Optional env variable to read config from

        :type config_file_name: str | unicode
        :type config_environment_variable: str | unicode

        :return: IniConfigParser object
        :rtype: IniConfigParser
        """
        self.config_file_name = config_file_name
        self.config_environment_variable = config_environment_variable
        self.known_special_keys = {
            # <var name>.lower(): (<read function>, <default>),
            'celery_accept_content': (self.read_list, ['application/json']),
        }

    def get_config_file(self):
        """Get the configuration file looking for it in several places.

        The lookup order is:
        1. A file named according to the value of the config_environment_variable env variable
        2. A file named config_file_name In the current working directory
        3. A file named .config_file_name in the user's home directory
        4. A file named config_file_name in the system configuration directory (/etc)
        """
        file_name = os.environ.get(self.config_environment_variable, self.config_file_name)

        if os.path.exists(file_name):
            return file_name

        user_file = os.path.expanduser(
            os.path.join('~', '.', self.config_file_name))
        if os.path.exists(user_file):
            return user_file

        global_file = os.path.join('/etc', self.config_file_name)
        if os.path.exists(global_file):
            return global_file

    def read_setting_from_env(self, settings, key, default=None):
        env_variable = key.upper()
        if env_variable in os.environ:
            return os.environ[env_variable]
        else:
            return settings.get(key, default)

    def read_setting_from_env_bool(self, settings, key, default=None):
        value = self.read_setting_from_env(settings, key, '').lower()
        if value == 'false':
            return False
        if value == 'true':
            return True
        return default

    def read_setting_from_env_int(self, settings, key, default=None):
        value = self.read_setting_from_env(settings, key, '').lower()
        return int(value)

    def read_mapping(self, settings, prop, available_keys=None, default=None, required=True):
        raw = self.read_setting_from_env(settings, prop, '')

        if raw.strip() == '':
            return default

        rows = raw.strip('\n ').split('\n')

        mapping = {}

        for row in rows:
            splitted_row = row.split('=')
            key = splitted_row[0].strip()
            if len(splitted_row) > 1:
                value = splitted_row[1].strip()
            else:
                value = ''
            if available_keys is None or key in available_keys:
                mapping[key] = value

        if available_keys is not None:
            if len(mapping.keys()) != len(available_keys) and 'testing' not in settings:
                return None

        return mapping

    def read_list(self, settings, prop, default=list()):
        raw = self.read_setting_from_env(settings, prop, None)
        if raw is None or raw.strip() == '':
            return default

        return [e for e in raw.split('\n') if e is not None and e.strip() != '']

    def read_configuration(self):
        """
        Read the settings from environment or .ini file and return them as a dict

        The values are decoded as JSON, or used as-is if they can't be decoded as JSON.
        """
        settings = {}

        config_file = self.get_config_file()
        if config_file is not None:
            config = configparser.RawConfigParser()
            config.read(config_file)

            if config.has_section(self.section):
                for key, val in config.items(self.section):
                    if key in self.known_special_keys:
                        func, default = self.known_special_keys[key]
                    else:
                        func = self.read_setting_from_env
                        default = ''
                    settings[key.upper()] = func({key: val}, key, default=default)

        return settings

class EtcdConfigParser(object):

    def __init__(self, namespace, host=None, port=None):
        """
        :param namespace: etcd namespace to read or write, ex. /eduid/webapp/common/
        :param host: Optional etcd host
        :param port: Optional etcd port

        :type host: str | unicode
        :type namespace: str | unicode
        :type port: int

        :return: EtcdConfigParser object
        :rtype: EtcdConfigParser
        """
        if not host:
            host = os.environ.get('ETCD_HOST', '127.0.0.1')
        if not port:
            port = int(os.environ.get('ETCD_PORT', '2379'))
        if not namespace.startswith('/') or not namespace.endswith('/'):
            raise ParserException('Namespace {!s} has to start and end with a \"/\" character'.format(namespace))
        self.ns = namespace.lower()

        self.client = etcd.Client(host, port)

    def _fq_key(self, key):
        """
        :param key: Key to look up
        :type key: str | unicode

        :return: Fully qualified key, self.ns + key
        :rtype: str | unicode
        """
        return '{!s}{!s}'.format(self.ns, key.lower())

    def read_configuration(self):
        """
        Recurse over keys in a given namespace and create a dict from the key-value pairs.

        Values will be json encoded on write and json decoded on read.

        Ex.

        ns = '/eduid/webapp/common/'

        Key and value in etcd:
        /eduid/webapp/common/saml_config -> "{xmlsec_binary': '/usr/bin/xmlsec1'}"

        This will return:
        {
            'SAML_CONFIG': {
                'xmlsec_binary': '/usr/bin/xmlsec1'
            }
        }

        :return: Config dict
        :rtype: dict
        """
        settings = {}
        for child in self.client.read(self.ns, recursive=True).children:
            # Remove namespace and uppercase the key
            key = child.key.lstrip(self.ns).upper()
            # Load etcd string with json to handle complex structures
            settings[key] = json.loads(child.value)
        return settings

    def get(self, key):
        """
        :param key: Key to look up
        :type key: str | unicode

        :return: JSON loaded value
        :rtype: str | unicode | int | float | list | dict
        """
        value = self.client.read(self._fq_key(key)).value
        return json.loads(value)

    def set(self, key, value):
        json_value = json.dumps(value)
        self.client.write(self._fq_key(key), json_value)

    def write_configuration(self, config):
        """
        Transforms a dict using the namespace to key-value pairs that get written to
        etcd in the set namespace.

        Values will be json encoded on write and json decoded on read.

        Ex.

        ns = '/eduid/webapp/common/'

        config = {
            'eduid': {
                'webapp': {
                    'common': {
                        'SAML_CONFIG': {
                            'xmlsec_binary': '/usr/bin/xmlsec1'
                        }
                    }
                }
            }
        }

        will end up in etcd as:

        /eduid/webapp/common/saml_config -> "{xmlsec_binary': '/usr/bin/xmlsec1'}"

        :param config: Config dict
        :type config: dict
        """
        # Remove first and last slash and create key hierarchy
        ns_keys = self.ns.lstrip('/').rstrip('/').split('/')
        # Traverse the dict using the list of keys from the namespace
        try:
            for key in ns_keys:
                config = config[key]
        except KeyError as e:
            raise ParserException('Namespace does not match configuration structure: {!s}'.format(e))
        # Write keys and values to etcd
        for key, value in config.items():
            self.set(key, value)

    def write_configuration_from_yaml_file(self, file_path):
        """
        :param file_path: Full path to a file with yaml content

        :type file_path: str | unicode
        """
        with open(file_path) as f:
            config = yaml.load(f)
            if not config:
                raise ParserException('No YAML found in {!s}'.format(file_path))
            self.write_configuration(config)
<commit_msg>Allow silent lookup error, don't lstrip if you dont want chars missing<commit_after># -*- coding: utf-8 -*-

import os
import os.path
import etcd
import yaml
import json
try:
    import ConfigParser as configparser
except ImportError:
    # Python 3
    import configparser

__author__ = 'lundberg'

class ParserException(Exception):

    def __init__(self, message):
        Exception.__init__(self)
        self.value = message

    def __str__(self):
        return self.value

class IniConfigParser(object):

    section = 'main'

    def __init__(self, config_file_name, config_environment_variable=None):
        """
        :param config_file_name: config files name
        :param config_environment_variable: Optional env variable to read config from

        :type config_file_name: str | unicode
        :type config_environment_variable: str | unicode

        :return: IniConfigParser object
        :rtype: IniConfigParser
        """
        self.config_file_name = config_file_name
        self.config_environment_variable = config_environment_variable
        self.known_special_keys = {
            # <var name>.lower(): (<read function>, <default>),
            'celery_accept_content': (self.read_list, ['application/json']),
        }

    def get_config_file(self):
        """Get the configuration file looking for it in several places.

        The lookup order is:
        1. A file named according to the value of the config_environment_variable env variable
        2. A file named config_file_name In the current working directory
        3. A file named .config_file_name in the user's home directory
        4. A file named config_file_name in the system configuration directory (/etc)
        """
        file_name = os.environ.get(self.config_environment_variable, self.config_file_name)

        if os.path.exists(file_name):
            return file_name

        user_file = os.path.expanduser(
            os.path.join('~', '.', self.config_file_name))
        if os.path.exists(user_file):
            return user_file

        global_file = os.path.join('/etc', self.config_file_name)
        if os.path.exists(global_file):
            return global_file

    def read_setting_from_env(self, settings, key, default=None):
        env_variable = key.upper()
        if env_variable in os.environ:
            return os.environ[env_variable]
        else:
            return settings.get(key, default)

    def read_setting_from_env_bool(self, settings, key, default=None):
        value = self.read_setting_from_env(settings, key, '').lower()
        if value == 'false':
            return False
        if value == 'true':
            return True
        return default

    def read_setting_from_env_int(self, settings, key, default=None):
        value = self.read_setting_from_env(settings, key, '').lower()
        return int(value)

    def read_mapping(self, settings, prop, available_keys=None, default=None, required=True):
        raw = self.read_setting_from_env(settings, prop, '')

        if raw.strip() == '':
            return default

        rows = raw.strip('\n ').split('\n')

        mapping = {}

        for row in rows:
            splitted_row = row.split('=')
            key = splitted_row[0].strip()
            if len(splitted_row) > 1:
                value = splitted_row[1].strip()
            else:
                value = ''
            if available_keys is None or key in available_keys:
                mapping[key] = value

        if available_keys is not None:
            if len(mapping.keys()) != len(available_keys) and 'testing' not in settings:
                return None

        return mapping

    def read_list(self, settings, prop, default=list()):
        raw = self.read_setting_from_env(settings, prop, None)
        if raw is None or raw.strip() == '':
            return default

        return [e for e in raw.split('\n') if e is not None and e.strip() != '']

    def read_configuration(self):
        """
        Read the settings from environment or .ini file and return them as a dict

        The values are decoded as JSON, or used as-is if they can't be decoded as JSON.
        """
        settings = {}

        config_file = self.get_config_file()
        if config_file is not None:
            config = configparser.RawConfigParser()
            config.read(config_file)

            if config.has_section(self.section):
                for key, val in config.items(self.section):
                    if key in self.known_special_keys:
                        func, default = self.known_special_keys[key]
                    else:
                        func = self.read_setting_from_env
                        default = ''
                    settings[key.upper()] = func({key: val}, key, default=default)

        return settings

class EtcdConfigParser(object):

    def __init__(self, namespace, host=None, port=None):
        """
        :param namespace: etcd namespace to read or write, ex. /eduid/webapp/common/
        :param host: Optional etcd host
        :param port: Optional etcd port

        :type host: str | unicode
        :type namespace: str | unicode
        :type port: int

        :return: EtcdConfigParser object
        :rtype: EtcdConfigParser
        """
        if not host:
            host = os.environ.get('ETCD_HOST', '127.0.0.1')
        if not port:
            port = int(os.environ.get('ETCD_PORT', '2379'))
        if not namespace.startswith('/') or not namespace.endswith('/'):
            raise ParserException('Namespace {!s} has to start and end with a \"/\" character'.format(namespace))
        self.ns = namespace.lower()

        self.client = etcd.Client(host, port)

    def _fq_key(self, key):
        """
        :param key: Key to look up
        :type key: str | unicode

        :return: Fully qualified key, self.ns + key
        :rtype: str | unicode
        """
        return '{!s}{!s}'.format(self.ns, key.lower())

    def read_configuration(self, silent=False):
        """
        :param silent: set to `True` if you want silent failure for missing keys.
        :type silent: bool
        :return: Configuration dict
        :rtype: dict

        Recurse over keys in a given namespace and create a dict from the key-value pairs.

        Values will be json encoded on write and json decoded on read.

        Ex.

        ns = '/eduid/webapp/common/'

        Key and value in etcd:
        /eduid/webapp/common/saml_config -> "{xmlsec_binary': '/usr/bin/xmlsec1'}"

        This will return:
        {
            'SAML_CONFIG': {
                'xmlsec_binary': '/usr/bin/xmlsec1'
            }
        }

        :return: Config dict
        :rtype: dict
        """
        settings = {}
        try:
            for child in self.client.read(self.ns, recursive=True).children:
                # Remove namespace and uppercase the key
                key = child.key.split('/')[-1].upper()
                # Load etcd string with json to handle complex structures
                settings[key] = json.loads(child.value)
        except etcd.EtcdKeyNotFound as e:
            if not silent:
                raise e
        return settings

    def get(self, key):
        """
        :param key: Key to look up
        :type key: str | unicode

        :return: JSON loaded value
        :rtype: str | unicode | int | float | list | dict
        """
        value = self.client.read(self._fq_key(key)).value
        return json.loads(value)

    def set(self, key, value):
        json_value = json.dumps(value)
        self.client.write(self._fq_key(key), json_value)

    def write_configuration(self, config):
        """
        Transforms a dict using the namespace to key-value pairs that get written to
        etcd in the set namespace.

        Values will be json encoded on write and json decoded on read.

        Ex.

        ns = '/eduid/webapp/common/'

        config = {
            'eduid': {
                'webapp': {
                    'common': {
                        'SAML_CONFIG': {
                            'xmlsec_binary': '/usr/bin/xmlsec1'
                        }
                    }
                }
            }
        }

        will end up in etcd as:

        /eduid/webapp/common/saml_config -> "{xmlsec_binary': '/usr/bin/xmlsec1'}"

        :param config: Config dict
        :type config: dict
        """
        # Remove first and last slash and create key hierarchy
        ns_keys = self.ns.lstrip('/').rstrip('/').split('/')
        # Traverse the dict using the list of keys from the namespace
        try:
            for key in ns_keys:
                config = config[key]
        except KeyError as e:
            raise ParserException('Namespace does not match configuration structure: {!s}'.format(e))
        # Write keys and values to etcd
        for key, value in config.items():
            self.set(key, value)

    def write_configuration_from_yaml_file(self, file_path):
        """
        :param file_path: Full path to a file with yaml content

        :type file_path: str | unicode
        """
        with open(file_path) as f:
            config = yaml.load(f)
            if not config:
                raise ParserException('No YAML found in {!s}'.format(file_path))
            self.write_configuration(config)
<|endoftext|>


<commit_before>from __future__ import print_function
from os import sys

from skbuild import setup

setup(
    name='itk-ultrasound',
    version='0.5.4',
    author='Matthew McCormick',
    author_email='matt.mccormick@kitware.com',
    packages=['itk'],
    package_dir={'itk': 'itk'},
    download_url=r'https://github.com/KitwareMedical/ITKUltrasound',
    description=(r'Filters for use with the Insight Toolkit (ITK)'
        ' that may be particularly useful for the reconstruction and'
        ' analysis of ultrasound images.'),
    long_description=(r'This package contains filters for use with the Insight Toolkit'
        ' (ITK) for the reconstruction and analysis of ultrasound images. This includes'
        ' B-mode image generation, scan conversion, strain imaging, and '
        ' ultrasound spectroscopy.'),
    classifiers=[
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python",
        "Programming Language :: C++",
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Education",
        "Intended Audience :: Healthcare Industry",
        "Intended Audience :: Science/Research",
        "Topic :: Scientific/Engineering",
        "Topic :: Scientific/Engineering :: Medical Science Apps.",
        "Topic :: Scientific/Engineering :: Information Analysis",
        "Topic :: Software Development :: Libraries",
        "Operating System :: Android",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: POSIX",
        "Operating System :: Unix",
        "Operating System :: MacOS"
        ],
    license='Apache',
    keywords='ITK InsightToolkit ultrasound imaging',
    url=r'https://www.insight-journal.org/browse/publication/722',
    install_requires=[
        r'itk>=5.3rc04',
        r'itk-bsplinegradient>=0.2.4',
        r'itk-higherorderaccurategradient>=1.1.0',
        r'itk-splitcomponents>=2.0.4',
        r'itk-strain>=0.3.3',
    ]
    )
<commit_msg>ENH: Bump ITKUltrasound to 0.5.5<commit_after>from __future__ import print_function
from os import sys

from skbuild import setup

setup(
    name='itk-ultrasound',
    version='0.5.5',
    author='Matthew McCormick',
    author_email='matt.mccormick@kitware.com',
    packages=['itk'],
    package_dir={'itk': 'itk'},
    download_url=r'https://github.com/KitwareMedical/ITKUltrasound',
    description=(r'Filters for use with the Insight Toolkit (ITK)'
        ' that may be particularly useful for the reconstruction and'
        ' analysis of ultrasound images.'),
    long_description=(r'This package contains filters for use with the Insight Toolkit'
        ' (ITK) for the reconstruction and analysis of ultrasound images. This includes'
        ' B-mode image generation, scan conversion, strain imaging, and '
        ' ultrasound spectroscopy.'),
    classifiers=[
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python",
        "Programming Language :: C++",
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: Education",
        "Intended Audience :: Healthcare Industry",
        "Intended Audience :: Science/Research",
        "Topic :: Scientific/Engineering",
        "Topic :: Scientific/Engineering :: Medical Science Apps.",
        "Topic :: Scientific/Engineering :: Information Analysis",
        "Topic :: Software Development :: Libraries",
        "Operating System :: Android",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: POSIX",
        "Operating System :: Unix",
        "Operating System :: MacOS"
        ],
    license='Apache',
    keywords='ITK InsightToolkit ultrasound imaging',
    url=r'https://www.insight-journal.org/browse/publication/722',
    install_requires=[
        r'itk>=5.3rc04',
        r'itk-bsplinegradient>=0.2.4',
        r'itk-higherorderaccurategradient>=1.1.0',
        r'itk-splitcomponents>=2.0.4',
        r'itk-strain>=0.3.3',
    ]
    )
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 setuptools

from ironic.openstack.common import setup as common_setup

project = 'ironic'

setuptools.setup(
    name=project,
    version=common_setup.get_version(project, '2013.1'),
    description='Bare Metal controller',
    classifiers=[
        'Environment :: OpenStack',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        ],
    include_package_data=True,
    setup_requires=['d2to1>=0.2.10,<0.3', 'pbr>=0.5,<0.6'],
    d2to1=True,
)
<commit_msg>Added Python-2.6 to the classifier.<commit_after>#!/usr/bin/env python
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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 setuptools

from ironic.openstack.common import setup as common_setup

project = 'ironic'

setuptools.setup(
    name=project,
    version=common_setup.get_version(project, '2013.1'),
    description='Bare Metal controller',
    classifiers=[
        'Environment :: OpenStack',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 2.6',
    ],
    include_package_data=True,
    setup_requires=['d2to1>=0.2.10,<0.3', 'pbr>=0.5,<0.6'],
    d2to1=True,
)
<|endoftext|>


<commit_before>#!/usr/bin/env python2

# This file is part of Local Scraperlibs.

import warnings
import os
from distutils.core import setup

def has_external_dependency(name):
    'Check that a non-Python dependency is installed.'
    for directory in os.environ['PATH'].split(':'):
        if os.path.exists(os.path.join(directory, name)):
            return True
    return False

if not has_external_dependency('pdftohtml'):
    warnings.warn(
        'Local Scraperlibs requires pdftohtml, but pdftohtml was not found\n'
        'in the PATH. You probably need to install it.'
    )

config = dict(name='scraperwiki',
    author='Francis Irving',
    author_email='francis@scraperwiki.com',
    description='Local version of ScraperWiki libraries',
    url='https://github.com/scraperwiki/scraperwiki-python',
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: SQL',
        'Topic :: Database :: Front-Ends',
    ],
    packages=['scraperwiki', 'scraperwiki.runlog'],

    version = '0.3.6',
    license='GPL',
   )

try:
    from setuptools import setup
    config['install_requires'] = ['dumptruck>=0.1.2', 'requests'],
except ImportError:
    pass

setup(**config)
<commit_msg>Increase version<commit_after>#!/usr/bin/env python2

# This file is part of Local Scraperlibs.

import warnings
import os
from distutils.core import setup

def has_external_dependency(name):
    'Check that a non-Python dependency is installed.'
    for directory in os.environ['PATH'].split(':'):
        if os.path.exists(os.path.join(directory, name)):
            return True
    return False

if not has_external_dependency('pdftohtml'):
    warnings.warn(
        'Local Scraperlibs requires pdftohtml, but pdftohtml was not found\n'
        'in the PATH. You probably need to install it.'
    )

config = dict(name='scraperwiki',
    author='Francis Irving',
    author_email='francis@scraperwiki.com',
    description='Local version of ScraperWiki libraries',
    url='https://github.com/scraperwiki/scraperwiki-python',
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: SQL',
        'Topic :: Database :: Front-Ends',
    ],
    packages=['scraperwiki', 'scraperwiki.runlog'],

    version = '0.3.7',
    license='GPL',
   )

try:
    from setuptools import setup
    config['install_requires'] = ['dumptruck>=0.1.2', 'requests'],
except ImportError:
    pass

setup(**config)
<|endoftext|>


<commit_before>from distutils.core import setup
from distutils.extension import Extension

setup(
    name='Couchbase Python SDK',
    ext_modules=[Extension(
        "couchbase/libcouchbase", ["couchbase/libcouchbase.c"],
        libraries=['couchbase'])
    ],
    packages=['couchbase']
)
<commit_msg>Added the command 'cythonize' to setup.py<commit_after>from distutils.core import setup, Command
from distutils.extension import Extension

try:
    from Cython import __version__ as cython_version

    from distutils.version import StrictVersion

    if StrictVersion(cython_version) <= StrictVersion("0.18"):
        print "You need a Cython version newer than 0.18 to enable 'cythonize'"
        raise ImportError

    from Cython.Build import cythonize

    class CythonizeCommand(Command):
        description = "Generate .c files out of .pyx"
        user_options = []

        def initialize_options(self):
            pass

        def finalize_options(self):
            pass

        def run(self):
            cythonize("couchbase/libcouchbase.pyx")

    cmdclass = {"cythonize": CythonizeCommand}
except ImportError:
    cmdclass = {}

setup(
    name = 'Couchbase Python SDK',
    cmdclass=cmdclass,
    ext_modules = [Extension(
        "couchbase/libcouchbase", ["couchbase/libcouchbase.c"],
        libraries=['couchbase'])
    ],
    packages=['couchbase']
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
#coding: utf8
from distutils.core import setup

for cmd in ('egg_info', 'develop'):
    import sys
    if cmd in sys.argv:
        from setuptools import setup

try:
    import sys
    reload(sys).setdefaultencoding("UTF-8")
except NameError:
    # python3 doesn't need this
    pass

version='0.0.3'

setup(
    name='django-mailru-money',
    version=version,
    author='Mikhail Korobov',
    author_email='kmike84@gmail.com',

    packages=['mailru_money', 'mailru_money/migrations'],

    url='https://bitbucket.org/kmike/django-mailru-money/',
    license = 'MIT license',
    description = "Приложение для подключения сайта к деньгам@mail.ru",

    long_description = open('README.rst').read(),

    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)
<commit_msg>bump version<commit_after>#!/usr/bin/env python
#coding: utf8
from distutils.core import setup

for cmd in ('egg_info', 'develop'):
    import sys
    if cmd in sys.argv:
        from setuptools import setup

try:
    import sys
    reload(sys).setdefaultencoding("UTF-8")
except NameError:
    # python3 doesn't need this
    pass

version='0.1'

setup(
    name='django-mailru-money',
    version=version,
    author='Mikhail Korobov',
    author_email='kmike84@gmail.com',

    packages=['mailru_money', 'mailru_money/migrations'],

    url='https://bitbucket.org/kmike/django-mailru-money/',
    license = 'MIT license',
    description = "Приложение для подключения сайта к деньгам@mail.ru",

    long_description = open('README.rst').read(),

    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-

from setuptools import setup

setup(
    name = 'TracMasterTickets',
    version = '2.1.1',
    packages = ['mastertickets'],
    package_data = { 'mastertickets': ['templates/*.html', 'htdocs/*.js', 'htdocs/*.css' ] },

    author = "Noah Kantrowitz",
    author_email = "noah@coderanger.net",
    description = "Provides support for ticket dependencies and master tickets.",
    license = "BSD",
    keywords = "trac plugin ticket dependencies master",
    url = "http://trac-hacks.org/wiki/MasterTicketsPlugin",
    classifiers = [
        'Framework :: Trac',
    ],

    install_requires = ['Trac', 'Genshi >= 0.5.dev-r698,==dev'],

    entry_points = {
        'trac.plugins': [
            'mastertickets.web_ui = mastertickets.web_ui',
            'mastertickets.api = mastertickets.api',
        ]
    }
)
<commit_msg>Version bump.<commit_after>#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-

from setuptools import setup

setup(
    name = 'TracMasterTickets',
    version = '2.1.2',
    packages = ['mastertickets'],
    package_data = { 'mastertickets': ['templates/*.html', 'htdocs/*.js', 'htdocs/*.css' ] },

    author = 'Noah Kantrowitz',
    author_email = 'noah@coderanger.net',
    description = 'Provides support for ticket dependencies and master tickets.',
    license = 'BSD',
    keywords = 'trac plugin ticket dependencies master',
    url = 'http://trac-hacks.org/wiki/MasterTicketsPlugin',
    classifiers = [
        'Framework :: Trac',
        #'Development Status :: 1 - Planning',
        # 'Development Status :: 2 - Pre-Alpha',
        # 'Development Status :: 3 - Alpha',
        # 'Development Status :: 4 - Beta',
        'Development Status :: 5 - Production/Stable',
        # 'Development Status :: 6 - Mature',
        # 'Development Status :: 7 - Inactive',
        'Environment :: Web Environment',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],

    install_requires = ['Trac>=0.11', 'Genshi>=0.5'],

    entry_points = {
        'trac.plugins': [
            'mastertickets.web_ui = mastertickets.web_ui',
            'mastertickets.api = mastertickets.api',
        ]
    }
)
<|endoftext|>


<commit_before>#!/usr/bin/env python

from setuptools import setup

setup(
    name='genonets',
    version='1.0.5',
    description='Framework for creating and analyzing genotype networks from data.',
    author='Fahad Khalid',
    author_email='fahad.khalid@ieu.uzh.ch',
    url='https://github.com/fkhalid/genonets',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
        'Operating System :: OS Independent',
        'Natural Language :: English',
        'Topic :: Scientific/Engineering :: Bio-Informatics',
    ],
    keywords='genonets genotype phenotype network',
    packages=['genonets'],
    package_data={
        'genonets': [
            'sample/*.py',
            'sample/*.txt',
            'sample/data/*.txt'
        ]
    },
    install_requires=[
        'python-igraph>=0.6',
        'numpy>=1.8.2'
    ]
)
<commit_msg>Updated version for upload to PyPI.<commit_after>#!/usr/bin/env python

from setuptools import setup

setup(
    name='genonets',
    version='1.0.6',
    description='Framework for creating and analyzing genotype networks from data.',
    author='Fahad Khalid',
    author_email='fahad.khalid@ieu.uzh.ch',
    url='https://github.com/fkhalid/genonets',
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
        'Operating System :: OS Independent',
        'Natural Language :: English',
        'Topic :: Scientific/Engineering :: Bio-Informatics',
    ],
    keywords='genonets genotype phenotype network',
    packages=['genonets'],
    package_data={
        'genonets': [
            'sample/*.py',
            'sample/*.txt',
            'sample/data/*.txt'
        ]
    },
    install_requires=[
        'python-igraph>=0.6',
        'numpy>=1.8.2'
    ]
)
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Standard library modules.
import os

# Third party modules.
from setuptools import setup, find_packages

# Local modules.

# Globals and constants variables.
BASEDIR = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(BASEDIR, 'VERSION')) as version_file:
    version = version_file.read().strip()

# Get the long description from the relevant file
with open('README.rst', 'r') as f:
    long_description = f.read()

setup(name='matplotlib-scalebar',
      version=version,
      description='Artist for matplotlib to display a scale bar',
      long_description=long_description,

      author='Philippe Pinard',
      author_email='philippe.pinard@gmail.com',
      maintainer='Philippe Pinard',
      maintainer_email='philippe.pinard@gmail.com',

      url='http://pyhmsa.readthedocs.org',
      license='BSD',
      keywords='matplotlib scale micron bar',

      classifiers=[
          'Development Status :: 4 - Beta',
          'Intended Audience :: Science/Research',
          'License :: OSI Approved :: MIT License',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 3',
          'Topic :: Scientific/Engineering :: Visualization'
        ],

      packages=find_packages(),
      package_data={},

      install_requires=['matplotlib'],

      zip_safe=True,

     )
<commit_msg>Add nose test to setup.<commit_after>#!/usr/bin/env python

# Standard library modules.
import os

# Third party modules.
from setuptools import setup, find_packages

# Local modules.

# Globals and constants variables.
BASEDIR = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(BASEDIR, 'VERSION')) as version_file:
    version = version_file.read().strip()

# Get the long description from the relevant file
with open('README.rst', 'r') as f:
    long_description = f.read()

setup(name='matplotlib-scalebar',
      version=version,
      description='Artist for matplotlib to display a scale bar',
      long_description=long_description,

      author='Philippe Pinard',
      author_email='philippe.pinard@gmail.com',
      maintainer='Philippe Pinard',
      maintainer_email='philippe.pinard@gmail.com',

      url='http://pyhmsa.readthedocs.org',
      license='BSD',
      keywords='matplotlib scale micron bar',

      classifiers=[
          'Development Status :: 4 - Beta',
          'Intended Audience :: Science/Research',
          'License :: OSI Approved :: MIT License',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 3',
          'Topic :: Scientific/Engineering :: Visualization'
        ],

      packages=find_packages(),
      package_data={},

      install_requires=['matplotlib'],

      zip_safe=True,

      test_suite='nose.collector'

     )
<|endoftext|>


<commit_before>#!/usr/bin/env python

try:
    from setuptools import setup, find_packages
    from setuptools.command.test import test
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages
    from setuptools.command.test import test

class mytest(test):
    def run(self, *args, **kwargs):
        from runtests import runtests
        runtests()
        # Upgrade().run(dist=True)
        # test.run(self, *args, **kwargs)

setup(
    name='gargoyle',
    version='0.1.2',
    author='DISQUS',
    author_email='opensource@disqus.com',
    url='http://github.com/disqus/gargoyle',
    description = 'Switches',
    packages=find_packages(),
    zip_safe=False,
    install_requires=[
        'django',
        'django-modeldict>=1.0.1',
        'nexus>=0.1.0',
        'django-jsonfield',
    ],
    test_suite = 'gargoyle.tests',
    include_package_data=True,
    cmdclass={"test": mytest},
    classifiers=[
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Operating System :: OS Independent',
        'Topic :: Software Development'
    ],
)<commit_msg>Bump version to 0.1.3<commit_after>#!/usr/bin/env python

try:
    from setuptools import setup, find_packages
    from setuptools.command.test import test
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages
    from setuptools.command.test import test

class mytest(test):
    def run(self, *args, **kwargs):
        from runtests import runtests
        runtests()
        # Upgrade().run(dist=True)
        # test.run(self, *args, **kwargs)

setup(
    name='gargoyle',
    version='0.1.3',
    author='DISQUS',
    author_email='opensource@disqus.com',
    url='http://github.com/disqus/gargoyle',
    description = 'Switches',
    packages=find_packages(),
    zip_safe=False,
    install_requires=[
        'django',
        'django-modeldict>=1.0.1',
        'nexus>=0.1.0',
        'django-jsonfield',
    ],
    test_suite = 'gargoyle.tests',
    include_package_data=True,
    cmdclass={"test": mytest},
    classifiers=[
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Operating System :: OS Independent',
        'Topic :: Software Development'
    ],
)<|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 Google 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.

from setuptools import setup
from setuptools.command.install import install

from os.path import dirname, join, isfile
from shutil import copy
import sys

def setup_python3():
    # Taken from "distribute" setup.py
    from distutils.filelist import FileList
    from distutils import dir_util, file_util, util, log

    tmp_src = join("build", "src")
    log.set_verbosity(1)
    fl = FileList()
    for line in open("MANIFEST.in"):
        if not line.strip():
            continue
        fl.process_template_line(line)
    dir_util.create_tree(tmp_src, fl.files)
    outfiles_2to3 = []
    for f in fl.files:
        outf, copied = file_util.copy_file(f, join(tmp_src, f), update=1)
        if copied and outf.endswith(".py"):
            outfiles_2to3.append(outf)

    util.run_2to3(outfiles_2to3)

    # arrange setup to use the copy
    sys.path.insert(0, tmp_src)

    return tmp_src

def find_longdesc():
    for path in ("docs/api/py/index.rst", "docs/index.rst"):
        try:
            index = join(dirname(__file__), path)
            return open(index).read()
        except IOError:
            pass

    print("WARNING: Can't find index.rst")
    return ""

if sys.version_info >= (3,):
    src_root = setup_python3()
else:
    src_root = "."

setup(
    cmdclass={'install': install},
    name='selenium',
    version="2.0",
    description='Python bindings for Selenium',
    long_description=find_longdesc(),
    url='http://code.google.com/p/selenium/',
    src_root=src_root,
    classifiers=['Development Status :: 5 - Production/Stable',
                     'Intended Audience :: Developers',
                     'License :: OSI Approved :: Apache Software License',
                     'Operating System :: POSIX',
                     'Operating System :: Microsoft :: Windows',
                     'Operating System :: MacOS :: MacOS X',
                     'Topic :: Software Development :: Testing',
                     'Topic :: Software Development :: Libraries',
                     'Programming Language :: Python'],
    package_dir={
        'selenium': 'py/selenium',
        'selenium.common': 'py/selenium/common',
        'selenium.test': 'py/test',
        'selenium.test.selenium': 'py/test/selenium',
        'selenium.test.selenium.webdriver': 'py/test/selenium/webdriver',
        'selenium.test.selenium.webdriver.chrome': 'py/test/selenium/webdriver/chrome',
        'selenium.test.selenium.webdriver.common': 'py/test/selenium/webdriver/common',
        'selenium.test.selenium.webdriver.firefox': 'py/test/selenium/webdriver/firefox',
        'selenium.test.selenium.webdriver.ie': 'py/test/selenium/webdriver/ie',
        'selenium.test.selenium.webdriver.remote': 'py/test/selenium/webdriver/remote',
        'selenium.webdriver': 'py/selenium/webdriver',
        'selenium.webdriver.chrome': 'py/selenium/webdriver/chrome',
        'selenium.webdriver.common': 'py/selenium/webdriver/common',
        'selenium.webdriver.firefox': 'py/selenium/webdriver/firefox',
        'selenium.webdriver.ie': 'py/selenium/webdriver/ie',
        'selenium.webdriver.remote': 'py/selenium/webdriver/remote',
    },
    packages=['selenium',
              'selenium.common',
              'selenium.test',
              'selenium.test.selenium',
              'selenium.test.selenium.webdriver',
              'selenium.test.selenium.webdriver.chrome',
              'selenium.test.selenium.webdriver.common',
              'selenium.test.selenium.webdriver.firefox',
              'selenium.test.selenium.webdriver.ie',
              'selenium.test.selenium.webdriver.remote',
              'selenium.webdriver',
              'selenium.webdriver.chrome',
              'selenium.webdriver.common',
              'selenium.webdriver.firefox',
              'selenium.webdriver.ie',
              'selenium.webdriver.remote', ],
    package_data={
        'selenium.webdriver.firefox': ['*.xpi'],
        'selenium.webdriver.ie': ['*.dll'],
    },
    include_package_data=True,
    install_requires=['rdflib==3.1.0'],
    zip_safe=False,

)
<commit_msg>DavidBurns updating version to be a 3 digit version number<commit_after>#!/usr/bin/env python
# Copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 Google 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.

from setuptools import setup
from setuptools.command.install import install

from os.path import dirname, join, isfile
from shutil import copy
import sys

def setup_python3():
    # Taken from "distribute" setup.py
    from distutils.filelist import FileList
    from distutils import dir_util, file_util, util, log

    tmp_src = join("build", "src")
    log.set_verbosity(1)
    fl = FileList()
    for line in open("MANIFEST.in"):
        if not line.strip():
            continue
        fl.process_template_line(line)
    dir_util.create_tree(tmp_src, fl.files)
    outfiles_2to3 = []
    for f in fl.files:
        outf, copied = file_util.copy_file(f, join(tmp_src, f), update=1)
        if copied and outf.endswith(".py"):
            outfiles_2to3.append(outf)

    util.run_2to3(outfiles_2to3)

    # arrange setup to use the copy
    sys.path.insert(0, tmp_src)

    return tmp_src

def find_longdesc():
    for path in ("docs/api/py/index.rst", "docs/index.rst"):
        try:
            index = join(dirname(__file__), path)
            return open(index).read()
        except IOError:
            pass

    print("WARNING: Can't find index.rst")
    return ""

if sys.version_info >= (3,):
    src_root = setup_python3()
else:
    src_root = "."

setup(
    cmdclass={'install': install},
    name='selenium',
    version="2.0.0",
    description='Python bindings for Selenium',
    long_description=find_longdesc(),
    url='http://code.google.com/p/selenium/',
    src_root=src_root,
    classifiers=['Development Status :: 5 - Production/Stable',
                     'Intended Audience :: Developers',
                     'License :: OSI Approved :: Apache Software License',
                     'Operating System :: POSIX',
                     'Operating System :: Microsoft :: Windows',
                     'Operating System :: MacOS :: MacOS X',
                     'Topic :: Software Development :: Testing',
                     'Topic :: Software Development :: Libraries',
                     'Programming Language :: Python'],
    package_dir={
        'selenium': 'py/selenium',
        'selenium.common': 'py/selenium/common',
        'selenium.test': 'py/test',
        'selenium.test.selenium': 'py/test/selenium',
        'selenium.test.selenium.webdriver': 'py/test/selenium/webdriver',
        'selenium.test.selenium.webdriver.chrome': 'py/test/selenium/webdriver/chrome',
        'selenium.test.selenium.webdriver.common': 'py/test/selenium/webdriver/common',
        'selenium.test.selenium.webdriver.firefox': 'py/test/selenium/webdriver/firefox',
        'selenium.test.selenium.webdriver.ie': 'py/test/selenium/webdriver/ie',
        'selenium.test.selenium.webdriver.remote': 'py/test/selenium/webdriver/remote',
        'selenium.webdriver': 'py/selenium/webdriver',
        'selenium.webdriver.chrome': 'py/selenium/webdriver/chrome',
        'selenium.webdriver.common': 'py/selenium/webdriver/common',
        'selenium.webdriver.firefox': 'py/selenium/webdriver/firefox',
        'selenium.webdriver.ie': 'py/selenium/webdriver/ie',
        'selenium.webdriver.remote': 'py/selenium/webdriver/remote',
    },
    packages=['selenium',
              'selenium.common',
              'selenium.test',
              'selenium.test.selenium',
              'selenium.test.selenium.webdriver',
              'selenium.test.selenium.webdriver.chrome',
              'selenium.test.selenium.webdriver.common',
              'selenium.test.selenium.webdriver.firefox',
              'selenium.test.selenium.webdriver.ie',
              'selenium.test.selenium.webdriver.remote',
              'selenium.webdriver',
              'selenium.webdriver.chrome',
              'selenium.webdriver.common',
              'selenium.webdriver.firefox',
              'selenium.webdriver.ie',
              'selenium.webdriver.remote', ],
    package_data={
        'selenium.webdriver.firefox': ['*.xpi'],
        'selenium.webdriver.ie': ['*.dll'],
    },
    include_package_data=True,
    install_requires=['rdflib==3.1.0'],
    zip_safe=False,

)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2018 by Jussi Vatjus-Anttila
:license: MIT, see LICENSE for more details.
"""
import os
import sys
from distutils.core import setup
from setuptools import find_packages
from setuptools.command.install import install

DESCRIPTION = "opentmi-client"
OWNER_NAMES = 'Jussi Vatjus-Anttila'
OWNER_EMAILS = 'jussiva@gmail.com'
VERSION = '0.3.2'

# Utility function to cat in a file (used for the README)
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

class VerifyVersionCommand(install):
    """Custom command to verify that the git tag matches our version"""
    description = 'verify that the git tag matches our version'

    def run(self):
        tag = os.getenv('CIRCLE_TAG')
        if tag != VERSION:
            info = "Git tag: {0} does not match the"\
            "version of this app: {1}".format(tag, VERSION)
            sys.exit(info)

setup(name='opentmi_client',
      version=VERSION,
      description=DESCRIPTION,
      long_description=read('README.md'),
      author=OWNER_NAMES,
      author_email=OWNER_EMAILS,
      maintainer=OWNER_NAMES,
      maintainer_email=OWNER_EMAILS,
      url='https://github.com/OpenTMI/opentmi-pyclient.git',
      packages=find_packages(exclude=['test', 'log', 'htmlcov', 'docs']),
      include_package_data=True,
      license="MIT",
      tests_require=read('dev_requirements.txt').splitlines(),
      test_suite='test',
      keywords='opentmi ci cd api sdk',
      entry_points={
          "console_scripts": [
              "opentmi=opentmi_client:opentmiclient_main",
          ]
      },
      install_requires=read('requirements.txt').splitlines(),
      classifiers=[
          "Programming Language :: Python :: 2.7",
          "Programming Language :: Python :: 3.6",
          "Programming Language :: Python :: 3.7",
          "License :: OSI Approved :: MIT License",
          "Operating System :: OS Independent",
      ],
      cmdclass={
          'verify': VerifyVersionCommand,
      }
     )
<commit_msg>version inc<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2018 by Jussi Vatjus-Anttila
:license: MIT, see LICENSE for more details.
"""
import os
import sys
from distutils.core import setup
from setuptools import find_packages
from setuptools.command.install import install

DESCRIPTION = "opentmi-client"
OWNER_NAMES = 'Jussi Vatjus-Anttila'
OWNER_EMAILS = 'jussiva@gmail.com'
VERSION = '0.3.3'

# Utility function to cat in a file (used for the README)
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

class VerifyVersionCommand(install):
    """Custom command to verify that the git tag matches our version"""
    description = 'verify that the git tag matches our version'

    def run(self):
        tag = os.getenv('CIRCLE_TAG')
        if tag != VERSION:
            info = "Git tag: {0} does not match the"\
            "version of this app: {1}".format(tag, VERSION)
            sys.exit(info)

setup(name='opentmi_client',
      version=VERSION,
      description=DESCRIPTION,
      long_description=read('README.md'),
      author=OWNER_NAMES,
      author_email=OWNER_EMAILS,
      maintainer=OWNER_NAMES,
      maintainer_email=OWNER_EMAILS,
      url='https://github.com/OpenTMI/opentmi-pyclient.git',
      packages=find_packages(exclude=['test', 'log', 'htmlcov', 'docs']),
      include_package_data=True,
      license="MIT",
      tests_require=read('dev_requirements.txt').splitlines(),
      test_suite='test',
      keywords='opentmi ci cd api sdk',
      entry_points={
          "console_scripts": [
              "opentmi=opentmi_client:opentmiclient_main",
          ]
      },
      install_requires=read('requirements.txt').splitlines(),
      classifiers=[
          "Programming Language :: Python :: 2.7",
          "Programming Language :: Python :: 3.6",
          "Programming Language :: Python :: 3.7",
          "License :: OSI Approved :: MIT License",
          "Operating System :: OS Independent",
      ],
      cmdclass={
          'verify': VerifyVersionCommand,
      }
     )
<|endoftext|>