<commit_before># -*- coding: utf-8 -*-
import sys
import os
from distutils.core import setup
from setuptools import find_packages

#########
# settings
#########

project_var_name = "pymmails"
sversion = "0.2"
versionPython = "%s.%s" % (sys.version_info.major, sys.version_info.minor)
path = "Lib/site-packages/" + project_var_name
readme = 'README.rst'

KEYWORDS = project_var_name + ', synchronization, files, Xavier, Dupré'
DESCRIPTION = """A module to download emails from an IMAP4 server"""
CLASSIFIERS = [
    'Programming Language :: Python :: 3',
    'Intended Audience :: Developers',
    'Topic :: Scientific/Engineering',
    'Topic :: Education',
    'License :: OSI Approved :: MIT License',
    'Development Status :: 5 - Production/Stable'
]

#######
# data
#######

packages = find_packages('src', exclude='src')
package_dir = {k: "src/" + k.replace(".", "/") for k in packages}
package_data = {}

############
# functions
############

def is_local():
    if \
       "bdist_msi" in sys.argv or \
       "build27" in sys.argv or \
       "build_script" in sys.argv or \
       "build_sphinx" in sys.argv or \
       "bdist_wheel" in sys.argv or \
       "bdist_wininst" in sys.argv or \
       "clean_pyd" in sys.argv or \
       "clean_space" in sys.argv or \
       "copy27" in sys.argv or \
       "copy_dist" in sys.argv or \
       "local_pypi" in sys.argv or \
       "notebook" in sys.argv or \
       "publish" in sys.argv or \
       "publish_doc" in sys.argv or \
       "register" in sys.argv or \
       "unittests" in sys.argv or \
       "unittests_LONG" in sys.argv or \
       "unittests_SKIP" in sys.argv or \
       "run27" in sys.argv or \
       "sdist" in sys.argv or \
       "setupdep" in sys.argv or \
       "test_local_pypi" in sys.argv or \
       "upload_docs" in sys.argv or \
       "write_version" in sys.argv:
        return True
    else:
        return False

def import_pyquickhelper():
    try:
        import pyquickhelper
    except ImportError:
        sys.path.append(
            os.path.normpath(
                os.path.abspath(
                    os.path.join(
                        os.path.dirname(__file__),
                        "..",
                        "pyquickhelper",
                        "src"))))
        try:
            import pyquickhelper
        except ImportError as e:
            message = "module pyquickhelper is needed to build the documentation ({0}), not found in path {1}".format(
                sys.executable,
                sys.path[
                    -1])
            raise ImportError(message) from e
    return pyquickhelper

def verbose():
    print("---------------------------------")
    print("package_dir =", package_dir)
    print("packages    =", packages)
    print("package_data=", package_data)
    print("current     =", os.path.abspath(os.getcwd()))
    print("---------------------------------")

##########
# version
##########

if is_local():
    def write_version():
        pyquickhelper = import_pyquickhelper()
        from pyquickhelper import write_version_for_setup
        return write_version_for_setup(__file__)

    write_version()

    if os.path.exists("version.txt"):
        with open("version.txt", "r") as f:
            lines = f.readlines()
        subversion = "." + lines[0].strip("\r\n ")
    else:
        raise FileNotFoundError("version.txt")
else:
    # when the module is installed, no commit number is displayed
    subversion = ""

##############
# common part
##############

if os.path.exists(readme):
    with open(readme, "r", encoding='utf-8-sig') as f:
        long_description = f.read()
else:
    long_description = ""

if "--verbose" in sys.argv:
    verbose()

if is_local():
    pyquickhelper = import_pyquickhelper()
    r = pyquickhelper.process_standard_options_for_setup(
        sys.argv, __file__, project_var_name,
        unittest_modules=["pyquickhelper"],
        requirements=["pyquickhelper"])
else:
    r = False

if len(sys.argv) == 1 and "--help" in sys.argv:
    pyquickhelper.process_standard_options_for_setup_help()

if not r:
    setup(
        name=project_var_name,
        version='%s%s' % (sversion, subversion),
        author='Xavier Dupré',
        author_email='xavier.dupre AT gmail.com',
        url="http://www.xavierdupre.fr/app/pymmails/helpsphinx/index.html",
        download_url="https://github.com/sdpython/pymmails/",
        description=DESCRIPTION,
        long_description=long_description,
        keywords=KEYWORDS,
        classifiers=CLASSIFIERS,
        packages=packages,
        package_dir=package_dir,
        package_data=package_data,
        install_requires=["pyquickhelper"],
    )
<commit_msg>update setup to fix an issue when pyquickhelper is not here<commit_after># -*- coding: utf-8 -*-
import sys
import os
from distutils.core import setup
from setuptools import find_packages

#########
# settings
#########

project_var_name = "pymmails"
sversion = "0.2"
versionPython = "%s.%s" % (sys.version_info.major, sys.version_info.minor)
path = "Lib/site-packages/" + project_var_name
readme = 'README.rst'

KEYWORDS = project_var_name + ', synchronization, files, Xavier, Dupré'
DESCRIPTION = """A module to download emails from an IMAP4 server"""
CLASSIFIERS = [
    'Programming Language :: Python :: 3',
    'Intended Audience :: Developers',
    'Topic :: Scientific/Engineering',
    'Topic :: Education',
    'License :: OSI Approved :: MIT License',
    'Development Status :: 5 - Production/Stable'
]

#######
# data
#######

packages = find_packages('src', exclude='src')
package_dir = {k: "src/" + k.replace(".", "/") for k in packages}
package_data = {}

############
# functions
############

def is_local():
    if \
       "bdist_msi" in sys.argv or \
       "build27" in sys.argv or \
       "build_script" in sys.argv or \
       "build_sphinx" in sys.argv or \
       "bdist_wheel" in sys.argv or \
       "bdist_wininst" in sys.argv or \
       "clean_pyd" in sys.argv or \
       "clean_space" in sys.argv or \
       "copy27" in sys.argv or \
       "copy_dist" in sys.argv or \
       "local_pypi" in sys.argv or \
       "notebook" in sys.argv or \
       "publish" in sys.argv or \
       "publish_doc" in sys.argv or \
       "register" in sys.argv or \
       "unittests" in sys.argv or \
       "unittests_LONG" in sys.argv or \
       "unittests_SKIP" in sys.argv or \
       "run27" in sys.argv or \
       "sdist" in sys.argv or \
       "setupdep" in sys.argv or \
       "test_local_pypi" in sys.argv or \
       "upload_docs" in sys.argv or \
       "write_version" in sys.argv:
        try:
            import_pyquickhelper()
        except ImportError:
            return False
        return True
    else:
        return False

def import_pyquickhelper():
    try:
        import pyquickhelper
    except ImportError:
        sys.path.append(
            os.path.normpath(
                os.path.abspath(
                    os.path.join(
                        os.path.dirname(__file__),
                        "..",
                        "pyquickhelper",
                        "src"))))
        try:
            import pyquickhelper
        except ImportError as e:
            message = "module pyquickhelper is needed to build the documentation ({0}), not found in path {1}".format(
                sys.executable,
                sys.path[
                    -1])
            raise ImportError(message) from e
    return pyquickhelper

def verbose():
    print("---------------------------------")
    print("package_dir =", package_dir)
    print("packages    =", packages)
    print("package_data=", package_data)
    print("current     =", os.path.abspath(os.getcwd()))
    print("---------------------------------")

##########
# version
##########

if is_local():
    def write_version():
        pyquickhelper = import_pyquickhelper()
        from pyquickhelper import write_version_for_setup
        return write_version_for_setup(__file__)

    write_version()

    if os.path.exists("version.txt"):
        with open("version.txt", "r") as f:
            lines = f.readlines()
        subversion = "." + lines[0].strip("\r\n ")
    else:
        raise FileNotFoundError("version.txt")
else:
    # when the module is installed, no commit number is displayed
    subversion = ""

##############
# common part
##############

if os.path.exists(readme):
    with open(readme, "r", encoding='utf-8-sig') as f:
        long_description = f.read()
else:
    long_description = ""

if "--verbose" in sys.argv:
    verbose()

if is_local():
    pyquickhelper = import_pyquickhelper()
    r = pyquickhelper.process_standard_options_for_setup(
        sys.argv, __file__, project_var_name,
        unittest_modules=["pyquickhelper"],
        requirements=["pyquickhelper"])
else:
    r = False

if len(sys.argv) == 1 and "--help" in sys.argv:
    pyquickhelper = import_pyquickhelper()
    pyquickhelper.process_standard_options_for_setup_help()

if not r:
    setup(
        name=project_var_name,
        version='%s%s' % (sversion, subversion),
        author='Xavier Dupré',
        author_email='xavier.dupre AT gmail.com',
        url="http://www.xavierdupre.fr/app/pymmails/helpsphinx/index.html",
        download_url="https://github.com/sdpython/pymmails/",
        description=DESCRIPTION,
        long_description=long_description,
        keywords=KEYWORDS,
        classifiers=CLASSIFIERS,
        packages=packages,
        package_dir=package_dir,
        package_data=package_data,
        install_requires=["pyquickhelper"],
    )
<|endoftext|>


<commit_before>from rsqueakvm import constants, error
from rsqueakvm.model.base import W_Object, W_AbstractObjectWithIdentityHash
from rsqueakvm.model.pointers import W_PointersObject
from rsqueakvm.model.compiled_methods import W_CompiledMethod
from rsqueakvm.util.version import VersionMixin

from rpython.rlib import jit, objectmodel

class W_BlockClosure(W_AbstractObjectWithIdentityHash):
    repr_classname = "W_BlockClosure"
    bytes_per_slot = 1
    _attrs_ = [
        "version",
        "_w_outerContext",
        "_startpc",
        "_numArgs", "_stack",
        "_w_method" ]
    _immutable_fields_ = [
        "version?",
        "_w_outerContext",
        "_startpc",
        "_numArgs", "_stack",
        "_w_method" ]
    objectmodel.import_from_mixin(VersionMixin)

    def pointers_become_one_way(self, space, from_w, to_w):
        W_AbstractObjectWithIdentityHash.pointers_become_one_way(self, space, from_w, to_w)
        ptrs = self.fetch_all(space)
        ptridx = 0
        for i, w_from in enumerate(from_w):
            try:
                ptridx = ptrs.index(w_from)
            except ValueError:
                continue
            w_to = to_w[i]
            ptrs[ptridx] = w_to
            w_from.post_become_one_way(w_to)
        self.store_all(space, ptrs)

    empty_stack = []

    @jit.unroll_safe
    def __init__(self, space, w_outerctxt, startpc, numArgs, size, stack=None):
        W_AbstractObjectWithIdentityHash.__init__(self)
        self._w_outerContext = w_outerctxt
        self._startpc = startpc
        self._numArgs = numArgs
        if stack:
            self._stack = stack
        elif size == 0:
            self._stack = self.empty_stack
        else:
            self._stack = [space.w_nil] * size
        self._fillin_w_method(space)

    def fillin(self, space, g_self):
        W_AbstractObjectWithIdentityHash.fillin(self, space, g_self)
        self._stack = [space.w_nil] * len(g_self.pointers)
        for i, g_obj in enumerate(g_self.pointers):
            g_obj.fillin(space)
            if i >= constants.BLKCLSR_SIZE:
                self.atput0(space, i - constants.BLKCLSR_SIZE, g_obj.w_object)
            elif i == constants.BLKCLSR_OUTER_CONTEXT:
                self._w_outerContext = g_obj.w_object
            elif i == constants.BLKCLSR_STARTPC:
                self._startpc = space.unwrap_int(g_obj.w_object)
            elif i == constants.BLKCLSR_NUMARGS:
                self._numArgs = space.unwrap_int(g_obj.w_object)
            else:
                assert False

    def fillin_finalize(self, space, g_self):
        self._fillin_w_method(space)

    @objectmodel.always_inline
    def _fillin_w_method(self, space):
        self._w_method = self._w_outerContext.fetch(space, constants.MTHDCTX_METHOD)

    def getclass(self, space):
        return space.w_BlockClosure

    def instsize(self):
        return constants.BLKCLSR_SIZE

    def varsize(self):
        return len(self._stack)

    def size(self):
        return self.instsize() + self.varsize()

    def tempsize(self):
        # We ignore the number of temps a block has, because the first
        # bytecodes of the block will initialize them for us. We will only
        # use this information for deciding where the stack pointer should be
        # initialy.
        # For a finding the correct number, see BlockClosure>#numTemps in an Image.
        return self.varsize() + self.numArgs()

    def fetch(self, space, index0):
        if index0 == constants.BLKCLSR_OUTER_CONTEXT:
            return self.w_outerContext()
        elif index0 == constants.BLKCLSR_STARTPC:
            return space.wrap_int(self.startpc())
        elif index0 == constants.BLKCLSR_NUMARGS:
            return space.wrap_int(self.numArgs())
        else:
            return self.at0(space, index0 - constants.BLKCLSR_SIZE)

    def at0(self, space, index0):
        return self._stack[index0]

    def w_outerContext(self):
        return self._w_outerContext

    def startpc(self):
        return self._startpc

    def numArgs(self):
        return self._numArgs

    def w_method(self):
        return self._w_method

    def store(self, space, index0, w_value):
        if index0 >= constants.BLKCLSR_SIZE:
            self.atput0(space, index0 - constants.BLKCLSR_SIZE, w_value)
        else:
            self.changed() # aborts trace
            if index0 == constants.BLKCLSR_OUTER_CONTEXT:
                self._w_outerContext = w_value
                self._fillin_w_method(space)
            elif index0 == constants.BLKCLSR_STARTPC:
                self._startpc = space.unwrap_int(w_value)
            elif index0 == constants.BLKCLSR_NUMARGS:
                self._numArgs = space.unwrap_int(w_value)
            else:
                assert False

    def atput0(self, space, index0, w_value):
        self._stack[index0] = w_value

    def fetch_all(self, space):
        return [self.w_outerContext(),
                space.wrap_int(self.startpc()),
                space.wrap_int(self.numArgs())] + self._stack

    @jit.unroll_safe
    def store_all(self, space, lst_w):
        for i, w_v in enumerate(lst_w):
            self.store(space, i, w_v)

    def _become(self, w_other):
        if not isinstance(w_other, W_BlockClosure):
            raise error.PrimitiveFailedError
        self.changed() # aborts trace
        self._numArgs, w_other._numArgs = w_other._numArgs, self._numArgs
        self._w_outerContext, w_other._w_outerContext = w_other._w_outerContext, self._w_outerContext
        self._startpc, w_other._startpc = w_other._startpc, self._startpc
        self._stack, w_other._stack = w_other._stack, self._stack
        W_AbstractObjectWithIdentityHash._become(self, w_other)

    def clone(self, space):
        copy = self.__class__(
            space, self.w_outerContext(), self.startpc(), self.numArgs(), self.varsize(), stack=list(self._stack))
        return copy

    def create_frame(self, space, arguments=[]):
        from rsqueakvm import storage_contexts
        s_outerContext = self.w_outerContext().as_context_get_shadow(space)
        assert not s_outerContext.pure_is_block_context()
        w_method = self.w_method()
        assert isinstance(w_method, W_CompiledMethod)
        w_receiver = s_outerContext.w_receiver()
        return storage_contexts.ContextPartShadow.build_method_context(
            space,
            w_method,
            w_receiver,
            arguments=arguments,
            closure=self
        )
<commit_msg>cache the w_receiver on the block closure, to avoid reading from the outer context<commit_after>from rsqueakvm import constants, error
from rsqueakvm.model.base import W_Object, W_AbstractObjectWithIdentityHash
from rsqueakvm.model.pointers import W_PointersObject
from rsqueakvm.model.compiled_methods import W_CompiledMethod
from rsqueakvm.util.version import VersionMixin

from rpython.rlib import jit, objectmodel

class W_BlockClosure(W_AbstractObjectWithIdentityHash):
    repr_classname = "W_BlockClosure"
    bytes_per_slot = 1
    _attrs_ = [
        "version",
        "_w_outerContext",
        "_startpc",
        "_numArgs", "_stack",
        "_w_method",
        "_w_receiver" ]
    _immutable_fields_ = [
        "version?",
        "_w_outerContext",
        "_startpc",
        "_numArgs", "_stack",
        "_w_method",
        "_w_receiver" ]
    objectmodel.import_from_mixin(VersionMixin)

    def pointers_become_one_way(self, space, from_w, to_w):
        W_AbstractObjectWithIdentityHash.pointers_become_one_way(self, space, from_w, to_w)
        ptrs = self.fetch_all(space)
        ptridx = 0
        for i, w_from in enumerate(from_w):
            try:
                ptridx = ptrs.index(w_from)
            except ValueError:
                continue
            w_to = to_w[i]
            ptrs[ptridx] = w_to
            w_from.post_become_one_way(w_to)
        self.store_all(space, ptrs)

    empty_stack = []

    @jit.unroll_safe
    def __init__(self, space, w_outerctxt, startpc, numArgs, size, stack=None):
        W_AbstractObjectWithIdentityHash.__init__(self)
        self._w_outerContext = w_outerctxt
        self._startpc = startpc
        self._numArgs = numArgs
        if stack:
            self._stack = stack
        elif size == 0:
            self._stack = self.empty_stack
        else:
            self._stack = [space.w_nil] * size
        self._fillin_w_method(space)
        self._fillin_w_receiver(space)

    def fillin(self, space, g_self):
        W_AbstractObjectWithIdentityHash.fillin(self, space, g_self)
        self._stack = [space.w_nil] * len(g_self.pointers)
        for i, g_obj in enumerate(g_self.pointers):
            g_obj.fillin(space)
            if i >= constants.BLKCLSR_SIZE:
                self.atput0(space, i - constants.BLKCLSR_SIZE, g_obj.w_object)
            elif i == constants.BLKCLSR_OUTER_CONTEXT:
                self._w_outerContext = g_obj.w_object
            elif i == constants.BLKCLSR_STARTPC:
                self._startpc = space.unwrap_int(g_obj.w_object)
            elif i == constants.BLKCLSR_NUMARGS:
                self._numArgs = space.unwrap_int(g_obj.w_object)
            else:
                assert False

    def fillin_finalize(self, space, g_self):
        self._fillin_w_method(space)
        self._fillin_w_receiver(space)

    @objectmodel.always_inline
    def _fillin_w_method(self, space):
        self._w_method = self._w_outerContext.fetch(space, constants.MTHDCTX_METHOD)

    @objectmodel.always_inline
    def _fillin_w_receiver(self, space):
        self._w_receiver = self._w_outerContext.fetch(space, constants.MTHDCTX_RECEIVER)

    def getclass(self, space):
        return space.w_BlockClosure

    def instsize(self):
        return constants.BLKCLSR_SIZE

    def varsize(self):
        return len(self._stack)

    def size(self):
        return self.instsize() + self.varsize()

    def tempsize(self):
        # We ignore the number of temps a block has, because the first
        # bytecodes of the block will initialize them for us. We will only
        # use this information for deciding where the stack pointer should be
        # initialy.
        # For a finding the correct number, see BlockClosure>#numTemps in an Image.
        return self.varsize() + self.numArgs()

    def fetch(self, space, index0):
        if index0 == constants.BLKCLSR_OUTER_CONTEXT:
            return self.w_outerContext()
        elif index0 == constants.BLKCLSR_STARTPC:
            return space.wrap_int(self.startpc())
        elif index0 == constants.BLKCLSR_NUMARGS:
            return space.wrap_int(self.numArgs())
        else:
            return self.at0(space, index0 - constants.BLKCLSR_SIZE)

    def at0(self, space, index0):
        return self._stack[index0]

    def w_outerContext(self):
        return self._w_outerContext

    def startpc(self):
        return self._startpc

    def numArgs(self):
        return self._numArgs

    def w_method(self):
        return self._w_method

    def w_receiver(self):
        return self._w_receiver

    def store(self, space, index0, w_value):
        if index0 >= constants.BLKCLSR_SIZE:
            self.atput0(space, index0 - constants.BLKCLSR_SIZE, w_value)
        else:
            self.changed() # aborts trace
            if index0 == constants.BLKCLSR_OUTER_CONTEXT:
                self._w_outerContext = w_value
                self._fillin_w_method(space)
                self._fillin_w_receiver(space)
            elif index0 == constants.BLKCLSR_STARTPC:
                self._startpc = space.unwrap_int(w_value)
            elif index0 == constants.BLKCLSR_NUMARGS:
                self._numArgs = space.unwrap_int(w_value)
            else:
                assert False

    def atput0(self, space, index0, w_value):
        self._stack[index0] = w_value

    def fetch_all(self, space):
        return [self.w_outerContext(),
                space.wrap_int(self.startpc()),
                space.wrap_int(self.numArgs())] + self._stack

    @jit.unroll_safe
    def store_all(self, space, lst_w):
        for i, w_v in enumerate(lst_w):
            self.store(space, i, w_v)

    def _become(self, w_other):
        if not isinstance(w_other, W_BlockClosure):
            raise error.PrimitiveFailedError
        self.changed() # aborts trace
        self._numArgs, w_other._numArgs = w_other._numArgs, self._numArgs
        self._w_outerContext, w_other._w_outerContext = w_other._w_outerContext, self._w_outerContext
        self._startpc, w_other._startpc = w_other._startpc, self._startpc
        self._stack, w_other._stack = w_other._stack, self._stack
        W_AbstractObjectWithIdentityHash._become(self, w_other)

    def clone(self, space):
        copy = self.__class__(
            space, self.w_outerContext(), self.startpc(), self.numArgs(), self.varsize(), stack=list(self._stack))
        return copy

    def create_frame(self, space, arguments=[]):
        from rsqueakvm import storage_contexts
        w_method = self.w_method()
        assert isinstance(w_method, W_CompiledMethod)
        w_receiver = self.w_receiver()
        return storage_contexts.ContextPartShadow.build_method_context(
            space,
            w_method,
            w_receiver,
            arguments=arguments,
            closure=self
        )
<|endoftext|>


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

from setuptools import setup, find_packages

setup(name = "gsconfig.py",
    version = "1.0",
    description = "GeoServer REST Configuration Client",
    keywords = "GeoServer REST Configuration",
    license = "MIT",
    url = "http://bitbucket.org/dwins/gsconfigpy",
    author = "David Winslow, Sebastian Benthall",
    author_email = "dwinslow@opengeo.org",
    install_requires = ['httplib2'],
    package_dir = {'':'src'},
    packages = find_packages('src'),
    test_suite = "test.catalogtests"
)

<commit_msg>Changed name from gsconfig.py to gsconfig and updated metadata<commit_after>#!/usr/bin/env python

from setuptools import setup, find_packages

setup(name = "gsconfig",
    version = "0.5",
    description = "GeoServer REST Configuration Client",
    keywords = "GeoServer REST Configuration",
    license = "MIT",
    url = "http://github.com/dwins/gsconfig.py",
    author = "David Winslow, Sebastian Benthall",
    author_email = "dwinslow@opengeo.org",
    install_requires = ['httplib2'],
    package_dir = {'':'src'},
    packages = find_packages('src'),
    test_suite = "test.catalogtests",
    classifiers   = [
                 'Development Status :: 4 - Beta',
                 'Intended Audience :: Developers',
                 'Intended Audience :: Science/Research',
                 'License :: OSI Approved :: MIT License',
                 'Operating System :: OS Independent',
                 'Programming Language :: Python',
                 'Topic :: Scientific/Engineering :: GIS',
)

<|endoftext|>


<commit_before>"""
Secured-Pi, 2016
This is a script for the Secured-Pi project dealing with the machine learning aspects of the facial recognition.

This script relies on the OpenCV 3.1 library installed with the opencv-contrib face module.
If you do not have OpenCV installed, I highly recommend that you attempt to do so using a
virtual box, making sure to also install the face module, which is part of the OpenCV-contrib
project.

For training, create a directory called 'training' inside of this directory.  Each person's photo should
be named like "member-1-a", where 1 identifies the person to whom the image belongs to, and the letter
increments for each photo.  For example, a training set of 2 people might contain the images:
member-1-a.gif
member-1-b.gif
member-2-a.gif
member-2-b.gif .. and so on ..

For accuracy, we recommend a minimum of __ pictures for each member.  It is also important that
no other files be contained in the training directory besides the pictures.
Just want to thank the creators of the tutorials at:
https://pythonprogramming.net/loading-video-python-opencv-tutorial/
"""

import os
import cv2
import numpy as np
import re
from PIL import Image

CASCADE_MODEL = 'haarcascade_frontalface_default.xml'
FACE_CASCADE = cv2.CascadeClassifier(CASCADE_MODEL)
TRAINING_SET_PATH = 'training'

def train_recognizer(recognizer=cv2.face.createLBPHFaceRecognizer, image_path=TRAINING_SET_PATH, save_file='recog_brain.yml', recog_model=None):
	"""Train the facial recognition software with some training photos.

	This will train the recognizer, and save the training.  This saved file
	will be used by test_individual to verify membership.
	"""
	recognizer = recognizer()
	if recog_model is not None:
		recognizer.load(recog_model)
	tr_files = os.listdir(image_path)
	tr_files = [image_path + '/' + f for f in tr_files]
	images = []		# image arrays of face cut-outs
	members = []	# this will be the ids of the members

	for tr_f in tr_files:
		print('training with file:' + tr_f)
		tr_img = np.array(Image.open(tr_f).convert('L'), 'uint8')
		curr_member = int(re.search('-(\d+)-', os.path.split(tr_f)[1]).group(1))
		curr_face = FACE_CASCADE.detectMultiScale(tr_img)

		for (x, y, w, h) in curr_face:
			images.append(tr_img[y: y + h, x: x + w])
			members.append(curr_member)
			# to see the images while training(demo purposes), uncomment lines below
			# cv2.imshow("Training...", tr_img[y: y + h, x: x + w])
			# cv2.waitKey(10)

	# cv2.destroyAllWindows()
	recognizer.train(images, np.array(members))
	recognizer.save(save_file)

def test_individual(image_to_test, threshold=40, recognizer=cv2.face.createLBPHFaceRecognizer, recog_model='recog_brain.yml'):
	"""Test if an individual has access to the lock.

	Make sure there is a recog_model file that has been generated by the train_recognizer function. Returns a boolean."""
	recognizer = recognizer()
	recognizer.load(recog_model)

	image_array = np.array(Image.open(image_to_test).convert('L'), 'uint8')
	curr_face = FACE_CASCADE.detectMultiScale(image_array)[0]
	x, y, w, h = curr_face
	test_image = image_array[y: y + h, x: x + w]

	member_prediction, confidence = recognizer.predict(test_image)
	print('member number: {}, confidence: {}'.format(member_prediction, confidence))
	if confidence > threshold:
		return False
	return True
<commit_msg>fixed linting issues on facial_recognition.py<commit_after>"""
Secured-Pi, 2016.

This is a script for the Secured-Pi project dealing with the machine learning
aspects of the facial recognition.

This script relies on the OpenCV 3.1 library installed with the opencv-contrib
face module. If you do not have OpenCV installed, I highly recommend that you
attempt to do so using a virtual box, making sure to also install the face
module, which is part of the OpenCV-contrib project.

For training, create a directory called 'training' inside of this directory.
Each person's photo should be named like "member-1-a", where 1 identifies the
person to whom the image belongs to, and the letter increments for each photo.
For example, a training set of 2 people might contain the images:
member-1-a.gif
member-1-b.gif
member-2-a.gif
member-2-b.gif .. and so on ..

For accuracy, we recommend a minimum of __ pictures for each member.  It is
also important that no other files be contained in the training directory
besides the pictures. Just want to thank the creators of the tutorials at:
https://pythonprogramming.net/loading-video-python-opencv-tutorial/
"""

import os
import cv2
import numpy as np
import re
from PIL import Image

CASCADE_MODEL = 'haarcascade_frontalface_default.xml'
FACE_CASCADE = cv2.CascadeClassifier(CASCADE_MODEL)
TRAINING_SET_PATH = 'training'

def train_recognizer(recognizer=cv2.face.createLBPHFaceRecognizer,
                     image_path=TRAINING_SET_PATH, save_file='recog_brain.yml',
                     recog_model=None):
    """Train the facial recognition software with some training photos.

    This will train the recognizer, and save the training.  This saved file
    will be used by test_individual to verify membership.
    """
    recognizer = recognizer()
    if recog_model is not None:
        recognizer.load(recog_model)
    tr_files = os.listdir(image_path)
    tr_files = [image_path + '/' + f for f in tr_files]
    images = []         # image arrays of face cut-outs
    members = []        # this will be the ids of the members

    for tr_f in tr_files:
        print('training with file:' + tr_f)
        tr_img = np.array(Image.open(tr_f).convert('L'), 'uint8')
        curr_member = int(re.search('-(\d+)-',
                          os.path.split(tr_f)[1]).group(1))
        curr_face = FACE_CASCADE.detectMultiScale(tr_img)

        for (x, y, w, h) in curr_face:
            images.append(tr_img[y: y + h, x: x + w])
            members.append(curr_member)
            # to see the images while training(demo), uncomment lines below:
            # cv2.imshow("Training...", tr_img[y: y + h, x: x + w])
            # cv2.waitKey(10)

    # cv2.destroyAllWindows()
    recognizer.train(images, np.array(members))
    recognizer.save(save_file)

def test_individual(image_to_test, threshold=40,
                    recognizer=cv2.face.createLBPHFaceRecognizer,
                    recog_model='recog_brain.yml'):
    """Test if an individual has access to the lock.

    Make sure there is a recog_model file that has been generated by the
    train_recognizer function. Returns a boolean.
    """
    recognizer = recognizer()
    recognizer.load(recog_model)

    image_array = np.array(Image.open(image_to_test).convert('L'), 'uint8')
    curr_face = FACE_CASCADE.detectMultiScale(image_array)[0]
    x, y, w, h = curr_face
    test_image = image_array[y: y + h, x: x + w]

    member_prediction, confidence = recognizer.predict(test_image)
    print('member number: {}, confidence: {}'.format(member_prediction,
                                                     confidence))
    if confidence > threshold:
        return False
    return True
<|endoftext|>


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

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

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

description = """
Octopus is a Python framework for microservices.
"""

requirements = [
    # TODO: put package requirements here
]

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

setup(
    name='octopus',
    version='0.0.0',
    description=description,
    long_description=readme,
    author="Wael Ben Zid El Guebsi",
    author_email='benzid.wael@hotmail.fr',
    url='https://github.com/benzid-wael/octopus',
    packages=[
        'octopus',
    ],
    package_dir={
        'octopus': 'octopus'
    },
    include_package_data=True,
    install_requires=requirements,
    license="ISCL",
    zip_safe=False,
    keywords='octopus',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: ISC License (ISCL)',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)
<commit_msg>Project github repo URL fixed<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

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

description = """
Octopus is a Python framework for microservices.
"""

requirements = [
    # TODO: put package requirements here
]

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

setup(
    name='octopus',
    version='0.0.0',
    description=description,
    long_description=readme,
    author="Wael Ben Zid El Guebsi",
    author_email='benzid.wael@hotmail.fr',
    url='https://github.com/OctopusProject/octopus',
    packages=[
        'octopus',
    ],
    package_dir={
        'octopus': 'octopus'
    },
    include_package_data=True,
    install_requires=requirements,
    license="ISCL",
    zip_safe=False,
    keywords='octopus',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: ISC License (ISCL)',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
    tests_require=test_requirements
)
<|endoftext|>


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

from setuptools import setup, find_packages

setup(name='django-locksmith',
      version='0.7.4',
      description='Django apps for API authentication and centralized authorization',
      author='James Turk',
      author_email='jturk@sunlightfoundation.com',
      license='BSD',
      url='http://github.com/sunlightlabs/django-locksmith/',
      packages=find_packages(),
      package_data={'locksmith': ['static/scripts/*.js', 'static/styles/*.css',
                                  'static/datatables/js/*.js', 'static/datatables/css/*.css',
                                  'static/datatables/images/*',
                                  'static/bootstrap/js/*.js', 'static/bootstrap/css/*.css',
                                  'static/bootstrap/img/*.png'],
                    'locksmith.hub': ['templates/locksmith/*.html', 'templates/locksmith/*.txt']},
)
<commit_msg>v0.7.5<commit_after>#!/usr/bin/env python

from setuptools import setup, find_packages

setup(name='django-locksmith',
      version='0.7.5',
      description='Django apps for API authentication and centralized authorization',
      author='James Turk',
      author_email='jturk@sunlightfoundation.com',
      license='BSD',
      url='http://github.com/sunlightlabs/django-locksmith/',
      packages=find_packages(),
      package_data={'locksmith': ['static/scripts/*.js', 'static/styles/*.css',
                                  'static/datatables/js/*.js', 'static/datatables/css/*.css',
                                  'static/datatables/images/*',
                                  'static/bootstrap/js/*.js', 'static/bootstrap/css/*.css',
                                  'static/bootstrap/img/*.png'],
                    'locksmith.hub': ['templates/locksmith/*.html', 'templates/locksmith/*.txt']},
)
<|endoftext|>


<commit_before># coding=utf-8
from __future__ import unicode_literals
from .. import Provider as PersonProvider

class Provider(PersonProvider):
    formats_female = (
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{prefix_female}} {{first_name_female}} {{last_name}}'
    )

    formats_male = (
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{prefix_male}} {{first_name_male}} {{last_name}}'

    )

    formats = formats_male + formats_female

    first_names_female = (
        'Agatha', 'Alana', 'Alexia', 'Alice', 'Alícia', 'Amanda',
        'Ana Beatriz', 'Ana Carolina', 'Ana Clara', 'Ana Julia', 'Ana Júlia',
        'Ana Laura', 'Ana Luiza', 'Ana Lívia', 'Ana Sophia', 'Ana Vitória',
        'Ana', 'Beatriz', 'Bianca', 'Brenda', 'Bruna', 'Bárbara', 'Camila',
        'Carolina', 'Caroline', 'Catarina', 'Cecília', 'Clara', 'Clarice',
        'Daniela', 'Eduarda', 'Elisa', 'Eloah', 'Emanuella', 'Emanuelly',
        'Emilly', 'Esther', 'Evelyn', 'Fernanda', 'Gabriela', 'Gabrielly',
        'Giovanna', 'Helena', 'Heloísa', 'Isabel', 'Isabella', 'Isabelly',
        'Isadora', 'Isis', 'Joana', 'Julia', 'Juliana', 'Júlia', 'Kamilly',
        'Lara', 'Larissa', 'Laura', 'Lavínia', 'Laís', 'Letícia', 'Lorena',
        'Luana', 'Luiza', 'Luna', 'Lívia', 'Maitê', 'Manuela', 'Marcela',
        'Maria Alice', 'Maria Cecília', 'Maria Clara', 'Maria Eduarda',
        'Maria Fernanda', 'Maria Julia', 'Maria Luiza', 'Maria Sophia',
        'Maria Vitória', 'Maria', 'Mariana', 'Mariane', 'Marina', 'Maysa',
        'Melissa', 'Milena', 'Mirella', 'Natália', 'Nicole', 'Nina', 'Olivia',
        'Pietra', 'Rafaela', 'Raquel', 'Rebeca', 'Sabrina', 'Sarah', 'Sofia',
        'Sophia', 'Sophie', 'Stella', 'Stephany', 'Valentina', 'Vitória',
        'Yasmin'
    )

    first_names_male = (
        'Alexandre', 'André', 'Anthony', 'Antônio', 'Arthur', 'Augusto',
        'Benjamin', 'Benício', 'Bernardo', 'Breno', 'Bruno', 'Bryan', 'Caio',
        'Calebe', 'Carlos Eduardo', 'Cauã', 'Cauê', 'Daniel', 'Danilo',
        'Davi Lucas', 'Davi Lucca', 'Davi Luiz', 'Davi', 'Diego', 'Diogo',
        'Eduardo', 'Emanuel', 'Enrico', 'Enzo Gabriel', 'Enzo', 'Erick',
        'Felipe', 'Fernando', 'Francisco', 'Gabriel', 'Guilherme',
        'Gustavo Henrique', 'Gustavo', 'Heitor', 'Henrique', 'Ian', 'Igor',
        'Isaac', 'Joaquim', 'João Felipe', 'João Gabriel', 'João Guilherme',
        'João Lucas', 'João Miguel', 'João Pedro', 'João Vitor', 'João',
        'Juan', 'Kaique', 'Kevin', 'Leandro', 'Leonardo', 'Levi', 'Lorenzo',
        'Lucas Gabriel', 'Lucas', 'Lucca', 'Luigi', 'Luiz Felipe',
        'Luiz Fernando', 'Luiz Gustavo', 'Luiz Henrique', 'Luiz Miguel',
        'Luiz Otávio', 'Marcelo', 'Marcos Vinicius', 'Matheus', 'Miguel',
        'Murilo', 'Nathan', 'Nicolas', 'Noah', 'Otávio', 'Paulo',
        'Pedro Henrique', 'Pedro Lucas', 'Pedro Miguel', 'Pedro', 'Pietro',
        'Rafael', 'Raul', 'Renan', 'Rodrigo', 'Ryan', 'Samuel', 'Thales',
        'Theo', 'Thiago', 'Thomas', 'Vicente', 'Vinicius', 'Vitor Gabriel',
        'Vitor Hugo', 'Vitor', 'Yago', 'Yuri'
    )

    first_names = first_names_male + first_names_female

    last_names = (
        'Almeida', 'Alves', 'Aragão', 'Araújo', 'Azevedo', 'Barbosa', 'Barros',
        'Caldeira', 'Campos', 'Cardoso', 'Cardoso,', 'Carvalho', 'Castro',
        'Cavalcanti', 'Correia', 'Costa', 'Costela', 'Cunha', 'da Conceição',
        'da Costa', 'da Cruz', 'da Cunha', 'da Luz', 'da Mata', 'da Mota',
        'da Paz', 'da Rocha', 'da Rosa', 'das Neves', 'Dias', 'Duarte',
        'Farias' 'Fernandes', 'Ferreira', 'Fogaça', 'Freitas', 'Gomes',
        'Gonçalves', 'Jesus', 'Lima', 'Lopes', 'Martins', 'Melo', 'Mendes',
        'Monteiro', 'Moraes', 'Moreira', 'Moura', 'Nascimento', 'Nogueira',
        'Novaes', 'Nunes', 'Oliveira', 'Peixoto', 'Pereira', 'Pinto', 'Pires',
        'Porto', 'Ramos', 'Rezende', 'Ribeiro', 'Rocha', 'Rodrigues', 'Sales',
        'Santos', 'Silva', 'Silveira', 'Souza', 'Teixeira', 'Viana', 'Vieira'
    )

    prefixes_female = ('Srta.', 'Sra.', 'Dra.')
    prefixes_male = ('Sr.', 'Dr.')
<commit_msg>Add sources<commit_after># coding=utf-8
from __future__ import unicode_literals
from .. import Provider as PersonProvider

class Provider(PersonProvider):
    formats_female = (
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{first_name_female}} {{last_name}}',
        '{{prefix_female}} {{first_name_female}} {{last_name}}'
    )

    formats_male = (
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{first_name_male}} {{last_name}}',
        '{{prefix_male}} {{first_name_male}} {{last_name}}'

    )

    formats = formats_male + formats_female

    """
    To a previous (undocumented?) list of female given names was added the 100
    most popular names in Brazil in 2014 and 2015 according to Exame magazine:
    * http://exame.abril.com.br/brasil/noticias/os-100-nomes-mais-comuns-no-brasil-em-2014
    * http://exame.abril.com.br/brasil/noticias/os-100-nomes-mais-comuns-no-brasil-em-2015
    """
    first_names_female = (
        'Agatha', 'Alana', 'Alexia', 'Alice', 'Alícia', 'Amanda',
        'Ana Beatriz', 'Ana Carolina', 'Ana Clara', 'Ana Julia', 'Ana Júlia',
        'Ana Laura', 'Ana Luiza', 'Ana Lívia', 'Ana Sophia', 'Ana Vitória',
        'Ana', 'Beatriz', 'Bianca', 'Brenda', 'Bruna', 'Bárbara', 'Camila',
        'Carolina', 'Caroline', 'Catarina', 'Cecília', 'Clara', 'Clarice',
        'Daniela', 'Eduarda', 'Elisa', 'Eloah', 'Emanuella', 'Emanuelly',
        'Emilly', 'Esther', 'Evelyn', 'Fernanda', 'Gabriela', 'Gabrielly',
        'Giovanna', 'Helena', 'Heloísa', 'Isabel', 'Isabella', 'Isabelly',
        'Isadora', 'Isis', 'Joana', 'Julia', 'Juliana', 'Júlia', 'Kamilly',
        'Lara', 'Larissa', 'Laura', 'Lavínia', 'Laís', 'Letícia', 'Lorena',
        'Luana', 'Luiza', 'Luna', 'Lívia', 'Maitê', 'Manuela', 'Marcela',
        'Maria Alice', 'Maria Cecília', 'Maria Clara', 'Maria Eduarda',
        'Maria Fernanda', 'Maria Julia', 'Maria Luiza', 'Maria Sophia',
        'Maria Vitória', 'Maria', 'Mariana', 'Mariane', 'Marina', 'Maysa',
        'Melissa', 'Milena', 'Mirella', 'Natália', 'Nicole', 'Nina', 'Olivia',
        'Pietra', 'Rafaela', 'Raquel', 'Rebeca', 'Sabrina', 'Sarah', 'Sofia',
        'Sophia', 'Sophie', 'Stella', 'Stephany', 'Valentina', 'Vitória',
        'Yasmin'
    )

    """
    To a previous (undocumented?) list of male given names was added the 100
    most popular names in Brazil in 2014 and 2015 according to this blog post:
    * http://exame.abril.com.br/brasil/noticias/os-100-nomes-mais-comuns-no-brasil-em-2014
    * http://exame.abril.com.br/brasil/noticias/os-100-nomes-mais-comuns-no-brasil-em-2015
    """
    first_names_male = (
        'Alexandre', 'André', 'Anthony', 'Antônio', 'Arthur', 'Augusto',
        'Benjamin', 'Benício', 'Bernardo', 'Breno', 'Bruno', 'Bryan', 'Caio',
        'Calebe', 'Carlos Eduardo', 'Cauã', 'Cauê', 'Daniel', 'Danilo',
        'Davi Lucas', 'Davi Lucca', 'Davi Luiz', 'Davi', 'Diego', 'Diogo',
        'Eduardo', 'Emanuel', 'Enrico', 'Enzo Gabriel', 'Enzo', 'Erick',
        'Felipe', 'Fernando', 'Francisco', 'Gabriel', 'Guilherme',
        'Gustavo Henrique', 'Gustavo', 'Heitor', 'Henrique', 'Ian', 'Igor',
        'Isaac', 'Joaquim', 'João Felipe', 'João Gabriel', 'João Guilherme',
        'João Lucas', 'João Miguel', 'João Pedro', 'João Vitor', 'João',
        'Juan', 'Kaique', 'Kevin', 'Leandro', 'Leonardo', 'Levi', 'Lorenzo',
        'Lucas Gabriel', 'Lucas', 'Lucca', 'Luigi', 'Luiz Felipe',
        'Luiz Fernando', 'Luiz Gustavo', 'Luiz Henrique', 'Luiz Miguel',
        'Luiz Otávio', 'Marcelo', 'Marcos Vinicius', 'Matheus', 'Miguel',
        'Murilo', 'Nathan', 'Nicolas', 'Noah', 'Otávio', 'Paulo',
        'Pedro Henrique', 'Pedro Lucas', 'Pedro Miguel', 'Pedro', 'Pietro',
        'Rafael', 'Raul', 'Renan', 'Rodrigo', 'Ryan', 'Samuel', 'Thales',
        'Theo', 'Thiago', 'Thomas', 'Vicente', 'Vinicius', 'Vitor Gabriel',
        'Vitor Hugo', 'Vitor', 'Yago', 'Yuri'
    )

    first_names = first_names_male + first_names_female

    """
    To a previous (undocumented?) list of family names was added the 70
    most popular family names in Brazil according to this blog post:
    * http://nomeschiques.com/os-70-sobrenomes-mais-comuns-e-famosos-do-brasil/
    """
    last_names = (
        'Almeida', 'Alves', 'Aragão', 'Araújo', 'Azevedo', 'Barbosa', 'Barros',
        'Caldeira', 'Campos', 'Cardoso', 'Cardoso,', 'Carvalho', 'Castro',
        'Cavalcanti', 'Correia', 'Costa', 'Costela', 'Cunha', 'da Conceição',
        'da Costa', 'da Cruz', 'da Cunha', 'da Luz', 'da Mata', 'da Mota',
        'da Paz', 'da Rocha', 'da Rosa', 'das Neves', 'Dias', 'Duarte',
        'Farias' 'Fernandes', 'Ferreira', 'Fogaça', 'Freitas', 'Gomes',
        'Gonçalves', 'Jesus', 'Lima', 'Lopes', 'Martins', 'Melo', 'Mendes',
        'Monteiro', 'Moraes', 'Moreira', 'Moura', 'Nascimento', 'Nogueira',
        'Novaes', 'Nunes', 'Oliveira', 'Peixoto', 'Pereira', 'Pinto', 'Pires',
        'Porto', 'Ramos', 'Rezende', 'Ribeiro', 'Rocha', 'Rodrigues', 'Sales',
        'Santos', 'Silva', 'Silveira', 'Souza', 'Teixeira', 'Viana', 'Vieira'
    )

    prefixes_female = ('Srta.', 'Sra.', 'Dra.')
    prefixes_male = ('Sr.', 'Dr.')
<|endoftext|>


<commit_before>#!/usr/bin/python
"""\

Pygr
****

Pygr is an open source software project used to develop graph database
interfaces for the popular Python language, with a strong emphasis
on bioinformatics applications ranging from genome-wide analysis of
alternative splicing patterns, to comparative genomics queries of
multi-genome alignment data.
"""\

import os
import sys
from distutils.core import setup, Extension

def runTests():
   testdir = os.path.join(os.getcwd(),"tests")
   sys.path.append(testdir)
   os.environ['PYGRPATH'] = os.path.join(os.getcwd(),"pygr")

   # version check
   v1, v2 = sys.version_info[:2]
   if v1 < 2:
      raise 'pygr does not support python 1.x'
   if v1 == 2 and v2 < 2:
      raise 'pygr does not support python2.1 or earlier version'

   try:
      import test_loader
   except ImportError:
      raise "Unable to load test code. Please check to see that test_loader.py resides in (%s)\n" % (testdir)

   try:
      import MySQLdb
   except ImportError:
      print "\nWarning: You do not have a required module installed (MySQLdb). While this module is not necessary to use core components, the provided apps code will not work. Installing anyway...\n"

   if (test_loader.TestFrameWork(testExtensions=False).go()):
      print "\nAll tests passed, continuing install...\n"
      return True
   else:
      print "\nSource tainted! This code has been tampered with, or has not been QA'd. Please retrieve a new archive.\n"
      return False

name = "pygr"
version = "1.0"

classifiers = """
Development Status :: 5 - Production/Stable
Operating System :: MacOS :: MacOS X
Operating System :: Microsoft :: Windows :: Windows NT/2000
Operating System :: OS Independent
Operating System :: POSIX
Operating System :: POSIX :: Linux
Operating System :: Unix
Programming Language :: Python
Topic :: Scientific/Engineering
Topic :: Scientific/Engineering :: Bioinformatics
"""

metadata = {
    'name': name,
    'version': version,
    'description': "Pygr",
    'long_description': __doc__,
    'author': "Christopher Lee",
    'author_email': "leec@chem.ucla.edu",
    'license': "GPL",
    'platforms': "ALL",
    'url': "http://sourceforge.net/projects/pygr",
    #'download_url': "http://prdownloads.sourceforge.net/pygr/" \
    #                "pygr-%s.tar.gz" % version,
    #'classifiers': [ c for c in classifiers.split('\n') if c ],

    'py_modules': [
	"pygr/__init__",
	"pygr/graphquery",
	"pygr/mapping",
        "pygr/coordinator",
        "pygr/Data",
        "pygr/nlmsa_utils",
        "pygr/nestedlist",
        "pygr/xnestedlist",
	"pygr/poa",
	"pygr/schema",
	"pygr/seqdb",
	"pygr/sequence",
	"pygr/sequtil",
	"pygr/sqlgraph",
        "pygr/parse_blast",
	"pygr/apps/__init__",
	"pygr/apps/leelabdb",
	"pygr/apps/seqref",
	"pygr/apps/splicegraph",
        "pygr/apps/maf2VSgraph",
        ]
   }

v1, v2 = sys.version_info[:2]
if v1 >= 2 and v2 > 2:
    metadata['download_url'] = "http://prdownloads.sourceforge.net/pygr/pygr-%s.tar.gz" % version
    metadata['classifiers'] = [ c for c in classifiers.split('\n') if c ]

def copyFile(source,target):
   'OS independent copy function'
   if source==target: # PROTECT AGAINST POSSIBILITY OF OVER-WRITING SELF
      return # NO NEED TO DO ANYTHING
   ifile=file(os.path.normpath(source))
   ofile=file(os.path.normpath(target),'w')
   ofile.write(ifile.read())
   ifile.close()
   ofile.close()

def compilePyrex(cfile):
   'for proper class pickling, pyrexc needs full-dotted-module-path filename format'
   modulename='.'.join(cfile.split('/')) # e.g. pygr/cdict.c -> pygc.cdict.c
   ctarget=os.path.join(os.path.dirname(cfile),modulename) # ADD DIRECTORY PATH
   copyFile(cfile[:-2]+'.pyx',ctarget[:-2]+'.pyx') # COPY pyx FILE TO DESIRED NAME
   try: # COPY pxd FILE IF IT EXISTS...
      copyFile(cfile[:-2]+'.pxd',ctarget[:-2]+'.pxd') # COPY pxd FILE TO DESIRED NAME
   except IOError:
      pass
   cmd='pyrexc %s.pyx'%ctarget[:-2]
   print cmd
   exit_status=os.system(cmd) # TRY USING PYREX TO COMPILE EXTENSIONS
   if exit_status!=0:  # CAN'T RUN THE PYREX COMPILER TO PRODUCE C
      print '\n\nPyrex compilation failed!  Is pyrexc missing or not in your PATH?'
      print 'Skipping extension module... you will be lacking some functionality:',modulename
      return False # SIGNAL COMPILATION FAILED
   copyFile(ctarget,cfile) # COPY .c FILE BACK TO DESIRED NAME
   return True # SIGNAL COMPILATION SUCCEEDED

def runSetup(script_args=None):
   'prepare extension module code, run distutils setup'
   buildExtensions=[]
   pyrexTargets={'pygr/cdict.c':
                 Extension('pygr.cdict',sources = ['pygr/cgraph.c', 'pygr/cdict.c']),
                 'pygr/cnestedlist.c':
                 Extension('pygr.cnestedlist',
                           sources = ['pygr/intervaldb.c', 'pygr/cnestedlist.c',
                                      'pygr/apps/maf2nclist.c']),
                 'pygr/seqfmt.c':Extension('pygr.seqfmt',sources = ['pygr/seqfmt.c'])}
   for cfile,extmodule in pyrexTargets.items():
      if os.access(cfile,os.R_OK):
         print 'Using existing pyrexc-generated C-code',cfile
      elif not compilePyrex(cfile):  # HMM, NO PYREXC COMPILED CODE, HAVE TO RUN PYREXC
         continue # PYREX COMPILATION FAILED, CAN'T ADD THIS MODULE TO OUR EXTENSIONS
      buildExtensions.append(extmodule)

   if len(buildExtensions)>0:
      metadata['ext_modules'] = buildExtensions

   setup(**metadata) # NOW DO THE BUILD AND WHATEVER ELSE IS REQUESTED

if __name__=='__main__':
   if runTests(): # DID EVERYTHING TEST OK?
      runSetup() # DO THE INSTALL
   else: # EXIT WITH ERROR CODE
      sys.exit(1)

<commit_msg>added checks for whether .c code is up to date relative to .pyx code<commit_after>#!/usr/bin/python
"""\

Pygr
****

Pygr is an open source software project used to develop graph database
interfaces for the popular Python language, with a strong emphasis
on bioinformatics applications ranging from genome-wide analysis of
alternative splicing patterns, to comparative genomics queries of
multi-genome alignment data.
"""\

import os
import sys
from distutils.core import setup, Extension

def runTests():
   testdir = os.path.join(os.getcwd(),"tests")
   sys.path.append(testdir)
   os.environ['PYGRPATH'] = os.path.join(os.getcwd(),"pygr")

   # version check
   v1, v2 = sys.version_info[:2]
   if v1 < 2:
      raise 'pygr does not support python 1.x'
   if v1 == 2 and v2 < 2:
      raise 'pygr does not support python2.1 or earlier version'

   try:
      import test_loader
   except ImportError:
      raise "Unable to load test code. Please check to see that test_loader.py resides in (%s)\n" % (testdir)

   try:
      import MySQLdb
   except ImportError:
      print "\nWarning: You do not have a required module installed (MySQLdb). While this module is not necessary to use core components, the provided apps code will not work. Installing anyway...\n"

   if (test_loader.TestFrameWork(testExtensions=False).go()):
      print "\nAll tests passed, continuing install...\n"
      return True
   else:
      print "\nSource tainted! This code has been tampered with, or has not been QA'd. Please retrieve a new archive.\n"
      return False

name = "pygr"
version = "1.0"

classifiers = """
Development Status :: 5 - Production/Stable
Operating System :: MacOS :: MacOS X
Operating System :: Microsoft :: Windows :: Windows NT/2000
Operating System :: OS Independent
Operating System :: POSIX
Operating System :: POSIX :: Linux
Operating System :: Unix
Programming Language :: Python
Topic :: Scientific/Engineering
Topic :: Scientific/Engineering :: Bioinformatics
"""

metadata = {
    'name': name,
    'version': version,
    'description': "Pygr",
    'long_description': __doc__,
    'author': "Christopher Lee",
    'author_email': "leec@chem.ucla.edu",
    'license': "GPL",
    'platforms': "ALL",
    'url': "http://sourceforge.net/projects/pygr",
    #'download_url': "http://prdownloads.sourceforge.net/pygr/" \
    #                "pygr-%s.tar.gz" % version,
    #'classifiers': [ c for c in classifiers.split('\n') if c ],

    'py_modules': [
	"pygr/__init__",
	"pygr/graphquery",
	"pygr/mapping",
        "pygr/coordinator",
        "pygr/Data",
        "pygr/nlmsa_utils",
        "pygr/nestedlist",
        "pygr/xnestedlist",
	"pygr/poa",
	"pygr/schema",
	"pygr/seqdb",
	"pygr/sequence",
	"pygr/sequtil",
	"pygr/sqlgraph",
        "pygr/parse_blast",
	"pygr/apps/__init__",
	"pygr/apps/leelabdb",
	"pygr/apps/seqref",
	"pygr/apps/splicegraph",
        "pygr/apps/maf2VSgraph",
        ]
   }

v1, v2 = sys.version_info[:2]
if v1 >= 2 and v2 > 2:
    metadata['download_url'] = "http://prdownloads.sourceforge.net/pygr/pygr-%s.tar.gz" % version
    metadata['classifiers'] = [ c for c in classifiers.split('\n') if c ]

def copyFile(source,target):
   'OS independent copy function'
   if source==target: # PROTECT AGAINST POSSIBILITY OF OVER-WRITING SELF
      return # NO NEED TO DO ANYTHING
   ifile=file(os.path.normpath(source))
   ofile=file(os.path.normpath(target),'w')
   ofile.write(ifile.read())
   ifile.close()
   ofile.close()

def compilePyrex(cfile):
   'for proper class pickling, pyrexc needs full-dotted-module-path filename format'
   modulename='.'.join(cfile.split('/')) # e.g. pygr/cdict.c -> pygc.cdict.c
   ctarget=os.path.join(os.path.dirname(cfile),modulename) # ADD DIRECTORY PATH
   copyFile(cfile[:-2]+'.pyx',ctarget[:-2]+'.pyx') # COPY pyx FILE TO DESIRED NAME
   try: # COPY pxd FILE IF IT EXISTS...
      copyFile(cfile[:-2]+'.pxd',ctarget[:-2]+'.pxd') # COPY pxd FILE TO DESIRED NAME
   except IOError:
      pass
   cmd='pyrexc %s.pyx'%ctarget[:-2]
   print cmd
   exit_status=os.system(cmd) # TRY USING PYREX TO COMPILE EXTENSIONS
   if exit_status!=0:  # CAN'T RUN THE PYREX COMPILER TO PRODUCE C
      print '\n\nPyrex compilation failed!  Is pyrexc missing or not in your PATH?'
      return False # SIGNAL COMPILATION FAILED
   copyFile(ctarget,cfile) # COPY .c FILE BACK TO DESIRED NAME
   return True # SIGNAL COMPILATION SUCCEEDED

def pyrexIsUpToDate(cfile):
   'True if .c file is newer than the .pyx file'
   cstat=os.stat(cfile)
   try:
      pyxstat=os.stat(cfile[:-2]+'.pyx')
   except OSError: # PYREX .pyx CODE IS MISSING??  JUST USE OUR EXISTING C CODE THEN.
      print 'Warning: pyrex code %s is missing!  Check your distribution!' % (cfile[:-2]+'.pyx')
      return True
   return cstat[8]>pyxstat[8] # COMPARE THEIR st_mtime VALUES

def runSetup(script_args=None):
   'prepare extension module code, run distutils setup'
   buildExtensions=[]
   pyrexTargets={'pygr/cdict.c':
                 Extension('pygr.cdict',sources = ['pygr/cgraph.c', 'pygr/cdict.c']),
                 'pygr/cnestedlist.c':
                 Extension('pygr.cnestedlist',
                           sources = ['pygr/intervaldb.c', 'pygr/cnestedlist.c',
                                      'pygr/apps/maf2nclist.c']),
                 'pygr/seqfmt.c':Extension('pygr.seqfmt',sources = ['pygr/seqfmt.c'])}
   for cfile,extmodule in pyrexTargets.items():
      if os.access(cfile,os.R_OK) and pyrexIsUpToDate(cfile):
         print 'Using existing pyrexc-generated C-code',cfile
      else:
         compilePyrex(cfile)  # HMM, NO PYREXC COMPILED CODE, HAVE TO RUN PYREXC
      if os.access(cfile,os.R_OK):
         buildExtensions.append(extmodule)
      else: # PYREX COMPILATION FAILED, CAN'T ADD THIS MODULE TO OUR EXTENSIONS
         print 'Skipping extension module... you will be lacking some functionality:',\
               cfile[:-2]

   if len(buildExtensions)>0:
      metadata['ext_modules'] = buildExtensions

   setup(**metadata) # NOW DO THE BUILD AND WHATEVER ELSE IS REQUESTED

if __name__=='__main__':
   if runTests(): # DID EVERYTHING TEST OK?
      runSetup() # DO THE INSTALL
   else: # EXIT WITH ERROR CODE
      sys.exit(1)

<|endoftext|>


<commit_before>import pytest
from falafel.mappers import ParseException
from falafel.mappers.interrupts import Interrupts
from falafel.tests import context_wrap

INT_MULTI = """
           CPU0       CPU1       CPU2       CPU3       CPU4       CPU5       CPU6       CPU7
  0:         37          0          0          0          0          0          0          0  IR-IO-APIC   2-edge      timer
  1:          3          2          1          0          3          3          0          3  IR-IO-APIC   1-edge      i8042
  8:          0          1          0          0          0          0          0          0  IR-IO-APIC   8-edge      rtc0
  9:      11107       2316       4040       1356       1324       1006        548        537  IR-IO-APIC   9-fasteoi   acpi
 12:         44         13          8         10          7         16        320         93  IR-IO-APIC  12-edge      i8042
 16:          4          2          2          8          0          6          7          0  IR-IO-APIC  16-fasteoi   ehci_hcd:usb1, mmc0
 18:          0          0          0          0          0          0          0          0  IR-IO-APIC  18-fasteoi   i801_smbus
 23:          6          6          4          4          0         10          3          0  IR-IO-APIC  23-fasteoi   ehci_hcd:usb2
 24:          0          0          0          0          0          0          0          0  DMAR-MSI   0-edge      dmar0
 25:          0          0          0          0          0          0          0          0  DMAR-MSI   1-edge      dmar1
 27:     242965     155333      52536      47894      35496      32961      27934      96634  IR-PCI-MSI 512000-edge      ahci[0000:00:1f.2]
 28:    2524672     433481     227987     212406     162014     175712     150609     151638  IR-PCI-MSI 327680-edge      xhci_hcd
 29:     974462     273360      84814     115282      66423      72322      48783      56791  IR-PCI-MSI 409600-edge      enp0s25
 30:        100         22         12         19         16          6         10          5  IR-PCI-MSI 524288-edge
 31:     321958      46760      42215      27668      34390      22665      29484      20514  IR-PCI-MSI 32768-edge      i915
 32:          7          1          2          7          0          3          0          6  IR-PCI-MSI 360448-edge      mei_me
 33:     193890      10271      22883       6823       3023       3918       2610       3798  IR-PCI-MSI 1572864-edge      iwlwifi
 34:        123         95         81         18         61          9         23         38  IR-PCI-MSI 442368-edge      snd_hda_intel:card2
 35:        460        102        375        269        123         48         38         23  IR-PCI-MSI 49152-edge      snd_hda_intel:card1
NMI:        210         92        179         96        177          0          0          0   Non-maskable interrupts
LOC:    7561411    2488524    6527767    2448192    6244091    2942086    6199519    2508884   Local timer interrupts
SPU:          0          0          0          0          0          0          0          0   Spurious interrupts
PMI:        210         92        179         96        177          0          0          0   Performance monitoring interrupts
IWI:          2          0          0          0          0          1          0          0   IRQ work interrupts
RTR:          0          0          0          0          0          0          0          0   APIC ICR read retries
RES:     181183     110341     106958      66026      92237      61031      72582      55959   Rescheduling interrupts
CAL:       2946       2842       2954       2995       2098       2835       2895       3016   Function call interrupts
TLB:     362051     255750     355120     266627     354757     264554     360694     266051   TLB shootdowns
TRM:          0          0          0          0          0          0          0          0   Thermal event interrupts
THR:          0          0          0          0          0          0          0          0   Threshold APIC interrupts
DFR:          0          0          0          0          0          0          0          0   Deferred Error APIC interrupts
MCE:          0          0          0          0          0          0          0          0   Machine check exceptions
MCP:        381        381        381        381        381        381        381        381   Machine check polls
ERR:          0
MIS:          0
PIN:          0          0          0          0          0          0          0          0   Posted-interrupt notification event
PIW:          0          0          0          0          0          0          0          0   Posted-interrupt wakeup event
""".strip()

INT_SINGLE = """
           CPU0
  0:         45   IO-APIC-edge      timer
  1:          3   IO-APIC-edge      i8042
  6:          3   IO-APIC-edge      floppy
  7:          0   IO-APIC-edge      parport0
  8:          1   IO-APIC-edge      rtc0
  9:          0   IO-APIC-fasteoi   acpi
HYP:          0   Hypervisor callback interrupts
ERR:          0
MIS:          0
""".strip()

INT_INVALID_1 = """
  0:         45   IO-APIC-edge      timer
  1:          3   IO-APIC-edge      i8042
  6:          3   IO-APIC-edge      floppy
""".strip()

INT_INVALID_2 = """

""".strip()

def test_interrupts():
    all_ints = Interrupts(context_wrap(INT_MULTI))
    assert len(all_ints.data) == 37
    assert all_ints.num_cpus == 8
    assert all_ints.get("i8042") == [all_ints.data[1], all_ints.data[4]]
    assert len(all_ints.get("IR-PCI-MSI")) == 9
    for one_int in all_ints:
        if one_int['irq'] == "NMI:":
            assert one_int['counts'] == ["210", "92", "179", "96", "177", "0", "0", "0"]
            assert one_int['type_device'] == "Non-maskable interrupts"
    all_ints = Interrupts(context_wrap(INT_SINGLE))
    assert len(all_ints.data) == 9
    for one_int in all_ints:
        assert len(one_int['counts']) == 1
    assert 'type_device' in all_ints.data[6]
    assert 'type_device' not in all_ints.data[7]
    assert 'type_device' not in all_ints.data[8]

    with pytest.raises(ParseException):
        Interrupts(context_wrap(INT_INVALID_1))

    with pytest.raises(ParseException):
        Interrupts(context_wrap(INT_INVALID_2))
<commit_msg>Interrupts tests at 100% code coverage<commit_after>import pytest
from falafel.mappers import ParseException
from falafel.mappers.interrupts import Interrupts
from falafel.tests import context_wrap

INT_MULTI = """
           CPU0       CPU1       CPU2       CPU3       CPU4       CPU5       CPU6       CPU7
  0:         37          0          0          0          0          0          0          0  IR-IO-APIC   2-edge      timer
  1:          3          2          1          0          3          3          0          3  IR-IO-APIC   1-edge      i8042
  8:          0          1          0          0          0          0          0          0  IR-IO-APIC   8-edge      rtc0
  9:      11107       2316       4040       1356       1324       1006        548        537  IR-IO-APIC   9-fasteoi   acpi
 12:         44         13          8         10          7         16        320         93  IR-IO-APIC  12-edge      i8042
 16:          4          2          2          8          0          6          7          0  IR-IO-APIC  16-fasteoi   ehci_hcd:usb1, mmc0
 18:          0          0          0          0          0          0          0          0  IR-IO-APIC  18-fasteoi   i801_smbus
 23:          6          6          4          4          0         10          3          0  IR-IO-APIC  23-fasteoi   ehci_hcd:usb2
 24:          0          0          0          0          0          0          0          0  DMAR-MSI   0-edge      dmar0
 25:          0          0          0          0          0          0          0          0  DMAR-MSI   1-edge      dmar1
 27:     242965     155333      52536      47894      35496      32961      27934      96634  IR-PCI-MSI 512000-edge      ahci[0000:00:1f.2]
 28:    2524672     433481     227987     212406     162014     175712     150609     151638  IR-PCI-MSI 327680-edge      xhci_hcd
 29:     974462     273360      84814     115282      66423      72322      48783      56791  IR-PCI-MSI 409600-edge      enp0s25
 30:        100         22         12         19         16          6         10          5  IR-PCI-MSI 524288-edge
 31:     321958      46760      42215      27668      34390      22665      29484      20514  IR-PCI-MSI 32768-edge      i915
 32:          7          1          2          7          0          3          0          6  IR-PCI-MSI 360448-edge      mei_me
 33:     193890      10271      22883       6823       3023       3918       2610       3798  IR-PCI-MSI 1572864-edge      iwlwifi
 34:        123         95         81         18         61          9         23         38  IR-PCI-MSI 442368-edge      snd_hda_intel:card2
 35:        460        102        375        269        123         48         38         23  IR-PCI-MSI 49152-edge      snd_hda_intel:card1
NMI:        210         92        179         96        177          0          0          0   Non-maskable interrupts
LOC:    7561411    2488524    6527767    2448192    6244091    2942086    6199519    2508884   Local timer interrupts
SPU:          0          0          0          0          0          0          0          0   Spurious interrupts
PMI:        210         92        179         96        177          0          0          0   Performance monitoring interrupts
IWI:          2          0          0          0          0          1          0          0   IRQ work interrupts
RTR:          0          0          0          0          0          0          0          0   APIC ICR read retries
RES:     181183     110341     106958      66026      92237      61031      72582      55959   Rescheduling interrupts
CAL:       2946       2842       2954       2995       2098       2835       2895       3016   Function call interrupts
TLB:     362051     255750     355120     266627     354757     264554     360694     266051   TLB shootdowns
TRM:          0          0          0          0          0          0          0          0   Thermal event interrupts
THR:          0          0          0          0          0          0          0          0   Threshold APIC interrupts
DFR:          0          0          0          0          0          0          0          0   Deferred Error APIC interrupts
MCE:          0          0          0          0          0          0          0          0   Machine check exceptions
MCP:        381        381        381        381        381        381        381        381   Machine check polls
ERR:          0
MIS:          0
PIN:          0          0          0          0          0          0          0          0   Posted-interrupt notification event
PIW:          0          0          0          0          0          0          0          0   Posted-interrupt wakeup event
""".strip()

INT_SINGLE = """
           CPU0
  0:         45   IO-APIC-edge      timer
  1:          3   IO-APIC-edge      i8042
  6:          3   IO-APIC-edge      floppy
  7:          0   IO-APIC-edge      parport0
  8:          1   IO-APIC-edge      rtc0
  9:          0   IO-APIC-fasteoi   acpi
HYP:          0   Hypervisor callback interrupts
ERR:          0
MIS:          0
""".strip()

INT_INVALID_1 = """
  0:         45   IO-APIC-edge      timer
  1:          3   IO-APIC-edge      i8042
  6:          3   IO-APIC-edge      floppy
""".strip()

INT_INVALID_2 = """

""".strip()

INT_NO_INTERRUPTS = """
           CPU0
"""

def test_interrupts():
    all_ints = Interrupts(context_wrap(INT_MULTI))
    assert len(all_ints.data) == 37
    assert all_ints.num_cpus == 8
    assert all_ints.get("i8042") == [all_ints.data[1], all_ints.data[4]]
    assert len(all_ints.get("IR-PCI-MSI")) == 9
    for one_int in all_ints:
        if one_int['irq'] == "NMI:":
            assert one_int['counts'] == ["210", "92", "179", "96", "177", "0", "0", "0"]
            assert one_int['type_device'] == "Non-maskable interrupts"
    all_ints = Interrupts(context_wrap(INT_SINGLE))
    assert len(all_ints.data) == 9
    for one_int in all_ints:
        assert len(one_int['counts']) == 1
    assert 'type_device' in all_ints.data[6]
    assert 'type_device' not in all_ints.data[7]
    assert 'type_device' not in all_ints.data[8]

    with pytest.raises(ParseException):
        Interrupts(context_wrap(INT_INVALID_1))

    with pytest.raises(ParseException):
        Interrupts(context_wrap(INT_INVALID_2))

    with pytest.raises(ParseException):
        Interrupts(context_wrap(INT_NO_INTERRUPTS))
<|endoftext|>


<commit_before>from setuptools import setup, find_packages
import sys, os

version = '1.1'

setup(name='PyroLibrary',
      version=version,
      description="Robot Framework Selenium2Library wrapper that integrates both Sauce and Sencha custom ui commands",
      long_description="""\
Robot Framework Selenium2Library wrapper that integrates both Sauce and Sencha custom ui commands""",
      classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      keywords='selenium python pybot factory sauce teamcity',
      author='Tallis Vanek',
      author_email='talliskane@gmail.com',
      url='https://github.com/Tallisado/pyrofactory',
      license='',
      packages=['pyro_library'],
      package_dir={'pyro_library': 'src/pyro_library'},
      install_requires=[
          "robotframework-selenium2library",
      ],
)<commit_msg>updates<commit_after>from distutils.core import setup

version = '1.1'

setup(name='pyrolibrary',
      version=version,
      description="Robot Framework Selenium2Library wrapper that integrates both Sauce and Sencha custom ui commands",
      long_description="""\
Robot Framework Selenium2Library wrapper that integrates both Sauce and Sencha custom ui commands""",
      classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      keywords='selenium python pybot factory sauce teamcity',
      author='Tallis Vanek',
      author_email='talliskane@gmail.com',
      url='https://github.com/Tallisado/pyrolibrary',
      license='',
      packages=['pyro_library'],
      package_dir={'pyro_library': 'src/pyro_library'},
      install_requires=[
          "robotframework-selenium2library",
      ],
)<|endoftext|>


<commit_before>
NAME = 'PyYAML'
VERSION = '3.08'
DESCRIPTION = "YAML parser and emitter for Python"
LONG_DESCRIPTION = """\
YAML is a data serialization format designed for human readability and
interaction with scripting languages.  PyYAML is a YAML parser and
emitter for Python.

PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
support, capable extension API, and sensible error messages.  PyYAML
supports standard YAML tags and provides Python-specific tags that allow
to represent an arbitrary Python object.

PyYAML is applicable for a broad range of tasks from complex
configuration files to object serialization and persistance."""
AUTHOR = "Kirill Simonov"
AUTHOR_EMAIL = 'xi@resolvent.net'
LICENSE = "MIT"
PLATFORMS = "Any"
URL = "http://pyyaml.org/wiki/PyYAML"
DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION)
CLASSIFIERS = [
    "Development Status :: 5 - Production/Stable",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.3",
    "Programming Language :: Python :: 2.4",
    "Programming Language :: Python :: 2.5",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.0",
    "Topic :: Software Development :: Libraries :: Python Modules",
    "Topic :: Text Processing :: Markup",
]

LIBYAML_CHECK = """
#include <yaml.h>

int main(void) {
    yaml_parser_t parser;
    yaml_emitter_t emitter;

    yaml_parser_initialize(&parser);
    yaml_parser_delete(&parser);

    yaml_emitter_initialize(&emitter);
    yaml_emitter_delete(&emitter);

    return 0;
}
"""

import sys, os.path

from distutils import log
from distutils.core import setup, Command
from distutils.core import Distribution as _Distribution
from distutils.core import Extension as _Extension
from distutils.dir_util import mkpath
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
from distutils.errors import CompileError, LinkError, DistutilsPlatformError

if 'setuptools.extension' in sys.modules:
    _Extension = sys.modules['setuptools.extension']._Extension
    sys.modules['distutils.core'].Extension = _Extension
    sys.modules['distutils.extension'].Extension = _Extension
    sys.modules['distutils.command.build_ext'].Extension = _Extension

with_pyrex = None
if sys.version_info[0] < 3:
    try:
        from Cython.Distutils.extension import Extension as _Extension
        from Cython.Distutils import build_ext as _build_ext
        with_pyrex = 'cython'
    except ImportError:
        try:
            # Pyrex cannot build _yaml.c at the moment,
            # but it may get fixed eventually.
            from Pyrex.Distutils import Extension as _Extension
            from Pyrex.Distutils import build_ext as _build_ext
            with_pyrex = 'pyrex'
        except ImportError:
            pass

class Distribution(_Distribution):

    def __init__(self, attrs=None):
        _Distribution.__init__(self, attrs)
        if not self.ext_modules:
            return
        for idx in range(len(self.ext_modules)-1, -1, -1):
            ext = self.ext_modules[idx]
            if not isinstance(ext, Extension):
                continue
            setattr(self, ext.attr_name, None)
            self.global_options = [
                    (ext.option_name, None,
                        "include %s (default if %s is available)"
                        % (ext.feature_description, ext.feature_name)),
                    (ext.neg_option_name, None,
                        "exclude %s" % ext.feature_description),
            ] + self.global_options
            self.negative_opt = self.negative_opt.copy()
            self.negative_opt[ext.neg_option_name] = ext.option_name

    def has_ext_modules(self):
        if not self.ext_modules:
            return False
        for ext in self.ext_modules:
            with_ext = self.ext_status(ext)
            if with_ext is None or with_ext:
                return True
        return False

    def ext_status(self, ext):
        if isinstance(ext, Extension):
            with_ext = getattr(self, ext.attr_name)
            return with_ext
        else:
            return True

class Extension(_Extension):

    def __init__(self, name, sources, feature_name, feature_description,
            feature_check, **kwds):
        if not with_pyrex:
            for filename in sources[:]:
                base, ext = os.path.splitext(filename)
                if ext == '.pyx':
                    sources.remove(filename)
                    sources.append('%s.c' % base)
        _Extension.__init__(self, name, sources, **kwds)
        self.feature_name = feature_name
        self.feature_description = feature_description
        self.feature_check = feature_check
        self.attr_name = 'with_' + feature_name.replace('-', '_')
        self.option_name = 'with-' + feature_name
        self.neg_option_name = 'without-' + feature_name

class build_ext(_build_ext):

    def run(self):
        optional = True
        disabled = True
        for ext in self.extensions:
            with_ext = self.distribution.ext_status(ext)
            if with_ext is None:
                disabled = False
            elif with_ext:
                optional = False
                disabled = False
                break
        if disabled:
            return
        try:
            _build_ext.run(self)
        except DistutilsPlatformError:
            exc = sys.exc_info()[1]
            if optional:
                log.warn(str(exc))
                log.warn("skipping build_ext")
            else:
                raise

    def get_source_files(self):
        self.check_extensions_list(self.extensions)
        filenames = []
        for ext in self.extensions:
            if with_pyrex == 'pyrex':
                self.pyrex_sources(ext.sources, ext)
            elif with_pyrex == 'cython':
                self.cython_sources(ext.sources, ext)
            for filename in ext.sources:
                filenames.append(filename)
                base = os.path.splitext(filename)[0]
                for ext in ['c', 'h', 'pyx', 'pxd']:
                    filename = '%s.%s' % (base, ext)
                    if filename not in filenames and os.path.isfile(filename):
                        filenames.append(filename)
        return filenames

    def get_outputs(self):
        self.check_extensions_list(self.extensions)
        outputs = []
        for ext in self.extensions:
            fullname = self.get_ext_fullname(ext.name)
            filename = os.path.join(self.build_lib,
                                    self.get_ext_filename(fullname))
            if os.path.isfile(filename):
                outputs.append(filename)
        return outputs

    def build_extensions(self):
        self.check_extensions_list(self.extensions)
        for ext in self.extensions:
            with_ext = self.distribution.ext_status(ext)
            if with_ext is None:
                with_ext = self.check_extension_availability(ext)
            if not with_ext:
                continue
            if with_pyrex == 'pyrex':
                ext.sources = self.pyrex_sources(ext.sources, ext)
            elif with_pyrex == 'cython':
                ext.sources = self.cython_sources(ext.sources, ext)
            self.build_extension(ext)

    def check_extension_availability(self, ext):
        cache = os.path.join(self.build_temp, 'check_%s.out' % ext.feature_name)
        if not self.force and os.path.isfile(cache):
            data = open(cache).read().strip()
            if data == '1':
                return True
            elif data == '0':
                return False
        mkpath(self.build_temp)
        src = os.path.join(self.build_temp, 'check_%s.c' % ext.feature_name)
        open(src, 'w').write(ext.feature_check)
        log.info("checking if %s is compilable" % ext.feature_name)
        try:
            [obj] = self.compiler.compile([src],
                    macros=ext.define_macros+[(undef,) for undef in ext.undef_macros],
                    include_dirs=ext.include_dirs,
                    extra_postargs=(ext.extra_compile_args or []),
                    depends=ext.depends)
        except CompileError:
            log.warn("")
            log.warn("%s is not found or a compiler error: forcing --%s"
                     % (ext.feature_name, ext.neg_option_name))
            log.warn("(if %s is installed correctly, you may need to"
                    % ext.feature_name)
            log.warn(" specify the option --include-dirs or uncomment and")
            log.warn(" modify the parameter include_dirs in setup.cfg)")
            open(cache, 'w').write('0\n')
            return False
        prog = 'check_%s' % ext.feature_name
        log.info("checking if %s is linkable" % ext.feature_name)
        try:
            self.compiler.link_executable([obj], prog,
                    output_dir=self.build_temp,
                    libraries=ext.libraries,
                    library_dirs=ext.library_dirs,
                    runtime_library_dirs=ext.runtime_library_dirs,
                    extra_postargs=(ext.extra_link_args or []))
        except LinkError:
            log.warn("")
            log.warn("%s is not found or a linker error: forcing --%s"
                     % (ext.feature_name, ext.neg_option_name))
            log.warn("(if %s is installed correctly, you may need to"
                    % ext.feature_name)
            log.warn(" specify the option --library-dirs or uncomment and")
            log.warn(" modify the parameter library_dirs in setup.cfg)")
            open(cache, 'w').write('0\n')
            return False
        open(cache, 'w').write('1\n')
        return True

class bdist_rpm(_bdist_rpm):

    def _make_spec_file(self):
        argv0 = sys.argv[0]
        features = []
        for ext in self.distribution.ext_modules:
            if not isinstance(ext, Extension):
                continue
            with_ext = getattr(self.distribution, ext.attr_name)
            if with_ext is None:
                continue
            if with_ext:
                features.append('--'+ext.option_name)
            else:
                features.append('--'+ext.neg_option_name)
        sys.argv[0] = ' '.join([argv0]+features)
        spec_file = _bdist_rpm._make_spec_file(self)
        sys.argv[0] = argv0
        return spec_file

class test(Command):

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        build_cmd = self.get_finalized_command('build')
        build_cmd.run()
        sys.path.insert(0, build_cmd.build_lib)
        if sys.version_info[0] < 3:
            sys.path.insert(0, 'tests/lib')
        else:
            sys.path.insert(0, 'tests/lib3')
        import test_all
        test_all.main([])

if __name__ == '__main__':

    package_dir = {
            '2': 'lib',
    }

    setup(
        name=NAME,
        version=VERSION,
        description=DESCRIPTION,
        long_description=LONG_DESCRIPTION,
        author=AUTHOR,
        author_email=AUTHOR_EMAIL,
        license=LICENSE,
        platforms=PLATFORMS,
        url=URL,
        download_url=DOWNLOAD_URL,
        classifiers=CLASSIFIERS,

        package_dir={'': {2: 'lib', 3: 'lib3'}[sys.version_info[0]]},
        packages=['yaml'],
        ext_modules=[
            Extension('_yaml', ['ext/_yaml.pyx'],
                'libyaml', "LibYAML bindings", LIBYAML_CHECK,
                libraries=['yaml']),
        ],

        distclass=Distribution,

        cmdclass={
            'build_ext': build_ext,
            'bdist_rpm': bdist_rpm,
            'test': test,
        },
    )

<commit_msg>Removed obsolete 'package_dir' line.<commit_after>
NAME = 'PyYAML'
VERSION = '3.08'
DESCRIPTION = "YAML parser and emitter for Python"
LONG_DESCRIPTION = """\
YAML is a data serialization format designed for human readability and
interaction with scripting languages.  PyYAML is a YAML parser and
emitter for Python.

PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
support, capable extension API, and sensible error messages.  PyYAML
supports standard YAML tags and provides Python-specific tags that allow
to represent an arbitrary Python object.

PyYAML is applicable for a broad range of tasks from complex
configuration files to object serialization and persistance."""
AUTHOR = "Kirill Simonov"
AUTHOR_EMAIL = 'xi@resolvent.net'
LICENSE = "MIT"
PLATFORMS = "Any"
URL = "http://pyyaml.org/wiki/PyYAML"
DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION)
CLASSIFIERS = [
    "Development Status :: 5 - Production/Stable",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.3",
    "Programming Language :: Python :: 2.4",
    "Programming Language :: Python :: 2.5",
    "Programming Language :: Python :: 2.6",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.0",
    "Topic :: Software Development :: Libraries :: Python Modules",
    "Topic :: Text Processing :: Markup",
]

LIBYAML_CHECK = """
#include <yaml.h>

int main(void) {
    yaml_parser_t parser;
    yaml_emitter_t emitter;

    yaml_parser_initialize(&parser);
    yaml_parser_delete(&parser);

    yaml_emitter_initialize(&emitter);
    yaml_emitter_delete(&emitter);

    return 0;
}
"""

import sys, os.path

from distutils import log
from distutils.core import setup, Command
from distutils.core import Distribution as _Distribution
from distutils.core import Extension as _Extension
from distutils.dir_util import mkpath
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
from distutils.errors import CompileError, LinkError, DistutilsPlatformError

if 'setuptools.extension' in sys.modules:
    _Extension = sys.modules['setuptools.extension']._Extension
    sys.modules['distutils.core'].Extension = _Extension
    sys.modules['distutils.extension'].Extension = _Extension
    sys.modules['distutils.command.build_ext'].Extension = _Extension

with_pyrex = None
if sys.version_info[0] < 3:
    try:
        from Cython.Distutils.extension import Extension as _Extension
        from Cython.Distutils import build_ext as _build_ext
        with_pyrex = 'cython'
    except ImportError:
        try:
            # Pyrex cannot build _yaml.c at the moment,
            # but it may get fixed eventually.
            from Pyrex.Distutils import Extension as _Extension
            from Pyrex.Distutils import build_ext as _build_ext
            with_pyrex = 'pyrex'
        except ImportError:
            pass

class Distribution(_Distribution):

    def __init__(self, attrs=None):
        _Distribution.__init__(self, attrs)
        if not self.ext_modules:
            return
        for idx in range(len(self.ext_modules)-1, -1, -1):
            ext = self.ext_modules[idx]
            if not isinstance(ext, Extension):
                continue
            setattr(self, ext.attr_name, None)
            self.global_options = [
                    (ext.option_name, None,
                        "include %s (default if %s is available)"
                        % (ext.feature_description, ext.feature_name)),
                    (ext.neg_option_name, None,
                        "exclude %s" % ext.feature_description),
            ] + self.global_options
            self.negative_opt = self.negative_opt.copy()
            self.negative_opt[ext.neg_option_name] = ext.option_name

    def has_ext_modules(self):
        if not self.ext_modules:
            return False
        for ext in self.ext_modules:
            with_ext = self.ext_status(ext)
            if with_ext is None or with_ext:
                return True
        return False

    def ext_status(self, ext):
        if isinstance(ext, Extension):
            with_ext = getattr(self, ext.attr_name)
            return with_ext
        else:
            return True

class Extension(_Extension):

    def __init__(self, name, sources, feature_name, feature_description,
            feature_check, **kwds):
        if not with_pyrex:
            for filename in sources[:]:
                base, ext = os.path.splitext(filename)
                if ext == '.pyx':
                    sources.remove(filename)
                    sources.append('%s.c' % base)
        _Extension.__init__(self, name, sources, **kwds)
        self.feature_name = feature_name
        self.feature_description = feature_description
        self.feature_check = feature_check
        self.attr_name = 'with_' + feature_name.replace('-', '_')
        self.option_name = 'with-' + feature_name
        self.neg_option_name = 'without-' + feature_name

class build_ext(_build_ext):

    def run(self):
        optional = True
        disabled = True
        for ext in self.extensions:
            with_ext = self.distribution.ext_status(ext)
            if with_ext is None:
                disabled = False
            elif with_ext:
                optional = False
                disabled = False
                break
        if disabled:
            return
        try:
            _build_ext.run(self)
        except DistutilsPlatformError:
            exc = sys.exc_info()[1]
            if optional:
                log.warn(str(exc))
                log.warn("skipping build_ext")
            else:
                raise

    def get_source_files(self):
        self.check_extensions_list(self.extensions)
        filenames = []
        for ext in self.extensions:
            if with_pyrex == 'pyrex':
                self.pyrex_sources(ext.sources, ext)
            elif with_pyrex == 'cython':
                self.cython_sources(ext.sources, ext)
            for filename in ext.sources:
                filenames.append(filename)
                base = os.path.splitext(filename)[0]
                for ext in ['c', 'h', 'pyx', 'pxd']:
                    filename = '%s.%s' % (base, ext)
                    if filename not in filenames and os.path.isfile(filename):
                        filenames.append(filename)
        return filenames

    def get_outputs(self):
        self.check_extensions_list(self.extensions)
        outputs = []
        for ext in self.extensions:
            fullname = self.get_ext_fullname(ext.name)
            filename = os.path.join(self.build_lib,
                                    self.get_ext_filename(fullname))
            if os.path.isfile(filename):
                outputs.append(filename)
        return outputs

    def build_extensions(self):
        self.check_extensions_list(self.extensions)
        for ext in self.extensions:
            with_ext = self.distribution.ext_status(ext)
            if with_ext is None:
                with_ext = self.check_extension_availability(ext)
            if not with_ext:
                continue
            if with_pyrex == 'pyrex':
                ext.sources = self.pyrex_sources(ext.sources, ext)
            elif with_pyrex == 'cython':
                ext.sources = self.cython_sources(ext.sources, ext)
            self.build_extension(ext)

    def check_extension_availability(self, ext):
        cache = os.path.join(self.build_temp, 'check_%s.out' % ext.feature_name)
        if not self.force and os.path.isfile(cache):
            data = open(cache).read().strip()
            if data == '1':
                return True
            elif data == '0':
                return False
        mkpath(self.build_temp)
        src = os.path.join(self.build_temp, 'check_%s.c' % ext.feature_name)
        open(src, 'w').write(ext.feature_check)
        log.info("checking if %s is compilable" % ext.feature_name)
        try:
            [obj] = self.compiler.compile([src],
                    macros=ext.define_macros+[(undef,) for undef in ext.undef_macros],
                    include_dirs=ext.include_dirs,
                    extra_postargs=(ext.extra_compile_args or []),
                    depends=ext.depends)
        except CompileError:
            log.warn("")
            log.warn("%s is not found or a compiler error: forcing --%s"
                     % (ext.feature_name, ext.neg_option_name))
            log.warn("(if %s is installed correctly, you may need to"
                    % ext.feature_name)
            log.warn(" specify the option --include-dirs or uncomment and")
            log.warn(" modify the parameter include_dirs in setup.cfg)")
            open(cache, 'w').write('0\n')
            return False
        prog = 'check_%s' % ext.feature_name
        log.info("checking if %s is linkable" % ext.feature_name)
        try:
            self.compiler.link_executable([obj], prog,
                    output_dir=self.build_temp,
                    libraries=ext.libraries,
                    library_dirs=ext.library_dirs,
                    runtime_library_dirs=ext.runtime_library_dirs,
                    extra_postargs=(ext.extra_link_args or []))
        except LinkError:
            log.warn("")
            log.warn("%s is not found or a linker error: forcing --%s"
                     % (ext.feature_name, ext.neg_option_name))
            log.warn("(if %s is installed correctly, you may need to"
                    % ext.feature_name)
            log.warn(" specify the option --library-dirs or uncomment and")
            log.warn(" modify the parameter library_dirs in setup.cfg)")
            open(cache, 'w').write('0\n')
            return False
        open(cache, 'w').write('1\n')
        return True

class bdist_rpm(_bdist_rpm):

    def _make_spec_file(self):
        argv0 = sys.argv[0]
        features = []
        for ext in self.distribution.ext_modules:
            if not isinstance(ext, Extension):
                continue
            with_ext = getattr(self.distribution, ext.attr_name)
            if with_ext is None:
                continue
            if with_ext:
                features.append('--'+ext.option_name)
            else:
                features.append('--'+ext.neg_option_name)
        sys.argv[0] = ' '.join([argv0]+features)
        spec_file = _bdist_rpm._make_spec_file(self)
        sys.argv[0] = argv0
        return spec_file

class test(Command):

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        build_cmd = self.get_finalized_command('build')
        build_cmd.run()
        sys.path.insert(0, build_cmd.build_lib)
        if sys.version_info[0] < 3:
            sys.path.insert(0, 'tests/lib')
        else:
            sys.path.insert(0, 'tests/lib3')
        import test_all
        test_all.main([])

if __name__ == '__main__':

    setup(
        name=NAME,
        version=VERSION,
        description=DESCRIPTION,
        long_description=LONG_DESCRIPTION,
        author=AUTHOR,
        author_email=AUTHOR_EMAIL,
        license=LICENSE,
        platforms=PLATFORMS,
        url=URL,
        download_url=DOWNLOAD_URL,
        classifiers=CLASSIFIERS,

        package_dir={'': {2: 'lib', 3: 'lib3'}[sys.version_info[0]]},
        packages=['yaml'],
        ext_modules=[
            Extension('_yaml', ['ext/_yaml.pyx'],
                'libyaml', "LibYAML bindings", LIBYAML_CHECK,
                libraries=['yaml']),
        ],

        distclass=Distribution,

        cmdclass={
            'build_ext': build_ext,
            'bdist_rpm': bdist_rpm,
            'test': test,
        },
    )

<|endoftext|>