#!/usr/bin/env python

from setuptools import setup

# Version info -- read without importing
_locals = {}
with open('releases/_version.py') as fp:
    exec(fp.read(), None, _locals)
version = _locals['__version__']

setup(
    name='releases',
    version=version,
    description='A Sphinx extension for changelog manipulation',
    long_description=open("README.rst").read(),
    author='Jeff Forcier',
    author_email='jeff@bitprophet.org',
    url='https://github.com/bitprophet/releases',
    packages=['releases'],
    install_requires=[
        'semantic_version<2.7',
        'sphinx>=1.3,<1.8',
    ],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Unix',
        'Operating System :: POSIX',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Software Development',
        'Topic :: Software Development :: Documentation',
        'Topic :: Documentation',
        'Topic :: Documentation :: Sphinx',
    ],
)

#!/usr/bin/env python

from setuptools import setup

# Version info -- read without importing
_locals = {}
with open('releases/_version.py') as fp:
    exec(fp.read(), None, _locals)
version = _locals['__version__']

setup(
    name='releases',
    version=version,
    description='A Sphinx extension for changelog manipulation',
    long_description=open("README.rst").read(),
    author='Jeff Forcier',
    author_email='jeff@bitprophet.org',
    url='https://github.com/bitprophet/releases',
    packages=['releases'],
    install_requires=[
        'semantic_version<2.7',
        'sphinx>=1.3',
    ],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Unix',
        'Operating System :: POSIX',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Software Development',
        'Topic :: Software Development :: Documentation',
        'Topic :: Documentation',
        'Topic :: Documentation :: Sphinx',
    ],
)

Remove upper limit for Sphinx version

Remove upper limit for Sphinx version


# -*- coding: utf-8 -*-
"""Setup for the DeepOBS package"""

import setuptools

def readme():
    with open('README.md') as f:
        return f.read()

setuptools.setup(
    name='deepobs',
    version='1.1.1',
    description='Deep Learning Optimizer Benchmark Suite',
    long_description=readme(),
    author='Frank Schneider, Lukas Balles and Philipp Hennig,',
    author_email='frank.schneider@tue.mpg.de',
    license='MIT',
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3.6",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
    ],
    install_requires=[
        'argparse', 'numpy', 'pandas', 'matplotlib', 'matplotlib2tikz',
        'seaborn'
    ],
    scripts=[
        'deepobs/scripts/deepobs_prepare_data.sh',
        'deepobs/scripts/deepobs_get_baselines.sh',
        'deepobs/scripts/deepobs_plot_results.py',
        'deepobs/scripts/deepobs_estimate_runtime.py'
    ],
    zip_safe=False)

# -*- coding: utf-8 -*-
"""Setup for the DeepOBS package"""

import setuptools

def readme():
    with open("README.md") as f:
        return f.read()

setuptools.setup(
    name="deepobs",
    version="1.1.2",
    description="Deep Learning Optimizer Benchmark Suite",
    long_description=readme(),
    author="Frank Schneider, Lukas Balles and Philipp Hennig,",
    author_email="frank.schneider@tue.mpg.de",
    license="MIT",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3.6",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
    ],
    install_requires=[
        "argparse",
        "numpy",
        "pandas",
        "matplotlib",
        "matplotlib2tikz==0.6.18",
        "seaborn",
    ],
    scripts=[
        "deepobs/scripts/deepobs_prepare_data.sh",
        "deepobs/scripts/deepobs_get_baselines.sh",
        "deepobs/scripts/deepobs_plot_results.py",
        "deepobs/scripts/deepobs_estimate_runtime.py",
    ],
    zip_safe=False,
)

Install specific version of matplotlib2tikz


#! /usr/bin/env python
'''
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, Inc

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''

from distutils.core import setup

__version__ = ''
execfile('targetcli/version.py')

setup(
    name = 'targetcli-fb',
    version = __version__,
    description = 'An administration shell for RTS storage targets.',
    license = 'Apache 2.0',
    maintainer = 'Andy Grover',
    maintainer_email = 'agrover@redhat.com',
    url = 'http://github.com/agrover/targetcli-fb',
    packages = ['targetcli'],
    scripts = ['scripts/targetcli'],
    )

#! /usr/bin/env python
'''
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, Inc

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''

from distutils.core import setup

__version__ = ''
exec(open('targetcli/version.py').read())

setup(
    name = 'targetcli-fb',
    version = __version__,
    description = 'An administration shell for RTS storage targets.',
    license = 'Apache 2.0',
    maintainer = 'Andy Grover',
    maintainer_email = 'agrover@redhat.com',
    url = 'http://github.com/agrover/targetcli-fb',
    packages = ['targetcli'],
    scripts = ['scripts/targetcli'],
    )

Replace execfile() with exec() since it does not work with Python 3

Signed-off-by: Christophe Vu-Brugier <1930e27f67e1e10d51770b88cb06d386f1aa46ae@yahoo.fr>


from distutils.core import setup

setup(
    name='resync',
    version='0.6.1',
    packages=['resync'],
    classifiers=["Development Status :: 3 - Alpha",
                 "Programming Language :: Python",
                 "Topic :: Software Development :: Libraries :: Python Modules",
                 "Environment :: Web Environment"],
    author='Simeon Warner',
    author_email='simeon.warner@cornell.edu',
    long_description=open('README.md').read(),
    url='http://github.com/resync/resync',
)

from distutils.core import setup

setup(
    name='resync',
    version='0.6.1',
    packages=['resync'],
    scripts=['bin/resync'],
    classifiers=["Development Status :: 3 - Alpha",
                 "Programming Language :: Python",
                 "Topic :: Software Development :: Libraries :: Python Modules",
                 "Environment :: Web Environment"],
    author='Simeon Warner',
    author_email='simeon.warner@cornell.edu',
    long_description=open('README.md').read(),
    url='http://github.com/resync/resync',
)

Add config to install resync script

Add config to install resync script


#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from pkg_resources import resource_filename

# depending on your execution context the version file
# may be located in a different place!
vsn_path = resource_filename(__name__, 'hvac/version')
if not os.path.exists(vsn_path):
    vsn_path = resource_filename(__name__, 'version')
    if not os.path.exists(vsn_path):
        print("%s is missing" % vsn_path)
        sys.exit(1)

setup(
    name='hvac',
    version=open(vsn_path, 'r').read(),
    description='HashiCorp Vault API client',
    author='Ian Unruh',
    author_email='ianunruh@gmail.com',
    url='https://github.com/ianunruh/hvac',
    keywords=['hashicorp', 'vault'],
    classifiers=['License :: OSI Approved :: Apache Software License'],
    packages=find_packages(),
    install_requires=[
        'requests>=2.7.0',
    ],
    include_package_data=True,
    package_data={'hvac': ['version']},
    extras_require={
        'parser': ['pyhcl>=0.2.1,<0.3.0']
    }
)

#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from pkg_resources import resource_filename

with open("README.md", "r") as fh:
    long_description = fh.read()

# depending on your execution context the version file
# may be located in a different place!
vsn_path = resource_filename(__name__, 'hvac/version')
if not os.path.exists(vsn_path):
    vsn_path = resource_filename(__name__, 'version')
    if not os.path.exists(vsn_path):
        print("%s is missing" % vsn_path)
        sys.exit(1)

setup(
    name='hvac',
    version=open(vsn_path, 'r').read(),
    description='HashiCorp Vault API client',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author='Ian Unruh',
    author_email='ianunruh@gmail.com',
    url='https://github.com/ianunruh/hvac',
    keywords=['hashicorp', 'vault'],
    classifiers=['License :: OSI Approved :: Apache Software License'],
    packages=find_packages(),
    install_requires=[
        'requests>=2.7.0',
    ],
    include_package_data=True,
    package_data={'hvac': ['version']},
    extras_require={
        'parser': ['pyhcl>=0.2.1,<0.3.0']
    }
)

Include README.md in package metadata

Include README.md in package metadata


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

from setuptools import setup

import inflection

setup(
    name='inflection',
    version=inflection.__version__,
    description="A port of Ruby on Rails inflector to Python",
    long_description=open('README.rst').read(),
    author='Janne Vanhala',
    author_email='janne.vanhala@gmail.com',
    url='http://github.com/jpvanhal/inflection',
    license='MIT',
    py_modules=['inflection'],
    zip_safe=False,
    python_requires='>=3.5',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
)

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

from setuptools import setup

import inflection

setup(
    name='inflection',
    version=inflection.__version__,
    description="A port of Ruby on Rails inflector to Python",
    long_description=open('README.rst').read(),
    author='Janne Vanhala',
    author_email='janne.vanhala@gmail.com',
    url='https://github.com/jpvanhal/inflection',
    license='MIT',
    py_modules=['inflection'],
    zip_safe=False,
    python_requires='>=3.5',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
)

Use HTTPS for the project url

Use HTTPS for the project url


#!/usr/bin/env python
# coding=utf-8
__author__ = 'kulakov.ilya@gmail.com'

from setuptools import setup
from sys import platform

REQUIREMENTS = []

if platform.startswith('darwin'):
    REQUIREMENTS.append('pyobjc >= 2.5')

setup(
    name="Power",
    version="1.1",
    description="Cross-platform system power status information.",
    author="Ilya Kulakov",
    author_email="kulakov.ilya@gmail.com",
    url="https://github.com/Kentzo/Power",
    platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"],
    packages=['power'],
    classifiers=[
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX :: Linux',
        'Topic :: System :: Power (UPS)',
        'Topic :: System :: Hardware',
        'Topic :: System :: Monitoring'
    ],
    install_requires=REQUIREMENTS
)

#!/usr/bin/env python
# coding=utf-8
__author__ = 'kulakov.ilya@gmail.com'

from setuptools import setup
from sys import platform

REQUIREMENTS = []

# Not avaialable at PyPi yet
# if platform.startswith('darwin'):
    # REQUIREMENTS.append('pyobjc >= 2.5')

setup(
    name="Power",
    version="1.1",
    description="Cross-platform system power status information.",
    author="Ilya Kulakov",
    author_email="kulakov.ilya@gmail.com",
    url="https://github.com/Kentzo/Power",
    platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"],
    packages=['power'],
    classifiers=[
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX :: Linux',
        'Topic :: System :: Power (UPS)',
        'Topic :: System :: Hardware',
        'Topic :: System :: Monitoring'
    ],
    install_requires=REQUIREMENTS
)

Remove PyObjC requirement since it's not avialable at PyPi yet.


#!/usr/bin/env python

from distutils.core import setup

version = "0.12"

"""Setup script for pexif"""

setup (
    name = "pexif",
    version = version,
    description = "A module for editing JPEG EXIF data",
    long_description = "This module allows you to parse and edit the EXIF data tags in a JPEG image.",
    author = "Ben Leslie",
    author_email = "benno@benno.id.au",
    url = "http://www.benno.id.au/code/pexif/",
    download_url = "http://www.benno.id.au/code/pexif/pexif-%s.tar.gz" % version,
    license = "http://www.opensource.org/licenses/mit-license.php",
    py_modules = ["pexif"],
    scripts = ["scripts/dump_exif.py", "scripts/setgps.py", "scripts/getgps.py", "scripts/noop.py",
               "scripts/timezone.py"],
    platforms = ["any"],
    classifiers = ["Development Status :: 4 - Beta",
                   "Intended Audience :: Developers",
                   "Operating System :: OS Independent",
                   "Programming Language :: Python",
                   "License :: OSI Approved :: Python Software Foundation License",
                   "Topic :: Multimedia :: Graphics"]
    )

#!/usr/bin/env python

from distutils.core import setup

version = "0.13"

"""Setup script for pexif"""

setup (
    name = "pexif",
    version = version,
    description = "A module for editing JPEG EXIF data",
    long_description = "This module allows you to parse and edit the EXIF data tags in a JPEG image.",
    author = "Ben Leslie",
    author_email = "benno@benno.id.au",
    url = "http://www.benno.id.au/code/pexif/",
    download_url = "http://www.benno.id.au/code/pexif/pexif-%s.tar.gz" % version,
    license = "http://www.opensource.org/licenses/mit-license.php",
    py_modules = ["pexif"],
    scripts = ["scripts/dump_exif.py", "scripts/setgps.py", "scripts/getgps.py", "scripts/noop.py",
               "scripts/timezone.py"],
    platforms = ["any"],
    classifiers = ["Development Status :: 4 - Beta",
                   "Intended Audience :: Developers",
                   "Operating System :: OS Independent",
                   "Programming Language :: Python",
                   "License :: OSI Approved :: Python Software Foundation License",
                   "Topic :: Multimedia :: Graphics"]
    )

Bump version number to 0.13

Bump version number to 0.13

git-svn-id: 2223166f32dfc0252f77f60c9446e3f27730b4ad@17 8ba0a3ab-1543-0410-831c-f9a674249a0d


from setuptools import setup
from os import path

readme = open(path.join(path.abspath(path.dirname(__file__)), 'README.md')).read()

setup(
    name='bottle-websocket',
    version='0.2',
    author='Zach Kelling',
    author_email='zeekayy@gmail.com',
    packages=['bottle_websocket',],
    description='WebSockets for bottle',
    long_description=readme,
    install_requires=['bottle', 'gevent-websocket'],
)

from setuptools import setup

setup(
    name='bottle-websocket',
    version='0.2.5',
    author='Zach Kelling',
    author_email='zeekayy@gmail.com',
    packages=['bottle_websocket',],
    package_data={'': ['README.md']},
    description='WebSockets for bottle',
    long_description=open('README.md'),
    install_requires=['bottle', 'gevent-websocket'],
)

Use package_data, and bump version.

Use package_data, and bump version.


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

setup(
    name='synapse',
    version='0.1.0',
    description='Synapse Distributed Key-Value Hypergraph Analysis Framework',
    author='Invisigoth Kenshoto',
    author_email='invisigoth.kenshoto@gmail.com',
    url='https://github.com/vertexproject/synapse',
    license='Apache License 2.0',

    packages=find_packages(exclude=['scripts',
                                    ]),

    include_package_data=True,

    install_requires=[
        'tornado>=3.2.2,<5.0.0',
        'pyOpenSSL>=16.2.0,<18.0.0',
        'msgpack==0.5.1',
        'xxhash>=1.0.1,<2.0.0',
        'lmdb>=0.94,<1.0.0',
        'regex>=2017.9.23',
        'PyYAML>=3.12,<4.0',
    ],

    classifiers=[
        'Development Status :: 4 - Beta',

        'License :: OSI Approved :: Apache Software License',

        'Topic :: System :: Clustering',
        'Topic :: System :: Distributed Computing',
        'Topic :: System :: Software Distribution',

        'Programming Language :: Python :: 3.6',
    ],
)

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

setup(
    name='synapse',
    version='0.1.0-alpha',
    description='Synapse Distributed Key-Value Hypergraph Analysis Framework',
    author='Invisigoth Kenshoto',
    author_email='invisigoth.kenshoto@gmail.com',
    url='https://github.com/vertexproject/synapse',
    license='Apache License 2.0',

    packages=find_packages(exclude=['scripts',
                                    ]),

    include_package_data=True,

    install_requires=[
        'tornado>=3.2.2,<5.0.0',
        'pyOpenSSL>=16.2.0,<18.0.0',
        'msgpack==0.5.1',
        'xxhash>=1.0.1,<2.0.0',
        'lmdb>=0.94,<1.0.0',
        'regex>=2017.9.23',
        'PyYAML>=3.12,<4.0',
    ],

    classifiers=[
        'Development Status :: 4 - Beta',

        'License :: OSI Approved :: Apache Software License',

        'Topic :: System :: Clustering',
        'Topic :: System :: Distributed Computing',
        'Topic :: System :: Software Distribution',

        'Programming Language :: Python :: 3.6',
    ],
)

Add -alpha prerelease version to version.


#!/usr/bin/env python

import os
import sys

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

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist bdist_wininst upload -r pypi')
    sys.exit()

with open('README.rst') as f:
    readme = f.read()
with open('LICENSE') as f:
    license = f.read()

setup(
    name='django-rest-surveys',
    version='0.1.0',
    description='A RESTful backend for giving surveys.',
    long_description=readme,
    author='Designlab',
    author_email='hello@trydesignlab.com',
    url='https://github.com/danxshap/django-rest-surveys',
    packages=['rest_surveys'],
    package_data={'': ['LICENSE']},
    package_dir={'rest_surveys': 'rest_surveys'},
    install_requires=['Django', 'django-inline-ordering'],
    license=license,
)

#!/usr/bin/env python

import os
import sys

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

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist bdist_wininst upload -r pypi')
    sys.exit()

with open('README.rst') as f:
    readme = f.read()
with open('LICENSE') as f:
    license = f.read()

setup(
    name='django-rest-surveys',
    version='0.1.0',
    description='A RESTful backend for giving surveys.',
    long_description=readme,
    author='Designlab',
    author_email='hello@trydesignlab.com',
    url='https://github.com/danxshap/django-rest-surveys',
    packages=['rest_surveys'],
    package_data={'': ['LICENSE']},
    package_dir={'rest_surveys': 'rest_surveys'},
    install_requires=['Django>=1.7', 'djangorestframework>=3.0', 'django-inline-ordering'],
    license=license,
)

Set the required versions of required packages


#!/usr/bin/env python

from setuptools import setup, find_packages

# Get version string
with open('gdx2py/version.py') as f: exec(f.read())

setup(name='GDX2py',
      version=__version__,  # pylint: disable=undefined-variable
      author='Erkka Rinne',
      author_email='erkka.rinne@vtt.fi',
      description='Read and write GAMS Data eXchange (GDX) files using Python',
      python_requires='>=3.6',
      install_requires=[
        'gdxcc>=7',
      ],
      setup_requires=['pytest-runner'],
      tests_require=['pytest', 'pytest-datadir'],
      url='https://github.com/ererkka/GDX2py',
      packages=find_packages(exclude=['tests']),
)

#!/usr/bin/env python

from setuptools import setup, find_packages

# Get version string
with open('gdx2py/version.py') as f: exec(f.read())

setup(name='GDX2py',
      version=__version__,  # pylint: disable=undefined-variable
      author='Erkka Rinne',
      author_email='erkka.rinne@vtt.fi',
      description='Read and write GAMS Data eXchange (GDX) files using Python',
      python_requires='>=3.6',
      install_requires=[
        'gdxcc>=7',
      ],
      setup_requires=['pytest-runner'],
      tests_require=['pytest', 'pytest-datadir'],
      url='https://github.com/ererkka/GDX2py',
      packages=find_packages(exclude=['tests']),
      classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Topic :: Scientific/Engineering",
        "Intended Audience :: Developers",
        "Development Status :: 4 - Beta"
    ],
)

Add classifiers to package info

Add classifiers to package info


"""Config for PyPI."""

from setuptools import find_packages
from setuptools import setup

setup(
    author='Kyle P. Johnson',
    author_email='kyle@kyle-p-johnson.com',
    classifiers=[
        'Intended Audience :: Education',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Chinese (Traditional)',
        'Natural Language :: English',
        'Natural Language :: Greek',
        'Natural Language :: Latin',
        'Operating System :: POSIX',
        'Programming Language :: Python :: 3.7',
        'Topic :: Scientific/Engineering :: Artificial Intelligence',
        'Topic :: Text Processing',
        'Topic :: Text Processing :: General',
        'Topic :: Text Processing :: Linguistic',
    ],
    description='NLP for the ancient world',
    install_requires=['gitpython',
                      'nltk',
                      'python-crfsuite',
                      'pyuca',
                      'pyyaml',
                      'regex',
                      'whoosh'],
    keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan', 'arabic', "germanic"],
    license='MIT',
    long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.',  # pylint: disable=C0301,
    name='cltk',
    packages=find_packages(),
    url='https://github.com/cltk/cltk',
    version='0.1.117',
    zip_safe=True,
    test_suite='cltk.tests.test_cltk',
)

"""Config for PyPI."""

from setuptools import find_packages
from setuptools import setup

setup(
    author='Kyle P. Johnson',
    author_email='kyle@kyle-p-johnson.com',
    classifiers=[
        'Intended Audience :: Education',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Chinese (Traditional)',
        'Natural Language :: English',
        'Natural Language :: Greek',
        'Natural Language :: Latin',
        'Operating System :: POSIX',
        'Programming Language :: Python :: 3.7',
        'Topic :: Scientific/Engineering :: Artificial Intelligence',
        'Topic :: Text Processing',
        'Topic :: Text Processing :: General',
        'Topic :: Text Processing :: Linguistic',
    ],
    description='NLP for the ancient world',
    install_requires=['gitpython',
                      'nltk',
                      'python-crfsuite',
                      'pyuca',
                      'pyyaml',
                      'regex',
                      'whoosh'],
    keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan', 'arabic', "germanic"],
    license='MIT',
    long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.',  # pylint: disable=C0301,
    name='cltk',
    packages=find_packages(),
    url='https://github.com/cltk/cltk',
    version='0.1.118',
    zip_safe=True,
    test_suite='cltk.tests.test_cltk',
)

Bump vers for Ensemble lemmatizer

Bump vers for Ensemble lemmatizer

From Patrick Burns @diyclassics https://github.com/cltk/cltk/pull/981


from os.path import isdir, isfile, join
from distutils import log

from setuptools import setup, find_packages

INSTALL_REQUIRES = [
    'BTrees',
    'zope.component',
    'zodbpickle',
    'ZODB',
    'zope.index',
    'zerodbext.catalog',
    'cachetools',
    'zc.zlibstorage',
    'pycryptodome',
    'flask-cors',
    'flask',
    'requests',
    'jsonpickle',
    'pyelliptic',
    'ecdsa',
    'zope.event',
    'zope.lifecycleevent',
    'ZEO',
    'six'
]

# This is to avoid build errors on brand new Amazon Ubuntu instances
# which may not have libffi-dev installed.
#
# If we have neither cffi nor ffi.h we fall back to pycryptodome.
# Note that the warning is only visible if pip is run with -v.

def have_cffi():
    try:
        import cffi
    except ImportError:
        return False
    else:
        return True

def have_ffi_h():
    include_dirs = ["/usr/include", "/usr/local/include"]
    for dir in include_dirs:
        if isdir(dir):
            if isfile(join(dir, "ffi.h")) or isfile(join(dir, "ffi", "ffi.h")):
                return True
    return False

if have_cffi() or have_ffi_h():
    INSTALL_REQUIRES.append("aes256gcm-nacl")
else:
    log.warn("warning: *** ffi.h not found - aes256gcm-nacl optimization disabled ***")
    INSTALL_REQUIRES.append("pycryptodome")

setup(
    name="zerodb",
    version="0.97.2.1",
    description="End-to-end encrypted database",
    author="ZeroDB Inc.",
    author_email="michael@zerodb.io",
    license="AGPLv3",
    url="http://zerodb.io",
    packages=find_packages(),
    install_requires=INSTALL_REQUIRES,
)

from setuptools import setup, find_packages

INSTALL_REQUIRES = [
    'BTrees',
    'zope.component',
    'zodbpickle',
    'ZODB',
    'zope.index',
    'zerodbext.catalog',
    'cachetools',
    'zc.zlibstorage',
    'pycryptodome',
    'flask-cors',
    'flask',
    'requests',
    'jsonpickle',
    'pyelliptic',
    'ecdsa',
    'zope.event',
    'zope.lifecycleevent',
    'aes256gcm-nacl',
    'ZEO',
    'six'
]

setup(
    name="zerodb",
    version="0.97.2.1",
    description="End-to-end encrypted database",
    author="ZeroDB Inc.",
    author_email="michael@zerodb.io",
    license="AGPLv3",
    url="http://zerodb.io",
    packages=find_packages(),
    install_requires=INSTALL_REQUIRES,
)

Revert "Fall back to pycryptodome if aes256gcm-nacl cannot be built."

This reverts commit f457b06dd1dd9d3b1d3577b5a8415868ff0cb3d8.


import os
import re
import sys
import platform
import subprocess
import multiprocessing

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion

cores = multiprocessing.cpu_count()*1.25

threads="-j" + str(int(cores))

class CMakeExtension(Extension):
    def __init__(self, name, sourcedir=''):
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)

def readme():
  with open("PYTHONREADME.md", "r") as fh:
    return fh.read()

def operatingsystem():
  if (platform.platform().find("Darwin") >= 0):
    return "Operating System :: MacOS"
  else:
    return "Operating System :: POSIX :: Linux"

setup(
    name='sharkbite',
    version='1.2.0.0',
    author='Marc Parisi',
    author_email='phrocker@apache.org',
    url='https://docs.sharkbite.io/',
    description='Apache Accumulo and Apache HDFS Python Connector',
    long_description=readme(),
    long_description_content_type='text/markdown',
    ext_modules=[CMakeExtension('sharkbite.pysharkbite')],
    zip_safe=False,
    classifiers=[
        "Programming Language :: C++",
        "License :: OSI Approved :: Apache Software License",
        operatingsystem(),
    ],
    python_requires='>=3.6',
    packages=['sharkbite']
)

import os
import re
import sys
import platform
import subprocess
import multiprocessing

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion

cores = multiprocessing.cpu_count()*1.25

threads="-j" + str(int(cores))

class CMakeExtension(Extension):
    def __init__(self, name, sourcedir=''):
        Extension.__init__(self, name, sources=[])
        self.sourcedir = os.path.abspath(sourcedir)

def readme():
  with open("PYTHONREADME.md", "r") as fh:
    return fh.read()

def operatingsystem():
  if (platform.platform().find("Darwin") >= 0):
    return "Operating System :: MacOS"
  else:
    return "Operating System :: POSIX :: Linux"

setup(
    name='sharkbite',
    version='1.2.0.1',
    author='Marc Parisi',
    author_email='phrocker@apache.org',
    url='https://docs.sharkbite.io/',
    description='Apache Accumulo and Apache HDFS Python Connector',
    long_description=readme(),
    long_description_content_type='text/markdown',
    ext_modules=[CMakeExtension('sharkbite.pysharkbite')],
    zip_safe=False,
    classifiers=[
        "Programming Language :: C++",
        "License :: OSI Approved :: Apache Software License",
        operatingsystem(),
    ],
    python_requires='>=3.6',
    packages=['sharkbite']
)

Update error in 3.7 release

Update error in 3.7 release


# Copyright (C) 2016-present the ayncpg authors and contributors
# <see AUTHORS file>
#
# This module is part of asyncpg and is released under
# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0

import setuptools
import sys

if sys.version_info < (3, 5):
    raise RuntimeError('asyncpg requires Python 3.5 or greater')

setuptools.setup(
    name='asyncpg',
    version='0.5.1',
    description='An asyncio PosgtreSQL driver',
    classifiers=[
        'License :: OSI Approved :: Apache Software License',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Operating System :: POSIX',
        'Operating System :: MacOS :: MacOS X',
        'Development Status :: 4 - Beta',
    ],
    platforms=['POSIX'],
    author='MagicStack Inc',
    author_email='hello@magic.io',
    license='Apache License, Version 2.0',
    packages=['asyncpg'],
    provides=['asyncpg'],
    include_package_data=True,
    ext_modules=[
        setuptools.Extension(
            "asyncpg.protocol.protocol",
            ["asyncpg/protocol/record/recordobj.c",
             "asyncpg/protocol/protocol.c"],
            extra_compile_args=['-O2'])
    ]
)

# Copyright (C) 2016-present the ayncpg authors and contributors
# <see AUTHORS file>
#
# This module is part of asyncpg and is released under
# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0

import setuptools
import sys

if sys.version_info < (3, 5):
    raise RuntimeError('asyncpg requires Python 3.5 or greater')

setuptools.setup(
    name='asyncpg',
    version='0.5.2',
    description='An asyncio PosgtreSQL driver',
    classifiers=[
        'License :: OSI Approved :: Apache Software License',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Operating System :: POSIX',
        'Operating System :: MacOS :: MacOS X',
        'Development Status :: 4 - Beta',
    ],
    platforms=['POSIX'],
    author='MagicStack Inc',
    author_email='hello@magic.io',
    license='Apache License, Version 2.0',
    packages=['asyncpg'],
    provides=['asyncpg'],
    include_package_data=True,
    ext_modules=[
        setuptools.Extension(
            "asyncpg.protocol.protocol",
            ["asyncpg/protocol/record/recordobj.c",
             "asyncpg/protocol/protocol.c"],
            extra_compile_args=['-O2'])
    ]
)

Bump the version to v0.5.2

Bump the version to v0.5.2


import subprocess
import sys
from distutils.core import setup, Command

class TestCommand(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        errno = subprocess.call([sys.executable, 'test_facebook.py'])
        raise SystemExit(errno)

setup(
    name='facebook-ads-api',
    version='0.1.42',
    author='Chee-Hyung Yoon',
    author_email='yoonchee@gmail.com',
    py_modules=['facebook', ],
    url='http://github.com/narrowcast/facebook-ads-api',
    license='LICENSE',
    description='Python client for the Facebook Ads API',
    long_description=open('README.md').read(),
    cmdclass={'test': TestCommand},
)

import subprocess
import sys
from distutils.core import setup, Command

class TestCommand(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        errno = subprocess.call([sys.executable, 'test_facebook.py'])
        raise SystemExit(errno)

setup(
    name='facebook-ads-api',
    version='0.1.43',
    author='Chee-Hyung Yoon',
    author_email='yoonchee@gmail.com',
    py_modules=['facebook', ],
    url='http://github.com/narrowcast/facebook-ads-api',
    license='LICENSE',
    description='Python client for the Facebook Ads API',
    long_description=open('README.md').read(),
    cmdclass={'test': TestCommand},
)

Bump up version after merging a pull request.


import numpy as np
from tempfile import NamedTemporaryFile
from microscopium import io as mio

def test_imsave_tif_compress():
    im = np.random.randint(0, 256, size=(1024, 1024, 3)).astype(np.uint8)
    with NamedTemporaryFile(suffix='.tif') as fout:
        fname = fout.name
        fout.close()
        mio.imsave(im, fname, compress=2)
        imin = mio.imread(fname)
        np.testing.assert_array_equal(im, imin)

import os
import numpy as np
from tempfile import NamedTemporaryFile
from microscopium import io as mio
from microscopium import pathutils as pth

def test_recursive_glob():
    abspath = os.path.dirname(__file__)
    tiffs0 = pth.all_matching_files(abspath, '*.tif')
    assert len(tiffs0) == 8
    assert tiffs0[0].startswith('/')
    tiffs1 = pth.all_matching_files(abspath, '*.TIF')
    assert len(tiffs1) == 0
    tiffs2 = pth.all_matching_files(abspath, '*.TIF', case_sensitive=False,
                                    full=False)
    assert len(tiffs2) == 8
    assert tiffs2[0].startswith('MYORES')

def test_imsave_tif_compress():
    im = np.random.randint(0, 256, size=(1024, 1024, 3)).astype(np.uint8)
    with NamedTemporaryFile(suffix='.tif') as fout:
        fname = fout.name
        fout.close()
        mio.imsave(im, fname, compress=2)
        imin = mio.imread(fname)
        np.testing.assert_array_equal(im, imin)

Improve test coverage by testing recursive glob


#!/usr/bin/env python3

import os
import time
import json
import requests
import pyperclip

API_KEY = os.environ.get('API_KEY')
# API_KEY = ""

def google_url_shorten(url):
    req_url = "https://www.googleapis.com/urlshortener/v1/url?" + API_KEY
    payload = {'longUrl': url}
    headers = {'content-type': 'application/json'}
    r = requests.post(req_url, data=json.dumps(payload), headers=headers)
    resp = json.loads(r.text)
    return resp["id"]

recent_value = ""
while True:
    tmp_value = pyperclip.paste()
    if (tmp_value != recent_value and not tmp_value.startswith("https://goo.gl") and not tmp_value.startswith("https://git")):
        recent_value = tmp_value
        url = str(recent_value)
        if url.startswith("http://") or url.startswith("https://") or url.startswith("www."):
            pyperclip.copy(google_url_shorten(url))
    time.sleep(0.5)

#!/usr/bin/env python3

import os
import time
import json
import requests
import pyperclip

API_KEY = os.environ.get('API_KEY')
# API_KEY = ""

def google_url_shorten(url):
    req_url = "https://www.googleapis.com/urlshortener/v1/url?" + str(API_KEY)
    payload = {'longUrl': url}
    headers = {'content-type': 'application/json'}
    r = requests.post(req_url, data=json.dumps(payload), headers=headers)
    resp = json.loads(r.text)
    return resp["id"]

recent_value = ""
while True:
    tmp_value = pyperclip.paste()
    if (tmp_value != recent_value and not tmp_value.startswith("https://goo.gl") and not tmp_value.startswith("https://git")):
        recent_value = tmp_value
        url = str(recent_value)
        if url.startswith("http://") or url.startswith("https://") or url.startswith("www."):
            pyperclip.copy(google_url_shorten(url))
    time.sleep(0.5)

Convert environment variable to string

Convert environment variable to string


from projects_controller import ProjectsController
from redirects_controller import RedirectsController
from flask import Flask, render_template, redirect, abort

DATA_DIR = 'data'

app = Flask(__name__)
app.url_map.strict_slashes = False

projects_controller = ProjectsController(DATA_DIR)
redirects_controller = RedirectsController(DATA_DIR)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.route('/')
def index():
    projects = projects_controller.get_current_projects()
    return render_template('index.html', projects=projects)

@app.route('/start')
def start_project():
    return render_template('start_project.html')

@app.route('/<dynamic>')
def project(dynamic):

    # First, test if if it's a project
    projects = projects_controller.get_all_projects()
    redirects = redirects_controller.get_redirects()

    if dynamic in projects:
        project_data = projects[dynamic]
        if 'conclusion_post' in project_data:
            # The project is over, we should redirect to the post
            return redirect(project_data['conclusion_post'])
        else:
          return render_template('project.html', project_data=project_data)

    # Next, check if it's a redirect
    elif dynamic in redirects:
        return redirect(redirects[dynamic])

    else:
        abort(404)

if __name__ == '__main__':
    app.run(debug=True)

from projects_controller import ProjectsController
from redirects_controller import RedirectsController
from flask import Flask, render_template, redirect, abort

DATA_DIR = 'data'

app = Flask(__name__)
app.url_map.strict_slashes = False

projects_controller = ProjectsController(DATA_DIR)
redirects_controller = RedirectsController(DATA_DIR)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.route('/')
def index():
    projects = projects_controller.get_current_projects()
    return render_template('index.html', projects=projects)

@app.route('/start')
def start_project():
    return render_template('start_project.html')

@app.route('/<dynamic>')
def project(dynamic):

    projects = projects_controller.get_all_projects()
    redirects = redirects_controller.get_redirects()

    # First, test if if it's a project
    if dynamic in projects:
        project_data = projects[dynamic]
        if 'conclusion_post' in project_data:
            # The project is over, we should redirect to the post
            return redirect(project_data['conclusion_post'])
        else:
          return render_template('project.html', project_data=project_data)

    # Next, check if it's a redirect
    elif dynamic in redirects:
        return redirect(redirects[dynamic])

    else:
        abort(404)

if __name__ == '__main__':
    app.run(debug=True)

Move comment to rational location

Move comment to rational location


from ..geoparse import Geoparser
import pytest

import spacy
nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger'])

@pytest.fixture(scope='session', autouse=True)
def geo():
    return Geoparser(nlp=nlp, threads=False, models_path = "/Users/ahalterman/MIT/Geolocation/mordecai_new/mordecai/mordecai/models/")

@pytest.fixture(scope='session', autouse=True)
def geo_thread():
    return Geoparser(nlp=nlp, threads=True, models_path = "/Users/ahalterman/MIT/Geolocation/mordecai_new/mordecai/mordecai/models/")

from ..geoparse import Geoparser
import pytest

import spacy
nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger'])

@pytest.fixture(scope='session', autouse=True)
def geo():
    return Geoparser(nlp=nlp, threads=False)

@pytest.fixture(scope='session', autouse=True)
def geo_thread():
    return Geoparser(nlp=nlp, threads=True)

Remove hardcoded paths from testing

Remove hardcoded paths from testing


# -*- coding: utf-8 -*-

import unittest
import sys
sys.path.insert(0, '../mafia')

from game import Game
from game import Player

from testclient.testmessenger import TestMessenger

class SmokeTest(unittest.TestCase):
    def setUp(self):
        self.messenger = TestMessenger()

    def test_smoke_test(self):
        game = Game('t,c,c,m', self.messenger)
        player_one = Player('one', 'one')
        player_two = Player('two', 'two')
        player_three = Player('three', 'three')
        player_four = Player('four', 'four')
        game.join(player_one)
        game.join(player_two)
        game.join(player_three)
        game.join(player_four)
        game.vote('one', 'three')
        game.vote('three', 'one')
        game.vote('two', 'three')
        game.vote('four', 'three')
        game.target('one', 'two')
        game.target('two', 'one')
        game.target('four', 'one')

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

# -*- coding: utf-8 -*-

import unittest
import sys
sys.path.insert(0, '../')

from mafia.game import Game
from mafia.game import Player

from testclient.testmessenger import TestMessenger

class SmokeTest(unittest.TestCase):
    def setUp(self):
        self.messenger = TestMessenger()

    def test_smoke_test(self):
        game = Game('t,c,c,m', self.messenger)
        player_one = Player('one', 'one')
        player_two = Player('two', 'two')
        player_three = Player('three', 'three')
        player_four = Player('four', 'four')
        game.join(player_one)
        game.join(player_two)
        game.join(player_three)
        game.join(player_four)
        game.vote('one', 'three')
        game.vote('three', 'one')
        game.vote('two', 'three')
        game.vote('four', 'three')
        game.target('one', 'two')
        game.target('two', 'one')
        game.target('four', 'one')

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

Change the smoke test imports to a relative import for consistency.


from hello_world import hello_world

from unittest import TestCase

class BasicTest(TestCase):
    def test_basic_hello_world(self):
        """
        Test basic hello world messaging
        """
        False

from hello_world import hello_world

from unittest import TestCase

class BasicTest(TestCase):
    def test_basic_hello_world(self):
        """
        Test basic hello world messaging
        """
        self.assertTrue(callable(hello_world))

Make things a little better

Make things a little better


import sys

def get_stdin():
    buf = ""
    for line in sys.stdin:
        buf = buf + line
    return buf

if(__name__ == "__main__"):
    st = get_stdin()
    print(st)

import sys

def get_stdin():
    buf = ""
    for line in sys.stdin:
        buf = buf + line
    return buf

if __name__ == "__main__":
    st = get_stdin()
    print(st)

Remove braces for Python sample

Remove braces for Python sample

Suggested by community member in an un-merged PR.

Signed-off-by: Alex Ellis (VMware) <5f7133baa0f5c7ca63ff11e11f2e2b0d2cf077c8@gmail.com>


import glob
import csv
import numpy as np
import matplotlib.pyplot as plt

for file in glob.glob("*.csv"):
    data = np.genfromtxt(file, delimiter = ',', names = True)

    plt.figure(figsize=(10,20))
    plt.suptitle(file)

    num_plots = len(data.dtype.names)
    count = 1
    for col_name in data.dtype.names:
        plt.subplot(num_plots, 1, count)
        plt.plot(data[col_name], label=col_name)
        plt.legend()
        count += 1

        ymin, ymax = plt.ylim()
        if ymin < 0 < ymax:
            plt.axhline(0, hold=True, color = 'grey') # plot line through zero

    mng = plt.get_current_fig_manager()
    if plt.get_backend() == 'TkAgg':
        mng.window.state('zoomed')
    elif plt.get_backend() == 'wxAgg':
        mng.frame.Maximize(True)
    elif plt.get_backend() == 'QT4Agg':
        mng.window.showMaximized()

    plt.savefig(file.rstrip('.csv') + '.pdf')
    plt.show()

import glob
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("test-results-plots.pdf")

for file in glob.glob("*.csv"):
    data = np.genfromtxt(file, delimiter = ',', names = True)

    plt.figure(figsize=(10,20))
    plt.suptitle(file)

    num_plots = len(data.dtype.names)
    count = 1
    for col_name in data.dtype.names:
        plt.subplot(num_plots, 1, count)
        plt.plot(data[col_name], label=col_name)
        plt.legend()
        count += 1

        ymin, ymax = plt.ylim()
        if ymin < 0 < ymax:
            plt.axhline(0, hold=True, color = 'grey') # plot line through zero

    pdf.savefig()

    mng = plt.get_current_fig_manager()
    if plt.get_backend() == 'TkAgg':
        mng.window.state('zoomed')
    elif plt.get_backend() == 'wxAgg':
        mng.frame.Maximize(True)
    elif plt.get_backend() == 'QT4Agg':
        mng.window.showMaximized()

    plt.show()
    plt.close()

pdf.close()

Save all simulation plots to one PDF instead of multiple


import sys
import pathlib

import hug

from overtime_calculator import auth, api

@hug.get("/", output=hug.output_format.html)
def base():
    return "
Hello, world
"

@hug.extend_api()
def with_other_apis():
    return [
        auth,
        api
    ]

if __name__ == '__main__':
    _file = pathlib.Path(sys.argv[0])
    module = _file.parent.name
    print(
        f"Start {module} with Hug, like so: hug --file {_file}",
        file=sys.stderr,
    )
    sys.exit(1)

Improve UX for those who use CLI

Enhancement: Improve UX for those who use CLI


# FIXME: pyuv_cffi needs to build the library BEFORE the standard library is patched
import pyuv_cffi

print('pyuv_cffi imported', pyuv_cffi)
import guv

guv.monkey_patch()
import guv.server
import logging
import time

from util import create_example
import logger

if not hasattr(time, 'perf_counter'):
    time.perf_counter = time.clock

logger.configure()
log = logging.getLogger()

response_times = []

def get_avg_time():
    global response_times
    times = response_times[-1000:]
    avg = sum(times) / len(times)

    if len(response_times) > 5000:
        response_times = times

    return avg

def handle(sock, addr):
    # client connected
    start_time = time.perf_counter()
    sock.sendall(create_example())
    sock.close()

    total_time = time.perf_counter() - start_time
    response_times.append(total_time)

if __name__ == '__main__':
    pool = guv.GreenPool()

    try:
        log.debug('Start')
        server_sock = guv.listen(('0.0.0.0', 8001))
        server = guv.server.Server(server_sock, handle, pool, 'spawn_n')
        server.start()
    except (SystemExit, KeyboardInterrupt):
        log.debug('average response time: {}'.format(get_avg_time()))
        log.debug('Bye!')

import guv

guv.monkey_patch()
import guv.server
import logging
import time

from util import create_example
import logger
from pympler import tracker

tr = tracker.SummaryTracker()

if not hasattr(time, 'perf_counter'):
    time.perf_counter = time.clock

logger.configure()
log = logging.getLogger()

response_times = []

def get_avg_time():
    global response_times
    times = response_times[-1000:]
    avg = sum(times) / len(times)

    if len(response_times) > 5000:
        response_times = times

    return avg

def handle(sock, addr):
    # client connected
    start_time = time.perf_counter()
    sock.sendall(create_example())
    sock.close()

    total_time = time.perf_counter() - start_time
    response_times.append(total_time)

if __name__ == '__main__':
    pool = guv.GreenPool()

    try:
        log.debug('Start')
        server_sock = guv.listen(('0.0.0.0', 8001))
        server = guv.server.Server(server_sock, handle, pool, 'spawn_n')
        server.start()
    except (SystemExit, KeyboardInterrupt):
        tr.print_diff()
        log.debug('Bye!')

Use pympler to look for memory leaks

Use pympler to look for memory leaks


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

""" Integration tests for Dataproc samples.

Creates a Dataproc cluster, uploads a pyspark file to Google Cloud Storage,
submits a job to Dataproc that runs the pyspark file, then downloads
the output logs from Cloud Storage and verifies the expected output."""

import create_cluster_and_submit_job
from gcp.testing.flaky import flaky

CLUSTER_NAME = 'testcluster2'
ZONE = 'us-central1-b'

@flaky
def test_e2e(cloud_config):
    output = create_cluster_and_submit_job.main(
        cloud_config.project, ZONE, CLUSTER_NAME, cloud_config.storage_bucket)
    assert "['Hello,', 'dog', 'elephant', 'panther', 'world!']" in output

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

""" Integration tests for Dataproc samples.

Creates a Dataproc cluster, uploads a pyspark file to Google Cloud Storage,
submits a job to Dataproc that runs the pyspark file, then downloads
the output logs from Cloud Storage and verifies the expected output."""

import create_cluster_and_submit_job
from gcp.testing.flaky import flaky

CLUSTER_NAME = 'testcluster2'
ZONE = 'us-central1-b'

@flaky
def test_e2e(cloud_config):
    output = create_cluster_and_submit_job.main(
        cloud_config.project, ZONE, CLUSTER_NAME, cloud_config.storage_bucket)
    assert b"['Hello,', 'dog', 'elephant', 'panther', 'world!']" in output

Fix Dataproc e2e for Python 3

Fix Dataproc e2e for Python 3


# Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.

"""
Tweepy.asynchronoous

Asynchronous interfaces with the Twitter API
"""

try:
    import aiohttp
except ModuleNotFoundError:
    from tweepy.errors import TweepyException
    raise TweepyException("tweepy.asynchronous requires aiohttp to be installed")

from tweepy.asynchronous.streaming import AsyncStream

# Tweepy
# Copyright 2009-2021 Joshua Roesslein
# See LICENSE for details.

"""
Tweepy.asynchronoous

Asynchronous interfaces with the Twitter API
"""

try:
    import aiohttp
    import oauthlib
except ModuleNotFoundError:
    from tweepy.errors import TweepyException
    raise TweepyException(
        "tweepy.asynchronous requires aiohttp and oauthlib to be installed"
    )

from tweepy.asynchronous.streaming import AsyncStream

Check oauthlib installation when importing asynchronous subpackage


#!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest

import mock

from nose.tools import assert_equal, assert_is_instance

from pandas_finance import get_stock

class PandasFinanceTestCase(unittest.TestCase):
    @mock.patch('pandas_finance.web.DataReader')
    def test_get_stock_called_correctly(self, mock_datareader):
        mock_datareader()
        start = datetime.datetime(1999, 4, 3, 0, 0)
        end = datetime.datetime(2005, 2, 5, 0, 0)
        get_stock('AAPL', start, end)
        mock_datareader.assert_called_with('AAPL', 'yahoo', start, end)

#!/usr/bin/env python
# encoding: utf-8
import datetime
import unittest

import mock

from nose.tools import assert_equal, assert_is_instance
from pandas_finance import get_stock, get_required_tickers

class PandasFinanceTestCase(unittest.TestCase):
    @mock.patch('pandas_finance.web.DataReader')
    def test_get_stock_called_correctly(self, mock_datareader):
        mock_datareader()
        start = datetime.datetime(1999, 4, 3, 0, 0)
        end = datetime.datetime(2005, 2, 5, 0, 0)
        get_stock('AAPL', start, end)
        mock_datareader.assert_called_with('AAPL', 'yahoo', start, end)

    def test_get_required_tickers_parses_tickers_with_newline(self):
        m = mock.mock_open(read_data='TWTR,FB,AAPL,MSFT\n')
        textfile = None  # only used to provide valid argument
        with mock.patch('pandas_finance.open', m, create=True):
            result = get_required_tickers(textfile)
        assert_equal('TWTR,FB,AAPL,MSFT', result)

Add test for parsing tickers.

Add test for parsing tickers.


# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os

from perf_insights import map_single_trace
from perf_insights import function_handle
from perf_insights.mre import file_handle
from perf_insights.mre import job as job_module

_METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html'

_METRIC_MAP_FUNCTION_NAME = 'metricMapFunction'

def _GetMetricsDir():
  return os.path.dirname(os.path.abspath(__file__))

def _GetMetricRunnerHandle(metric):
  assert isinstance(metric, basestring)
  metrics_dir = _GetMetricsDir()
  metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME)

  modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)]
  map_function_handle = function_handle.FunctionHandle(
      modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric})

  return job_module.Job(map_function_handle, None)

def RunMetric(filename, metric, extra_import_options=None):
  th = file_handle.URLFileHandle(filename, 'file://' + filename)
  result = map_single_trace.MapSingleTrace(
      th, _GetMetricRunnerHandle(metric), extra_import_options)

  return result

# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os

from perf_insights import map_single_trace
from perf_insights import function_handle
from perf_insights.mre import file_handle
from perf_insights.mre import job as job_module

_METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html'

_METRIC_MAP_FUNCTION_NAME = 'metricMapFunction'

def _GetMetricsDir():
  return os.path.dirname(os.path.abspath(__file__))

def _GetMetricRunnerHandle(metric):
  assert isinstance(metric, basestring)
  metrics_dir = _GetMetricsDir()
  metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME)

  modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)]
  map_function_handle = function_handle.FunctionHandle(
      modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric})

  return job_module.Job(map_function_handle, None)

def RunMetric(filename, metric, extra_import_options=None):
  url = 'file://' + os.path.abspath(filename)
  th = file_handle.URLFileHandle(filename, url)
  result = map_single_trace.MapSingleTrace(
      th, _GetMetricRunnerHandle(metric), extra_import_options)

  return result

Support relative paths in bin/run_metric

As a result of this patch, it will be possible to run:

  bin/run_metric MemoryMetric test_data/memory_dumps.json
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^

instead of:

  bin/run_metric MemoryMetric $PWD/test_data/memory_dumps.json
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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


from enum import IntEnum
from discord import Embed

class OpStatus(IntEnum):
	SUCCESS = 0x2ECC71,
	FAILURE = 0xc0392B,
	WARNING = 0xf39C12,
	NONE = None

def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed:
	name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name
	embed = Embed(
		title=title,
		description=desc,
		color=status.value if status is not None else OpStatus.WARNING
	)
	embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url)
	return embed

from enum import IntEnum
from discord import Embed

class OpStatus(IntEnum):
	SUCCESS = 0x2ECC71,
	FAILURE = 0xc0392B,
	WARNING = 0xf39C12,
	NONE = -1

def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed:
	name = ctx.message.server.me.nick if ctx.message.server.me.nick is not None else ctx.bot.user.name
	embed = Embed(
		title=title,
		description=desc,
		color=status.value if status is not None and status is not -1 else None if status is -1 else OpStatus.WARNING
	)
	embed.set_author(name=name, icon_url=ctx.bot.user.avatar_url)
	return embed

Fix issue with enum not accepting null

Fix issue with enum not accepting null


# Author: Braedy Kuzma
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^posts/$', views.PostsView.as_view(), name='posts'),
    url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
        name='post'),
    url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
        views.CommentView.as_view(), name='comments'),
    url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
        name='author'),
    url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
        views.AuthorFriendsView.as_view(), name='friends')
]

# Author: Braedy Kuzma
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^posts/$', views.PostsView.as_view(), name='posts'),
    url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(),
        name='post'),
    url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$',
        views.CommentView.as_view(), name='comments'),
    url(r'^author/posts/$', views.PostView.as_view(), name='authorpost'),
    url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/$', views.AuthorView.as_view(),
        name='author'),
    url(r'^author/(?P<aid>[0-9a-fA-F\-]+)/friends/$',
        views.AuthorFriendsView.as_view(), name='friends')
]

Add extra endpoint for posts?

Add extra endpoint for posts?


from __future__ import unicode_literals

from imaginary.world import ImaginaryWorld
from imaginary.objects import Thing, Container, Exit
from imaginary.garments import createShirt, createPants
from imaginary.iimaginary import IClothing, IClothingWearer

from examplegame.squeaky import Squeaker

def world(store):
    def room(name):
        it = Thing(store=store, name=name)
        Container.createFor(it, capacity=1000)
        return it
    world = ImaginaryWorld(store=store,
                           origin=room("The Beginning"))
    protagonist = world.create("An Example Player")
    shirt = createShirt(store=store, name="shirt", location=world.origin)
    pants = createPants(store=store, name="pants", location=world.origin)
    middle = room("The Middle")
    wearer = IClothingWearer(protagonist)
    wearer.putOn(IClothing(shirt))
    wearer.putOn(IClothing(pants))
    Exit.link(world.origin, middle, "north")

    squeakerThing = Thing(name="squeaker", location=middle, store=store)
    Squeaker.createFor(squeakerThing)
    return world

from __future__ import unicode_literals

from imaginary.world import ImaginaryWorld
from imaginary.objects import Thing, Container, Exit
from imaginary.garments import createShirt, createPants
from imaginary.iimaginary import IClothing, IClothingWearer

from examplegame.squeaky import Squeaker

def world(store):
    def room(name):
        it = Thing(
            store=store,
            name=name,
            proper=True,
        )
        Container.createFor(it, capacity=1000)
        return it
    world = ImaginaryWorld(store=store,
                           origin=room("The Beginning"))
    protagonist = world.create("An Example Player")
    shirt = createShirt(store=store, name="shirt", location=world.origin)
    pants = createPants(store=store, name="pants", location=world.origin)
    middle = room("The Middle")
    wearer = IClothingWearer(protagonist)
    wearer.putOn(IClothing(shirt))
    wearer.putOn(IClothing(pants))
    Exit.link(world.origin, middle, "north")

    squeakerThing = Thing(name="squeaker", location=middle, store=store)
    Squeaker.createFor(squeakerThing)
    return world

Make rooms in the example game (grammatically) "proper" (nouns)


#!/usr/bin/env python2
#
# USAGE: geturl.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#

import sys
import svn._wc
import svn.util

def main(pool, files):
  for f in files:
    entry = svn._wc.svn_wc_entry(f, 0, pool)
    print svn._wc.svn_wc_entry_t_url_get(entry)

if __name__ == '__main__':
  svn.util.run_app(main, sys.argv[1:])

#!/usr/bin/env python2
#
# USAGE: geturl.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#

import os
import sys

import svn.wc
import svn.util

def main(pool, files):
  for f in files:
    dirpath = fullpath = os.path.abspath(f)
    if not os.path.isdir(dirpath):
      dirpath = os.path.dirname(dirpath)
    adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, 1, 1, pool)
    try:
      entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
      print svn.wc.svn_wc_entry_t_url_get(entry)
    except:
      svn.wc.svn_wc_adm_close(adm_baton)

if __name__ == '__main__':
  svn.util.run_app(main, sys.argv[1:])

Update the example to use the new access baton stuff.

git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@844036 13f79535-47bb-0310-9956-ffa450edef68


# coding: utf-8

from interface import *

class SpeechParameters(object):

    """
    Speech parameters
    """

    def __init__(self, f0, spectrum_envelope, aperiodicity):
        self.f0 = f0
        self.spectrum_envelope = spectrum_envelope
        self.aperiodicity = aperiodicity

class VoiceConverter(object):

    """
    Voice conversion

    This class assumes:
      - *_parameterizer implements `Parameterizer`
      - *_converter implements `Converter`
      - analyzer implements `Analyzer`
      - synthesizer implments `Synthesizer`

    analyzer and synthesizer must be specified explicitly.

    *_parameterizer and *_converter can be None.

    TODO:
    parameterizerは、デフォでTrasparentParameterizer
    （つまり特徴量をそのままパスするだけのparamterizer）にする？
    """

    def __init__(self,
                 f0_parameterizer=None,
                 f0_converter=None,
                 spectrum_envelope_parameterizer=None,
                 spectrum_envelope_converter=None,
                 aperiodicity_parameterizer=None,
                 aperiodicity_converter=None,
                 analyzer=None,
                 synthesizer=None
                 ):
        self.f0_converter = f0_converter
        self.f0_parameterizer = f0_parameterizer
        self.spectrum_envelope_converter = spectrum_envelope_converter
        self.spectrum_envelope_parameterizer = spectrum_envelope_parameterizer
        self.aperiodicity_converter = aperiodicity_converter
        self.aperiodicity_parameterizer = aperiodicity_parameterizer

        if analyzer == None or synthesizer == None:
            raise "backend must be specified explicitly!"

        self.analyzer = analyzer
        self.synthesizer = synthesizer

        # speech paramters will be stored.
        self.params = None

    def analyze(self, x):
        """
        Decompose speech into parametric representation
        """
        self.params = self.analyzer.analyze(x)

    def convert(self):
        """
        Perform speech parameter conversion
        """
        if self.params == None:
            raise "`analyze` must be called before `convert`"

        if self.f0_converter != None:
            self.params.f0 = self.f0_parameterizer.backward(
                self.f0_converter.convert(
                    self.f0_parameterizer.forward(self.params.f0)
                )
            )

        if self.spectrum_envelope_converter != None:
            self.params.spectrum_envelop = \
                self.spectrum_envelope_parameterizer.backward(
                    self.spectrum_envelope_converter.convert(
                        self.spectrum_envelope_parameterizer.forward(
                            self.params.spectrum_envelope
                        )
                    )
                )

        if self.aperiodicity_converter != None:
            self.params.aperiodicity = self.aperiodicity_parameterizer.backward(
                self.aperiodicity_converter.convert(
                    self.aperiodicity_parameterizer.forward(
                        self.params.aperiodicity)
                )
            )

    def synthesis(self):
        """
        Synthesize speech waveform
        """
        if self.params == None:
            raise "`analyze` must be called before `synthesis`"

        return self.synthesizer.synthesis(self.params)

Add class `VoiceConverter` that peforms all required processes in statistical voice conversion: speech analysis, feature parameterization, feature conversion and waveform syntheis


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

import pbr.version

version_info = pbr.version.VersionInfo('muranoagent')

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

import pbr.version

version_info = pbr.version.VersionInfo('murano-agent')

Fix murano agent component name

Fix murano agent component name

Change-Id: I8f76630d3f007f89585b3418ff661c48004a2b5f
Closes-bug: #1373347


""" XXX: fish """

__all__ = ['display', 'color', 'surface', 'Color', 'time', 'event',
           'constants', 'sprite', 'Rect', 'Surface', 'QUIT', 'init',
           'mouse', 'locals', 'image']

from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from pygame.constants import QUIT
from pygame import display, color, surface, time, event, constants, sprite,\
     mouse, locals, images
# XXX
from pygame.display import init

""" XXX: fish """

__all__ = ['display', 'color', 'surface', 'Color', 'time', 'event',
           'constants', 'sprite', 'Rect', 'Surface', 'QUIT', 'init',
           'mouse', 'locals', 'image']

from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from pygame.constants import QUIT
from pygame import display, color, surface, time, event, constants, sprite,\
     mouse, locals, image
# XXX
from pygame.display import init

Fix error introduced in rebase

Fix error introduced in rebase


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

from subprocess import Popen,PIPE
import shlex
import logging

class ExecProc:

    def __init__(self):
        self.command = None
        self.debug = False

    def setDebug(self,debug):
        self.debug = debug

    def setCommand(self,command):
        if type(command) != str:
            raise ValueError
        self.command = command

    def execute(self):
        if self.command == None:
            raise ValueError
        args = shlex.split(self.command)
        if self.debug == True:
            logging.info("command=\"%s\"",self.command)
        p = Popen(args,stdout=PIPE)
        o,e = p.communicate()
        if self.debug == True:
            logging.info("output=\"%s\"",o)
        return o

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

from subprocess import Popen,PIPE
import shlex
import logging

class ExecProc:

    def __init__(self):
        self.command = None
        self.debug = False

    def setDebug(self,debug):
        self.debug = debug

    def setCommand(self,command):
        if type(command) != str:
            raise ValueError
        self.command = command

    def execute(self):
        if self.command == None:
            raise ValueError
        # Remove Carriage Returns
        command = self.command.strip('\r')
        args = shlex.split(command)
        if self.debug == True:
            logging.info("command=\"%s\"",args)
        p = Popen(args,stdout=PIPE)
        o,e = p.communicate()
        if self.debug == True:
            logging.info("output=\"%s\"",o)
            logging.info(':'.join(x.encode('hex') for x in o))
        return o

Add output of command in hex

Add output of command in hex


from django.shortcuts import render, get_object_or_404

from mozcal.events.models import Event, Space, FunctionalArea

def one(request, slug):
  event = get_object_or_404(Event, slug=slug)

  return render(request, 'event.html', { 'event': event })

def all(request):
  events = Event.objects.all()
  spaces = Space.objects.all()
  areas = FunctionalArea.objects.all()

  return render(request, 'events_all.html', {
    'events': events,
    'spaces': spaces,
    'areas': areas
  })

from django.shortcuts import render, get_object_or_404

from mozcal.events.models import Event, Space, FunctionalArea

def one(request, slug):
  event = get_object_or_404(Event, slug=slug)

  return render(request, 'event.html', { 'event': event })

def all(request):
  search_string = request.GET.get('search', '')

  events = Event.objects.filter(title__icontains=search_string)
  spaces = Space.objects.all()
  areas = FunctionalArea.objects.all()

  return render(request, 'events_all.html', {
    'events': events,
    'spaces': spaces,
    'areas': areas
  })

Allow filtering of events by title

Allow filtering of events by title


import sublime
import os

def getSetting(key,default=None):
	s = sublime.load_settings("Fuse.sublime-settings")
	return s.get(key, default)

def getFusePathFromSettings():
	path = getSetting("fuse_path_override")
	if path == "" or path == None:
		return "fuse"
	else:
		return path+"/fuse"

def setSetting(key,value):
	s = sublime.load_settings("Fuse.sublime-settings")
	s.set(key, value)
	sublime.save_settings("Fuse.sublime-settings")

def isSupportedSyntax(syntaxName):
	return syntaxName == "Uno" or syntaxName == "UX"

def getExtension(path):
	base = os.path.basename(path)
	return os.path.splitext(base)[0]

def getRowCol(view, pos):
	rowcol = view.rowcol(pos)
	rowcol = (rowcol[0] + 1, rowcol[1] + 1)
	return {"Line": rowcol[0], "Character": rowcol[1]}

import sublime
import os

def getSetting(key,default=None):
	s = sublime.load_settings("Fuse.sublime-settings")
	return s.get(key, default)

def getFusePathFromSettings():
	path = getSetting("fuse_path_override")
	if path == "" or path == None:
		if os.path.isfile("/usr/bin/fuse"):
			return "/usr/bin/fuse"
		else:
			return "/usr/local/bin/fuse"
	else:
		return path+"/fuse"

def setSetting(key,value):
	s = sublime.load_settings("Fuse.sublime-settings")
	s.set(key, value)
	sublime.save_settings("Fuse.sublime-settings")

def isSupportedSyntax(syntaxName):
	return syntaxName == "Uno" or syntaxName == "UX"

def getExtension(path):
	base = os.path.basename(path)
	return os.path.splitext(base)[0]

def getRowCol(view, pos):
	rowcol = view.rowcol(pos)
	rowcol = (rowcol[0] + 1, rowcol[1] + 1)
	return {"Line": rowcol[0], "Character": rowcol[1]}

Make Sublime plugin work with new Fuse install location

We changed the location of fuse from /usr/bin to /usr/local/bin to be
compatible with El Capitan. The latter is not on path in Sublime, so use
absolute paths for fuse.


# -*- coding: utf-8 -*-
import pytest
from .utils import get, versioned_reverse as reverse, assert_fields_exist

# === util methods ===

def get_list(api_client, version='v1'):
    list_url = reverse('user-list', version=version)
    return get(api_client, list_url)

def assert_user_fields_exist(data, version='v1'):
    # TODO: incorporate version parameter into version aware
    # parts of test code
    fields = (
        'last_login',
        'username',
        'email',
        'date_joined',
        'first_name',
        'last_name',
        'uuid',
        'department_name',
        'organization',
        'is_staff',
        'display_name',
    )
    assert_fields_exist(data, fields)

# === tests ===

@pytest.mark.django_db
def test__get_user_list(api_client, user, organization):
    organization.admin_users.add(user)
    api_client.force_authenticate(user=user)
    response = get_list(api_client)
    print(response.data)
    assert_user_fields_exist(response.data['data'][0])

# -*- coding: utf-8 -*-
import pytest
from .utils import get, versioned_reverse as reverse, assert_fields_exist

# === util methods ===

def get_list(api_client, version='v1'):
    list_url = reverse('user-list', version=version)
    return get(api_client, list_url)

def get_detail(api_client, detail_pk, version='v1'):
    detail_url = reverse('user-detail', version=version, kwargs={'pk': detail_pk})
    return get(api_client, detail_url)

def assert_user_fields_exist(data, version='v1'):
    # TODO: incorporate version parameter into version aware
    # parts of test code
    fields = (
        'last_login',
        'username',
        'email',
        'date_joined',
        'first_name',
        'last_name',
        'uuid',
        'department_name',
        'organization',
        'is_staff',
        'display_name',
    )
    assert_fields_exist(data, fields)

# === tests ===

@pytest.mark.django_db
def test__get_user_list(api_client, user, organization):
    organization.admin_users.add(user)
    api_client.force_authenticate(user=user)
    response = get_detail(api_client, user.pk)
    print(response.data)
    assert_user_fields_exist(response.data)

Check user detail in test

Check user detail in test


import discord
from discord.ext import commands

class Misc:
    @commands.command()
    async def highfive(self, ctx):
        """
        Give Yutu a high-five
        """
        await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))

    @commands.command()
    async def cute(self, ctx, user: discord.Member = None):
        """
        Tell someone they are cute!

        Tells a user that you think they are cute, if you don't give a user, then Yutu will let you know that you are cute.
        """
        if user is None:
            first = ctx.me
            second = ctx.author
        else:
            first = ctx.author
            second = user
        post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first,
                                                                                second))
        post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
        await ctx.send(embed=post)

import discord
from discord.ext import commands

class Misc:
    @commands.command()
    async def highfive(self, ctx: commands.Context):
        """
        Give Yutu a high-five
        """
        await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))

    @commands.command()
    async def cute(self, ctx: commands.Context, user: discord.Member = None):
        """
        Tell someone they are cute!

        Tells a user that you think they are cute, if you don't give a user, then Yutu will let you know that you are cute.
        """
        if user is None:
            first = ctx.me
            second = ctx.author
        else:
            first = ctx.author
            second = user
        post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first,
                                                                                second))
        post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
        await ctx.send(embed=post)

Add type markers for ctx objects

Add type markers for ctx objects


from django.conf.urls import url
from push import views

urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^sender', views.sender, name = 'sender'),
    url(r'^notification_list', views.notification_list, name = 'notification_list'),
    url(r'^settings', views.settings, name = 'settings'),
    url(r'^notification', views.notification, name = 'notification'),
    url(r'^register', views.device_token_register, name = 'device_token_register'),
    url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'),
]

from django.conf.urls import url
from push import views

urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^sender', views.sender, name = 'sender'),
    url(r'^notification_list', views.notification_list, name = 'notification_list'),
    url(r'^settings', views.settings, name = 'settings'),
    url(r'^notification', views.notification, name = 'notification'),
    url(r'^(?P<username>\w+)/register', views.device_token_register, name = 'device_token_register'),
    url(r'^delete/device_token/(?P<device_token_id>\d+)/$', views.delete_device_token, name = 'delete_device_token'),
]

Modify device_token register URL dispatcher


import os
import json
import socket

import requests

from flask import request, jsonify, Response, abort

from dadd.worker import app
from dadd.worker.proc import ChildProcess

@app.route('/run/', methods=['POST'])
def run_process():
    proc = ChildProcess(request.json)
    proc.run()
    return jsonify(proc.info())

@app.route('/register/', methods=['POST'])
def register_with_master():
    register(app)
    return jsonify({'message': 'ok'})

def register(host, port):
    sess = requests.Session()

    if 'USERNAME' in app.config and 'PASSWORD' in app.config:
        sess.auth = (app.config['USERNAME'], app.config['PASSWORD'])
    sess.headers = {'content-type': 'application/json'}

    try:
        url = app.config['MASTER_URL'] + '/api/hosts/'
        resp = sess.post(url, data=json.dumps({
            'host': app.config.get('HOSTNAME', socket.getfqdn()),
            'port': port
        }))
        if not resp.ok:
            app.logger.warning('Error registering with master: %s' %
                               app.config['MASTER_URL'])
    except Exception as e:
        app.logger.warning('Connection Error: %s' % e)

@app.route('/logs/<path>', methods=['GET'])
def tail_log(path):
    if os.path.exists(path) and path.startswith('/tmp/'):
        return Response(open(path), content_type='text/plain')
    abort(404)

import os
import json
import socket

import requests

from flask import request, jsonify, Response, abort

from dadd.worker import app
from dadd.worker.proc import ChildProcess

@app.route('/run/', methods=['POST'])
def run_process():
    proc = ChildProcess(request.json)
    proc.run()
    return jsonify(proc.info())

@app.route('/register/', methods=['POST'])
def register_with_master():
    register(app.config['HOST'], app.config['PORT'])
    return jsonify({'message': 'ok'})

def register(host, port):
    sess = requests.Session()

    if 'USERNAME' in app.config and 'PASSWORD' in app.config:
        sess.auth = (app.config['USERNAME'], app.config['PASSWORD'])
    sess.headers = {'content-type': 'application/json'}

    try:
        url = app.config['MASTER_URL'] + '/api/hosts/'
        resp = sess.post(url, data=json.dumps({
            'host': app.config.get('HOSTNAME', socket.getfqdn()),
            'port': port
        }))
        if not resp.ok:
            app.logger.warning('Error registering with master: %s' %
                               app.config['MASTER_URL'])
    except Exception as e:
        app.logger.warning('Connection Error: %s' % e)

@app.route('/logs/<path:path>', methods=['GET'])
def tail_log(path):
    path = '/' + path
    if os.path.exists(path) and path.startswith('/tmp/'):
        return Response(open(path), content_type='text/plain')
    abort(404)

Fix up the manual register URL in the worker and fix the initial log tail.


import os
import re
import cffi

_directive_re = re.compile(r'^\s*#.*?$(?m)')

def make_ffi(module_path, crate_path, cached_header_filename=None):
    """Creates a FFI instance for the given configuration."""
    if cached_header_filename is not None and \
       os.path.isfile(cached_header_filename):
        with open(cached_header_filename, 'rb') as f:
            header = f.read()
    else:
        from .bindgen import generate_header
        header = generate_header(crate_path)
    header = _directive_re.sub('', header)
    ffi = cffi.FFI()
    ffi.cdef(header)
    ffi.set_source(module_path, None)
    return ffi

import os
import re
import sys
import cffi

_directive_re = re.compile(r'^\s*#.*?$(?m)')

def make_ffi(module_path, crate_path, cached_header_filename=None):
    """Creates a FFI instance for the given configuration."""
    if cached_header_filename is not None and \
       os.path.isfile(cached_header_filename):
        with open(cached_header_filename, 'rb') as f:
            header = f.read()
    else:
        from .bindgen import generate_header
        header = generate_header(crate_path)
    header = _directive_re.sub('', header)

    if os.environ.get('SNAEK_DEBUG_HEADER') == '1':
        sys.stderr.write('/* generated header for "%s" */\n' % module_path)
        sys.stderr.write(header)
        sys.stderr.write('\n')
        sys.stderr.flush()

    ffi = cffi.FFI()
    ffi.cdef(header)
    ffi.set_source(module_path, None)
    return ffi

Add a way to dump the header during setup.py runs


#!/usr/bin/env python2

import os, shutil

def print_warning(message, *args, **kwargs):
    import colortext
    if args or kwargs: message = message.format(*args, **kwargs)
    colortext.write(message, color='red')

def print_error_and_die(message, *args, **kwargs):
    print_warning(message + "  Aborting...", *args, **kwargs)
    raise SystemExit(1)

def clear_directory(directory):
    if os.path.exists(directory): shutil.rmtree(directory)
    os.makedirs(directory)

def mkdir(newdir):
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        os.makedirs(newdir)

Add a friendly mkdir() function.

Add a friendly mkdir() function.


from django.test import TestCase

# Create your tests here.

from django.core.urlresolvers import resolve
from django.test import TestCase

from layout.views import home

class HomePageTest(TestCase):

    def test_root_url_resolves_to_home_page(self):
        found = resolve('/')
        self.assertEqual(found.func, home)

Add home page resolve test to layout

Add home page resolve test to layout


#!/usr/bin/env python

import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib

import lmj.tnn

logging.basicConfig(
    stream=sys.stdout,
    format='%(levelname).1s %(asctime)s %(message)s',
    level=logging.INFO)

URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')

if not os.path.isfile(DATASET):
    logging.info('downloading mnist digit dataset from %s' % URL)
    urllib.urlretrieve(URL, DATASET)
    logging.info('saved mnist digits to %s' % DATASET)

class Main(lmj.tnn.Main):
    def get_network(self):
        return lmj.tnn.Autoencoder

    def get_datasets(self):
        return [(x, ) for x, _ in cPickle.load(gzip.open(DATASET))]

path = os.path.join(tempfile.gettempdir(), 'mnist-autoencoder.pkl.gz')
Main().train().save(path)
print 'saved network to', path

#!/usr/bin/env python

import cPickle
import gzip
import logging
import os
import sys
import tempfile
import urllib

import lmj.tnn

logging.basicConfig(
    stream=sys.stdout,
    format='%(levelname).1s %(asctime)s %(message)s',
    level=logging.INFO)

URL = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
DATASET = os.path.join(tempfile.gettempdir(), 'mnist.pkl.gz')

if not os.path.isfile(DATASET):
    logging.info('downloading mnist digit dataset from %s' % URL)
    urllib.urlretrieve(URL, DATASET)
    logging.info('saved mnist digits to %s' % DATASET)

class Main(lmj.tnn.Main):
    def get_network(self):
        return lmj.tnn.Autoencoder

    def get_datasets(self):
        return [x for x, _ in cPickle.load(gzip.open(DATASET))]

path = os.path.join(tempfile.gettempdir(), 'mnist-autoencoder.pkl.gz')
Main().train().save(path)
print 'saved network to', path

Return unlabeled data for the autoencoder as a straight array.


from client import WebHDFSClient

__version__ = '1.0'

from errors import WebHDFSError
from client import WebHDFSClient
from attrib import WebHDFSObject

__version__ = '1.0'

Make other API classes available from base module.


from ..utils import *

##
# Minions

class OG_023:
	"Primal Fusion"
	play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM)

OG_023t = buff(+1, +1)

class OG_209:
	"Hallazeal the Ascended"
	events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT))

from ..utils import *

##
# Minions

class OG_023:
	"Primal Fusion"
	play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM)

OG_023t = buff(+1, +1)

class OG_026:
	"Eternal Sentinel"
	play = UnlockOverload(CONTROLLER)

class OG_209:
	"Hallazeal the Ascended"
	events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT))

##
# Spells

class OG_206:
	"Stormcrack"
	play = Hit(TARGET, 4)

##
# Weapons

class OG_031:
	"Hammer of Twilight"
	deathrattle = Summon(CONTROLLER, "OG_031a")

Implement Eternal Sentinel, Stormcrack and Hammer of Twilight


from . import TheInternetTestCase
from helium.api import click, Text, press, CONTROL, COMMAND, write
from sys import platform

class WYSIWYGEditorTest(TheInternetTestCase):
	def get_page(self):
		return "http://the-internet.herokuapp.com/tinymce"
	def test_use_wysiwyg_editor(self):
		self.assertTrue(Text("Your content goes here.").exists())
		click("Your content goes here.")
		if platform == 'darwin':
			press(COMMAND + 'a')
		else:
			press(CONTROL + 'a')
		write("Hello Helium!")
		self.assertTrue(Text("Hello Helium!").exists())

from . import TheInternetTestCase
from helium.api import click, Text, write

class WYSIWYGEditorTest(TheInternetTestCase):
	def get_page(self):
		return "http://the-internet.herokuapp.com/tinymce"
	def test_use_wysiwyg_editor(self):
		self.assertTrue(Text("Your content goes here.").exists())
		click("File")
		click("New document")
		write("Hello Helium!")
		self.assertTrue(Text("Hello Helium!").exists())

Simplify the WYSIWYG editor test case.

Simplify the WYSIWYG editor test case.


# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
from __future__ import unicode_literals

class NullNameError(ValueError):
    """
    Raised when a name is empty.
    """

class InvalidCharError(ValueError):
    """
    Raised when includes invalid character(s) within a string.
    """

class InvalidCharWindowsError(InvalidCharError):
    """
    Raised when includes Windows specific invalid character(s) within a string.
    """

class InvalidLengthError(ValueError):
    """
    Raised when a string too long/short.
    """

class ReservedNameError(ValueError):
    """
    Raised when a string is matched a reserved name.
    """

# encoding: utf-8

"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""

from __future__ import absolute_import
from __future__ import unicode_literals

class InvalidNameError(ValueError):
    """
    Base class of invalid name error.
    """

class NullNameError(InvalidNameError):
    """
    Raised when a name is empty.
    """

class InvalidCharError(InvalidNameError):
    """
    Raised when includes invalid character(s) within a string.
    """

class InvalidCharWindowsError(InvalidCharError):
    """
    Raised when includes Windows specific invalid character(s) within a string.
    """

class InvalidLengthError(InvalidNameError):
    """
    Raised when a string too long/short.
    """

class ReservedNameError(InvalidNameError):
    """
    Raised when a string is matched a reserved name.
    """

Add base class of invalid name error

Add base class of invalid name error


# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

VERSION = (0, 7, "0.dev")
__version__ = ".".join([str(s) for s in VERSION])

__title__ = "platformio"
__description__ = ("A cross-platform code builder and library manager")
__url__ = "https://github.com/ivankravets/platformio"

__author__ = "Ivan Kravets"
__email__ = "me@ikravets.com"

__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014 Ivan Kravets"

# __apiurl__ = "http://127.0.0.1:8080"
__apiurl__ = "http://api.platformio.ikravets.com"
__pkgmanifesturl__ = "http://platformio.ikravets.com/packages/manifest.json"

# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

VERSION = (0, 7, "0.dev")
__version__ = ".".join([str(s) for s in VERSION])

__title__ = "platformio"
__description__ = ("A cross-platform code builder and library manager")
__url__ = "https://github.com/ivankravets/platformio"

__author__ = "Ivan Kravets"
__email__ = "me@ikravets.com"

__license__ = "MIT License"
__copyright__ = "Copyright (C) 2014 Ivan Kravets"

# __apiurl__ = "http://127.0.0.1:8080"
__apiurl__ = "http://api.platformio.ikravets.com"
__pkgmanifesturl__ = "http://dl.platformio.ikravets.com/packages/manifest.json"

Switch package manifest to dl.platformio


#!/usr/bin/env python

""" Some tools for dealing with reversible numbers for problem 145 from Project Euler.
    https://projecteuler.net/problem=145
"""

def is_odd(num):
    """ Check if an integer is odd. """
    if num % 2 != 0:
        return True
    else:
        return False

def is_reversible(num):
    """ Check if a number is reversible given the above definition. """
    num_str = str(num)
    rev_num = int("".join(reversed(num_str)))

    total = num + rev_num

    for digit in str(total):
        if not is_odd(int(digit)):
            return False

    return True

if __name__ == "__main__":
    # check some odd and even numbers
    assert is_odd(1), "1 should be odd"
    assert not is_odd(2), "2 should not be odd"
    assert not is_odd(100), "100 should not be odd"
    assert is_odd(10001), "10001 should be odd"

    # check the example reversible numbers
    assert is_reversible(36), "36 should be reversible"
    assert is_reversible(63), "63 should be reversible"
    assert is_reversible(409), "409 should be reversible"
    assert is_reversible(904), "904 should be reversible"

    print "all assertions passed"

#!/usr/bin/env python

""" Some tools for dealing with reversible numbers for problem 145 from Project Euler.
    https://projecteuler.net/problem=145
"""

def is_odd(num):
    """ Check if an integer is odd. """
    if num % 2 != 0:
        return True
    else:
        return False

def is_reversible(num):
    """ Check if a number is reversible given the above definition. """
    num_str = str(num)
    rev_str = "".join(reversed(num_str))

    if int(rev_str[0]) == 0:
        return False

    total = num + int(rev_str)

    for digit in str(total):
        if not is_odd(int(digit)):
            return False

    return True

if __name__ == "__main__":
    # check some odd and even numbers
    assert is_odd(1), "1 should be odd"
    assert not is_odd(2), "2 should not be odd"
    assert not is_odd(100), "100 should not be odd"
    assert is_odd(10001), "10001 should be odd"

    # check the example reversible numbers
    assert is_reversible(36), "36 should be reversible"
    assert is_reversible(63), "63 should be reversible"
    assert is_reversible(409), "409 should be reversible"
    assert is_reversible(904), "904 should be reversible"

    assert not is_reversible(10), "10 should not be reversible. (leading zero.)"

    print "all assertions passed"

Add check for leading zeroes.

Add check for leading zeroes.