instruction
stringlengths 18
2.94k
| input
stringlengths 0
2.17k
| output
stringlengths 47
3.36k
|
---|---|---|
Declare queues when broker is instantiated
| """
sentry.queue.client
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
| """
sentry.queue.client
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
|
Fix interpretation of parameters for names list modification
| from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel not in recipient.channels and "i" in user.mode:
return ""
return representation
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"uni": InvisibleMode()
}
}
def cleanup(self):
self.ircd.removeMode("uni") | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"uni": InvisibleMode()
}
}
def cleanup(self):
self.ircd.removeMode("uni") |
Include data files in built package
| # !/usr/bin/env python
from setuptools import setup, find_packages
setup(name='symbtrsynthesis',
version='1.0.1-dev',
description='An (adaptive) synthesizer for SymbTr-MusicXML scores',
author='Hasan Sercan Atli',
url='https://github.com/hsercanatli/symbtrsynthesis',
packages=find_packages(),
include_package_data=True, install_requires=['numpy']
)
| # !/usr/bin/env python
from setuptools import setup, find_packages
setup(name='symbtrsynthesis',
version='1.0.1-dev',
description='An (adaptive) synthesizer for SymbTr-MusicXML scores',
author='Hasan Sercan Atli',
url='https://github.com/hsercanatli/symbtrsynthesis',
packages=find_packages(),
package_data={'symbtrsynthesis': ['data/*.json']},
include_package_data=True, install_requires=['numpy']
)
|
Increment minor version and set up for git flow
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'TRX',
'author': 'Kyle Maxwell, based on Paterva\'s library',
'url': 'https://github.com/krmaxwell/TRX',
'download_url': 'https://github.com/krmaxwell/TRX',
'author_email': 'krmaxwell@gmail.com',
'version': '0.1',
'install_requires': ['nose'],
'packages': ['TRX'],
'scripts': [],
'name': 'TRX'
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'TRX',
'author': 'Kyle Maxwell, based on Paterva\'s library',
'url': 'https://github.com/krmaxwell/TRX',
'download_url': 'https://github.com/krmaxwell/TRX',
'author_email': 'krmaxwell@gmail.com',
'version': '0.2',
'install_requires': ['nose'],
'packages': ['TRX'],
'scripts': [],
'name': 'TRX'
}
setup(**config)
|
Use `open` instead of `file` for compatibility
|
import os
from setuptools import setup, find_packages
VERSION = '1.4.5'
setup(
namespace_packages = ['tiddlywebplugins'],
name = 'tiddlywebplugins.atom',
version = VERSION,
description = 'A TiddlyWeb plugin that provides an Atom feed of tiddler collections.',
long_description=file(os.path.join(os.path.dirname(__file__), 'README')).read(),
author = 'Chris Dent',
url = 'http://pypi.python.org/pypi/tiddlywebplugins.atom',
packages = find_packages(exclude=['test']),
author_email = 'cdent@peermore.com',
platforms = 'Posix; MacOS X; Windows',
install_requires = ['setuptools',
'tiddlyweb>=1.4.2',
'feedgenerator'],
'extras_require': {
'testing': ['tiddlywebwiki', 'tiddlywebplugins.markdown']
},
zip_safe = False,
license = 'BSD',
)
|
import os
from setuptools import setup, find_packages
VERSION = '1.4.5'
setup(
namespace_packages = ['tiddlywebplugins'],
name = 'tiddlywebplugins.atom',
version = VERSION,
description = 'A TiddlyWeb plugin that provides an Atom feed of tiddler collections.',
long_description=open(os.path.join(os.path.dirname(__file__), 'README')).read(),
author = 'Chris Dent',
url = 'http://pypi.python.org/pypi/tiddlywebplugins.atom',
packages = find_packages(exclude=['test']),
author_email = 'cdent@peermore.com',
platforms = 'Posix; MacOS X; Windows',
install_requires = ['setuptools',
'tiddlyweb>=1.4.2',
'feedgenerator'],
'extras_require': {
'testing': ['tiddlywebwiki', 'tiddlywebplugins.markdown']
},
zip_safe = False,
license = 'BSD',
)
|
Set 0.1.1 as minimum version of loam
| from setuptools import setup
with open('README.rst') as rdm:
README = rdm.read()
setup(
name='qjobs',
use_scm_version=True,
description='Get a clean and flexible output from qstat',
long_description=README,
url='https://github.com/amorison/qjobs',
author='Adrien Morison',
author_email='adrien.morison@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
packages=['qjobs'],
entry_points={
'console_scripts': ['qjobs = qjobs.__main__:main']
},
setup_requires=['setuptools_scm'],
install_requires=['setuptools_scm', 'loam'],
)
| from setuptools import setup
with open('README.rst') as rdm:
README = rdm.read()
setup(
name='qjobs',
use_scm_version=True,
description='Get a clean and flexible output from qstat',
long_description=README,
url='https://github.com/amorison/qjobs',
author='Adrien Morison',
author_email='adrien.morison@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
packages=['qjobs'],
entry_points={
'console_scripts': ['qjobs = qjobs.__main__:main']
},
setup_requires=['setuptools_scm'],
install_requires=['setuptools_scm', 'loam>=0.1.1'],
)
|
Change version number for new pypi image
|
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# typing library was introduced as a core module in version 3.5.0
requires = ["dirlistproc", "jsonasobj", "rdflib", "rdflib-jsonld"]
if sys.version_info < (3, 5):
requires.append("typing")
setup(
name='SNOMEDToOWL',
version='0.2.2',
packages=['SNOMEDCTToOWL', 'SNOMEDCTToOWL.RF2Files'],
package_data={'SNOMEDCTToOWL' : ['conf/*.json']},
url='http://github.com/hsolbrig/SNOMEDToOWL',
license='Apache License 2.0',
author='Harold Solbrig',
author_email='solbrig.harold@mayo.edu',
description='"Spackman OWL" transformation test and validation tool',
long_description='Document and test SNOMED RF2 to OWL transformations',
install_requires=requires,
scripts=['scripts/RF2Filter', 'scripts/SNOMEDToOWL', 'scripts/CompareRDF', 'scripts/modifiedPerlScript.pl'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Healthcare Industry',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only']
)
|
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# typing library was introduced as a core module in version 3.5.0
requires = ["dirlistproc", "jsonasobj", "rdflib", "rdflib-jsonld"]
if sys.version_info < (3, 5):
requires.append("typing")
setup(
name='SNOMEDToOWL',
version='0.2.3',
packages=['SNOMEDCTToOWL', 'SNOMEDCTToOWL.RF2Files'],
package_data={'SNOMEDCTToOWL' : ['conf/*.json']},
url='http://github.com/hsolbrig/SNOMEDToOWL',
license='Apache License 2.0',
author='Harold Solbrig',
author_email='solbrig.harold@mayo.edu',
description='"Spackman OWL" transformation test and validation tool',
long_description='Document and test SNOMED RF2 to OWL transformations',
install_requires=requires,
scripts=['scripts/RF2Filter', 'scripts/SNOMEDToOWL', 'scripts/CompareRDF', 'scripts/modifiedPerlScript.pl'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Healthcare Industry',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only']
)
|
Remove plain 'django-admin-sortable' from requirements
This is only required to test migrations, not for new installs.
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from aldryn_faq import __version__
REQUIREMENTS = [
'aldryn-apphooks-config',
'aldryn-reversion',
'aldryn-search',
'django-admin-sortable',
'django-admin-sortable2>=0.5.0',
'django-parler',
'django-sortedm2m',
]
CLASSIFIERS = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks',
]
setup(
name='aldryn-faq',
version=__version__,
description='FAQ addon for django CMS',
author='Divio AG',
author_email='info@divio.ch',
url='https://github.com/aldryn/aldryn-faq',
packages=find_packages(),
license='LICENSE.txt',
platforms=['OS Independent'],
install_requires=REQUIREMENTS,
classifiers=CLASSIFIERS,
include_package_data=True,
zip_safe=False
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from aldryn_faq import __version__
REQUIREMENTS = [
'aldryn-apphooks-config',
'aldryn-reversion',
'aldryn-search',
# 'django-admin-sortable',
'django-admin-sortable2>=0.5.0',
'django-parler',
'django-sortedm2m',
]
CLASSIFIERS = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks',
]
setup(
name='aldryn-faq',
version=__version__,
description='FAQ addon for django CMS',
author='Divio AG',
author_email='info@divio.ch',
url='https://github.com/aldryn/aldryn-faq',
packages=find_packages(),
license='LICENSE.txt',
platforms=['OS Independent'],
install_requires=REQUIREMENTS,
classifiers=CLASSIFIERS,
include_package_data=True,
zip_safe=False
)
|
Update outdated link to repository, per @cknv
| import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.4',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='brandon@rhodesmill.org',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
| import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.4',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='brandon@rhodesmill.org',
url='https://github.com/brandon-rhodes/python-adventure',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
|
Remove dev indentifier; crank Development Status; updated URL to point to project page
| from setuptools import setup
setup(
name='kf5py',
py_modules = ['kf5py'],
version='0.1.dev5',
author='Chris Teplovs',
author_email='dr.chris@problemshift.com',
url='https://github.com/problemshift/kf5py',
license='LICENSE.txt',
description='Python-based utilities for KF5.',
install_requires=[
"requests >= 2.3.0"
],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Development Status :: 1 - Planning",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"
]
)
| from setuptools import setup
setup(
name='kf5py',
py_modules = ['kf5py'],
version='0.1.0',
author='Chris Teplovs',
author_email='dr.chris@problemshift.com',
url='http://problemshift.github.io/kf5py/',
license='LICENSE.txt',
description='Python-based utilities for KF5.',
install_requires=[
"requests >= 2.3.0"
],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Development Status :: 3 - Alpha",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"
]
)
|
Fix long description format to be markdown
| #! /usr/bin/env python
from setuptools import setup
import re
from os import path
version = ''
with open('cliff/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1)
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md')) as f:
long_description = f.read()
setup(name='mediacloud-cliff',
version=version,
description='Media Cloud CLIFF API Client Library',
long_description=long_description,
author='Rahul Bhargava',
author_email='rahulb@media.mit.edu',
url='http://cliff.mediacloud.org',
packages={'cliff'},
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=['requests'],
license='MIT',
zip_safe=False
)
| #! /usr/bin/env python
from setuptools import setup
import re
from os import path
version = ''
with open('cliff/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1)
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md')) as f:
long_description = f.read()
setup(name='mediacloud-cliff',
version=version,
description='Media Cloud CLIFF API Client Library',
long_description=long_description,
long_description_content_type='text/markdown',
author='Rahul Bhargava',
author_email='rahulb@media.mit.edu',
url='http://cliff.mediacloud.org',
packages={'cliff'},
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=['requests'],
license='MIT',
zip_safe=False
)
|
Include static subdirectories in package
| """
Favien
======
Network canvas community.
"""
from setuptools import setup
setup(
name='Favien',
version='dev',
url='https://github.com/limeburst/favien',
author='Jihyeok Seo',
author_email='me@limeburst.net',
description='Network canvas community',
long_description=__doc__,
zip_safe=False,
packages=['favien', 'favien.web'],
package_data={
'favien.web': ['templates/*.*', 'templates/*/*.*', 'static/*.*',
'translations/*/LC_MESSAGES/*'],
},
message_extractors={
'favien/web/templates': [
('**.html', 'jinja2', {
'extensions': 'jinja2.ext.autoescape,'
'jinja2.ext.with_'
})
]
},
install_requires=[
'Flask',
'Flask-Babel',
'SQLAlchemy',
'boto',
'click',
'redis',
'requests',
'requests_oauthlib',
],
entry_points={
'console_scripts': ['fav = favien.cli:cli'],
}
)
| """
Favien
======
Network canvas community.
"""
from setuptools import setup
setup(
name='Favien',
version='dev',
url='https://github.com/limeburst/favien',
author='Jihyeok Seo',
author_email='me@limeburst.net',
description='Network canvas community',
long_description=__doc__,
zip_safe=False,
packages=['favien', 'favien.web'],
package_data={
'favien.web': ['templates/*.*', 'templates/*/*.*',
'static/*.*', 'static/*/*.*',
'translations/*/LC_MESSAGES/*'],
},
message_extractors={
'favien/web/templates': [
('**.html', 'jinja2', {
'extensions': 'jinja2.ext.autoescape,'
'jinja2.ext.with_'
})
]
},
install_requires=[
'Flask',
'Flask-Babel',
'SQLAlchemy',
'boto',
'click',
'redis',
'requests',
'requests_oauthlib',
],
entry_points={
'console_scripts': ['fav = favien.cli:cli'],
}
)
|
Install the proper version of Django
| #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from setuptools import setup
def convert_readme():
try:
check_call(["pandoc", "-f", "markdown_github", "-t",
"rst", "-o", "README.rst", "README.md"])
except (OSError, CalledProcessError):
return open('README.md').read()
return open('README.rst').read()
setup(
name='django-mongoengine-forms',
version='0.4.4',
description="An implementation of django forms using mongoengine.",
author='Thom Wiggers',
author_email='thom@thomwiggers.nl',
packages=['mongodbforms', 'tests'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
license='New BSD License',
long_description=convert_readme(),
include_package_data=True,
provides=['mongodbforms'],
obsoletes=['mongodbforms'],
url='https://github.com/thomwiggers/django-mongoengine-forms/',
zip_safe=False,
install_requires=['setuptools', 'django>=1.8', 'mongoengine>=0.10.0'],
tests_require=['mongomock'],
test_suite="tests.suite",
)
| #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from setuptools import setup
import six
requirements = ['setuptools', 'mongoengine>=0.10.0']
if six.PY3:
requirements.append('django')
else:
requirements.append('django<2')
def convert_readme():
try:
check_call(["pandoc", "-f", "markdown_github", "-t",
"rst", "-o", "README.rst", "README.md"])
except (OSError, CalledProcessError):
return open('README.md').read()
return open('README.rst').read()
setup(
name='django-mongoengine-forms',
version='0.4.4',
description="An implementation of django forms using mongoengine.",
author='Thom Wiggers',
author_email='thom@thomwiggers.nl',
packages=['mongodbforms', 'tests'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
license='New BSD License',
long_description=convert_readme(),
include_package_data=True,
provides=['mongodbforms'],
obsoletes=['mongodbforms'],
url='https://github.com/thomwiggers/django-mongoengine-forms/',
zip_safe=False,
install_requires=requirements,
tests_require=['mongomock'],
test_suite="tests.suite",
)
|
Include kafka-check, bump to v0.2.6
| from setuptools import setup
from setuptools import find_packages
from yelp_kafka_tool import __version__
setup(
name="yelp-kafka-tool",
version=__version__,
author="Distributed systems team",
author_email="team-dist-sys@yelp.com",
description="Kafka management tools",
packages=find_packages(exclude=["scripts", "tests"]),
data_files=[
("bash_completion.d",
["bash_completion.d/kafka-info"]),
],
scripts=[
"scripts/kafka-info",
"scripts/kafka-reassignment",
"scripts/kafka-partition-manager",
"scripts/kafka-consumer-manager",
"scripts/yelpkafka",
],
install_requires=[
"argcomplete",
"kazoo>=2.0.post2,<3.0.0",
"PyYAML<4.0.0",
"yelp-kafka>=4.0.0,<5.0.0",
"requests<3.0.0"
],
)
| from setuptools import setup
from setuptools import find_packages
from yelp_kafka_tool import __version__
setup(
name="yelp-kafka-tool",
version=__version__,
author="Distributed systems team",
author_email="team-dist-sys@yelp.com",
description="Kafka management tools",
packages=find_packages(exclude=["scripts", "tests"]),
data_files=[
("bash_completion.d",
["bash_completion.d/kafka-info"]),
],
scripts=[
"scripts/kafka-info",
"scripts/kafka-reassignment",
"scripts/kafka-partition-manager",
"scripts/kafka-consumer-manager",
"scripts/yelpkafka",
"scripts/kafka-check",
],
install_requires=[
"argcomplete",
"kazoo>=2.0.post2,<3.0.0",
"PyYAML<4.0.0",
"yelp-kafka>=4.0.0,<5.0.0",
"requests<3.0.0"
],
)
|
Enable module to be compiled with msvc and gcc compilers
| from setuptools import setup, Extension
import numpy
ext_modules=[
Extension(
"heat_diffusion_experiment.cython_versions",
["heat_diffusion_experiment/cython_versions.pyx"],
language='c++',
extra_compile_args=['/openmp'],
# extra_link_args=['/openmp'],
),
]
setup(
name = 'heat_diffusion_experiment',
ext_modules = ext_modules,
include_dirs=[numpy.get_include()],
packages=['heat_diffusion_experiment'],
)
| from setuptools import setup, Extension
import numpy
import sys
if sys.platform == 'linux'
extra_compile_args = ['-fopenmp'
extra_link_args = ['-fopenmp']
else:
extra_compile_args = ['-/openmp']
extra_link_args = ['-/openmp']
ext_modules=[
Extension(
"heat_diffusion_experiment.cython_versions",
["heat_diffusion_experiment/cython_versions.pyx"],
language='c++',
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
),
]
setup(
name = 'heat_diffusion_experiment',
ext_modules = ext_modules,
include_dirs=[numpy.get_include()],
packages=['heat_diffusion_experiment'],
)
|
Add pykqml dependency lower limit
| from setuptools import setup, find_packages
def main():
setup(name='bioagents',
version='0.0.1',
description='Biological Reasoning Agents',
long_description='Biological Reasoning Agents',
author='Benjamin Gyori',
author_email='benjamin_gyori@hms.harvard.edu',
url='http://github.com/sorgerlab/bioagents',
packages=find_packages(),
install_requires=['indra', 'pykqml'],
include_package_data=True,
keywords=['systems', 'biology', 'model', 'pathway', 'assembler',
'nlp', 'mechanism', 'biochemistry'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Mathematics',
],
)
if __name__ == '__main__':
main()
| from setuptools import setup, find_packages
def main():
setup(name='bioagents',
version='0.0.1',
description='Biological Reasoning Agents',
long_description='Biological Reasoning Agents',
author='Benjamin Gyori',
author_email='benjamin_gyori@hms.harvard.edu',
url='http://github.com/sorgerlab/bioagents',
packages=find_packages(),
install_requires=['indra', 'pykqml>=1.2'],
include_package_data=True,
keywords=['systems', 'biology', 'model', 'pathway', 'assembler',
'nlp', 'mechanism', 'biochemistry'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Chemistry',
'Topic :: Scientific/Engineering :: Mathematics',
],
)
if __name__ == '__main__':
main()
|
BLD: Use PEP 508 version markers.
So that environment tooling, e.g. `pipenv` can use the python version markers
when determining dependencies.
| #!/usr/bin/env python
from setuptools import setup, find_packages
import sys
long_description = ''
if 'upload' in sys.argv:
with open('README.rst') as f:
long_description = f.read()
def extras_require():
return {
'test': [
'tox>=2.0',
'pytest>=2.8.5',
'pytest-cov>=1.8.1',
'pytest-pep8>=1.0.6',
],
}
def install_requires():
requires = ['six']
if sys.version_info[:2] < (3, 5):
requires.append("typing>=3.5.2")
if sys.version_info[0] == 2:
requires.append("funcsigs>=1.0.2")
return requires
setup(
name='python-interface',
version='1.4.0',
description="Pythonic Interface definitions",
author="Scott Sanderson",
author_email="scott.b.sanderson90@gmail.com",
packages=find_packages(),
long_description=long_description,
license='Apache 2.0',
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Pre-processors',
],
url='https://github.com/ssanderson/interface',
install_requires=install_requires(),
extras_require=extras_require(),
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
import sys
long_description = ''
if 'upload' in sys.argv:
with open('README.rst') as f:
long_description = f.read()
def extras_require():
return {
'test': [
'tox>=2.0',
'pytest>=2.8.5',
'pytest-cov>=1.8.1',
'pytest-pep8>=1.0.6',
],
}
def install_requires():
return [
'six',
'typing>=3.5.2;python_version<"3.5"',
'funcsigs>=1.0.2;python_version<"3"'
]
setup(
name='python-interface',
version='1.4.0',
description="Pythonic Interface definitions",
author="Scott Sanderson",
author_email="scott.b.sanderson90@gmail.com",
packages=find_packages(),
long_description=long_description,
license='Apache 2.0',
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Pre-processors',
],
url='https://github.com/ssanderson/interface',
install_requires=install_requires(),
extras_require=extras_require(),
)
|
[python] Add some paths where to find test binary
Adds /usr/lib/debug early to list, as some systems (debian) have unstripped libs in there
Adds /lib/i386-linux-gnu for systems that does multiarch (debian)
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@153174 91177308-0d34-0410-b5e6-96231b3b80d8
| import os.path
import unittest
POSSIBLE_TEST_BINARIES = [
'libreadline.so.5',
'libreadline.so.6',
]
POSSIBLE_TEST_BINARY_PATHS = [
'/lib',
'/usr/lib',
'/usr/local/lib',
]
class TestBase(unittest.TestCase):
def get_test_binary(self):
"""Helper to obtain a test binary for object file testing.
FIXME Support additional, highly-likely targets or create one
ourselves.
"""
for d in POSSIBLE_TEST_BINARY_PATHS:
for lib in POSSIBLE_TEST_BINARIES:
path = os.path.join(d, lib)
if os.path.exists(path):
return path
raise Exception('No suitable test binaries available!')
get_test_binary.__test__ = False
| import os.path
import unittest
POSSIBLE_TEST_BINARIES = [
'libreadline.so.5',
'libreadline.so.6',
]
POSSIBLE_TEST_BINARY_PATHS = [
'/usr/lib/debug',
'/lib',
'/usr/lib',
'/usr/local/lib',
'/lib/i386-linux-gnu',
]
class TestBase(unittest.TestCase):
def get_test_binary(self):
"""Helper to obtain a test binary for object file testing.
FIXME Support additional, highly-likely targets or create one
ourselves.
"""
for d in POSSIBLE_TEST_BINARY_PATHS:
for lib in POSSIBLE_TEST_BINARIES:
path = os.path.join(d, lib)
if os.path.exists(path):
return path
raise Exception('No suitable test binaries available!')
get_test_binary.__test__ = False
|
Change task to create a taskHistory object
| # -*- coding: utf-8 -*-
from dbaas.celery import app
from util.decorators import only_one
from models import CeleryHealthCheck
#from celery.utils.log import get_task_logger
#LOG = get_task_logger(__name__)
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
def set_celery_healthcheck_last_update(self):
LOG.info("Setting Celery healthcheck last update")
CeleryHealthCheck.set_last_update()
return | # -*- coding: utf-8 -*-
from dbaas.celery import app
from util.decorators import only_one
from models import CeleryHealthCheck
from notification.models import TaskHistory
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
@only_one(key="celery_healthcheck_last_update", timeout=20)
def set_celery_healthcheck_last_update(self):
try:
task_history = TaskHistory.register(request=self.request, user=None)
LOG.info("Setting Celery healthcheck last update")
CeleryHealthCheck.set_last_update()
task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details="Finished")
except Exception, e:
LOG.warn("Oopss...{}".format(e))
task_history.update_status_for(TaskHistory.STATUS_ERROR, details=e)
finally:
return
|
Add Error Message To Server
| # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software distributed under the License is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and
# limitations under the License.
import urllib2
import json
from google.appengine.ext import vendor
vendor.add('lib')
from flask import Flask
app = Flask(__name__)
from api_key import key
@app.route('/get_author/<title>')
def get_author(title):
host = 'https://www.googleapis.com/books/v1/volumes?q={}&key={}&country=US'.format(title, key)
request = urllib2.Request(host)
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, error:
contents = error.read()
return str(contents)
html = response.read()
author = json.loads(html)['items'][0]['volumeInfo']['authors'][0]
return author
if __name__ == '__main__':
app.run(debug=True)
| # Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
# law or agreed to in writing, software distributed under the License is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and
# limitations under the License.
import urllib2
import json
from google.appengine.ext import vendor
vendor.add('lib')
from flask import Flask
app = Flask(__name__)
from api_key import key
@app.route('/get_author/<title>')
def get_author(title):
host = 'https://www.googleapis.com/books/v1/volumes?q={}&key={}&country=US'.format(title, key)
request = urllib2.Request(host)
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, error:
contents = error.read()
print ('Received error from Books API {}'.format(contents))
return str(contents)
html = response.read()
author = json.loads(html)['items'][0]['volumeInfo']['authors'][0]
return author
if __name__ == '__main__':
app.run(debug=True)
|
Update regression test for variable-length pattern problem in the matcher.
| '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
@pytest.mark.xfail
def test_issue850():
matcher = Matcher(Vocab())
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank'])
match = matcher(doc)
assert len(match) == 1
start, end, label, ent_id = match
assert start == 0
assert end == 4
| '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
from __future__ import print_function
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
def test_basic_case():
matcher = Matcher(Vocab(
lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', LOWER: 'and'},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
@pytest.mark.xfail
def test_issue850():
'''The problem here is that the variable-length pattern matches the
succeeding token. We then don't handle the ambiguity correctly.'''
matcher = Matcher(Vocab(
lex_attr_getters={LOWER: lambda string: string.lower()}))
IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True)
matcher.add_pattern(
"FarAway",
[
{LOWER: "bob"},
{'OP': '*', IS_ANY_TOKEN: True},
{LOWER: 'frank'}
])
doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank'])
match = matcher(doc)
assert len(match) == 1
ent_id, label, start, end = match[0]
assert start == 0
assert end == 4
|
Fix error in loading trees
Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda | #! /usr/bin/env python3
import os
import shutil
import datetime
import sys
import argparse
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=read_newick(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
| #! /usr/bin/env python3
import os
import shutil
import datetime
import sys
from ete3 import Tree
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasattr(node,"fastapath"):
fastas_fn=node.fastapath.split("@")
for fasta_fn in fastas_fn:
print(fasta_fn)
else:
children=node.get_children()
for child in children:
self.process_node(child)
if __name__ == "__main__":
assert(len(sys.argv)==2)
newick_fn=sys.argv[1]
ti=TreeIndex(
tree_newick_fn=newick_fn,
)
ti.process_node(ti.tree.get_tree_root())
|
Load user from migration registry when creating system user
Always load models from the registry in migration files.
I hate the idea of touching a migration already released, but
this one prevents us from adding new properties to User.
If we load the User directly (not from registry) when creating
the user model, we'll try to create a user with column that does
not exist at the time of this migration.
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import migrations
def add_user(*args):
User = get_user_model()
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def add_user(apps, *args):
User = apps.get_model('ideascube', 'User')
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sdb_level'),
('search', '0001_initial'),
]
operations = [
migrations.RunPython(add_user, None),
]
|
Break out dispatch, and drop prepare. Easier testing
|
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
request = Request(event, context)
resp = self.prepare(request)
if resp:
return resp
kwargs = event.get('pathParameters') or {}
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
|
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
kwargs = event.get('pathParameters') or {}
self.dispatch(request, **kwargs)
def dispatch(self, request, **kwargs):
func = getattr(self, request.method.lower())
try:
resp = func(request, **kwargs)
except:
import traceback
log.error(self)
log.error(traceback.format_exc())
return response(body='Internal server Error', status=500)
if isinstance(resp, Response):
resp = resp.render()
return resp
def prepare(self, request):
pass
|
Fix tf session not being set as default
| from ..kernel import Kernel
from scannerpy import DeviceType
import tensorflow as tf
class TensorFlowKernel(Kernel):
def __init__(self, config):
# If this is a CPU kernel, tell TF that it should not use
# any GPUs for its graph operations
cpu_only = True
visible_device_list = []
tf_config = tf.ConfigProto()
for handle in config.devices:
if handle.type == DeviceType.GPU.value:
visible_device_list.append(str(handle.id))
cpu_only = False
if cpu_only:
tf_config.device_count['GPU'] = 0
else:
tf_config.gpu_options.visible_device_list = ','.join(visible_device_list)
# TODO: wrap this in "with device"
self.config = config
self.tf_config = tf_config
self.graph = self.build_graph()
self.sess = tf.Session(config=self.tf_config, graph=self.graph)
self.protobufs = config.protobufs
def close(self):
self.sess.close()
def build_graph(self):
raise NotImplementedError
def execute(self):
raise NotImplementedError
| from ..kernel import Kernel
from scannerpy import DeviceType
import tensorflow as tf
class TensorFlowKernel(Kernel):
def __init__(self, config):
# If this is a CPU kernel, tell TF that it should not use
# any GPUs for its graph operations
cpu_only = True
visible_device_list = []
tf_config = tf.ConfigProto()
for handle in config.devices:
if handle.type == DeviceType.GPU.value:
visible_device_list.append(str(handle.id))
cpu_only = False
if cpu_only:
tf_config.device_count['GPU'] = 0
else:
tf_config.gpu_options.visible_device_list = ','.join(visible_device_list)
# TODO: wrap this in "with device"
self.config = config
self.tf_config = tf_config
self.graph = self.build_graph()
self.sess = tf.Session(config=self.tf_config, graph=self.graph)
self.sess.as_default()
self.protobufs = config.protobufs
def close(self):
self.sess.close()
def build_graph(self):
raise NotImplementedError
def execute(self):
raise NotImplementedError
|
migrations: Fix zulipinternal migration corner case.
It's theoretically possible to have configured a Zulip server where
the system bots live in the same realm as normal users (and may have
in fact been the default in early Zulip releases? Unclear.). We
should handle these without the migration intended to clean up naming
for the system bot realm crashing.
Fixes #13660.
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
|
Return project ordered by date
| import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages
from flask_frozen import Freezer
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FREEZER_DESTINATION = 'dist'
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
freezer = Freezer(app)
@app.route('/')
@app.route('/bio/')
def index():
return render_template('bio.html', pages=pages)
@app.route('/portfolio/')
def portfolio():
return render_template('portfolio.html', pages=pages)
@app.route('/portfolio/<path:path>/')
def page(path):
page = pages.get_or_404(path)
return render_template('page.html', page=page)
@app.route('/contatti/')
def contatti():
page = pages.get_or_404("contatti")
return render_template('page.html', page=page)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == "build":
freezer.freeze()
else:
app.run(port=8080)
| import sys
from flask import Flask, render_template
from flask_flatpages import FlatPages, flatpages
from flask_frozen import Freezer
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FREEZER_DESTINATION = 'dist'
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
freezer = Freezer(app)
@app.route('/')
@app.route('/bio/')
def index():
return render_template('bio.html', pages=pages)
@app.route('/portfolio/')
def portfolio():
projects = (p for p in pages if 'date' in p.meta)
projects = sorted(projects, reverse=True, key=lambda p: p.meta['date'])
return render_template('portfolio.html', pages=projects)
@app.route('/portfolio/<path:path>/')
def page(path):
page = pages.get_or_404(path)
return render_template('project.html', page=page)
@app.route('/contatti/')
def contatti():
page = pages.get_or_404("contatti")
return render_template('page.html', page=page)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == "build":
freezer.freeze()
else:
app.run(port=8080) |
Add teardown of integration test
| from kitten.server import KittenServer
from gevent.pool import Group
from mock import MagicMock
class TestPropagation(object):
def setup_method(self, method):
self.servers = Group()
for port in range(4):
ns = MagicMock()
ns.port = 9812 + port
server = KittenServer(ns)
self.servers.spawn(server.listen_forever)
def test_node_propagation(self):
"""
Tests that check node propagation
1) Spin up four servers.
2) Make the first one send a sync request to all three others.
3) Count the numbers of requests made.
4) Check databases to see that they all know each other.
"""
pass
| from kitten.server import KittenServer
from gevent.pool import Group
from mock import MagicMock
class TestPropagation(object):
def setup_method(self, method):
self.servers = Group()
for port in range(4):
ns = MagicMock()
ns.port = 9812 + port
server = KittenServer(ns)
self.servers.spawn(server.listen_forever)
def teardown_method(self, method):
self.servers.kill(timeout=1)
def test_node_propagation(self):
"""
Tests that check node propagation
1) Spin up four servers.
2) Make the first one send a sync request to all three others.
3) Count the numbers of requests made.
4) Check databases to see that they all know each other.
"""
pass
|
Change single quotes to double | #!/usr/bin/env python
import unittest
import ghstats
class TestStats(unittest.TestCase):
def test_cli(self):
"""
Test command line arguments.
"""
count = ghstats.main_cli(["kefir500/apk-icon-editor", "-q", "-d"])
self.assertTrue(count > 0)
def test_releases(self):
"""
Download all releases.
"""
stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, False, ghstats.get_env_token(), False)
self.assertTrue(isinstance(stats, list))
count = ghstats.get_stats_downloads(stats, True)
self.assertTrue(count > 0)
def test_release(self):
"""
Download latest release.
"""
stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, True, ghstats.get_env_token(), False)
self.assertTrue(isinstance(stats, dict))
count = ghstats.get_stats_downloads(stats, True)
self.assertTrue(count > 0)
def test_invalid(self):
"""
Check nonexistent repository.
"""
self.assertRaises(ghstats.GithubRepoError,
lambda: ghstats.download_stats("kefir500", "foobar", None, False,
ghstats.get_env_token(), True))
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
import unittest
import ghstats
class TestStats(unittest.TestCase):
def test_cli(self):
"""
Test command line arguments.
"""
count = ghstats.main_cli(["kefir500/apk-icon-editor", "-q", "-d"])
self.assertTrue(count > 0)
def test_releases(self):
"""
Download all releases.
"""
stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, False, ghstats.get_env_token(), False)
self.assertTrue(isinstance(stats, list))
count = ghstats.get_stats_downloads(stats, True)
self.assertTrue(count > 0)
def test_release(self):
"""
Download latest release.
"""
stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, True, ghstats.get_env_token(), False)
self.assertTrue(isinstance(stats, dict))
count = ghstats.get_stats_downloads(stats, True)
self.assertTrue(count > 0)
def test_invalid(self):
"""
Check nonexistent repository.
"""
self.assertRaises(ghstats.GithubRepoError,
lambda: ghstats.download_stats("kefir500", "foobar", None, False,
ghstats.get_env_token(), True))
if __name__ == "__main__":
unittest.main()
|
Add match_distance flag to load_data_frame()
| import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
| import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ...
:param class_labels: if True, the class label is assumed to be present as the second-to-last column
:param match_distance: if True, the distance between the closest match is assumed to be present as the last column
:return: a pandas DataFrame loaded from the given path
"""
column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text']
if class_labels:
column_names.append('class')
if match_distance:
column_names.append('distance')
data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False,
names=column_names)
if sort_reindex:
data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort')
data_df.reset_index(inplace=True, drop=True)
assert data_df.isnull().sum().sum() == 0
return data_df
|
Simplify the code for downloading resources.
Use downloadPage instead of our own class.
| import os
from twisted.internet import reactor, defer, protocol
from twisted.web.client import RedirectAgent, Agent
from ooni.settings import config
from ooni.resources import inputs, geoip
agent = RedirectAgent(Agent(reactor))
class SaveToFile(protocol.Protocol):
def __init__(self, finished, filesize, filename):
self.finished = finished
self.remaining = filesize
self.outfile = open(filename, 'wb')
def dataReceived(self, bytes):
if self.remaining:
display = bytes[:self.remaining]
self.outfile.write(display)
self.remaining -= len(display)
else:
self.outfile.close()
def connectionLost(self, reason):
self.outfile.close()
self.finished.callback(None)
@defer.inlineCallbacks
def download_resource(resources):
for filename, resource in resources.items():
print "Downloading %s" % filename
filename = os.path.join(config.resources_directory, filename)
response = yield agent.request("GET", resource['url'])
finished = defer.Deferred()
response.deliverBody(SaveToFile(finished, response.length, filename))
yield finished
if resource['action'] is not None:
yield defer.maybeDeferred(resource['action'],
filename,
*resource['action_args'])
print "%s written." % filename
def download_inputs():
return download_resource(inputs)
def download_geoip():
return download_resource(geoip)
| import os
from twisted.internet import defer
from twisted.web.client import downloadPage
from ooni.settings import config
from ooni.resources import inputs, geoip
@defer.inlineCallbacks
def download_resource(resources):
for filename, resource in resources.items():
print "Downloading %s" % filename
filename = os.path.join(config.resources_directory, filename)
yield downloadPage(resource['url'], filename)
if resource['action'] is not None:
yield defer.maybeDeferred(resource['action'],
filename,
*resource['action_args'])
print "%s written." % filename
def download_inputs():
return download_resource(inputs)
def download_geoip():
return download_resource(geoip)
|
Reimplement using bottle and add 3 endpoints
| from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):
def post(self):
args = parser.parse_args()
txt = args['txt']
rp = reach.process_text(txt, offline=False)
st = rp.statements
json_statements = {}
json_statements['statements'] = []
for s in st:
s_json = s.to_json()
json_statements['statements'].append(s_json)
json_statements = json.dumps(json_statements)
return json_statements, 201
api.add_resource(InputText, '/parse')
class InputStmtJSON(Resource):
def post(self):
args = parser.parse_args()
print(args)
json_data = args['json']
json_dict = json.loads(json_data)
st = []
for j in json_dict['statements']:
s = Statement.from_json(j)
print(s)
st.append(s)
return 201
api.add_resource(InputStmtJSON, '/load')
if __name__ == '__main__':
app.run(debug=True)
| import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
if tp and tp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in tp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_text', method='POST')
def reach_process_text():
body = json.load(request.body)
text = body.get('text')
rp = reach.process_text(text)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
@route('/reach/process_pmc', method='POST')
def reach_process_pmc():
body = json.load(request.body)
pmcid = body.get('pmcid')
rp = reach.process_pmc(pmcid)
if rp and rp.statements:
stmts = json.dumps([json.loads(st.to_json()) for st
in rp.statements])
res = {'statements': stmts}
return res
else:
res = {'statements': []}
return res
if __name__ == '__main__':
app = default_app()
run(app)
|
Revert "x,y should be y,x"
This reverts commit 7636eb6ce4f23c6f787aed02590499b6d2ea60b2.
| #!/usr/bin/env python
"""
Contains player and NPC-classes.
"""
import logging
from Item import Item
class Person(object):
"""
Base class for all characters in game.
"""
DEFAULT_HEALTH = 100
def __init__(self, health=DEFAULT_HEALTH, position):
"""
Defaults to facing north. Facing codes:
- 0: North
- 1: East
- 2: South
- 3: West
@param health The health that is given at init.
@param position [x, y] the position at init.
"""
if not isinstance(position, (tuple, list)):
logging.error(
"Position should be tuple/list with [y, x], set it to [0, 0]"
)
position = [0, 0]
self.health, self.position, self.facing = health, position, 0
class Player(Person):
"""
Contains the player-controlled character.
"""
def __init__(self, health=DEFAULT_HEALTH, position):
super(Player, self).__init__(health, position)
self.inventory = []
def give_item(self, item):
if not isinstance(item, Item):
logging.error(
"Item given to player is not item instance."
)
return
self.inventory.append(item)
class NPC(Person):
"""
Contains a character controlled by the game.
"""
def next_step():
"""
Since the game controls this character, some algorithm should say where
it moves.
TODO
"""
pass
| #!/usr/bin/env python
"""
Contains player and NPC-classes.
"""
import logging
from Item import Item
class Person(object):
"""
Base class for all characters in game.
"""
DEFAULT_HEALTH = 100
def __init__(self, health=DEFAULT_HEALTH, position):
"""
Defaults to facing north. Facing codes:
- 0: North
- 1: East
- 2: South
- 3: West
@param health The health that is given at init.
@param position [x, y] the position at init.
"""
if not isinstance(position, (tuple, list)):
logging.error(
"Position should be tuple/list with [x, y], set it to [0, 0]"
)
position = [0, 0]
self.health, self.position, self.facing = health, position, 0
class Player(Person):
"""
Contains the player-controlled character.
"""
def __init__(self, health=DEFAULT_HEALTH, position):
super(Player, self).__init__(health, position)
self.inventory = []
def give_item(self, item):
if not isinstance(item, Item):
logging.error(
"Item given to player is not item instance."
)
return
self.inventory.append(item)
class NPC(Person):
"""
Contains a character controlled by the game.
"""
def next_step():
"""
Since the game controls this character, some algorithm should say where
it moves.
TODO
"""
pass
|
Remove old exports from subdue.core
| __all__ = [
'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
| __all__ = [
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|\__,_|\___|
"""
DEFAULT_DRIVER_CODE = """\
#!/usr/bin/env python
from subdue.sub import main
main()
"""
verbose = False
def set_color_policy(policy):
_color.color_policy = policy
def die(msg):
_sys.stderr.write(msg)
_sys.stderr.write("\n")
_sys.stderr.flush()
_sys.exit(1)
|
Update to catch up with Sublime-Linter API
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, util, highlight
class PugLint(NodeLinter):
"""Provides an interface to pug-lint."""
cmd = 'pug-lint @ *'
regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)'
multiline = False
tempfile_suffix = 'pug'
error_stream = util.STREAM_BOTH
defaults = {
'selector': 'text.pug, source.pypug, text.jade',
'--reporter=': 'inline'
}
default_type = highlight.WARNING
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ben Edwards
# Copyright (c) 2015 Ben Edwards
#
# License: MIT
#
"""This module exports the PugLint plugin class."""
from SublimeLinter.lint import NodeLinter, WARNING
class PugLint(NodeLinter):
"""Provides an interface to pug-lint."""
cmd = 'pug-lint ${temp_file} ${args}'
regex = r'^.+?:(?P<line>\d+)(:(?P<col>\d+) | )(?P<message>.+)'
multiline = False
tempfile_suffix = 'pug'
error_stream = util.STREAM_BOTH
defaults = {
'selector': 'text.pug, source.pypug, text.jade',
'--reporter=': 'inline'
}
default_type = WARNING
|
FIX disable product supplier pricelist
| # -*- coding: utf-8 -*-
{
'name': 'Product Supplier Pricelist',
'version': '1.0',
'category': 'Product',
'sequence': 14,
'summary': '',
'description': """
Product Supplier Pricelist
==========================
Add sql constraint to restrict:
1. That you can only add one supplier to a product per company
2. That you can add olny one record of same quantity for a supplier pricelist
It also adds to more menus (and add some related fields) on purchase/product.
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'purchase',
],
'data': [
'product_view.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | # -*- coding: utf-8 -*-
{
'name': 'Product Supplier Pricelist',
'version': '1.0',
'category': 'Product',
'sequence': 14,
'summary': '',
'description': """
Product Supplier Pricelist
==========================
Add sql constraint to restrict:
1. That you can only add one supplier to a product per company
2. That you can add olny one record of same quantity for a supplier pricelist
It also adds to more menus (and add some related fields) on purchase/product.
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'purchase',
],
'data': [
'product_view.xml',
],
'demo': [
],
'test': [
],
# TODO fix this module and make installable
'installable': False,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
Increment static resource to account for CDN JS
| import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = COMPETITIONSEASON
CONFIG["static_resource_version"] = 2
| import json
import os
DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
# The CONFIG variables should have exactly the same structure between environments
# Eventually a test environment should be added. -gregmarra 17 Jul 2012
if DEBUG:
CONFIG = {
"env": "dev",
"memcache": False,
}
else:
CONFIG = {
"env": "prod",
"memcache": True,
}
CONFIG['landing_handler'] = COMPETITIONSEASON
CONFIG["static_resource_version"] = 3
|
Use score as well in annotations table
| #!/usr/bin/env python
"""A script to sum the rpkm values for all genes for each annotation."""
import pandas as pd
import argparse
import sys
def main(args):
rpkm_table =pd.read_table(args.rpkm_table, index_col=0)
annotations = pd.read_table(args.annotation_table, header=None, names=["gene_id", "annotation", "evalue"])
annotation_rpkm = {}
for annotation, annotation_df in annotations.groupby('annotation'):
annotation_rpkm[annotation] = rpkm_table.ix[annotation_df.gene_id].sum()
annotation_rpkm_df = pd.DataFrame.from_dict(annotation_rpkm, orient='index')
# sort the columns of the dataframe
annotation_rpkm_df = annotation_rpkm_df.reindex(columns=sorted(rpkm_table.columns))
annotation_rpkm_df.to_csv(sys.stdout, sep='\t')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("rpkm_table")
parser.add_argument("annotation_table")
args = parser.parse_args()
main(args)
| #!/usr/bin/env python
"""A script to sum the rpkm values for all genes for each annotation."""
import pandas as pd
import argparse
import sys
def main(args):
rpkm_table =pd.read_table(args.rpkm_table, index_col=0)
annotations = pd.read_table(args.annotation_table, header=None, names=["gene_id", "annotation", "evalue", "score"])
annotation_rpkm = {}
for annotation, annotation_df in annotations.groupby('annotation'):
annotation_rpkm[annotation] = rpkm_table.ix[annotation_df.gene_id].sum()
annotation_rpkm_df = pd.DataFrame.from_dict(annotation_rpkm, orient='index')
# sort the columns of the dataframe
annotation_rpkm_df = annotation_rpkm_df.reindex(columns=sorted(rpkm_table.columns))
annotation_rpkm_df.to_csv(sys.stdout, sep='\t')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("rpkm_table")
parser.add_argument("annotation_table")
args = parser.parse_args()
main(args)
|
Remove code which blanks patch files
| #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Look for a patch file from our collection (which is
# in the pyscraper/patches folder in Public Whip CVS)
patchfile = os.path.join("patches", fileshort + ".patch")
if not os.path.isfile(patchfile):
return False
while True:
# Apply the patch
shutil.copyfile(filein, fileout)
# delete temporary file that might have been created by a previous patch failure
filoutorg = fileout + ".orig"
if os.path.isfile(filoutorg):
os.remove(filoutorg)
status = os.system("patch --quiet %s <%s" % (fileout, patchfile))
if status == 0:
return True
print "Error running 'patch' on file %s, blanking it out" % fileshort
os.rename(patchfile, patchfile + ".old~")
blankfile = open(patchfile, "w")
blankfile.close()
| #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Look for a patch file from our collection (which is
# in the pyscraper/patches folder in Public Whip CVS)
patchfile = os.path.join("patches", fileshort + ".patch")
if not os.path.isfile(patchfile):
return False
while True:
# Apply the patch
shutil.copyfile(filein, fileout)
# delete temporary file that might have been created by a previous patch failure
filoutorg = fileout + ".orig"
if os.path.isfile(filoutorg):
os.remove(filoutorg)
status = os.system("patch --quiet %s <%s" % (fileout, patchfile))
if status == 0:
return True
raise Exception, "Error running 'patch' on file %s" % fileshort
#print "blanking out %s" % fileshort
#os.rename(patchfile, patchfile + ".old~")
#blankfile = open(patchfile, "w")
#blankfile.close()
|
DEVOPS-42: Fix webapp password reset link
| from django.contrib.auth import views
from django.urls import path, re_path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
re_path(
r"^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
| from django.contrib.auth import views
from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
path(
r"account/reset/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
|
Reword about user giving dimensions | """
multiplication-table.py
Author: <your name here>
Credit: <list sources used, if any>
Assignment:
Write and submit a Python program that prints a multiplication table. The user
must be able to determine the width and height of the table before it is printed.
The final multiplication table should look like this:
Width of multiplication table: 10
Height of multiplication table: 8
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
"""
| """
multiplication-table.py
Author: <your name here>
Credit: <list sources used, if any>
Assignment:
Write and submit a Python program that prints a multiplication table. The user
must be prompted to give the width and height of the table before it is printed.
The final multiplication table should look like this:
Width of multiplication table: 10
Height of multiplication table: 8
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
"""
|
Support to specify the valid external network name
In some deployments, the retrieved external network by the
def get_external_networks in Snaps checked by "router:external"
is not available. So it is necessary to specify the available
external network as an env by user.
Change-Id: I333e91dd106ed307541a9a197280199fde86bd30
Signed-off-by: Linda Wang <81613bebe84fa394bbc7c5cc1c21989c9bff2c52@huawei.com>
| # Copyright (c) 2015 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the first external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
| # Copyright (c) 2015 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the configured external network name or
the first retrieved external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external_networks(neutron)
if (hasattr(CONST, 'EXTERNAL_NETWORK')):
extnet_config = CONST.__getattribute__('EXTERNAL_NETWORK')
for ext_net in ext_nets:
if ext_net.name == extnet_config:
return extnet_config
return ext_nets[0].name if ext_nets else ""
def get_active_compute_cnt(os_creds):
"""
Returns the number of active compute servers
:param: os_creds: an instance of snaps OSCreds object
:return: the number of active compute servers
"""
nova = nova_utils.nova_client(os_creds)
computes = nova_utils.get_availability_zone_hosts(nova, zone_name='nova')
return len(computes)
|
Use the mint database for capsule data
| #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.configLine("store sqlite:///%s/database.sqlite" %
capsuleDataDir)
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
| #
# Copyright (c) 2009 rPath, Inc.
#
# All Rights Reserved
#
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
dbDriver = self.db.db.driver
dbConnectString = self.db.db.db.database
cfg.configLine("store %s:///%s" % (dbDriver, dbConnectString))
cfg.configLine("indexDir %s/packages" % capsuleDataDir)
cfg.configLine("systemsPath %s/systems" % capsuleDataDir)
dataSources = self.db.platformMgr.listPlatformSources().platformSource
# XXX we only deal with RHN for now
if dataSources:
cfg.configLine("user RHN %s %s" % (dataSources[0].username,
dataSources[0].password))
# XXX channels are hardcoded for now
cfg.configLine("channels rhel-i386-as-4")
cfg.configLine("channels rhel-x86_64-as-4")
cfg.configLine("channels rhel-i386-server-5")
cfg.configLine("channels rhel-x86_64-server-5")
util.mkdirChain(capsuleDataDir)
return cfg
def getIndexer(self):
cfg = self.getIndexerConfig()
return rpath_capsule_indexer.Indexer(cfg)
|
Implement function to load data from directory
| from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
def usage():
print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file")
if __name__ == '__main__':
dir_doc = dict_file = postings_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-i':
dir_doc = a
elif o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
else:
assert False, "unhandled option"
if dir_doc == None or dict_file == None or postings_file == None:
usage()
sys.exit(2)
| from nltk.tokenize import word_tokenize, sent_tokenize
import getopt
import sys
import os
import io
def load_data(dir_doc):
docs = {}
for dirpath, dirnames, filenames in os.walk(dir_doc):
for name in filenames:
file = os.path.join(dirpath, name)
with io.open(file, 'r+') as f:
docs[name] = f.read()
return docs
def usage():
print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file")
if __name__ == '__main__':
dir_doc = dict_file = postings_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-i':
dir_doc = a
elif o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
else:
assert False, "unhandled option"
if dir_doc == None or dict_file == None or postings_file == None:
usage()
sys.exit(2)
load_data(dir_doc) |
Set long description to current README.md content
| #!/usr/bin/python
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name = "docker-scripts",
version = "0.3.0",
packages = find_packages(),
url='https://github.com/goldmann/docker-scripts',
author='Marek Goldmann',
author_email='marek.goldmann@gmail.com',
description = 'A swiss-knife tool that could be useful for people working with Docker',
license='MIT',
keywords = 'docker',
entry_points={
'console_scripts': ['docker-scripts=docker_scripts.cli.main:run'],
},
install_requires=requirements
)
| #!/usr/bin/python
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name = "docker-scripts",
version = "0.3.0",
packages = find_packages(),
url='https://github.com/goldmann/docker-scripts',
author='Marek Goldmann',
author_email='marek.goldmann@gmail.com',
description = 'A swiss-knife tool that could be useful for people working with Docker',
license='MIT',
keywords = 'docker',
long_description=open('README.md').read(),
entry_points={
'console_scripts': ['docker-scripts=docker_scripts.cli.main:run'],
},
install_requires=requirements
)
|
Update install requires, add opps >= 0.2
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='opps-admin',
version='0.1',
description='Opps Admin, drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap.',
long_description=open('README.rst').read(),
author='sshwsfc',
url='http://www.oppsproject.org',
download_url='http://github.com/opps/opps-admin/tarball/master',
packages=find_packages(exclude=('doc', 'docs',)),
include_package_data=True,
install_requires=[
'setuptools',
'django>=1.4',
'xlwt',
'django-crispy-forms>=1.2.3',
'django-reversion',
],
zip_safe=True,
keywords=['admin', 'django', 'xadmin', 'bootstrap'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
"Programming Language :: JavaScript",
'Programming Language :: Python',
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='opps-admin',
version='0.1',
description='Opps Admin, drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap.',
long_description=open('README.rst').read(),
author='sshwsfc',
url='http://www.oppsproject.org',
download_url='http://github.com/opps/opps-admin/tarball/master',
packages=find_packages(exclude=('doc', 'docs',)),
include_package_data=True,
install_requires=[
'setuptools',
'opps>=0.2',
'xlwt',
'django-crispy-forms>=1.2.3',
],
zip_safe=True,
keywords=['admin', 'django', 'xadmin', 'bootstrap', 'opps', 'opps-admin'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
"Programming Language :: JavaScript",
'Programming Language :: Python',
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
]
)
|
Use requirement.txt entries to populate package requirements
| from setuptools import setup
setup(name="save_skype",
version="0.1",
description="Extract and save Skype chats.",
url="https://github.com/thismachinechills/save_skype",
author="thismachinechills (Alex)",
license="AGPL 3.0",
packages=['save_skype'],
zip_safe=True,
install_requires=["click", "html_wrapper"],
keywords="skype main.db extract chats".split(' '),
entry_points={"console_scripts":
["save_skype = save_skype.extract:cmd"]})
| from setuptools import setup
with open('requirements.txt', 'r') as file:
requirements = file.readlines()
setup(name="save_skype",
version="0.1.1",
description="Extract and save Skype chats.",
url="https://github.com/thismachinechills/save_skype",
author="thismachinechills (Alex)",
license="AGPL 3.0",
packages=['save_skype'],
zip_safe=True,
install_requires=requirements,
keywords="skype main.db extract chats".split(' '),
entry_points={"console_scripts":
["save_skype = save_skype.extract:cmd"]})
|
Remove an install_requires library which is already part of Python since 2.7
| from setuptools import setup, find_packages
with open('README.md') as f:
long_description = f.read()
setup(
name='jiradoc',
version='0.1',
description='A JIRAdoc parser',
long_description=long_description,
url='https://github.com/lucianovdveekens/jiradoc',
author='Luciano van der Veekens',
author_email='lucianovdveekens@gmail.com',
packages=find_packages(),
install_requires=['argparse', 'ply'],
package_data={
'jiradoc': ['data/test.jiradoc']
},
entry_points={
'console_scripts': [
'jiradoc=jiradoc.__main__:main',
],
},
)
| from setuptools import setup, find_packages
with open('README.md') as f:
long_description = f.read()
setup(
name='jiradoc',
version='0.1',
description='A JIRAdoc parser',
long_description=long_description,
url='https://github.com/lucianovdveekens/jiradoc',
author='Luciano van der Veekens',
author_email='lucianovdveekens@gmail.com',
packages=find_packages(),
install_requires=['ply'],
package_data={
'jiradoc': ['data/test.jiradoc']
},
entry_points={
'console_scripts': [
'jiradoc=jiradoc.__main__:main',
],
},
)
|
Include contrib module in installed package
See https://github.com/yola/yolacom/pull/1775#issuecomment-76513787
| from setuptools import setup
import proxyprefix
setup(
name='proxyprefix',
version=proxyprefix.__version__,
description='Prefix SCRIPT_NAME with X-Forwarded-Prefix header',
long_description=proxyprefix.__doc__,
author='Yola',
author_email='engineers@yola.com',
license='MIT (Expat)',
url='https://github.com/yola/proxyprefix',
packages=['proxyprefix'],
test_suite='nose.collector',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
],
extras_require = {
'djproxy': ['djproxy>=2.0.0'],
},
)
| from setuptools import find_packages, setup
import proxyprefix
setup(
name='proxyprefix',
version=proxyprefix.__version__,
description='Prefix SCRIPT_NAME with X-Forwarded-Prefix header',
long_description=proxyprefix.__doc__,
author='Yola',
author_email='engineers@yola.com',
license='MIT (Expat)',
url='https://github.com/yola/proxyprefix',
packages=find_packages(exclude=['tests', 'tests.*']),
test_suite='nose.collector',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
],
extras_require = {
'djproxy': ['djproxy>=2.0.0'],
},
)
|
Add requests and six as explicit dependencies
| from setuptools import setup
setup(
name = "ironic-discoverd",
version = "0.2.0",
description = "Simple hardware discovery for OpenStack Ironic",
author = "Dmitry Tantsur",
author_email = "dtansur@redhat.com",
url = "https://github.com/Divius/ironic-discoverd/",
packages = ['ironic_discoverd'],
install_requires = ['Flask', 'python-ironicclient', 'eventlet',
'python-keystoneclient'],
entry_points = {'console_scripts': ["ironic-discoverd = ironic_discoverd.main:main"]},
)
| from setuptools import setup
setup(
name = "ironic-discoverd",
version = "0.2.0",
description = "Simple hardware discovery for OpenStack Ironic",
author = "Dmitry Tantsur",
author_email = "dtansur@redhat.com",
url = "https://github.com/Divius/ironic-discoverd/",
packages = ['ironic_discoverd'],
install_requires = ['Flask', 'python-ironicclient', 'eventlet',
'python-keystoneclient', 'requests', 'six'],
entry_points = {'console_scripts': ["ironic-discoverd = ironic_discoverd.main:main"]},
)
|
Fix broken GitHub repository URL
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'name' : 'Redis Grepper',
'description' : 'Perform regex searches through Redis values',
'author' : 'Ionut G. Stan',
'author_email' : 'ionut.g.stan@gmail.com',
'url' : 'http://github.com/igstan/regis-grep',
'download_url' : 'http://github.com/igstan/redis-grep/zipball/0.1.1',
'version' : '0.1.1',
'install_requires' : ['redis'],
'py_modules' : ['redisgrep'],
'scripts' : ['redis-grep'],
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'name' : 'Redis Grepper',
'description' : 'Perform regex searches through Redis values',
'author' : 'Ionut G. Stan',
'author_email' : 'ionut.g.stan@gmail.com',
'url' : 'http://github.com/igstan/redis-grep',
'download_url' : 'http://github.com/igstan/redis-grep/zipball/0.1.1',
'version' : '0.1.1',
'install_requires' : ['redis'],
'py_modules' : ['redisgrep'],
'scripts' : ['redis-grep'],
}
setup(**config)
|
Bump package version forward to next development version
Change-Id: Ia04ceb0e83d4927e75a863252571ed76f83b2ef1
| #!/usr/bin/env python
import os
from setuptools import setup
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = 'voltha',
version = '1.3.0',
author = 'Open Networking Foundation, et al',
author_email = 'info@opennetworking.org',
description = ('Virtual Optical Line Terminal (OLT) Hardware Abstraction'),
license = 'Apache License 2.0',
keywords = 'volt gpon cord',
url = 'https://gerrit.opencord.org/#/q/project:voltha',
packages=['voltha', 'tests'],
long_description=read('README.md'),
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: System :: Networking',
'Programming Language :: Python',
'License :: OSI Approved :: Apache License 2.0',
],
)
| #!/usr/bin/env python
import os
from setuptools import setup
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = 'voltha',
version = '2.0.0-dev',
author = 'Open Networking Foundation, et al',
author_email = 'info@opennetworking.org',
description = ('Virtual Optical Line Terminal (OLT) Hardware Abstraction'),
license = 'Apache License 2.0',
keywords = 'volt gpon cord',
url = 'https://gerrit.opencord.org/#/q/project:voltha',
packages=['voltha', 'tests'],
long_description=read('README.md'),
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: System :: Networking',
'Programming Language :: Python',
'License :: OSI Approved :: Apache License 2.0',
],
)
|
Install pyramid 1.5 or newer which has the new SignedCookieSessionFactory
| # -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = (
'cnx-archive',
'cnx-epub',
'openstax-accounts',
'psycopg2',
'pyramid',
'pyramid_multiauth',
)
tests_require = [
'webtest',
]
extras_require = {
'test': tests_require,
}
description = """\
Application for accepting publication requests to the Connexions Archive."""
if not IS_PY3:
tests_require.append('mock')
setup(
name='cnx-publishing',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url="https://github.com/connexions/cnx-publishing",
license='LGPL, See also LICENSE.txt',
description=description,
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
test_suite='cnxpublishing.tests',
packages=find_packages(),
include_package_data=True,
package_data={
'cnxpublishing': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points="""\
[paste.app_factory]
main = cnxpublishing.main:main
[console_scripts]
cnx-publishing-initdb = cnxpublishing.scripts.initdb:main
""",
)
| # -*- coding: utf-8 -*-
import sys
from setuptools import setup, find_packages
IS_PY3 = sys.version_info > (3,)
install_requires = (
'cnx-archive',
'cnx-epub',
'openstax-accounts',
'psycopg2',
'pyramid>=1.5',
'pyramid_multiauth',
)
tests_require = [
'webtest',
]
extras_require = {
'test': tests_require,
}
description = """\
Application for accepting publication requests to the Connexions Archive."""
if not IS_PY3:
tests_require.append('mock')
setup(
name='cnx-publishing',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url="https://github.com/connexions/cnx-publishing",
license='LGPL, See also LICENSE.txt',
description=description,
install_requires=install_requires,
tests_require=tests_require,
extras_require=extras_require,
test_suite='cnxpublishing.tests',
packages=find_packages(),
include_package_data=True,
package_data={
'cnxpublishing': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points="""\
[paste.app_factory]
main = cnxpublishing.main:main
[console_scripts]
cnx-publishing-initdb = cnxpublishing.scripts.initdb:main
""",
)
|
Add placeholder CAPAPI key for tests.
| # Django settings used by pytest
# WARNING: this imports from .settings_dev instead of config.settings, meaning it chooses to IGNORE any settings in
# config/settings/settings.py. This is potentially better (in that it doesn't return different results locally than
# it will on CI), but also potentially worse (in that you can't try out settings tweaks in settings.py and run tests
# against them).
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
| # Django settings used by pytest
# WARNING: this imports from .settings_dev instead of config.settings, meaning it chooses to IGNORE any settings in
# config/settings/settings.py. This is potentially better (in that it doesn't return different results locally than
# it will on CI), but also potentially worse (in that you can't try out settings tweaks in settings.py and run tests
# against them).
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
CAPAPI_API_KEY = '12345'
|
Set latitude of Lake Superior
| #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:31:42 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
|
Fix vx.expose so it works when a name is passed
| import vx
def _expose(f, name=None):
if name is None:
name = f.__name__.lstrip('_')
if getattr(vx, name, None) is not None:
raise AttributeError("Cannot expose duplicate name: '{}'".format(name))
setattr(vx, name, f)
return f
vx.expose = _expose
@vx.expose
def _repeat(c, times=4):
for _ in range(times):
c()
| import vx
def _expose(f=None, name=None):
if name is None:
name = f.__name__.lstrip('_')
if getattr(vx, name, None) is not None:
raise AttributeError("Cannot expose duplicate name: '{}'".format(name))
if f is None:
def g(f):
setattr(vx, name, f)
return f
return g
setattr(vx, name, f)
return f
vx.expose = _expose
@vx.expose
def _repeat(c, times=4):
for _ in range(times):
c()
|
Add mass_api_client as Package; fix typo
| #!/usr/bin/env python
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
| #!/usr/bin/env python
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_requires=['requests==2.13.0', 'marshmallow==2.12.2'],
packages=['mass_api_client', ],
)
|
Fix pyNeuroML dependecy link to go to specific commit
| from setuptools import setup
setup(
name='ChannelWorm',
long_description=open('README.md').read(),
install_requires=[
'cypy',
'sciunit',
'PyOpenWorm',
'PyNeuroML'
],
dependency_links=[
'git+https://github.com/scidash/sciunit.git#egg=sciunit',
'git+https://github.com/openworm/PyOpenWorm.git#egg=PyOpenWorm',
'git+https://github.com/NeuroML/pyNeuroML.git#egg=PyNeuroML@5aeab1243567d9f4a8ce16516074dc7b93dfbf37'
]
)
| from setuptools import setup
setup(
name='ChannelWorm',
long_description=open('README.md').read(),
install_requires=[
'cypy',
'sciunit',
'PyOpenWorm',
'PyNeuroML'
],
dependency_links=[
'git+https://github.com/scidash/sciunit.git#egg=sciunit',
'git+https://github.com/openworm/PyOpenWorm.git#egg=PyOpenWorm',
'git+https://github.com/NeuroML/pyNeuroML.git@5aeab1243567d9f4a8ce16516074dc7b93dfbf37'
]
)
|
Upgrade tangled 0.1a9 => 1.0a12
| from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.sqlalchemy',
version='1.0a6.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=PEP420PackageFinder.find(include=['tangled*']),
install_requires=[
'tangled>=0.1a9',
'SQLAlchemy',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup, PEP420PackageFinder
setup(
name='tangled.sqlalchemy',
version='1.0a6.dev0',
description='Tangled SQLAlchemy integration',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.sqlalchemy/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=PEP420PackageFinder.find(include=['tangled*']),
install_requires=[
'tangled>=1.0a12',
'SQLAlchemy',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Support Wagtail 1.0 -> 1.3.x
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtailpress',
version='0.1',
packages=['wagtailpress'],
include_package_data=True,
license='BSD License',
description='wagtailpress is an Django app which extends the Wagtail CMS to be similar to WordPress.',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/FlipperPA/wagtailpress',
author='Timothy Allen',
author_email='tim@pyphilly.org',
install_requires=[
'wagtail>=1.0,<2.0',
'Markdown==2.6.2',
'Pygments==2.0.2',
'django-bootstrap3==6.2.2',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtailpress',
version='0.1',
packages=['wagtailpress'],
include_package_data=True,
license='BSD License',
description='wagtailpress is an Django app which extends the Wagtail CMS to be similar to WordPress.',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/FlipperPA/wagtailpress',
author='Timothy Allen',
author_email='tim@pyphilly.org',
install_requires=[
'wagtail>=1.0,<1.4',
'Markdown==2.6.2',
'Pygments==2.0.2',
'django-bootstrap3==6.2.2',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Upgrade SQLAlchemy 1.1.6 => 1.2.0
| from setuptools import setup
setup(
name='tangled.website',
version='1.0a1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'tangled.auth>=0.1a3',
'tangled.session>=0.1a3',
'tangled.site>=1.0a5',
'SQLAlchemy>=1.1.6',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
)
| from setuptools import setup
setup(
name='tangled.website',
version='1.0a1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='https://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'tangled.auth>=0.1a3',
'tangled.session>=0.1a3',
'tangled.site>=1.0a5',
'SQLAlchemy>=1.2.0',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
)
|
Allow installation with Python 2
| """
Setup file for clowder
"""
import sys
from setuptools import setup
# Written according to the docs at
# https://packaging.python.org/en/latest/distributing.html
if sys.version_info[0] < 3:
sys.exit('This script requires python 3.0 or higher to run.')
setup(
name='clowder-repo',
description='A tool for managing code',
version='2.3.0',
url='http://clowder.cat',
author='Joe DeCapo',
author_email='joe@polka.cat',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5'
],
packages=['clowder', 'clowder.utility'],
entry_points={
'console_scripts': [
'clowder=clowder.cmd:main',
]
},
install_requires=['argcomplete', 'colorama', 'GitPython', 'PyYAML', 'termcolor']
)
| """
Setup file for clowder
"""
from setuptools import setup
# Written according to the docs at
# https://packaging.python.org/en/latest/distributing.html
setup(
name='clowder-repo',
description='A tool for managing code',
version='2.3.0',
url='http://clowder.cat',
author='Joe DeCapo',
author_email='joe@polka.cat',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5'
],
packages=['clowder', 'clowder.utility'],
entry_points={
'console_scripts': [
'clowder=clowder.cmd:main',
]
},
install_requires=['argcomplete', 'colorama', 'GitPython', 'PyYAML', 'termcolor']
)
|
Increment version after change to get_base_url | import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='parserutils',
description='A collection of performant parsing utilities',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml',
version='1.2.3',
packages=[
'parserutils', 'parserutils.tests'
],
install_requires=[
'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/parserutils',
license='BSD',
cmdclass={'test': RunTests}
)
| import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='parserutils',
description='A collection of performant parsing utilities',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml',
version='1.2.4',
packages=[
'parserutils', 'parserutils.tests'
],
install_requires=[
'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/parserutils',
license='BSD',
cmdclass={'test': RunTests}
)
|
Change version to 0.2.7 according to fix.
| # -*- coding: utf-8 -*-
from distutils.core import setup
__version__ = '0.2.6'
setup(name='tg2ext.express',
version=__version__,
description='tg2ext.express, a small extension for TurboGears2',
long_description=open("README.md").read(),
author='Mingcai SHEN',
author_email='archsh@gmail.com',
packages=['tg2ext', 'tg2ext.express'],
#package_dir={'tg2ext': 'tg2ext'},
#package_data={'tg2ext': ['controller', 'exceptions']},
license="The MIT License (MIT)",
platforms=["any"],
install_requires=[
'TurboGears2>=2.3.1',
'SQLAlchemy>=0.8.2',
],
url='https://github.com/archsh/tg2ext.express')
| # -*- coding: utf-8 -*-
from distutils.core import setup
__version__ = '0.2.7'
setup(name='tg2ext.express',
version=__version__,
description='tg2ext.express, a small extension for TurboGears2',
long_description=open("README.md").read(),
author='Mingcai SHEN',
author_email='archsh@gmail.com',
packages=['tg2ext', 'tg2ext.express'],
#package_dir={'tg2ext': 'tg2ext'},
#package_data={'tg2ext': ['controller', 'exceptions']},
license="The MIT License (MIT)",
platforms=["any"],
install_requires=[
'TurboGears2>=2.3.1',
'SQLAlchemy>=0.8.2',
],
url='https://github.com/archsh/tg2ext.express')
|
Update treeherder-client dependency from * to >=2.0.1
To ensure deprecated versions of TreeherderClient aren't being used if
the virtualenv is reused.
Notably 2.0.1 includes an API URL fix that will prevent 404s once
non-canonical URLs are disabled in bug 1234233.
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = [
"Jinja2",
"taskcluster>=0.0.24",
"arrow",
"requests>=2.4.3,<=2.7.0",
"PyYAML",
"chunkify",
"treeherder-client",
"PGPy",
"buildtools",
"python-jose",
]
test_requirements = [
"pytest",
"pytest-cov",
"flake8",
"mock",
]
setup(
name='releasetasks',
version='0.3.3',
description="""Mozilla Release Promotion Tasks contains code to generate
release-related Taskcluster graphs.""",
long_description=readme,
author="Rail Aliiev",
author_email='rail@mozilla.com',
url='https://github.com/rail/releasetasks',
packages=[
'releasetasks',
],
package_dir={'releasetasks':
'releasetasks'},
include_package_data=True,
install_requires=requirements,
license="MPL",
zip_safe=False,
keywords='releasetasks',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements,
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = [
"Jinja2",
"taskcluster>=0.0.24",
"arrow",
"requests>=2.4.3,<=2.7.0",
"PyYAML",
"chunkify",
"treeherder-client>=2.0.1",
"PGPy",
"buildtools",
"python-jose",
]
test_requirements = [
"pytest",
"pytest-cov",
"flake8",
"mock",
]
setup(
name='releasetasks',
version='0.3.3',
description="""Mozilla Release Promotion Tasks contains code to generate
release-related Taskcluster graphs.""",
long_description=readme,
author="Rail Aliiev",
author_email='rail@mozilla.com',
url='https://github.com/rail/releasetasks',
packages=[
'releasetasks',
],
package_dir={'releasetasks':
'releasetasks'},
include_package_data=True,
install_requires=requirements,
license="MPL",
zip_safe=False,
keywords='releasetasks',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
],
test_suite='tests',
tests_require=test_requirements,
)
|
Remove py3 for the moment
| from setuptools import setup
setup(
name='icapservice',
version='0.1.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=False,
install_requires=['six'],
include_package_data=True,
package_data={'': ['LICENSE']},
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
),
)
| from setuptools import setup
setup(
name='icapservice',
version='0.1.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=False,
install_requires=['six'],
include_package_data=True,
package_data={'': ['LICENSE']},
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
#'Programming Language :: Python :: 3',
#'Programming Language :: Python :: 3.4',
#'Programming Language :: Python :: 3.5',
),
)
|
Add wider description for wheel and egg packages
| from setuptools import setup, find_packages
setup(
name="virgil-sdk",
version="5.0.0",
packages=find_packages(),
install_requires=[
'virgil-crypto',
],
author="Virgil Security",
author_email="support@virgilsecurity.com",
url="https://virgilsecurity.com/",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Security :: Cryptography",
],
license="BSD",
description="Virgil keys service SDK",
long_description="Virgil keys service SDK",
)
| from setuptools import setup, find_packages
setup(
name="virgil-sdk",
version="5.0.0",
packages=find_packages(),
install_requires=[
'virgil-crypto',
],
author="Virgil Security",
author_email="support@virgilsecurity.com",
url="https://virgilsecurity.com/",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Security :: Cryptography",
],
license="BSD",
description="""
Virgil Security provides a set of APIs for adding security to any application. In a few simple steps you can encrypt communication, securely store data, provide passwordless login, and ensure data integrity.
Virgil SDK allows developers to get up and running with Virgil API quickly and add full end-to-end (E2EE) security to their existing digital solutions to become HIPAA and GDPR compliant and more.(изменено)
Virgil Python Crypto Library is a high-level cryptographic library that allows you to perform all necessary operations for secure storing and transferring data and everything required to become HIPAA and GDPR compliant.
""",
long_description="Virgil keys service SDK",
)
|
Remove readme from package data.
| from distutils.core import setup
setup(
name='Zinc',
version='0.1.7',
author='John Wang',
author_email='john@zinc.io',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
| from distutils.core import setup
setup(
name='Zinc',
version='0.1.8',
author='John Wang',
author_email='john@zinc.io',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']},
include_package_data=True,
url='https://github.com/wangjohn/zinc_cli',
license='LICENSE.txt',
description='Wrapper for Zinc ecommerce API (zinc.io)',
install_requires=[
"requests >= 1.1.0"
],
)
|
Add classifier for Python 3.3
| #!/usr/bin/env python3
import sys
from distutils.core import setup
setup(
name='pathlib',
version=open('VERSION.txt').read().strip(),
py_modules=['pathlib'],
license='MIT License',
description='Object-oriented filesystem paths',
long_description=open('README.txt').read(),
author='Antoine Pitrou',
author_email='solipsis@pitrou.net',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Filesystems',
],
download_url='https://pypi.python.org/pypi/pathlib/',
url='http://readthedocs.org/docs/pathlib/',
)
| #!/usr/bin/env python3
import sys
from distutils.core import setup
setup(
name='pathlib',
version=open('VERSION.txt').read().strip(),
py_modules=['pathlib'],
license='MIT License',
description='Object-oriented filesystem paths',
long_description=open('README.txt').read(),
author='Antoine Pitrou',
author_email='solipsis@pitrou.net',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Filesystems',
],
download_url='https://pypi.python.org/pypi/pathlib/',
url='http://readthedocs.org/docs/pathlib/',
)
|
Fix Docker image tag inconsistency after merge commits
The image pushed is always given by `git rev-parse HEAD`, but the tag
for the image requested from Docker was retrieved from git log. Merge
commits were ignored by the latter. Now the tag is set to `git
rev-parse HEAD` both on push and retrieve.
| from setuptools import setup, find_packages
import os
import subprocess
os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")
versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
os.remove(versionFile)
git_commit = subprocess.check_output('git log --pretty=oneline -n 1 -- $(pwd)', shell=True).split()[0]
with open(versionFile, 'w') as versionFH:
versionFH.write("cactus_commit = '%s'" % git_commit)
setup(
name="progressiveCactus",
version="1.0",
author="Benedict Paten",
package_dir = {'': 'src'},
packages=find_packages(where='src'),
include_package_data=True,
package_data={'cactus': ['*_config.xml']},
# We use the __file__ attribute so this package isn't zip_safe.
zip_safe=False,
install_requires=[
'decorator',
'subprocess32',
'psutil',
'networkx==1.11'],
entry_points={
'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
| from setuptools import setup, find_packages
import os
import subprocess
os.system("pip install git+https://github.com/ComparativeGenomicsToolkit/sonLib@toil")
versionFile = "src/cactus/shared/version.py"
if os.path.exists(versionFile):
os.remove(versionFile)
git_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip()
with open(versionFile, 'w') as versionFH:
versionFH.write("cactus_commit = '%s'" % git_commit)
setup(
name="progressiveCactus",
version="1.0",
author="Benedict Paten",
package_dir = {'': 'src'},
packages=find_packages(where='src'),
include_package_data=True,
package_data={'cactus': ['*_config.xml']},
# We use the __file__ attribute so this package isn't zip_safe.
zip_safe=False,
install_requires=[
'decorator',
'subprocess32',
'psutil',
'networkx==1.11'],
entry_points={
'console_scripts': ['cactus = cactus.progressive.cactus_progressive:main']},)
|
Fix exclude of sample_project for installation.
| import os
from setuptools import setup, find_packages
packages = find_packages()
packages.remove('sample_project')
classifiers = """
Topic :: Internet :: WWW/HTTP :: Dynamic Content
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Programming Language :: Python
Topic :: Software Development :: Libraries :: Python Modules
Development Status :: 4 - Beta
"""
setup(
name='django-pagelets',
version='0.5',
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
packages=packages,
install_requires = [],
include_package_data = True,
exclude_package_data={
'': ['*.sql', '*.pyc'],
'pagelets': ['media/*'],
},
url='http://http://github.com/caktus/django-pagelets',
license='LICENSE.txt',
description='Simple, flexible app for integrating static, unstructured '
'content in a Django site',
classifiers = filter(None, classifiers.split("\n")),
long_description=open('README.rst').read(),
)
| import os
from setuptools import setup, find_packages
packages = find_packages(exclude=['sample_project'])
classifiers = """
Topic :: Internet :: WWW/HTTP :: Dynamic Content
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Programming Language :: Python
Topic :: Software Development :: Libraries :: Python Modules
Development Status :: 4 - Beta
Operating System :: OS Independent
"""
setup(
name='django-pagelets',
version='0.5',
author='Caktus Consulting Group',
author_email='solutions@caktusgroup.com',
packages=packages,
install_requires = [],
include_package_data = True,
exclude_package_data={
'': ['*.sql', '*.pyc'],
'pagelets': ['media/*'],
},
url='http://http://github.com/caktus/django-pagelets',
license='LICENSE.txt',
description='Simple, flexible app for integrating static, unstructured '
'content in a Django site',
classifiers = filter(None, classifiers.split("\n")),
long_description=open('README.rst').read(),
)
|
Remove data_sets from backdrop user search. Fixes
| from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
fields = ('name',)
extra = 0
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email', 'data_sets']
list_display = ('email', 'numer_of_datasets_user_has_access_to',)
list_per_page = 30
def queryset(self, request):
return BackdropUser.objects.annotate(
dataset_count=models.Count('data_sets')
)
def numer_of_datasets_user_has_access_to(self, obj):
return obj.dataset_count
numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'
admin.site.register(BackdropUser, BackdropUserAdmin)
| from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
fields = ('name',)
extra = 0
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email']
list_display = ('email', 'numer_of_datasets_user_has_access_to',)
list_per_page = 30
def queryset(self, request):
return BackdropUser.objects.annotate(
dataset_count=models.Count('data_sets')
)
def numer_of_datasets_user_has_access_to(self, obj):
return obj.dataset_count
numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count'
admin.site.register(BackdropUser, BackdropUserAdmin)
|
Use the latest version of openstax-accounts
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.6',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='info@cnx.org',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
|
Use py_modules and not packages
| import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="aaron@agoragames.com",
packages = ['eventsocket'],
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
| import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="aaron@agoragames.com",
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt',
py_modules = ['eventsocket'],
description='Easy to use TCP socket based on libevent',
install_requires = requirements,
long_description=open('README.rst').read(),
keywords=['socket', 'event'],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'
]
)
|
Include generated static content in package manifest
| from setuptools import setup, find_packages
setup(name='git-auto-deploy',
version='0.9',
url='https://github.com/olipo186/Git-Auto-Deploy',
author='Oliver Poignant',
author_email='oliver@poignant.se',
packages = find_packages(),
package_data={'gitautodeploy': ['data/*', 'wwwroot/*']},
entry_points={
'console_scripts': [
'git-auto-deploy = gitautodeploy.__main__:main'
]
},
install_requires=[
'lockfile'
],
description = "Deploy your GitHub, GitLab or Bitbucket projects automatically on Git push events or webhooks.",
long_description = "GitAutoDeploy consists of a HTTP server that listens for Web hook requests sent from GitHub, GitLab or Bitbucket servers. This application allows you to continuously and automatically deploy you projects each time you push new commits to your repository."
)
| from setuptools import setup, find_packages
import os
import sys
def package_files(package_path, directory_name):
paths = []
directory_path = os.path.join(package_path, directory_name)
for (path, directories, filenames) in os.walk(directory_path):
relative_path = os.path.relpath(path, package_path)
for filename in filenames:
if filename[0] == ".":
continue
paths.append(os.path.join(relative_path, filename))
return paths
# Get path to project
package_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "gitautodeploy")
# Get list of data files
wwwroot_files = package_files(package_path, "wwwroot")
data_files = package_files(package_path, "data")
setup(name='git-auto-deploy',
version='0.9.1',
url='https://github.com/olipo186/Git-Auto-Deploy',
author='Oliver Poignant',
author_email='oliver@poignant.se',
packages = find_packages(),
package_data={'gitautodeploy': data_files + wwwroot_files},
entry_points={
'console_scripts': [
'git-auto-deploy = gitautodeploy.__main__:main'
]
},
install_requires=[
'lockfile'
],
description = "Deploy your GitHub, GitLab or Bitbucket projects automatically on Git push events or webhooks.",
long_description = "GitAutoDeploy consists of a HTTP server that listens for Web hook requests sent from GitHub, GitLab or Bitbucket servers. This application allows you to continuously and automatically deploy you projects each time you push new commits to your repository."
)
|
Revert "Move beautifulsoup4 from requires to install_requires"
This reverts commit cb5ddc006489920eb43e5b0815c8ff75f74b1107.
install_requires is not supported by distutils and would need setuptools
instead. Perhaps move to setuptools in the future, but revert for now.
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from distutils.core import setup
import gygax
setup(
name="gygax",
version=gygax.__version__,
description="A minimalistic IRC bot",
long_description=open("README").read(),
author="Tiit Pikma",
author_email="1042524+thsnr@users.noreply.github.com",
url="https://github.com/thsnr/gygax",
packages=["gygax", "gygax.modules"],
scripts=["scripts/gygax"],
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: No Input/Output (Daemon)",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.7",
"Topic :: Communications :: Chat :: Internet Relay Chat",
],
install_requires=['beautifulsoup4'],
)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from distutils.core import setup
import gygax
setup(
name="gygax",
version=gygax.__version__,
description="A minimalistic IRC bot",
long_description=open("README").read(),
author="Tiit Pikma",
author_email="1042524+thsnr@users.noreply.github.com",
url="https://github.com/thsnr/gygax",
packages=["gygax", "gygax.modules"],
scripts=["scripts/gygax"],
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: No Input/Output (Daemon)",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.7",
"Topic :: Communications :: Chat :: Internet Relay Chat",
],
requires=['beautifulsoup4'],
)
|
Convert MD to reST for pypi
| #!/usr/bin/env python
from setuptools import setup
setup(name='xml_models2',
version='0.7.0',
description='XML backed models queried from external REST apis',
author='Geoff Ford and Chris Tarttelin and Cam McHugh',
author_email='g_ford@hotmail.ccom',
url='http://github.com/alephnullplex/xml_models',
packages=['xml_models'],
install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'],
tests_require=['mock', 'nose', 'coverage'],
test_suite="nose.collector"
)
| #!/usr/bin/env python
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='xml_models2',
version='0.7.0',
description='XML backed models queried from external REST apis',
long_description=long_description,
author='Geoff Ford and Chris Tarttelin and Cam McHugh',
author_email='g_ford@hotmail.ccom',
url='http://github.com/alephnullplex/xml_models',
packages=['xml_models'],
install_requires=['lxml', 'python-dateutil', 'pytz', 'future', 'requests'],
tests_require=['mock', 'nose', 'coverage'],
test_suite="nose.collector"
)
|
Increment version for 0.0.2 release.
| from setuptools import setup
setup(
name='twisted-hl7',
version='0.0.2dev',
author='John Paulett',
author_email = 'john@paulett.org',
url = 'http://twisted-hl7.readthedocs.org',
license = 'BSD',
platforms = ['POSIX', 'Windows'],
keywords = ['HL7', 'Health Level 7', 'healthcare', 'health care',
'medical record', 'twisted'],
classifiers = [
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Development Status :: 3 - Alpha',
'Framework :: Twisted',
'Intended Audience :: Developers',
'Intended Audience :: Healthcare Industry',
'Topic :: Communications',
'Topic :: Scientific/Engineering :: Medical Science Apps.',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'
],
packages = ['twistedhl7'],
install_requires = [
# require twisted, but allow client to require specific version
'twisted',
'hl7'
],
)
| from setuptools import setup
setup(
name='twisted-hl7',
version='0.0.2',
author='John Paulett',
author_email = 'john@paulett.org',
url = 'http://twisted-hl7.readthedocs.org',
license = 'BSD',
platforms = ['POSIX', 'Windows'],
keywords = ['HL7', 'Health Level 7', 'healthcare', 'health care',
'medical record', 'twisted'],
classifiers = [
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Development Status :: 3 - Alpha',
'Framework :: Twisted',
'Intended Audience :: Developers',
'Intended Audience :: Healthcare Industry',
'Topic :: Communications',
'Topic :: Scientific/Engineering :: Medical Science Apps.',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'
],
packages = ['twistedhl7'],
install_requires = [
# require twisted, but allow client to require specific version
'twisted',
'hl7'
],
)
|
Exclude tests package from distribution
| #!/usr/bin/env python
import sys, os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Hack to prevent "TypeError: 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function when setup.py exits
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
except ImportError:
pass
setup(
name='Willow',
version='0.4a0',
description='A Python image library that sits on top of Pillow, Wand and OpenCV',
author='Karl Hobley',
author_email='karlhobley10@gmail.com',
url='',
packages=find_packages(),
include_package_data=True,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=[],
zip_safe=False,
)
| #!/usr/bin/env python
import sys, os
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Hack to prevent "TypeError: 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function when setup.py exits
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
except ImportError:
pass
setup(
name='Willow',
version='0.4a0',
description='A Python image library that sits on top of Pillow, Wand and OpenCV',
author='Karl Hobley',
author_email='karlhobley10@gmail.com',
url='',
packages=find_packages(exclude=['tests']),
include_package_data=True,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=[],
zip_safe=False,
)
|
Change extra from 3 to 0.
| # coding: utf-8
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
| # coding: utf-8
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class Meta:
model = Carousel
def clean_domid(self):
data = self.cleaned_data['domid']
if not re.match(r'^[a-zA-Z_]\w*$', data):
raise ValidationError(_("The name must be a single word beginning with a letter"))
return data
class CarouselItemInline(admin.StackedInline):
model = CarouselItem
extra = 0
class CarouselPlugin(CMSPluginBase):
model = Carousel
form = CarouselForm
name = _("Carousel")
render_template = "cmsplugin_bootstrap_carousel/carousel.html"
inlines = [
CarouselItemInline,
]
def render(self, context, instance, placeholder):
context.update({'instance' : instance})
return context
plugin_pool.register_plugin(CarouselPlugin)
|
Update version number to 1.0.
| #!/usr/bin/env python
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='0.05',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica.org",
maintainer= "IOAM",
maintainer_email= "developers@topographica.org",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
# (until packaging tested)
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
| #!/usr/bin/env python
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica.org",
maintainer= "IOAM",
maintainer_email= "developers@topographica.org",
platforms=['Windows', 'Mac OS X', 'Linux'],
license='BSD',
url='http://ioam.github.com/param/',
packages = ["param"],
classifiers = [
"License :: OSI Approved :: BSD License",
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Intended Audience :: Developers",
"Natural Language :: English",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries"]
))
if __name__=="__main__":
setup(**setup_args)
|
Allow two command arguments for in and out files, or none for standard filter operations
| #!/usr/bin/env python
# mdstrip.py: makes new notebook from old, stripping md out
"""A tool to copy cell_type=("code") into a new file
without grabbing headers/markdown (most importantly the md)
NOTE: may want to grab the headers after all, or define new ones?"""
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
else:
infile = sys.stdin
outfile = sys.stdout
normalize(nbf.read(infile, "ipynb"), sys.stdout) | #!/usr/bin/env python
# mdstrip.py: makes new notebook from old, stripping md out
"""A tool to copy cell_type=("code") into a new file
without grabbing headers/markdown (most importantly the md)
NOTE: may want to grab the headers after all, or define new ones?"""
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("code"):
cell.outputs = []
cell.prompt_number = ""
cell_list.append(cell)
output_nb = nbf.new_notebook() # XXX should set name ...
output_nb.worksheets.append(nbf.new_worksheet(cells=cell_list))
nbf.write(output_nb, out_file, "ipynb")
if __name__ == "__main__":
if len(sys.argv) == 3:
infile = open(sys.argv[1])
outfile = open(sys.argv[2],"w")
elif len(sys.argv) != 1:
sys.exit("normalize: two arguments or none, please")
else:
infile = sys.stdin
outfile = sys.stdout
try:
normalize(nbf.read(infile, "ipynb"), outfile)
except Exception as e:
sys.exit("Normalization error: '{}'".format(str(e))) |
Fix GStreamer packages use of prefix
| GstreamerXzPackage (project = 'gstreamer', name = 'gstreamer', version = '1.4.5', configure_flags = [
'--disable-gtk-doc',
'--prefix="%{prefix}'
])
| GstreamerXzPackage (project = 'gstreamer', name = 'gstreamer', version = '1.4.5', configure_flags = [
'--disable-gtk-doc',
'--prefix=%{prefix}'
])
|
Downgrade script already running to info
| #!/usr/bin/env python
'''Checks processes'''
#===============================================================================
# Import modules
#===============================================================================
# Standard Library
import os
import subprocess
import logging
# Third party modules
# Application modules
#===============================================================================
# Check script is running
#===============================================================================
def is_running(script_name):
'''Checks list of processes for script name and filters out lines with the
PID and parent PID. Returns a TRUE if other script with the same name is
found running.'''
try:
logger = logging.getLogger('root')
cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout,
stdout=subprocess.PIPE)
cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout,
stdout=subprocess.PIPE)
cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout,
stdout=subprocess.PIPE)
cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout,
stdout=subprocess.PIPE)
other_script_found = cmd5.communicate()[0]
if other_script_found:
logger.error('Script already runnning. Exiting...')
logger.error(other_script_found)
return True
return False
except Exception, e:
logger.error('System check failed ({error_v}). Exiting...'.format(
error_v=e))
return True
| #!/usr/bin/env python
'''Checks processes'''
#===============================================================================
# Import modules
#===============================================================================
# Standard Library
import os
import subprocess
import logging
# Third party modules
# Application modules
#===============================================================================
# Check script is running
#===============================================================================
def is_running(script_name):
'''Checks list of processes for script name and filters out lines with the
PID and parent PID. Returns a TRUE if other script with the same name is
found running.'''
try:
logger = logging.getLogger('root')
cmd1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['grep', '-v', 'grep'], stdin=cmd1.stdout,
stdout=subprocess.PIPE)
cmd3 = subprocess.Popen(['grep', '-v', str(os.getpid())], stdin=cmd2.stdout,
stdout=subprocess.PIPE)
cmd4 = subprocess.Popen(['grep', '-v', str(os.getppid())], stdin=cmd3.stdout,
stdout=subprocess.PIPE)
cmd5 = subprocess.Popen(['grep', script_name], stdin=cmd4.stdout,
stdout=subprocess.PIPE)
other_script_found = cmd5.communicate()[0]
if other_script_found:
logger.info('Script already runnning. Exiting...')
logger.info(other_script_found)
return True
return False
except Exception, e:
logger.error('System check failed ({error_v}). Exiting...'.format(
error_v=e))
return True
|
Modify test_extract_listings() to account for the change in output from extract_listings()
| from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
for row in extract_listings(test_parse):
print type(row)
assert isinstance(row, bs4.element.Tag)
| from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_read_search_result():
test_body, test_encoding = read_search_results()
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert test_encoding == 'utf-8'
def test_parse_source():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
assert isinstance(test_parse, bs4.BeautifulSoup)
def test_extract_listings():
test_body, test_encoding = read_search_results()
test_parse = parse_source(test_body, test_encoding)
test_data = extract_listings(test_parse)
assert isinstance(test_data, list)
for dict_ in test_data:
assert isinstance(dict_, dict) |
Make shared static path OS-agnostic
| from datetime import datetime
import alabaster
# Alabaster theme + mini-extension
html_theme_path = [alabaster.get_path()]
extensions = ['alabaster']
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "Pythonic remote execution",
'github_user': 'fabric',
'github_repo': 'fabric',
'gittip_user': 'bitprophet',
'analytics_id': 'UA-18486793-1',
}
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'searchbox.html',
'donate.html',
]
}
# Regular settings
project = 'Fabric'
year = datetime.now().year
copyright = '%d Jeff Forcier' % year
master_doc = 'index'
templates_path = ['_templates']
exclude_trees = ['_build']
source_suffix = '.rst'
default_role = 'obj'
| from os.path import join
from datetime import datetime
import alabaster
# Alabaster theme + mini-extension
html_theme_path = [alabaster.get_path()]
extensions = ['alabaster']
# Paths relative to invoking conf.py - not this shared file
html_static_path = [join('..', '_shared_static')]
html_theme = 'alabaster'
html_theme_options = {
'description': "Pythonic remote execution",
'github_user': 'fabric',
'github_repo': 'fabric',
'gittip_user': 'bitprophet',
'analytics_id': 'UA-18486793-1',
}
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'searchbox.html',
'donate.html',
]
}
# Regular settings
project = 'Fabric'
year = datetime.now().year
copyright = '%d Jeff Forcier' % year
master_doc = 'index'
templates_path = ['_templates']
exclude_trees = ['_build']
source_suffix = '.rst'
default_role = 'obj'
|
Update BrowserifyCompiler for n Pipeline settings.
| import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
command = "%s %s %s > %s" % (
getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'),
getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
| import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cache busting hashes between ".browserify" and ".js"
return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None
def compile_file(self, infile, outfile, outdated=False, force=False):
pipeline_settings = getattr(settings, 'PIPELINE', {})
command = "%s %s %s > %s" % (
pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'),
pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''),
infile,
outfile
)
return self.execute_command(command)
def execute_command(self, command, content=None, cwd=None):
"""This is like the one in SubProcessCompiler, except it checks the exit code."""
import subprocess
pipe = subprocess.Popen(command, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
if content:
content = smart_bytes(content)
stdout, stderr = pipe.communicate(content)
if self.verbose:
print(stderr)
if pipe.returncode != 0:
raise CompilerError(stderr)
return stdout
|
Switch UI tests back to google chrome.
| import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
| import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDriverManager
@pytest.fixture(scope="session")
def chromedriver():
try:
options = Options()
options.headless = True
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
url = 'http://localhost:9000'
driver.get(url + "/gettingstarted")
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Sign in'))
#Login to Graylog
uid_field = driver.find_element_by_name("username")
uid_field.clear()
uid_field.send_keys("admin")
password_field = driver.find_element_by_name("password")
password_field.clear()
password_field.send_keys("admin")
password_field.send_keys(Keys.RETURN)
WebDriverWait(driver, 30).until(expected_conditions.title_contains('Getting started'))
#Run tests
yield driver
finally:
driver.quit()
|
Fix add pool member code
| from lib.actions import BaseAction
__all__ = [
'CreatePoolMemberAction'
]
class CreatePoolMemberAction(BaseAction):
api_type = 'loadbalancer'
def run(self, region, pool_id, node_id, port):
driver = self._get_lb_driver(region)
pool = driver.ex_get_pool(pool_id)
node = driver.ex.get_node(node_id)
member = driver.ex_create_pool_member(pool, node, port)
return self.resultsets.formatter(member)
| from lib.actions import BaseAction
__all__ = [
'CreatePoolMemberAction'
]
class CreatePoolMemberAction(BaseAction):
api_type = 'loadbalancer'
def run(self, region, pool_id, node_id, port):
driver = self._get_lb_driver(region)
pool = driver.ex_get_pool(pool_id)
node = driver.ex_get_node(node_id)
member = driver.ex_create_pool_member(pool, node, port)
return self.resultsets.formatter(member)
|
Add url_validator function and respond aciton to test url
| from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
| from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
def url_validator(url):
try:
code = urllib.urlopen(url).getcode()
if code == 200:
return True
except:
return False
def test_url(message, url):
if url_validator(url[1:len(url)-1]):
message.reply('VALID URL')
else:
message.reply('NOT VALID URL')
|
Define noop close() for FakeFile
| import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
| import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
def close(self):
"""
Always hold fake files open.
"""
pass
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
|
Fix issues due to module rename
| #!/usr/bin/env python
# Copyright 2016 University of Chicago
# Licensed under the APL 2.0 license
import log
import log.handlers
import os
LOG_FILENAME = '~/logs/fsurf.log'
MAX_BYTES = 1024*1024*50 # 50 MB
NUM_BACKUPS = 10 # 10 files
def initialize_logging():
"""
Initialize logging for fsurf
:return: None
"""
logger = log.getLogger('fsurf')
log_file = os.path.abspath(os.path.expanduser(LOG_FILENAME))
handle = log.handlers.RotatingFileHandler(log_file,
mode='a',
maxBytes=MAX_BYTES,
backupCount=NUM_BACKUPS)
handle.setLevel(log.WARN)
logger.addHandler(handle)
def set_debugging():
"""
Configure logging to output debug messages
:return: None
"""
logger = log.getLogger('fsurf')
log_file = os.path.abspath(os.path.expanduser('~/logs/fsurf_debug.log'))
handle = log.FileHandler(log_file)
handle.setLevel(log.DEBUG)
logger.addHandler(handle)
def get_logger():
"""
Get logger that can be used for logging
:return: logger object
"""
return log.getLogger('fsurf') | #!/usr/bin/env python
# Copyright 2016 University of Chicago
# Licensed under the APL 2.0 license
import logging
import logging.handlers
import os
LOG_FILENAME = '~/logs/fsurf.log'
MAX_BYTES = 1024*1024*50 # 50 MB
NUM_BACKUPS = 10 # 10 files
def initialize_logging():
"""
Initialize logging for fsurf
:return: None
"""
logger = logging.getLogger('fsurf')
log_file = os.path.abspath(os.path.expanduser(LOG_FILENAME))
handle = logging.handlers.RotatingFileHandler(log_file,
mode='a',
maxBytes=MAX_BYTES,
backupCount=NUM_BACKUPS)
handle.setLevel(logging.WARN)
logger.addHandler(handle)
def set_debugging():
"""
Configure logging to output debug messages
:return: None
"""
logger = logging.getLogger('fsurf')
log_file = os.path.abspath(os.path.expanduser('~/logs/fsurf_debug.log'))
handle = logging.FileHandler(log_file)
handle.setLevel(logging.DEBUG)
logger.addHandler(handle)
def get_logger():
"""
Get logger that can be used for logging
:return: logger object
"""
return logging.getLogger('fsurf')
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 44