commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 0 2.94k | new_contents stringlengths 1 4.43k | subject stringlengths 15 444 | message stringlengths 16 3.45k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 5 43.2k | prompt stringlengths 17 4.58k | response stringlengths 1 4.43k | prompt_tagged stringlengths 58 4.62k | response_tagged stringlengths 1 4.43k | text stringlengths 132 7.29k | text_tagged stringlengths 173 7.33k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f454b3d66cb2cb19936ca591b7d873683eb1da5 | autoapi/base.py | autoapi/base.py | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.__dict__)
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
| from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.get_context_data())
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
def get_context_data(self):
return self.__dict__
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
| Make context output behavior overridable | Make context output behavior overridable
| Python | mit | rtfd/sphinx-autoapi,rtfd/sphinx-autoapi,rtfd/sphinx-autoapi,rtfd/sphinx-autoapi | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.__dict__)
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
Make context output behavior overridable | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.get_context_data())
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
def get_context_data(self):
return self.__dict__
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
| <commit_before>from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.__dict__)
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
<commit_msg>Make context output behavior overridable<commit_after> | from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.get_context_data())
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
def get_context_data(self):
return self.__dict__
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
| from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.__dict__)
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
Make context output behavior overridablefrom .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.get_context_data())
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
def get_context_data(self):
return self.__dict__
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
| <commit_before>from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.__dict__)
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
<commit_msg>Make context output behavior overridable<commit_after>from .settings import env
class AutoAPIBase(object):
language = 'base'
type = 'base'
def __init__(self, obj):
self.obj = obj
def render(self, ctx=None):
if not ctx:
ctx = {}
template = env.get_template(
'{language}/{type}.rst'.format(language=self.language, type=self.type)
)
ctx.update(**self.get_context_data())
return template.render(**ctx)
def get_absolute_path(self):
return "/autoapi/{type}/{name}".format(
type=self.type,
name=self.name,
)
def get_context_data(self):
return self.__dict__
class UnknownType(AutoAPIBase):
def render(self, ctx=None):
print "Unknown Type: %s" % (self.obj['type'])
super(UnknownType, self).render(ctx=ctx)
|
ccddc17f49d0e4a506cf2a967495f4da12358c41 | setup.py | setup.py | from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.11',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.11',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
| from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.12',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
| Fix bugs in item and user knn | Fix bugs in item and user knn
| Python | mit | ArthurFortes/CaseRecommender | from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.11',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.11',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
Fix bugs in item and user knn | from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.12',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
| <commit_before>from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.11',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.11',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
<commit_msg>Fix bugs in item and user knn<commit_after> | from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.12',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
| from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.11',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.11',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
Fix bugs in item and user knnfrom distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.12',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
| <commit_before>from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.11',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.11',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
<commit_msg>Fix bugs in item and user knn<commit_after>from distutils.core import setup
from setuptools import find_packages
__author__ = "Arthur Fortes"
setup(
name='CaseRecommender',
packages=find_packages(),
version='0.0.12',
license='GPL3 License',
description='A recommender systems framework for Python',
author='Arthur Fortes',
author_email='fortes.arthur@gmail.com',
url='https://github.com/ArthurFortes/CaseRecommender',
download_url='https://github.com/ArthurFortes/CaseRecommender/tarball/0.0.12',
keywords=['recommender systems', 'framework', 'collaborative filtering', 'content-based filtering'],
classifiers=[],
)
|
2d56080e18c44dcc6d49bba3b25fc2e4368cb1f4 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
| #!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/developersociety/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
| Update GitHub repos from blancltd to developersociety | Update GitHub repos from blancltd to developersociety
| Python | bsd-3-clause | developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter | #!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
Update GitHub repos from blancltd to developersociety | #!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/developersociety/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
| <commit_before>#!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
<commit_msg>Update GitHub repos from blancltd to developersociety<commit_after> | #!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/developersociety/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
| #!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
Update GitHub repos from blancltd to developersociety#!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/developersociety/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
| <commit_before>#!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/blancltd/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
<commit_msg>Update GitHub repos from blancltd to developersociety<commit_after>#!/usr/bin/env python
from setuptools import find_packages, setup
install_requires = [
'Django>=1.8,<1.10',
'django-mptt>=0.7',
'django-mptt-admin>=0.3',
'sorl-thumbnail>=12.2',
'django-taggit>=0.21.3',
'python-dateutil>=2.6.0',
]
setup(
name='django-glitter',
version='0.2',
description='Glitter for Django',
long_description=open('README.rst').read(),
url='https://github.com/developersociety/django-glitter',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
],
license='BSD',
install_requires=install_requires,
)
|
af01ceeb16f8c1f7bdaaf73065b048852b7b6df0 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
| from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio==0.36.0',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
| Fix rasterio to version 0.36.0 now that 1.0 is out | Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version.
| Python | apache-2.0 | ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project,ricardog/raster-project | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version. | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio==0.36.0',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
| <commit_before>from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
<commit_msg>Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version.<commit_after> | from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio==0.36.0',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
| from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version.from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio==0.36.0',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
| <commit_before>from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
<commit_msg>Fix rasterio to version 0.36.0 now that 1.0 is out
There are some incompatibilities between the two. Until I can go to NHM
to upgrade their setup, I'll pin it to the old version.<commit_after>from setuptools import setup, find_packages
setup(
name='projections',
version='0.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
'gdal',
'fiona',
'geopy',
'joblib',
'matplotlib',
'netCDF4',
'numba',
'numpy',
'pandas',
'pylru',
'pyparsing',
'rasterio==0.36.0',
'rpy2',
'setuptools',
'shapely',
'xlrd',
],
entry_points='''
[console_scripts]
extract_values=projections.scripts.extract_values:main
gen_hyde=projections.scripts.gen_hyde:main
gen_sps=projections.scripts.gen_sps:main
hyde2nc=projections.scripts.hyde2nc:main
nc_dump=projections.scripts.nc_dump:main
nctomp4=projections.scripts.nctomp4:main
project=projections.scripts.project:cli
r2py=projections.scripts.r2py:main
rview=projections.scripts.rview:main
tifftomp4=projections.scripts.tifftomp4:main
tiffcmp=projections.scripts.tiffcmp:main
''',
build_ext='''
include_dirs=/usr/local/include
'''
)
|
bf7d547e5fb6ef1d46fdf773318f32a139929590 | bottery/message.py | bottery/message.py | import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.fromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
| import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
| Use utcfromtimestamp instead of fromtimestamp on Message | Use utcfromtimestamp instead of fromtimestamp on Message
| Python | mit | rougeth/bottery | import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.fromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
Use utcfromtimestamp instead of fromtimestamp on Message | import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
| <commit_before>import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.fromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
<commit_msg>Use utcfromtimestamp instead of fromtimestamp on Message<commit_after> | import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
| import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.fromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
Use utcfromtimestamp instead of fromtimestamp on Messageimport os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
| <commit_before>import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.fromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
<commit_msg>Use utcfromtimestamp instead of fromtimestamp on Message<commit_after>import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
class Message:
def __init__(self, id, platform, user, text, timestamp, raw):
self.id = id
self.platform = platform
self.user = user
self.text = text
self.timestamp = timestamp
self.raw = raw
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user
}
default_context.update(context)
return template.render(**default_context)
|
85ffe172eb00c25d35990bab313be7a0194dddb1 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://github.com/asperous/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
) | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0.1',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://asperous.github.io/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
) | Add version number to reflect orderedict bug | Add version number to reflect orderedict bug
| Python | mit | andychase/pipeless | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://github.com/asperous/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
)Add version number to reflect orderedict bug | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0.1',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://asperous.github.io/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
) | <commit_before>#!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://github.com/asperous/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
)<commit_msg>Add version number to reflect orderedict bug<commit_after> | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0.1',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://asperous.github.io/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
) | #!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://github.com/asperous/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
)Add version number to reflect orderedict bug#!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0.1',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://asperous.github.io/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
) | <commit_before>#!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://github.com/asperous/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
)<commit_msg>Add version number to reflect orderedict bug<commit_after>#!/usr/bin/env python
from distutils.core import setup
setup(name='Pipeless',
version='1.0.1',
description='Simple pipelines building framework.',
long_description= \
""" [=|Pipeless|=] provides a simple framework
for building a data pipeline.
It's an advanced version of this:
function4(function3(function2(function1(0))))
It looks like this:
>>> function, run, _ = pipeline(lambda item, e: None)
>>> @function
... def up_one(): return lambda item: item+1
>>> list(run([0, 1, 3]))
[1, 2, 4]
>>> @function
... def twofer(): return lambda item: [item, item]
>>> list(run([0, 1, 3]))
[1, 1, 2, 2, 4, 4]
* Pipelines operate over sources
* Functions can return 1 Item, None to drop the item, or
a generator to expand the item.
Also provides a simple Optionally-Argumented NamedTuple and a Commmand Line Generator.
""",
author='Andy Chase',
author_email='andy@asperous.us',
url='http://asperous.github.io/pipeless',
download_url="https://github.com/asperous/pipeless/archive/master.zip",
license="MIT",
py_modules=['pipeless']
) |
1b94c9d46a349597e2c04858dfe9f2916af9f15b | setup.py | setup.py | import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
| import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
| Update classifiers through Python 3.6 | Update classifiers through Python 3.6 | Python | apache-2.0 | Tinche/aiofiles | import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
Update classifiers through Python 3.6 | import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
| <commit_before>import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
<commit_msg>Update classifiers through Python 3.6<commit_after> | import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
| import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
Update classifiers through Python 3.6import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
| <commit_before>import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
<commit_msg>Update classifiers through Python 3.6<commit_after>import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='tinchester@gmail.com',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
|
db0c911379e90254461a8888ba42ff65e0914240 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.5'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
| Bump minimal Django version in install_requires. | Bump minimal Django version in install_requires.
| Python | mit | zsiciarz/django-envelope,zsiciarz/django-envelope | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.5'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
Bump minimal Django version in install_requires. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
| <commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.5'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
<commit_msg>Bump minimal Django version in install_requires.<commit_after> | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.5'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
Bump minimal Django version in install_requires.import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
| <commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.5'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
<commit_msg>Bump minimal Django version in install_requires.<commit_after>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-envelope',
version=__import__('envelope').__version__,
description='A contact form app for Django',
long_description=read('README.rst'),
author='Zbigniew Siciarz',
author_email='zbigniew@siciarz.net',
url='http://github.com/zsiciarz/django-envelope',
download_url='http://pypi.python.org/pypi/django-envelope',
license='MIT',
install_requires=['Django>=1.8'],
packages=find_packages(exclude=['example_project', 'tests']),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT 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',
'Topic :: Utilities',
],
)
|
c61ce07bbf5ace2186e107c58f4a095789ae215c | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=['eventlet'],
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=find_packages(),
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
| Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages | Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages
| Python | mit | tempbottle/eventlet,tempbottle/eventlet,lindenlab/eventlet,lindenlab/eventlet,lindenlab/eventlet,collinstocks/eventlet,collinstocks/eventlet | #!/usr/bin/env python
from setuptools import setup
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=['eventlet'],
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=find_packages(),
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
| <commit_before>#!/usr/bin/env python
from setuptools import setup
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=['eventlet'],
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
<commit_msg>Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages<commit_after> | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=find_packages(),
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=['eventlet'],
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=find_packages(),
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
| <commit_before>#!/usr/bin/env python
from setuptools import setup
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=['eventlet'],
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
<commit_msg>Patch from Chuck Thier to properly install subpackages (eventlet.hubs and eventlet.support) now that we have subpackages<commit_after>#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='eventlet',
version='0.2',
description='Coroutine-based networking library',
author='Linden Lab',
author_email='eventletdev@lists.secondlife.com',
url='http://wiki.secondlife.com/wiki/Eventlet',
packages=find_packages(),
install_requires=['greenlet'],
long_description="""
Eventlet is a networking library written in Python. It achieves
high scalability by using non-blocking io while at the same time
retaining high programmer usability by using coroutines to make
the non-blocking io operations appear blocking at the source code
level.""",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers",
"Development Status :: 4 - Beta"]
)
|
44c14a9af100781645976aec1ae1bc700bd008b9 | setup.py | setup.py | from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
| from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy',
'matplotlib'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
| Add matplotlib to runtime dependencies. | Add matplotlib to runtime dependencies.
| Python | bsd-3-clause | emtpb/pyfds | from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
Add matplotlib to runtime dependencies. | from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy',
'matplotlib'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
| <commit_before>from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
<commit_msg>Add matplotlib to runtime dependencies.<commit_after> | from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy',
'matplotlib'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
| from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
Add matplotlib to runtime dependencies.from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy',
'matplotlib'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
| <commit_before>from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
<commit_msg>Add matplotlib to runtime dependencies.<commit_after>from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme_file:
long_description = readme_file.read()
setup(
name='pyfds',
description='Modular field simulation tool using finite differences.',
long_description=long_description,
url='http://emt.uni-paderborn.de',
author='Leander Claes',
author_email='claes@emt.uni-paderborn.de',
license='Proprietary',
# Automatically generate version number from git tags
use_scm_version=True,
packages=[
'pyfds'
],
# Runtime dependencies
install_requires=[
'numpy',
'scipy',
'matplotlib'
],
# Setup/build dependencies; setuptools_scm required for git-based versioning
setup_requires=['setuptools_scm'],
# For a list of valid classifiers, see
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for full list.
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: Other/Proprietary License',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
],
)
|
727cda368514f15ec53ef195ffcd6161d0796521 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
],
)
| #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
'PermissionsLogging',
],
)
| Add PermissionsLogging for log files. | Add PermissionsLogging for log files.
| Python | apache-2.0 | uw-it-aca/spacescout_web,uw-it-aca/spacescout_web,uw-it-aca/spacescout_web | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
],
)
Add PermissionsLogging for log files. | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
'PermissionsLogging',
],
)
| <commit_before>#!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
],
)
<commit_msg>Add PermissionsLogging for log files.<commit_after> | #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
'PermissionsLogging',
],
)
| #!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
],
)
Add PermissionsLogging for log files.#!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
'PermissionsLogging',
],
)
| <commit_before>#!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
],
)
<commit_msg>Add PermissionsLogging for log files.<commit_after>#!/usr/bin/env python
from distutils.core import setup
setup(name='SpaceScout-Web',
version='1.0',
description='Web frontend for SpaceScout',
install_requires=[
'Django>=1.4,<1.5',
'oauth2',
'oauth_provider',
'django-compressor<2.0',
'django-mobility',
'django-templatetag-handlebars',
'simplejson',
'python-ldap',
'mock<=1.0.1',
'PermissionsLogging',
],
)
|
2bf87e4417257518e7d43bd421eaccd555fc4f4c | setup.py | setup.py | import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/dcramer/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
| import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/coffin/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
| Fix URL to point to a valid repo | Fix URL to point to a valid repo
| Python | bsd-3-clause | rossowl/coffin,akx/coffin,rossowl/coffin | import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/dcramer/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
Fix URL to point to a valid repo | import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/coffin/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
| <commit_before>import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/dcramer/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
<commit_msg>Fix URL to point to a valid repo<commit_after> | import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/coffin/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
| import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/dcramer/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
Fix URL to point to a valid repoimport os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/coffin/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
| <commit_before>import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/dcramer/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
<commit_msg>Fix URL to point to a valid repo<commit_after>import os
from setuptools import setup, find_packages
setup(name='Coffin',
version=".".join(map(str, __import__("coffin").__version__)),
description='Jinja2 adapter for Django',
author='Christopher D. Leary',
author_email='cdleary@gmail.com',
maintainer='David Cramer',
maintainer_email='dcramer@gmail.com',
url='http://github.com/coffin/coffin',
packages=find_packages(),
#install_requires=['Jinja2', 'django>=1.2'],
classifiers=[
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development"
],
)
|
11fc4fe8ad5caa072ed0827762a2f75319deec82 | setup.py | setup.py | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| Update the PyPI version to 7.0.11. | Update the PyPI version to 7.0.11.
| Python | mit | Doist/todoist-python | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
Update the PyPI version to 7.0.11. | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| <commit_before># -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
<commit_msg>Update the PyPI version to 7.0.11.<commit_after> | # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| # -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
Update the PyPI version to 7.0.11.# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
| <commit_before># -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
<commit_msg>Update the PyPI version to 7.0.11.<commit_after># -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.11',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
a3125b11e6f509b2d80cf989440bd99c713242a4 | setup.py | setup.py | #!/usr/bin/python
import os
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
| #!/usr/bin/python3
import os
from distutils.core import setup
from io import open
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), encoding='utf8').read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
| Read the README file with UTF-8 encoding. | Read the README file with UTF-8 encoding.
This commit fixes an install issue in Python 3.5 where the read() function raises an encoding error. It uses
the open function from the io module so that the code will be compatible with both Python 2 and 3.
| Python | bsd-2-clause | tamentis/rpdb | #!/usr/bin/python
import os
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
Read the README file with UTF-8 encoding.
This commit fixes an install issue in Python 3.5 where the read() function raises an encoding error. It uses
the open function from the io module so that the code will be compatible with both Python 2 and 3. | #!/usr/bin/python3
import os
from distutils.core import setup
from io import open
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), encoding='utf8').read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
| <commit_before>#!/usr/bin/python
import os
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
<commit_msg>Read the README file with UTF-8 encoding.
This commit fixes an install issue in Python 3.5 where the read() function raises an encoding error. It uses
the open function from the io module so that the code will be compatible with both Python 2 and 3.<commit_after> | #!/usr/bin/python3
import os
from distutils.core import setup
from io import open
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), encoding='utf8').read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
| #!/usr/bin/python
import os
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
Read the README file with UTF-8 encoding.
This commit fixes an install issue in Python 3.5 where the read() function raises an encoding error. It uses
the open function from the io module so that the code will be compatible with both Python 2 and 3.#!/usr/bin/python3
import os
from distutils.core import setup
from io import open
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), encoding='utf8').read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
| <commit_before>#!/usr/bin/python
import os
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
<commit_msg>Read the README file with UTF-8 encoding.
This commit fixes an install issue in Python 3.5 where the read() function raises an encoding error. It uses
the open function from the io module so that the code will be compatible with both Python 2 and 3.<commit_after>#!/usr/bin/python3
import os
from distutils.core import setup
from io import open
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), encoding='utf8').read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name="rpdb",
version="0.1.6",
description="pdb wrapper with remote access via tcp socket",
long_description=README + "\n\n" + CHANGES,
author="Bertrand Janin",
author_email="b@janin.com",
url="http://tamentis.com/projects/rpdb",
packages=["rpdb"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.0",
"Programming Language :: Python :: 3.1",
"Topic :: Software Development :: Debuggers",
]
)
|
264143c5208df1afa20eceff286849ca8362e5a7 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'mock==1.0.1',
'xworkflows==1.0.0',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'xworkflows==1.0.0',
],
tests_require=[
'mock==1.0.1',
'py.test>=2.8.5',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
| Make test dependencies more explicit | Make test dependencies more explicit
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'mock==1.0.1',
'xworkflows==1.0.0',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
Make test dependencies more explicit | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'xworkflows==1.0.0',
],
tests_require=[
'mock==1.0.1',
'py.test>=2.8.5',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'mock==1.0.1',
'xworkflows==1.0.0',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
<commit_msg>Make test dependencies more explicit<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'xworkflows==1.0.0',
],
tests_require=[
'mock==1.0.1',
'py.test>=2.8.5',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'mock==1.0.1',
'xworkflows==1.0.0',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
Make test dependencies more explicit#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'xworkflows==1.0.0',
],
tests_require=[
'mock==1.0.1',
'py.test>=2.8.5',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'mock==1.0.1',
'xworkflows==1.0.0',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
<commit_msg>Make test dependencies more explicit<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
root = os.path.abspath(os.path.dirname(__file__))
version = __import__('swf').__version__
with open(os.path.join(root, 'README.rst')) as f:
README = f.read()
setup(
name='simple-workflow',
version=version,
license='MIT',
description='Amazon simple workflow service wrapper for python',
long_description=README + '\n\n',
author='Oleiade',
author_email='tcrevon@gmail.com',
url='http://github.com/botify-labs/python-simple-workflow',
keywords='amazon simple wokflow swf python',
zip_safe=True,
install_requires=[
'boto',
'xworkflows==1.0.0',
],
tests_require=[
'mock==1.0.1',
'py.test>=2.8.5',
],
package_dir={'': '.'},
include_package_data=False,
packages=[
'swf',
'swf.actors',
'swf.querysets',
'swf.models',
'swf.models.event',
'swf.models.decision',
'swf.models.history',
],
)
|
1e1ee9998a5e1461b1688d55218d793402fbb4d7 | setup.py | setup.py | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
| import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['Django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
| Use the official notation of the Django package | Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible. | Python | bsd-3-clause | tubaman/django-macaddress | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible. | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['Django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
| <commit_before>import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
<commit_msg>Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible.<commit_after> | import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['Django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
| import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible.import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['Django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
| <commit_before>import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
<commit_msg>Use the official notation of the Django package
Even if pypi is case insensitive, all other packages include django with an uppercase D.
This package using lowercase will lead to uninstalls/reinstalls when using pip-compile and other tools.
Please accept the change to make it compatible.<commit_after>import os
from setuptools import setup, find_packages
version = "1.4.0"
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-macaddress",
version = version,
url = 'http://github.com/tubaman/django-macaddress',
license = 'BSD',
description = "MAC address model and form fields for Django apps.",
long_description = read('README.rst'),
author = 'Ryan Nowakowski',
author_email = 'tubaman@fattuba.com',
maintainer = 'Arun K. R.',
maintainer_email = 'the1.arun@gmail.com',
packages = ['macaddress', 'macaddress.tests'],
install_requires = ['netaddr'],
tests_require = ['Django'],
test_suite="runtests.runtests",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
)
|
df91e2840e84ecbcf74a46eb40c467dfe7d9a21e | setup.py | setup.py | """Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| """Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5/releases/tag/v0.1',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| Change url to point to tagged release | Change url to point to tagged release
| Python | mit | richmilne/pymd5 | """Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
Change url to point to tagged release | """Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5/releases/tag/v0.1',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| <commit_before>"""Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
<commit_msg>Change url to point to tagged release<commit_after> | """Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5/releases/tag/v0.1',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| """Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
Change url to point to tagged release"""Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5/releases/tag/v0.1',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
| <commit_before>"""Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
<commit_msg>Change url to point to tagged release<commit_after>"""Setup for pymd5 module and command-line script."""
from setuptools import setup
def readme():
"""Use text contained in README.rst as long description."""
with open('README.rst') as desc:
return desc.read()
setup(name='pymd5',
version='0.1',
description=('Recursively calculate and display MD5 file hashes '
'for all files rooted in a directory.'),
long_description=readme(),
url='https://github.com/richmilne/pymd5/releases/tag/v0.1',
author='Richard Milne',
author_email='richmilne@hotmail.com',
license='MIT',
packages=['pymd5'],
include_package_data=True,
entry_points={
'console_scripts': ['pymd5=pymd5:_read_args']
},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
|
cb41b0ab31e42165f8a525edf2332d15986f7168 | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic_discourse_sso',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
| from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic-discourse-sso',
license='Apache 2.0',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
| Correct some Python package metadata | Correct some Python package metadata
| Python | apache-2.0 | ImageMarkup/discourse_sso,ImageMarkup/discourse_sso,ImageMarkup/discourse_sso | from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic_discourse_sso',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
Correct some Python package metadata | from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic-discourse-sso',
license='Apache 2.0',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
| <commit_before>from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic_discourse_sso',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
<commit_msg>Correct some Python package metadata<commit_after> | from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic-discourse-sso',
license='Apache 2.0',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
| from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic_discourse_sso',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
Correct some Python package metadatafrom setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic-discourse-sso',
license='Apache 2.0',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
| <commit_before>from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic_discourse_sso',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
<commit_msg>Correct some Python package metadata<commit_after>from setuptools import find_packages, setup
setup(
name='isic-discourse-sso',
version='1.0.0',
description='Girder plugin for a Discourse Single-Sign-On provider.',
url='https://github.com/ImageMarkup/isic-discourse-sso',
license='Apache 2.0',
packages=find_packages(exclude=['test']),
python_requires='>=3.6',
install_requires=['girder>=3.0.0a2'],
entry_points={'girder.plugin': ['isic_discourse_sso = isic_discourse_sso:DiscourseSSO']},
)
|
f166d8aeb3bd6aa79813548068b5c6f687d8f26b | setup.py | setup.py | from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"numpy",
"requests",
"scipy" # I tried getting rid of this, but numpy is shit so [](#yuishrug)
]
}
setup( **settings ) | from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"requests"
]
}
setup( **settings )
| Remove scipy and numpy deps | Remove scipy and numpy deps
| Python | mit | erkghlerngm44/malaffinity | from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"numpy",
"requests",
"scipy" # I tried getting rid of this, but numpy is shit so [](#yuishrug)
]
}
setup( **settings )Remove scipy and numpy deps | from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"requests"
]
}
setup( **settings )
| <commit_before>from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"numpy",
"requests",
"scipy" # I tried getting rid of this, but numpy is shit so [](#yuishrug)
]
}
setup( **settings )<commit_msg>Remove scipy and numpy deps<commit_after> | from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"requests"
]
}
setup( **settings )
| from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"numpy",
"requests",
"scipy" # I tried getting rid of this, but numpy is shit so [](#yuishrug)
]
}
setup( **settings )Remove scipy and numpy depsfrom setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"requests"
]
}
setup( **settings )
| <commit_before>from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"numpy",
"requests",
"scipy" # I tried getting rid of this, but numpy is shit so [](#yuishrug)
]
}
setup( **settings )<commit_msg>Remove scipy and numpy deps<commit_after>from setuptools import setup
from codecs import open
from os import path
# Open up settings
here = path.abspath(path.dirname(__file__))
about = {}
with open(path.join(here, "README.rst"), encoding="utf-8") as file:
long_description = file.read()
with open(path.join(here, "malaffinity", "__about__.py")) as file:
exec(file.read(), about)
settings = {
"name": about["__title__"],
"version": about["__version__"],
"description": about["__summary__"],
"long_description": long_description,
"url": about["__uri__"],
"author": about["__author__"],
"author_email": about["__email__"],
"license": about["__license__"],
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
],
"keywords": "affinity mal myanimelist",
"packages": ["malaffinity"],
"install_requires": [
"bs4",
"requests"
]
}
setup( **settings )
|
b39d23cf2181d5d5af9c49a890c58fb19f2aad64 | setup.py | setup.py | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.4',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
| #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.5',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
| Tag version 0.5 with bytes/text fix | Tag version 0.5 with bytes/text fix
| Python | isc | tgs/requests-jwt | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.4',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
Tag version 0.5 with bytes/text fix | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.5',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
| <commit_before>#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.4',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
<commit_msg>Tag version 0.5 with bytes/text fix<commit_after> | #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.5',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
| #!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.4',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
Tag version 0.5 with bytes/text fix#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.5',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
| <commit_before>#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.4',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
<commit_msg>Tag version 0.5 with bytes/text fix<commit_after>#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='requests-jwt',
version='0.5',
url='https://github.com/tgs/requests-jwt',
modules=['requests_jwt'],
install_requires=[ 'requests', 'PyJWT' ],
tests_require=['httpretty'],
test_suite='tests.suite',
provides=[ 'requests_jwt' ],
author='Thomas Grenfell Smith',
author_email='thomathom@gmail.com',
description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.',
license='ISC',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
'License :: OSI Approved :: ISC License (ISCL)',
],
)
|
21d19c32eb93e34dfba3f66cc44ab36685fd018c | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.4'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.5'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
| Update aiohttp version constraint to <3.5 | Update aiohttp version constraint to <3.5 | Python | apache-2.0 | pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc,pengutronix/aiohttp-json-rpc | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.4'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
Update aiohttp version constraint to <3.5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.5'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.4'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
<commit_msg>Update aiohttp version constraint to <3.5<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.5'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.4'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
Update aiohttp version constraint to <3.5#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.5'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.4'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
<commit_msg>Update aiohttp version constraint to <3.5<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__name__ == '__main__' and setup(name='aiohttp-json-rpc',
version='0.11.1',
author='Florian Scherf',
url='https://github.com/pengutronix/aiohttp-json-rpc/',
author_email='f.scherf@pengutronix.de',
license='Apache 2.0',
install_requires=['aiohttp>=3,<3.5'],
python_requires='>=3.5',
packages=find_packages(),
zip_safe=False,
entry_points={
'pytest11': [
'aiohttp-json-rpc = aiohttp_json_rpc.pytest',
]
})
|
1a09dca23b62e815cbce0860fe5786f51d5f207c | setup.py | setup.py | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
| Change package version to 0.5.0 | Change package version to 0.5.0
| Python | bsd-3-clause | vmalyi/adb_android | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
Change package version to 0.5.0 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
| <commit_before>#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
<commit_msg>Change package version to 0.5.0<commit_after> | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
Change package version to 0.5.0#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
| <commit_before>#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.4.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
<commit_msg>Change package version to 0.5.0<commit_after>#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [
]
test_requirements = [
]
setup(
name='adb_android',
version='0.5.0',
description="Enables android adb in your python script",
long_description='This python package is a wrapper for standard android adb\
implementation. It allows you to execute android adb commands in your \
python script.',
author='Viktor Malyi',
author_email='v.stratus@gmail.com',
url='https://github.com/vmalyi/adb_android',
packages=[
'adb_android',
],
package_dir={'adb_android':'adb_android'},
include_package_data=True,
install_requires=requirements,
license="GNU",
keywords='adb, android',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Topic :: Software Development :: Testing',
'Intended Audience :: Developers'
],
test_suite='tests',
)
|
46d89e06f9b6fbc06b72bb50b84b1dd28887fd09 | setup.py | setup.py | import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
| import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt']},
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
| Fix another problem where package data was not included | Fix another problem where package data was not included
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
Fix another problem where package data was not included | import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt']},
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
| <commit_before>import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
<commit_msg>Fix another problem where package data was not included<commit_after> | import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt']},
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
| import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
Fix another problem where package data was not includedimport sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt']},
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
| <commit_before>import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
<commit_msg>Fix another problem where package data was not included<commit_after>import sys
from chandra_aca import __version__
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.args = []
def run_tests(self):
# Import here because outside the eggs aren't loaded
import pytest
errno = pytest.main(self.args)
sys.exit(errno)
setup(name='chandra_aca',
author='Jean Connelly, Tom Aldcroft',
description='Chandra Aspect Camera Tools',
author_email='jconnelly@cfa.harvard.edu',
version=__version__,
zip_safe=False,
packages=['chandra_aca', 'chandra_aca.tests'],
package_data={'chandra_aca.tests': ['data/*.txt']},
tests_require=['pytest'],
cmdclass={'test': PyTest},
)
|
2b4c1f32e75c5884179d58b9fc27d19336677181 | setup.py | setup.py | from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.0",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
)
| from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.5",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| Add python 3 compatibility in pip install | Add python 3 compatibility in pip install
| Python | mit | supercast-tv/python-mpd-parser,caststack/python-mpegdash,caststack/python-mpd-parser | from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.0",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
)
Add python 3 compatibility in pip install | from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.5",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| <commit_before>from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.0",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
)
<commit_msg>Add python 3 compatibility in pip install<commit_after> | from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.5",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.0",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
)
Add python 3 compatibility in pip installfrom os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.5",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| <commit_before>from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.0",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
)
<commit_msg>Add python 3 compatibility in pip install<commit_after>from os.path import dirname, abspath, join, exists
from setuptools import setup
long_description = None
if exists("README.md"):
long_description = open("README.md").read()
install_reqs = [req for req in open(abspath(join(dirname(__file__), 'requirements.txt')))]
tests_reqs = [req for req in open(abspath(join(dirname(__file__), 'test-requirements.txt')))]
setup(
name="mpegdash",
packages=["mpegdash"],
description="MPEG-DASH MPD(Media Presentation Description) Parser",
long_description=long_description,
author="supercast",
author_email="gamzabaw@gmail.com",
version="0.1.5",
license="MIT",
zip_safe=False,
include_package_data=True,
install_requires=install_reqs,
url="https://github.com/caststack/python-mpegdash",
tests_require=tests_reqs,
test_suite="tests.my_module_suite",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
54b3663206d80aa2dbe4f93c6f8ce9fc45424bf3 | src/rf/apps/home/urls.py | src/rf/apps/home/urls.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/',
FavoriteCreateDestroyView.as_view()),
url(r'layers/', LayerListView.as_view()),
url(r'', home_page, name='home_page'),
)
| # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/$',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/$',
FavoriteCreateDestroyView.as_view()),
url(r'layers/$', LayerListView.as_view()),
url(r'^$', home_page, name='home_page'),
url(r'login/$', home_page),
url(r'sign-up/$', home_page),
url(r'send-activation/$', home_page),
url(r'forgot/$', home_page),
url(r'logout/$', home_page),
url(r'activate/$', home_page),
)
| Add URLs to redirect to home_page | Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404.
| Python | apache-2.0 | azavea/raster-foundry,aaronxsu/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,kdeloach/raster-foundry,kdeloach/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,kdeloach/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,aaronxsu/raster-foundry | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/',
FavoriteCreateDestroyView.as_view()),
url(r'layers/', LayerListView.as_view()),
url(r'', home_page, name='home_page'),
)
Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404. | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/$',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/$',
FavoriteCreateDestroyView.as_view()),
url(r'layers/$', LayerListView.as_view()),
url(r'^$', home_page, name='home_page'),
url(r'login/$', home_page),
url(r'sign-up/$', home_page),
url(r'send-activation/$', home_page),
url(r'forgot/$', home_page),
url(r'logout/$', home_page),
url(r'activate/$', home_page),
)
| <commit_before># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/',
FavoriteCreateDestroyView.as_view()),
url(r'layers/', LayerListView.as_view()),
url(r'', home_page, name='home_page'),
)
<commit_msg>Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404.<commit_after> | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/$',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/$',
FavoriteCreateDestroyView.as_view()),
url(r'layers/$', LayerListView.as_view()),
url(r'^$', home_page, name='home_page'),
url(r'login/$', home_page),
url(r'sign-up/$', home_page),
url(r'send-activation/$', home_page),
url(r'forgot/$', home_page),
url(r'logout/$', home_page),
url(r'activate/$', home_page),
)
| # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/',
FavoriteCreateDestroyView.as_view()),
url(r'layers/', LayerListView.as_view()),
url(r'', home_page, name='home_page'),
)
Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404.# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/$',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/$',
FavoriteCreateDestroyView.as_view()),
url(r'layers/$', LayerListView.as_view()),
url(r'^$', home_page, name='home_page'),
url(r'login/$', home_page),
url(r'sign-up/$', home_page),
url(r'send-activation/$', home_page),
url(r'forgot/$', home_page),
url(r'logout/$', home_page),
url(r'activate/$', home_page),
)
| <commit_before># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/',
FavoriteCreateDestroyView.as_view()),
url(r'layers/', LayerListView.as_view()),
url(r'', home_page, name='home_page'),
)
<commit_msg>Add URLs to redirect to home_page
Also refine some other URLs, so that, for example, layers/blah will result in a 404.<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from rest_framework.routers import SimpleRouter
from apps.home.views import (home_page,
UserLayerViewSet,
LayerListView,
FavoriteListView,
FavoriteCreateDestroyView)
username_regex = r'[\w.@+-]+'
slug_regex = r'[-_\w]+'
# Use router for UserLayerViewSet to generate urls automatically. This
# can only be done for ViewSets.
router = SimpleRouter()
router.register(r'user/(?P<username>' + username_regex + r')/layers',
UserLayerViewSet, base_name='user_layers')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'user/(?P<username>' + username_regex + r')/favorites/$',
FavoriteListView.as_view()),
url(r'user/(?P<username>' + username_regex + r')/layers/(?P<slug>' +
slug_regex + r')/favorite/$',
FavoriteCreateDestroyView.as_view()),
url(r'layers/$', LayerListView.as_view()),
url(r'^$', home_page, name='home_page'),
url(r'login/$', home_page),
url(r'sign-up/$', home_page),
url(r'send-activation/$', home_page),
url(r'forgot/$', home_page),
url(r'logout/$', home_page),
url(r'activate/$', home_page),
)
|
f9b3670732d6b211e69873b098dd6f0f3de2f0cb | call_subprocess.py | call_subprocess.py | """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import call
def call_and_check_errors():
call_args = ('wc', '-l', 'my_file')
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
if '__main__' == __name__:
call_and_check_errors()
| """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import CalledProcessError, call, check_output
import sys
def call_and_check_errors():
call_args = ('touch', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
def call_and_get_output():
call_args = ('wc', '-l', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
try:
stdout = check_output(call_args)
print(stdout)
except CalledProcessError:
print('Error during call.')
if '__main__' == __name__:
call_and_get_output()
| Add call subprocess and print output | Add call subprocess and print output
| Python | mit | MattMS/Python_3_examples | """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import call
def call_and_check_errors():
call_args = ('wc', '-l', 'my_file')
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
if '__main__' == __name__:
call_and_check_errors()
Add call subprocess and print output | """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import CalledProcessError, call, check_output
import sys
def call_and_check_errors():
call_args = ('touch', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
def call_and_get_output():
call_args = ('wc', '-l', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
try:
stdout = check_output(call_args)
print(stdout)
except CalledProcessError:
print('Error during call.')
if '__main__' == __name__:
call_and_get_output()
| <commit_before>"""
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import call
def call_and_check_errors():
call_args = ('wc', '-l', 'my_file')
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
if '__main__' == __name__:
call_and_check_errors()
<commit_msg>Add call subprocess and print output<commit_after> | """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import CalledProcessError, call, check_output
import sys
def call_and_check_errors():
call_args = ('touch', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
def call_and_get_output():
call_args = ('wc', '-l', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
try:
stdout = check_output(call_args)
print(stdout)
except CalledProcessError:
print('Error during call.')
if '__main__' == __name__:
call_and_get_output()
| """
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import call
def call_and_check_errors():
call_args = ('wc', '-l', 'my_file')
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
if '__main__' == __name__:
call_and_check_errors()
Add call subprocess and print output"""
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import CalledProcessError, call, check_output
import sys
def call_and_check_errors():
call_args = ('touch', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
def call_and_get_output():
call_args = ('wc', '-l', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
try:
stdout = check_output(call_args)
print(stdout)
except CalledProcessError:
print('Error during call.')
if '__main__' == __name__:
call_and_get_output()
| <commit_before>"""
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import call
def call_and_check_errors():
call_args = ('wc', '-l', 'my_file')
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
if '__main__' == __name__:
call_and_check_errors()
<commit_msg>Add call subprocess and print output<commit_after>"""
Demo of calling subprocesses.
Links
-----
- https://docs.python.org/3/library/io.html
- https://docs.python.org/3/library/subprocess.html
"""
from subprocess import CalledProcessError, call, check_output
import sys
def call_and_check_errors():
call_args = ('touch', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
result = call(call_args)
if 0 != result:
print('Error during call.')
def call_and_get_output():
call_args = ('wc', '-l', sys.argv[0])
call_args_str = ' '.join(call_args)
print(call_args_str)
try:
stdout = check_output(call_args)
print(stdout)
except CalledProcessError:
print('Error during call.')
if '__main__' == __name__:
call_and_get_output()
|
4c1237d2969d735cfcf9f3c10cf27cb801996e32 | tests/test_integration.py | tests/test_integration.py | """Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
| """Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
| Use Sauce Labs for selenium testing when available | Use Sauce Labs for selenium testing when available
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal | """Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
Use Sauce Labs for selenium testing when available | """Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
| <commit_before>"""Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
<commit_msg>Use Sauce Labs for selenium testing when available<commit_after> | """Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
| """Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
Use Sauce Labs for selenium testing when available"""Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
| <commit_before>"""Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
<commit_msg>Use Sauce Labs for selenium testing when available<commit_after>"""Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
|
c7beb58c8f5d6f0efd0f7abeb608f9de27a3ac28 | src/waldur_mastermind/marketplace_rancher/processors.py | src/waldur_mastermind/marketplace_rancher/processors.py | from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
| from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
'security_groups',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
| Allow to pass security_groups from marketplace to Rancher plugin. | Allow to pass security_groups from marketplace to Rancher plugin.
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur | from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
Allow to pass security_groups from marketplace to Rancher plugin. | from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
'security_groups',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
| <commit_before>from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
<commit_msg>Allow to pass security_groups from marketplace to Rancher plugin.<commit_after> | from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
'security_groups',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
| from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
Allow to pass security_groups from marketplace to Rancher plugin.from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
'security_groups',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
| <commit_before>from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
<commit_msg>Allow to pass security_groups from marketplace to Rancher plugin.<commit_after>from waldur_mastermind.marketplace import processors
from waldur_rancher import views as rancher_views
class RancherCreateProcessor(processors.BaseCreateResourceProcessor):
viewset = rancher_views.ClusterViewSet
fields = (
'name',
'description',
'nodes',
'tenant_settings',
'ssh_public_key',
'install_longhorn',
'security_groups',
)
class RancherDeleteProcessor(processors.DeleteResourceProcessor):
viewset = rancher_views.ClusterViewSet
|
9148b45f05fbc7697864967d343b0b63d91fa33b | temba/msgs/migrations/0037_backfill_recipient_counts.py | temba/msgs/migrations/0037_backfill_recipient_counts.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if broadcast.recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
| Add migration to backfill recipient counts | Add migration to backfill recipient counts
| Python | agpl-3.0 | reyrodrigues/EU-SMS,tsotetsi/textily-web,pulilab/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,ewheeler/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,reyrodrigues/EU-SMS,pulilab/rapidpro,tsotetsi/textily-web,reyrodrigues/EU-SMS,ewheeler/rapidpro,tsotetsi/textily-web,ewheeler/rapidpro | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
Add migration to backfill recipient counts | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if broadcast.recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
<commit_msg>Add migration to backfill recipient counts<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if broadcast.recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
Add migration to backfill recipient counts# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if broadcast.recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
<commit_msg>Add migration to backfill recipient counts<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0036_auto_20151103_1014'),
]
def backfill_recipient_counts(apps, schema):
Broadcast = apps.get_model('msgs', 'Broadcast')
Msg = apps.get_model('msgs', 'Msg')
# get all broadcasts with 0 recipients
for broadcast in Broadcast.objects.filter(recipient_count=0):
# set to # of msgs
broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()
if broadcast.recipient_count > 0:
broadcast.save()
print "Updated %d to %d recipients" % (broadcast.id, broadcast.recipient_count)
operations = [
migrations.RunPython(backfill_recipient_counts)
]
|
7c0db5fb36f082cfe95c4969df4cc15d1c88578d | icforum/forum/forms.py | icforum/forum/forms.py | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
| from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise forms.ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
| Fix bug on sign in page when invalid credentials are given | Fix bug on sign in page when invalid credentials are given
| Python | apache-2.0 | rdujardin/icforum,rdujardin/icforum,rdujardin/icforum | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
Fix bug on sign in page when invalid credentials are given | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise forms.ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
| <commit_before>from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
<commit_msg>Fix bug on sign in page when invalid credentials are given<commit_after> | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise forms.ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
| from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
Fix bug on sign in page when invalid credentials are givenfrom django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise forms.ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
| <commit_before>from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
<commit_msg>Fix bug on sign in page when invalid credentials are given<commit_after>from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise forms.ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
class EditMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="Edit message", widget=forms.Textarea)
|
eee3ec1df295b51979f031e4fa7e6476cbb9a167 | ideasbox/blog/forms.py | ideasbox/blog/forms.py | from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
},
fields = "__all__"
| from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
}
fields = "__all__"
| Remove comma turning dict to tuple without my consent | Remove comma turning dict to tuple without my consent
| Python | agpl-3.0 | ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube | from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
},
fields = "__all__"
Remove comma turning dict to tuple without my consent | from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
}
fields = "__all__"
| <commit_before>from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
},
fields = "__all__"
<commit_msg>Remove comma turning dict to tuple without my consent<commit_after> | from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
}
fields = "__all__"
| from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
},
fields = "__all__"
Remove comma turning dict to tuple without my consentfrom django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
}
fields = "__all__"
| <commit_before>from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
},
fields = "__all__"
<commit_msg>Remove comma turning dict to tuple without my consent<commit_after>from django import forms
from .models import Content
class ContentForm(forms.ModelForm):
class Meta:
model = Content
widgets = {
# We need a normalized date string for JS datepicker, so we take
# control over the format to bypass L10N.
"published_at": forms.DateInput(format='%Y-%m-%d')
}
fields = "__all__"
|
3a2daf3c5acc9489705de13ffac8efce5c81c736 | pyrpl/test/test_redpitaya.py | pyrpl/test/test_redpitaya.py | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname)
self.assertEqual(r.hk.led, 0)
| # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_password(self):
self.assertIsNotNone(
self.password,
msg="Set RP_PASSWORD=<your redpitaya password> to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname, password=self.password)
self.assertEqual(r.hk.led, 0)
| Update test_connect to read password from env. variable | Update test_connect to read password from env. variable
| Python | mit | lneuhaus/pyrpl,lneuhaus/pyrpl,lneuhaus/pyrpl,lneuhaus/pyrpl | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname)
self.assertEqual(r.hk.led, 0)
Update test_connect to read password from env. variable | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_password(self):
self.assertIsNotNone(
self.password,
msg="Set RP_PASSWORD=<your redpitaya password> to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname, password=self.password)
self.assertEqual(r.hk.led, 0)
| <commit_before># unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname)
self.assertEqual(r.hk.led, 0)
<commit_msg>Update test_connect to read password from env. variable<commit_after> | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_password(self):
self.assertIsNotNone(
self.password,
msg="Set RP_PASSWORD=<your redpitaya password> to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname, password=self.password)
self.assertEqual(r.hk.led, 0)
| # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname)
self.assertEqual(r.hk.led, 0)
Update test_connect to read password from env. variable# unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_password(self):
self.assertIsNotNone(
self.password,
msg="Set RP_PASSWORD=<your redpitaya password> to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname, password=self.password)
self.assertEqual(r.hk.led, 0)
| <commit_before># unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname)
self.assertEqual(r.hk.led, 0)
<commit_msg>Update test_connect to read password from env. variable<commit_after># unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_password(self):
self.assertIsNotNone(
self.password,
msg="Set RP_PASSWORD=<your redpitaya password> to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname, password=self.password)
self.assertEqual(r.hk.led, 0)
|
55af5785d1aedff028f85229af691d5f59ba434a | python_cowbull_server/__init__.py | python_cowbull_server/__init__.py | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import argparse
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
#
# Step 1 - Check any command line arguments passed
#
parser = argparse.ArgumentParser()
parser.add_argument('--env',
dest='showenvvars',
default=False,
action='store_true',
help="Show the environment variables that can be set by this app")
args = parser.parse_args()
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
# Decide if using ANSI or GUI
if args.showenvvars:
print('')
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('')
exit(0)
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
) | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
print('')
print('-'*80)
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('-'*80)
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('-'*80)
print('')
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
) | Remove parameter support (due to unittest module) and modify to print parameters on each run. | Remove parameter support (due to unittest module) and modify to print parameters on each run.
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import argparse
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
#
# Step 1 - Check any command line arguments passed
#
parser = argparse.ArgumentParser()
parser.add_argument('--env',
dest='showenvvars',
default=False,
action='store_true',
help="Show the environment variables that can be set by this app")
args = parser.parse_args()
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
# Decide if using ANSI or GUI
if args.showenvvars:
print('')
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('')
exit(0)
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
)Remove parameter support (due to unittest module) and modify to print parameters on each run. | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
print('')
print('-'*80)
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('-'*80)
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('-'*80)
print('')
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
) | <commit_before># Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import argparse
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
#
# Step 1 - Check any command line arguments passed
#
parser = argparse.ArgumentParser()
parser.add_argument('--env',
dest='showenvvars',
default=False,
action='store_true',
help="Show the environment variables that can be set by this app")
args = parser.parse_args()
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
# Decide if using ANSI or GUI
if args.showenvvars:
print('')
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('')
exit(0)
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
)<commit_msg>Remove parameter support (due to unittest module) and modify to print parameters on each run.<commit_after> | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
print('')
print('-'*80)
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('-'*80)
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('-'*80)
print('')
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
) | # Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import argparse
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
#
# Step 1 - Check any command line arguments passed
#
parser = argparse.ArgumentParser()
parser.add_argument('--env',
dest='showenvvars',
default=False,
action='store_true',
help="Show the environment variables that can be set by this app")
args = parser.parse_args()
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
# Decide if using ANSI or GUI
if args.showenvvars:
print('')
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('')
exit(0)
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
)Remove parameter support (due to unittest module) and modify to print parameters on each run.# Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
print('')
print('-'*80)
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('-'*80)
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('-'*80)
print('')
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
) | <commit_before># Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import argparse
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
#
# Step 1 - Check any command line arguments passed
#
parser = argparse.ArgumentParser()
parser.add_argument('--env',
dest='showenvvars',
default=False,
action='store_true',
help="Show the environment variables that can be set by this app")
args = parser.parse_args()
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
# Decide if using ANSI or GUI
if args.showenvvars:
print('')
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('')
exit(0)
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
)<commit_msg>Remove parameter support (due to unittest module) and modify to print parameters on each run.<commit_after># Initialization code. Placed in a separate Python package from the main
# app, this code allows the app created to be imported into any other
# package, module, or method.
import logging # Import standard logging - for levels only
from python_cowbull_server.Configurator import Configurator
from flask import Flask
# Instantiate the Flask application as app
app = Flask(__name__)
c = Configurator()
print('')
print('-'*80)
print('The following environment variables may be set to dynamically')
print('configure the server. Alternately, these can be defined in a ')
print('file and passed using the env. var. COWBULL_CONFIG.')
print('')
print('Please note. Env. Vars can be *ALL* lowercase or *ALL* uppercase.')
print('-'*80)
print('')
for name, desc in c.get_variables():
print(name, '-->', desc)
print('-'*80)
print('')
c.execute_load(app)
error_handler = c.error_handler
error_handler.log(
method="__init__",
module="python_cowbull_server",
message="Initialization complete.",
logger=logging.info
) |
47337d203d4b67dce71f33ab5a14c0a7342c94ae | server.py | server.py | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) | Remove trailing slashes from routes. | Remove trailing slashes from routes.
| Python | mit | davidsoncasey/quiver,davidsoncasey/quiver,davidsoncasey/quiver,davidsoncasey/quiver,davidsoncasey/quiver | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True)Remove trailing slashes from routes. | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) | <commit_before>import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True)<commit_msg>Remove trailing slashes from routes.<commit_after> | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) | import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True)Remove trailing slashes from routes.import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) | <commit_before>import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot/', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data/', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True)<commit_msg>Remove trailing slashes from routes.<commit_after>import StringIO
import base64
import signal
import flask
from quiver.plotter import FieldPlotter
app = flask.Flask(__name__)
@app.route('/')
def quiver():
'''Route for homepage'''
return flask.render_template('quiver.html')
@app.route('/plot', methods=['GET',])
def plot():
equation_string = flask.request.args.get('equation')
diff_equation = FieldPlotter()
diff_equation.set_equation_from_string(equation_string)
diff_equation.make_plot()
# If plotting was successful, write plot out
if diff_equation.figure:
# Write output to memory and add to response object
output = StringIO.StringIO()
response = flask.make_response(base64.b64encode(diff_equation.write_data(output)))
response.mimetype = 'image/png'
return response
else:
return flask.make_response('')
@app.route('/data', methods=['GET',])
def data():
equation_string = flask.request.args.get('equation')
plotter = FieldPlotter()
plotter.set_equation_from_string(equation_string)
plotter.make_data()
if __name__ == '__main__':
app.run(debug=True) |
82178af68dde7754cade01e9d5f092c9889ab957 | tomorrow_corrector/bot.py | tomorrow_corrector/bot.py | import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
while True:
run_bot()
time.sleep(30)
| import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
misspellings = ['tommorow', 'tommorrow', 'tomorow']
comment_cache = []
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
if any(string in comment.body.lower() for string in misspellings) and not comment.id in comment_cache:
comment.reply('I think you meant "tomorrow".')
comment_cache.append(comment.id)
while True:
run_bot()
time.sleep(30)
| Check if comment body contains misspelling, reply if so | Check if comment body contains misspelling, reply if so
| Python | mit | kshvmdn/reddit-bots | import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
while True:
run_bot()
time.sleep(30)
Check if comment body contains misspelling, reply if so | import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
misspellings = ['tommorow', 'tommorrow', 'tomorow']
comment_cache = []
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
if any(string in comment.body.lower() for string in misspellings) and not comment.id in comment_cache:
comment.reply('I think you meant "tomorrow".')
comment_cache.append(comment.id)
while True:
run_bot()
time.sleep(30)
| <commit_before>import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
while True:
run_bot()
time.sleep(30)
<commit_msg>Check if comment body contains misspelling, reply if so<commit_after> | import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
misspellings = ['tommorow', 'tommorrow', 'tomorow']
comment_cache = []
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
if any(string in comment.body.lower() for string in misspellings) and not comment.id in comment_cache:
comment.reply('I think you meant "tomorrow".')
comment_cache.append(comment.id)
while True:
run_bot()
time.sleep(30)
| import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
while True:
run_bot()
time.sleep(30)
Check if comment body contains misspelling, reply if soimport praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
misspellings = ['tommorow', 'tommorrow', 'tomorow']
comment_cache = []
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
if any(string in comment.body.lower() for string in misspellings) and not comment.id in comment_cache:
comment.reply('I think you meant "tomorrow".')
comment_cache.append(comment.id)
while True:
run_bot()
time.sleep(30)
| <commit_before>import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
while True:
run_bot()
time.sleep(30)
<commit_msg>Check if comment body contains misspelling, reply if so<commit_after>import praw, time
# replace with your username/password
username, password = USERNAME, PASSWORD
r = praw.Reddit(user_agent='A "tomorrow"-misspelling corrector by /u/tomorrow_corrector')
r.login(username, password, disable_warning=True)
misspellings = ['tommorow', 'tommorrow', 'tomorow']
comment_cache = []
def run_bot():
'''Check /r/all for mispellings in comments and reply to them.'''
subreddit = r.get_subreddit('all')
comments = subreddit.get_comments(limit=25)
for comment in comments:
if any(string in comment.body.lower() for string in misspellings) and not comment.id in comment_cache:
comment.reply('I think you meant "tomorrow".')
comment_cache.append(comment.id)
while True:
run_bot()
time.sleep(30)
|
f2a1dba207d870ebd287ebdf71f721b348c2ea36 | tests/test_redis_storage.py | tests/test_redis_storage.py | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
with hiro.Timeline().freeze() as timeline:
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
| import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
| Remove hiro timeline context in redis test | Remove hiro timeline context in redis test
| Python | mit | alisaifee/sifr,alisaifee/sifr | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
with hiro.Timeline().freeze() as timeline:
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
Remove hiro timeline context in redis test | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
| <commit_before>import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
with hiro.Timeline().freeze() as timeline:
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
<commit_msg>Remove hiro timeline context in redis test<commit_after> | import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
| import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
with hiro.Timeline().freeze() as timeline:
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
Remove hiro timeline context in redis testimport unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
| <commit_before>import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
with hiro.Timeline().freeze() as timeline:
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
<commit_msg>Remove hiro timeline context in redis test<commit_after>import unittest
import datetime
import hiro
import redis
from sifr.span import Minute, Day
from sifr.storage import MemoryStorage, RedisStorage
class RedisStorageTests(unittest.TestCase):
def setUp(self):
self.redis = redis.Redis()
self.redis.flushall()
def test_incr_simple_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.incr(span)
storage.incr(span)
self.assertEqual(storage.get(span), 2)
def test_incr_unique_minute(self):
red = redis.Redis()
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(red)
storage.incr_unique(span, "1")
storage.incr_unique(span, "1")
storage.incr_unique(span, "2")
self.assertEqual(storage.get_unique(span), 2)
def test_tracker_minute(self):
span = Minute(datetime.datetime.now(), ["minute_span"])
storage = RedisStorage(self.redis)
storage.track(span, "1", 3)
storage.track(span, "1", 3)
storage.track(span, "2", 3)
storage.track(span, "3", 3)
self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
|
b6663ab3ee1791d9b1fd3aee24bf0509a4cebe84 | tests/test_youtube_cache.py | tests/test_youtube_cache.py | import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
| import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache, YouTubePlaylistCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
@pytest.fixture
def youtube_playlist_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubePlaylistCache(playlist_id='PLOZioxrIwCv33zt5aFFjWqDoEMm55MVA9', alias='test-playlist', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
def test_youtube_playlist_cache(youtube_playlist_cache):
youtube_playlist_cache.get_playlist_info()
playlist_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-playlist.json')
assert os.path.exists(playlist_cache_filepath)
| Add test for YouTube playlist | Add test for YouTube playlist
| Python | mit | learningequality/ricecooker,learningequality/ricecooker,learningequality/ricecooker,learningequality/ricecooker | import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
Add test for YouTube playlist | import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache, YouTubePlaylistCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
@pytest.fixture
def youtube_playlist_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubePlaylistCache(playlist_id='PLOZioxrIwCv33zt5aFFjWqDoEMm55MVA9', alias='test-playlist', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
def test_youtube_playlist_cache(youtube_playlist_cache):
youtube_playlist_cache.get_playlist_info()
playlist_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-playlist.json')
assert os.path.exists(playlist_cache_filepath)
| <commit_before>import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
<commit_msg>Add test for YouTube playlist<commit_after> | import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache, YouTubePlaylistCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
@pytest.fixture
def youtube_playlist_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubePlaylistCache(playlist_id='PLOZioxrIwCv33zt5aFFjWqDoEMm55MVA9', alias='test-playlist', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
def test_youtube_playlist_cache(youtube_playlist_cache):
youtube_playlist_cache.get_playlist_info()
playlist_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-playlist.json')
assert os.path.exists(playlist_cache_filepath)
| import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
Add test for YouTube playlistimport os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache, YouTubePlaylistCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
@pytest.fixture
def youtube_playlist_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubePlaylistCache(playlist_id='PLOZioxrIwCv33zt5aFFjWqDoEMm55MVA9', alias='test-playlist', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
def test_youtube_playlist_cache(youtube_playlist_cache):
youtube_playlist_cache.get_playlist_info()
playlist_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-playlist.json')
assert os.path.exists(playlist_cache_filepath)
| <commit_before>import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
<commit_msg>Add test for YouTube playlist<commit_after>import os
import pytest
from ricecooker.utils.youtube_cache import YouTubeVideoCache, YouTubePlaylistCache
""" *********** YouTube Cache FIXTURES *********** """
@pytest.fixture
def youtube_video_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubeVideoCache(video_id='DFZb2qBIrEw', alias='test-video', cache_dir=cache_dir)
@pytest.fixture
def youtube_playlist_cache():
cache_dir = os.path.join('tests', 'testcontent', 'youtubecache')
assert os.path.isdir(cache_dir), 'Incorrect directory path setting'
return YouTubePlaylistCache(playlist_id='PLOZioxrIwCv33zt5aFFjWqDoEMm55MVA9', alias='test-playlist', cache_dir=cache_dir)
""" *********** YouTube Cache TESTS *********** """
def test_youtube_video_cache(youtube_video_cache):
youtube_video_cache.get_video_info()
video_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-video.json')
assert os.path.exists(video_cache_filepath)
def test_youtube_playlist_cache(youtube_playlist_cache):
youtube_playlist_cache.get_playlist_info()
playlist_cache_filepath = os.path.join('tests', 'testcontent', 'youtubecache', 'test-playlist.json')
assert os.path.exists(playlist_cache_filepath)
|
1f74b7ea4fdbcae6166477e56d1a6ccc81f6a5c8 | valohai_cli/exceptions.py | valohai_cli/exceptions.py | import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(RuntimeError):
pass
class NoProject(ClickException):
pass
| import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(ClickException, RuntimeError):
pass
class NoProject(ClickException):
pass
| Make ConfigurationError also a ClickException | Make ConfigurationError also a ClickException
| Python | mit | valohai/valohai-cli | import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(RuntimeError):
pass
class NoProject(ClickException):
pass
Make ConfigurationError also a ClickException | import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(ClickException, RuntimeError):
pass
class NoProject(ClickException):
pass
| <commit_before>import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(RuntimeError):
pass
class NoProject(ClickException):
pass
<commit_msg>Make ConfigurationError also a ClickException<commit_after> | import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(ClickException, RuntimeError):
pass
class NoProject(ClickException):
pass
| import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(RuntimeError):
pass
class NoProject(ClickException):
pass
Make ConfigurationError also a ClickExceptionimport click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(ClickException, RuntimeError):
pass
class NoProject(ClickException):
pass
| <commit_before>import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(RuntimeError):
pass
class NoProject(ClickException):
pass
<commit_msg>Make ConfigurationError also a ClickException<commit_after>import click
from click import ClickException
class APIError(ClickException):
def __init__(self, response):
super(APIError, self).__init__(response.text)
self.response = response
self.request = response.request
def show(self, file=None):
click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red')
class ConfigurationError(ClickException, RuntimeError):
pass
class NoProject(ClickException):
pass
|
273c7b89f02469ef1a6c53b6287412cd48881428 | matador/commands/deployment/deployment.py | matador/commands/deployment/deployment.py | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = None
for line in text:
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
| import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = ''
for line in text.splitlines(keepends=True):
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
| Add splitlines method to substitute_keywords | Add splitlines method to substitute_keywords
| Python | mit | Empiria/matador | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = None
for line in text:
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
Add splitlines method to substitute_keywords | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = ''
for line in text.splitlines(keepends=True):
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
| <commit_before>import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = None
for line in text:
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
<commit_msg>Add splitlines method to substitute_keywords<commit_after> | import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = ''
for line in text.splitlines(keepends=True):
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
| import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = None
for line in text:
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
Add splitlines method to substitute_keywordsimport logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = ''
for line in text.splitlines(keepends=True):
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
| <commit_before>import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = None
for line in text:
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
<commit_msg>Add splitlines method to substitute_keywords<commit_after>import logging
import subprocess
import re
def substitute_keywords(text, repo_folder, commit):
substitutions = {
'version': commit,
'date': subprocess.check_output(
['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit],
stderr=subprocess.STDOUT),
}
new_text = ''
for line in text.splitlines(keepends=True):
for key, value in substitutions.items():
rexp = '%s:.*' % key
line = re.sub(rexp, '%s: %s' % (key, value), line)
new_text += line
return new_text
class DeploymentCommand(object):
def __init__(self, *args):
self._logger = logging.getLogger(__name__)
self.args = args
self._execute()
def _execute(self):
raise NotImplementedError
|
5a27b1ff443db49a9c70cb6980653f615cca1b33 | meetup_facebook_bot/messenger/message_validators.py | meetup_facebook_bot/messenger/message_validators.py | def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'like talk' in messaging_event['postback']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
| def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if not is_quick_button(messaging_event):
return False
return 'like talk' in messaging_event['message']['quick_reply']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
| Fix bug in like validator | Fix bug in like validator
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'like talk' in messaging_event['postback']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
Fix bug in like validator | def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if not is_quick_button(messaging_event):
return False
return 'like talk' in messaging_event['message']['quick_reply']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
| <commit_before>def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'like talk' in messaging_event['postback']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
<commit_msg>Fix bug in like validator<commit_after> | def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if not is_quick_button(messaging_event):
return False
return 'like talk' in messaging_event['message']['quick_reply']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
| def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'like talk' in messaging_event['postback']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
Fix bug in like validatordef is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if not is_quick_button(messaging_event):
return False
return 'like talk' in messaging_event['message']['quick_reply']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
| <commit_before>def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'like talk' in messaging_event['postback']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
<commit_msg>Fix bug in like validator<commit_after>def is_quick_button(messaging_event):
if 'message' not in messaging_event:
return False
if 'quick_reply' not in messaging_event['message']:
return False
return True
def is_talk_ask_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'ask talk' in messaging_event['postback']['payload']
def is_talk_info_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'info talk' in messaging_event['postback']['payload']
def is_talk_rate_command(messaging_event):
if 'postback' not in messaging_event:
return False
return 'rate talk' in messaging_event['postback']['payload']
def is_talk_like_command(messaging_event):
if not is_quick_button(messaging_event):
return False
return 'like talk' in messaging_event['message']['quick_reply']['payload']
def has_sender_id(messaging_event):
return 'sender' in messaging_event and 'id' in messaging_event['sender']
|
fdfeb16f0ae6cdad7eaf223cf6b6dbd7586e63ec | tc_purger/handlers/purger.py | tc_purger/handlers/purger.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
exists = yield gen.maybe_future(
self.context.modules.storage.exists(imageurl)
)
if exists:
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
else:
self._error(404, 'Image not found at the given URL')
@gen.coroutine
def execute_image_operations(self):
pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
@gen.coroutine
def execute_image_operations(self):
pass
| Purge should always be attempted | Purge should always be attempted
Since the original is very volatile (in memcache), its absence shouldn't
prevent the thumbnails from being purged.
Furthermore, knowing whether the item was there beforehand isn't
very useful.
Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77
| Python | mit | wikimedia/thumbor-purger | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
exists = yield gen.maybe_future(
self.context.modules.storage.exists(imageurl)
)
if exists:
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
else:
self._error(404, 'Image not found at the given URL')
@gen.coroutine
def execute_image_operations(self):
pass
Purge should always be attempted
Since the original is very volatile (in memcache), its absence shouldn't
prevent the thumbnails from being purged.
Furthermore, knowing whether the item was there beforehand isn't
very useful.
Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
@gen.coroutine
def execute_image_operations(self):
pass
| <commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
exists = yield gen.maybe_future(
self.context.modules.storage.exists(imageurl)
)
if exists:
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
else:
self._error(404, 'Image not found at the given URL')
@gen.coroutine
def execute_image_operations(self):
pass
<commit_msg>Purge should always be attempted
Since the original is very volatile (in memcache), its absence shouldn't
prevent the thumbnails from being purged.
Furthermore, knowing whether the item was there beforehand isn't
very useful.
Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77<commit_after> | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
@gen.coroutine
def execute_image_operations(self):
pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
exists = yield gen.maybe_future(
self.context.modules.storage.exists(imageurl)
)
if exists:
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
else:
self._error(404, 'Image not found at the given URL')
@gen.coroutine
def execute_image_operations(self):
pass
Purge should always be attempted
Since the original is very volatile (in memcache), its absence shouldn't
prevent the thumbnails from being purged.
Furthermore, knowing whether the item was there beforehand isn't
very useful.
Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77# -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
@gen.coroutine
def execute_image_operations(self):
pass
| <commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
exists = yield gen.maybe_future(
self.context.modules.storage.exists(imageurl)
)
if exists:
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
else:
self._error(404, 'Image not found at the given URL')
@gen.coroutine
def execute_image_operations(self):
pass
<commit_msg>Purge should always be attempted
Since the original is very volatile (in memcache), its absence shouldn't
prevent the thumbnails from being purged.
Furthermore, knowing whether the item was there beforehand isn't
very useful.
Change-Id: I014df0bce00983031b9dec9d48126c25b1688a77<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community, Wikimedia Foundation
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
import urllib
from tornado import gen
from thumbor.handlers.imaging import ImagingHandler
class UrlPurgerHandler(ImagingHandler):
@classmethod
def regex(cls):
'''
:return: The regex used for routing.
:rtype: string
'''
return r'/purge/?(?P<image>.+)?'
@gen.coroutine
def get(self, **kw):
imageurl = urllib.quote(kw['image'].encode('utf8'))
self.context.modules.storage.remove(imageurl)
self.context.modules.result_storage.remove(imageurl)
self.set_status(204)
@gen.coroutine
def execute_image_operations(self):
pass
|
d0e625ff77ed905b1b120568c87ca32fa92c0020 | teknologr/members/lookups.py | teknologr/members/lookups.py | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args)
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args).order_by('surname', 'given_names')[:10]
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return obj._get_full_name()
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return obj._get_full_name()
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return obj._get_full_name()
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True | Refactor AJAX search to use member model methods | Refactor AJAX search to use member model methods
| Python | mit | Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args)
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return TrueRefactor AJAX search to use member model methods | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args).order_by('surname', 'given_names')[:10]
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return obj._get_full_name()
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return obj._get_full_name()
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return obj._get_full_name()
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True | <commit_before>from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args)
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True<commit_msg>Refactor AJAX search to use member model methods<commit_after> | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args).order_by('surname', 'given_names')[:10]
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return obj._get_full_name()
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return obj._get_full_name()
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return obj._get_full_name()
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True | from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args)
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return TrueRefactor AJAX search to use member model methodsfrom ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args).order_by('surname', 'given_names')[:10]
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return obj._get_full_name()
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return obj._get_full_name()
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return obj._get_full_name()
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True | <commit_before>from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args)
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return "%s %s" % (escape(obj.surname), escape(obj.given_names))
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True<commit_msg>Refactor AJAX search to use member model methods<commit_after>from ajax_select import register, LookupChannel
from members.models import *
from django.utils.html import escape
@register('member')
class MemberLookup(LookupChannel):
model = Member
def get_query(self, q, request):
from django.db.models import Q
args = []
for word in q.split():
args.append(Q(given_names__icontains=word) | Q(surname__icontains=word))
if not args:
return [] # No words in query (only spaces?)
return Member.objects.filter(*args).order_by('surname', 'given_names')[:10]
def get_result(self, obj):
""" result is the simple text that is the completion of what the person typed """
return obj._get_full_name()
def format_match(self, obj):
""" (HTML) formatted item for display in the dropdown """
return obj._get_full_name()
def format_item_display(self, obj):
""" (HTML) formatted item for displaying item in the selected deck area """
return obj._get_full_name()
def check_auth(self, request):
#TODO: Actual authentication?
#The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough
return True |
b78a79da5753f2c379501daa921fc47d26350dc5 | datapackage_pipelines_fiscal/processors/update_model_in_registry.py | datapackage_pipelines_fiscal/processors/update_model_in_registry.py | import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
params = {}
if 'babbageModel' in dp:
model = dp['babbageModel']
datapackage = copy.deepcopy(dp)
del datapackage['babbageModel']
params.update(dict(
model=model,
datapackage=datapackage
))
if datapackage_url:
params['datapackage_url'] = datapackage_url
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
| import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
datapackage = copy.deepcopy(dp)
params = {}
if 'babbageModel' in datapackage:
model = datapackage['babbageModel']
del datapackage['babbageModel']
params['model'] = model
if datapackage_url:
params['datapackage_url'] = datapackage_url
params['datapackage'] = datapackage
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
| Change where we're saving the datapackage | Change where we're saving the datapackage
| Python | mit | openspending/datapackage-pipelines-fiscal | import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
params = {}
if 'babbageModel' in dp:
model = dp['babbageModel']
datapackage = copy.deepcopy(dp)
del datapackage['babbageModel']
params.update(dict(
model=model,
datapackage=datapackage
))
if datapackage_url:
params['datapackage_url'] = datapackage_url
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
Change where we're saving the datapackage | import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
datapackage = copy.deepcopy(dp)
params = {}
if 'babbageModel' in datapackage:
model = datapackage['babbageModel']
del datapackage['babbageModel']
params['model'] = model
if datapackage_url:
params['datapackage_url'] = datapackage_url
params['datapackage'] = datapackage
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
| <commit_before>import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
params = {}
if 'babbageModel' in dp:
model = dp['babbageModel']
datapackage = copy.deepcopy(dp)
del datapackage['babbageModel']
params.update(dict(
model=model,
datapackage=datapackage
))
if datapackage_url:
params['datapackage_url'] = datapackage_url
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
<commit_msg>Change where we're saving the datapackage<commit_after> | import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
datapackage = copy.deepcopy(dp)
params = {}
if 'babbageModel' in datapackage:
model = datapackage['babbageModel']
del datapackage['babbageModel']
params['model'] = model
if datapackage_url:
params['datapackage_url'] = datapackage_url
params['datapackage'] = datapackage
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
| import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
params = {}
if 'babbageModel' in dp:
model = dp['babbageModel']
datapackage = copy.deepcopy(dp)
del datapackage['babbageModel']
params.update(dict(
model=model,
datapackage=datapackage
))
if datapackage_url:
params['datapackage_url'] = datapackage_url
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
Change where we're saving the datapackageimport os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
datapackage = copy.deepcopy(dp)
params = {}
if 'babbageModel' in datapackage:
model = datapackage['babbageModel']
del datapackage['babbageModel']
params['model'] = model
if datapackage_url:
params['datapackage_url'] = datapackage_url
params['datapackage'] = datapackage
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
| <commit_before>import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
params = {}
if 'babbageModel' in dp:
model = dp['babbageModel']
datapackage = copy.deepcopy(dp)
del datapackage['babbageModel']
params.update(dict(
model=model,
datapackage=datapackage
))
if datapackage_url:
params['datapackage_url'] = datapackage_url
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
<commit_msg>Change where we're saving the datapackage<commit_after>import os
import copy
from datapackage_pipelines.wrapper import process
from os_package_registry import PackageRegistry
ES_ADDRESS = os.environ.get('ELASTICSEARCH_ADDRESS')
def modify_datapackage(dp, parameters, *_):
dataset_id = parameters['dataset-id']
loaded = parameters.get('loaded')
datapackage_url = parameters.get('datapackage-url')
if ES_ADDRESS:
registry = PackageRegistry(ES_ADDRESS)
datapackage = copy.deepcopy(dp)
params = {}
if 'babbageModel' in datapackage:
model = datapackage['babbageModel']
del datapackage['babbageModel']
params['model'] = model
if datapackage_url:
params['datapackage_url'] = datapackage_url
params['datapackage'] = datapackage
if loaded is not None:
params['loaded'] = loaded
params['loading_status'] = 'done' if loaded else 'loading-data'
registry.update_model(
dataset_id,
**params
)
return dp
if __name__ == '__main__':
process(modify_datapackage=modify_datapackage)
|
b4e92b84c275568041a4a9771a03ee0b9bb3fc48 | visram/tests/test_visram.py | visram/tests/test_visram.py | """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
| """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, result_chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
| Fix test to properly compare chart types | Fix test to properly compare chart types
A variable was being compared to itself
| Python | mit | Spferical/visram | """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
Fix test to properly compare chart types
A variable was being compared to itself | """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, result_chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
| <commit_before>"""For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
<commit_msg>Fix test to properly compare chart types
A variable was being compared to itself<commit_after> | """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, result_chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
| """For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
Fix test to properly compare chart types
A variable was being compared to itself"""For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, result_chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
| <commit_before>"""For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
<commit_msg>Fix test to properly compare chart types
A variable was being compared to itself<commit_after>"""For testing"""
import visram.chart
import unittest
class TestVisram(unittest.TestCase):
def _test_chart_type(self, chart_type):
fig, axes, result_chart_type = visram.chart.create_chart(
chart_type, 'spectral')
# output chart type should be the same as the input
self.assertEqual(chart_type, result_chart_type)
# test size of bounds is not near-zero
xlim = axes.get_xlim()
ylim = axes.get_ylim()
self.assertNotAlmostEqual(xlim[0] - xlim[1], 0)
self.assertNotAlmostEqual(ylim[0] - ylim[1], 0)
def test_ram_chart(self):
self._test_chart_type('ram')
def test_cpu_chart(self):
self._test_chart_type('cpu')
if __name__ == '__main__':
unittest.main()
|
4903afcec3d22d046c39a5b565366dc13472c6fd | zosimus/chartchemy/utils.py | zosimus/chartchemy/utils.py | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to) if render_to else render_to
title = escape(title) if title else title
x_axis_title = escape(x_axis_title) if x_axis_title else x_axis_title
y_axis_title = escape(y_axis_title) if y_axis_title else y_axis_title
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
| import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to.encode('ascii', 'ignore')) if render_to else 'render_to'
title = escape(title.encode('ascii', 'ignore')) if title else 'title'
x_axis_title = escape(x_axis_title.encode('ascii', 'ignore')) if x_axis_title else 'x axis'
y_axis_title = escape(y_axis_title.encode('ascii', 'ignore')) if y_axis_title else 'y axis'
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c.encode('ascii', 'ignore')) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
| Fix unicode error in series | Fix unicode error in series | Python | bsd-2-clause | pgollakota/zosimus,pgollakota/zosimus | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to) if render_to else render_to
title = escape(title) if title else title
x_axis_title = escape(x_axis_title) if x_axis_title else x_axis_title
y_axis_title = escape(y_axis_title) if y_axis_title else y_axis_title
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
Fix unicode error in series | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to.encode('ascii', 'ignore')) if render_to else 'render_to'
title = escape(title.encode('ascii', 'ignore')) if title else 'title'
x_axis_title = escape(x_axis_title.encode('ascii', 'ignore')) if x_axis_title else 'x axis'
y_axis_title = escape(y_axis_title.encode('ascii', 'ignore')) if y_axis_title else 'y axis'
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c.encode('ascii', 'ignore')) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
| <commit_before>import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to) if render_to else render_to
title = escape(title) if title else title
x_axis_title = escape(x_axis_title) if x_axis_title else x_axis_title
y_axis_title = escape(y_axis_title) if y_axis_title else y_axis_title
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
<commit_msg>Fix unicode error in series<commit_after> | import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to.encode('ascii', 'ignore')) if render_to else 'render_to'
title = escape(title.encode('ascii', 'ignore')) if title else 'title'
x_axis_title = escape(x_axis_title.encode('ascii', 'ignore')) if x_axis_title else 'x axis'
y_axis_title = escape(y_axis_title.encode('ascii', 'ignore')) if y_axis_title else 'y axis'
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c.encode('ascii', 'ignore')) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
| import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to) if render_to else render_to
title = escape(title) if title else title
x_axis_title = escape(x_axis_title) if x_axis_title else x_axis_title
y_axis_title = escape(y_axis_title) if y_axis_title else y_axis_title
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
Fix unicode error in seriesimport simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to.encode('ascii', 'ignore')) if render_to else 'render_to'
title = escape(title.encode('ascii', 'ignore')) if title else 'title'
x_axis_title = escape(x_axis_title.encode('ascii', 'ignore')) if x_axis_title else 'x axis'
y_axis_title = escape(y_axis_title.encode('ascii', 'ignore')) if y_axis_title else 'y axis'
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c.encode('ascii', 'ignore')) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
| <commit_before>import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to) if render_to else render_to
title = escape(title) if title else title
x_axis_title = escape(x_axis_title) if x_axis_title else x_axis_title
y_axis_title = escape(y_axis_title) if y_axis_title else y_axis_title
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
<commit_msg>Fix unicode error in series<commit_after>import simplejson
from django.utils.html import escape
def render_highcharts_options(render_to, categories, series, title, x_axis_title, y_axis_title, series_name):
"""Accepts the parameters to render a chart and returns a JSON serialized Highcharts options object."""
# Escape all the character strings to make them HTML safe.
render_to = escape(render_to.encode('ascii', 'ignore')) if render_to else 'render_to'
title = escape(title.encode('ascii', 'ignore')) if title else 'title'
x_axis_title = escape(x_axis_title.encode('ascii', 'ignore')) if x_axis_title else 'x axis'
y_axis_title = escape(y_axis_title.encode('ascii', 'ignore')) if y_axis_title else 'y axis'
# Categories (dimensions) come from the use. Escape them too.
categories = [escape(c.encode('ascii', 'ignore')) for c in categories]
hco = {
"chart": {
"renderTo": render_to,
"type": 'column'
},
"title": {
"text": title
},
"xAxis": {
"title": {
"text": x_axis_title
},
"categories": categories
},
"yAxis": {
"title": {
"text": y_axis_title,
}
},
"series": [{
"name": series_name,
"data": series,
}]
}
return simplejson.dumps(hco, use_decimal=True)
|
f1bdcde329b5b03e453f193720066914c908d46d | api/schemas.py | api/schemas.py | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
section = marshmallow.fields.Str()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
| import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allow_none=True)
section = marshmallow.fields.Str(allow_none=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
| Allow story location and section to be null | Allow story location and section to be null
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
section = marshmallow.fields.Str()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
Allow story location and section to be null | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allow_none=True)
section = marshmallow.fields.Str(allow_none=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
| <commit_before>import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
section = marshmallow.fields.Str()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
<commit_msg>Allow story location and section to be null<commit_after> | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allow_none=True)
section = marshmallow.fields.Str(allow_none=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
| import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
section = marshmallow.fields.Str()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
Allow story location and section to be nullimport marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allow_none=True)
section = marshmallow.fields.Str(allow_none=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
| <commit_before>import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
section = marshmallow.fields.Str()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
<commit_msg>Allow story location and section to be null<commit_after>import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allow_none=True)
section = marshmallow.fields.Str(allow_none=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'stories' if many else 'story'
return {key: data}
class PersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
name = marshmallow.fields.Str(required=True)
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'people' if many else 'person'
return {key: data}
class AddStoryPersonSchema(marshmallow.Schema):
id = marshmallow.fields.Int()
@marshmallow.post_dump(pass_many=True)
def wrap(self, data, many):
key = 'story_people' if many else 'story_person'
return {key: data}
|
9aa4957392249ed43fd061f9efb88b5821e19a67 | swh/web/ui/service.py | swh/web/ui/service.py | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_find(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
| # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_exist(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
| Refactor following storage's api backend change | Refactor following storage's api backend change
| Python | agpl-3.0 | SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_find(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
Refactor following storage's api backend change | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_exist(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
| <commit_before># Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_find(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
<commit_msg>Refactor following storage's api backend change<commit_after> | # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_exist(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
| # Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_find(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
Refactor following storage's api backend change# Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_exist(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
| <commit_before># Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_find(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
<commit_msg>Refactor following storage's api backend change<commit_after># Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui import main
from swh.web.ui import query
def lookup_hash(q):
"""Given a string query q of one hash, lookup its hash to the backend.
Args:
query, hash as a string (sha1, sha256, etc...)
Returns:
a string message (found, not found or a potential error explanation)
Raises:
OSError (no route to host), etc... Network issues in general
"""
hash = query.categorize_hash(q)
if hash != {}:
present = main.storage().content_exist(hash)
return 'Found!' if present else 'Not Found'
return """This is not a hash.
Hint: hexadecimal string with length either 20 (sha1) or 32 (sha256)."""
def lookup_hash_origin(hash):
"""Given a hash, return the origin of such content if any is found.
Args:
hash: key/value dictionary
Returns:
The origin for such hash if it's found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
return "origin is 'master' from 'date'"
|
962bbd745569600a9cfff5d5ee70f03a05a24e26 | laundry/status/models.py | laundry/status/models.py | from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.response_text)
| from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.machine_type)
| Fix __unicode__() method in Response | Fix __unicode__() method in Response
| Python | agpl-3.0 | justathoughtor2/psu-hn-laundry,justathoughtor2/psu-hn-laundry,justathoughtor2/psu-hn-laundry | from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.response_text)
Fix __unicode__() method in Response | from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.machine_type)
| <commit_before>from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.response_text)
<commit_msg>Fix __unicode__() method in Response<commit_after> | from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.machine_type)
| from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.response_text)
Fix __unicode__() method in Responsefrom django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.machine_type)
| <commit_before>from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.response_text)
<commit_msg>Fix __unicode__() method in Response<commit_after>from django.db import models
class Query(models.Model):
query_text = models.CharField(max_length=200)
def __unicode__(self):
return u'%s' % (self.query_text)
class Response(models.Model):
query = models.ForeignKey(Query)
machine_type = models.CharField(max_length=200)
machine_in_use = models.IntegerField(default=-1)
def __unicode__(self):
return u'%s' % (self.machine_type)
|
4e4262f3d9cde4394d08681c517fcec4e2e9a336 | shellpython/tests/test_helpers.py | shellpython/tests/test_helpers.py | import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd())
with Dir(os.path.join('locator')):
self.assertEqual(os.path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
| import unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_dir, 'data'), os.getcwd())
with Dir(path.join('locator')):
self.assertEqual(path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
| Fix directory tests, __file__ may return relative path and now it is taken into consideration | Fix directory tests, __file__ may return relative path and now it is
taken into consideration
| Python | bsd-3-clause | lamerman/shellpy | import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd())
with Dir(os.path.join('locator')):
self.assertEqual(os.path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
Fix directory tests, __file__ may return relative path and now it is
taken into consideration | import unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_dir, 'data'), os.getcwd())
with Dir(path.join('locator')):
self.assertEqual(path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
| <commit_before>import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd())
with Dir(os.path.join('locator')):
self.assertEqual(os.path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
<commit_msg>Fix directory tests, __file__ may return relative path and now it is
taken into consideration<commit_after> | import unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_dir, 'data'), os.getcwd())
with Dir(path.join('locator')):
self.assertEqual(path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
| import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd())
with Dir(os.path.join('locator')):
self.assertEqual(os.path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
Fix directory tests, __file__ may return relative path and now it is
taken into considerationimport unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_dir, 'data'), os.getcwd())
with Dir(path.join('locator')):
self.assertEqual(path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
| <commit_before>import unittest
import tempfile
import os
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = os.path.split(__file__)[0]
with Dir(os.path.join(cur_dir, 'data')):
self.assertEqual(os.path.join(cur_dir, 'data'), os.getcwd())
with Dir(os.path.join('locator')):
self.assertEqual(os.path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
<commit_msg>Fix directory tests, __file__ may return relative path and now it is
taken into consideration<commit_after>import unittest
import tempfile
import os
from os import path
from shellpython.helpers import Dir
class TestDirectory(unittest.TestCase):
def test_relative_dirs(self):
cur_dir = path.dirname(path.abspath(__file__))
with Dir(path.join(cur_dir, 'data')):
self.assertEqual(path.join(cur_dir, 'data'), os.getcwd())
with Dir(path.join('locator')):
self.assertEqual(path.join(cur_dir, 'data', 'locator'), os.getcwd())
def test_absolute_dirs(self):
with Dir(tempfile.gettempdir()):
self.assertEqual(tempfile.gettempdir(), os.getcwd())
|
f1266219af530d1cc65019e7b7d40367c3daa024 | observatory/emaillist/methods.py | observatory/emaillist/methods.py | from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
| from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
from django.core.urlresolvers import reverse
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
#Doing a separate email for each person so we can allow unsubscription links
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
| Update format to produce a valid link | Update format to produce a valid link
| Python | isc | rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory | from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
Update format to produce a valid link | from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
from django.core.urlresolvers import reverse
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
#Doing a separate email for each person so we can allow unsubscription links
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
| <commit_before>from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
<commit_msg>Update format to produce a valid link<commit_after> | from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
from django.core.urlresolvers import reverse
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
#Doing a separate email for each person so we can allow unsubscription links
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
| from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
Update format to produce a valid linkfrom django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
from django.core.urlresolvers import reverse
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
#Doing a separate email for each person so we can allow unsubscription links
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
| <commit_before>from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="http://rcos.rpi.edu/email/remove/%s"> Unsubscribe From RCOS Emails</a>' % (body, addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
<commit_msg>Update format to produce a valid link<commit_after>from django.core.mail import EmailMessage
from emaillist.models import EmailExclusion
from django.core.urlresolvers import reverse
def send_mail(subject, body, from_email, recipient_list, fail_silently=False):
to = [addr for addr in recipient_list if not EmailExclusion.excluded(addr)]
#Doing a separate email for each person so we can allow unsubscription links
for addr in to:
#For now use default email body with an unsubscribe link
html_content = '%s <br><a href="%s"> Unsubscribe From RCOS Emails</a>' % (body, reverse('emaillist.views.remove', args=[addr]), addr)
msg = EmailMessage(subject, html_content, from_email, [addr])
msg.content_subtype = "html" # Main content is now text/html
msg.send(fail_silently = fail_silently)
|
049ec8a07aeb2344b7617ab5eb039c61f52fec45 | Pig-Latin/pig_latin.py | Pig-Latin/pig_latin.py | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self, sentence):
self.sentence = sentence
print self.convert_sentence()
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin("Hello eric ryan there")
| class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self):
self.sentence = raw_input("Enter a sentence to be converted into pig latin: ")
print self.convert_sentence()
while True:
play_again = raw_input("Do you want to play again? Type yes or no ").lower()
if play_again == "yes":
Pig_latin()
break
elif play_again == "no":
print "thanks for playing!"
break
else:
print "Please type yes or no!"
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin()
| Add user functionality to Pig Latin class | Add user functionality to Pig Latin class
| Python | mit | Bigless27/Python-Projects | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self, sentence):
self.sentence = sentence
print self.convert_sentence()
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin("Hello eric ryan there")
Add user functionality to Pig Latin class | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self):
self.sentence = raw_input("Enter a sentence to be converted into pig latin: ")
print self.convert_sentence()
while True:
play_again = raw_input("Do you want to play again? Type yes or no ").lower()
if play_again == "yes":
Pig_latin()
break
elif play_again == "no":
print "thanks for playing!"
break
else:
print "Please type yes or no!"
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin()
| <commit_before>class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self, sentence):
self.sentence = sentence
print self.convert_sentence()
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin("Hello eric ryan there")
<commit_msg>Add user functionality to Pig Latin class<commit_after> | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self):
self.sentence = raw_input("Enter a sentence to be converted into pig latin: ")
print self.convert_sentence()
while True:
play_again = raw_input("Do you want to play again? Type yes or no ").lower()
if play_again == "yes":
Pig_latin()
break
elif play_again == "no":
print "thanks for playing!"
break
else:
print "Please type yes or no!"
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin()
| class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self, sentence):
self.sentence = sentence
print self.convert_sentence()
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin("Hello eric ryan there")
Add user functionality to Pig Latin classclass Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self):
self.sentence = raw_input("Enter a sentence to be converted into pig latin: ")
print self.convert_sentence()
while True:
play_again = raw_input("Do you want to play again? Type yes or no ").lower()
if play_again == "yes":
Pig_latin()
break
elif play_again == "no":
print "thanks for playing!"
break
else:
print "Please type yes or no!"
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin()
| <commit_before>class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self, sentence):
self.sentence = sentence
print self.convert_sentence()
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin("Hello eric ryan there")
<commit_msg>Add user functionality to Pig Latin class<commit_after>class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u", "A", "E", "I", "O", "U"]
def __init__(self):
self.sentence = raw_input("Enter a sentence to be converted into pig latin: ")
print self.convert_sentence()
while True:
play_again = raw_input("Do you want to play again? Type yes or no ").lower()
if play_again == "yes":
Pig_latin()
break
elif play_again == "no":
print "thanks for playing!"
break
else:
print "Please type yes or no!"
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
converted_sentence = []
for word in new_sentence:
if word[0] in self.vowels:
converted_sentence.append(word)
else:
converted_sentence.append(''.join(self.word_converter(word)))
return (' ').join(converted_sentence)
def word_converter(self,word):
solution = list(word)
for letter in list(word):
if letter not in self.vowels:
solution.remove(letter)
solution.append(letter)
else:
break
solution.append("ay")
return solution
Pig_latin()
|
297253b3cbeb91f29f8a51f7108f22d0b9c8cfb9 | app.py | app.py | """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
response = requests.get('http://localhouse:3001/time')
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
| """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
try:
response = requests.get('http://localhouse:3001/time')
except requests.exceptions.ConnectionError:
return 'Unavailable'
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
| Update get_time to handle connection errors. | Update get_time to handle connection errors.
| Python | mit | danriti/short-circuit,danriti/short-circuit | """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
response = requests.get('http://localhouse:3001/time')
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
Update get_time to handle connection errors. | """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
try:
response = requests.get('http://localhouse:3001/time')
except requests.exceptions.ConnectionError:
return 'Unavailable'
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
| <commit_before>""" app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
response = requests.get('http://localhouse:3001/time')
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
<commit_msg>Update get_time to handle connection errors.<commit_after> | """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
try:
response = requests.get('http://localhouse:3001/time')
except requests.exceptions.ConnectionError:
return 'Unavailable'
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
| """ app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
response = requests.get('http://localhouse:3001/time')
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
Update get_time to handle connection errors.""" app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
try:
response = requests.get('http://localhouse:3001/time')
except requests.exceptions.ConnectionError:
return 'Unavailable'
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
| <commit_before>""" app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
response = requests.get('http://localhouse:3001/time')
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
<commit_msg>Update get_time to handle connection errors.<commit_after>""" app.py """
from flask import Flask, render_template
import requests
app = Flask(__name__)
def get_time():
try:
response = requests.get('http://localhouse:3001/time')
except requests.exceptions.ConnectionError:
return 'Unavailable'
return response.json().get('datetime')
def get_user():
response = requests.get('http://localhost:3002/user')
return response.json().get('name')
@app.errorhandler(500)
def page_not_found(_):
return 'Server error', 500
@app.route("/")
def hello():
time = get_time()
name = get_user()
return render_template('hello.html', name=name, time=time)
if __name__ == "__main__":
app.run(port=3000, debug=True)
|
50de60d8c1fe196ea18369d95ab328f9ef709159 | tools/pdtools/pdtools/devices/camera.py | tools/pdtools/pdtools/devices/camera.py | import base64
import cStringIO
import requests
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return cStringIO.StringIO(result.content)
else:
return None
| import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| Use six.BytesIO for Python3 compatibility | Use six.BytesIO for Python3 compatibility
| Python | apache-2.0 | ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop | import base64
import cStringIO
import requests
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return cStringIO.StringIO(result.content)
else:
return None
Use six.BytesIO for Python3 compatibility | import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| <commit_before>import base64
import cStringIO
import requests
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return cStringIO.StringIO(result.content)
else:
return None
<commit_msg>Use six.BytesIO for Python3 compatibility<commit_after> | import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| import base64
import cStringIO
import requests
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return cStringIO.StringIO(result.content)
else:
return None
Use six.BytesIO for Python3 compatibilityimport base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
| <commit_before>import base64
import cStringIO
import requests
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return cStringIO.StringIO(result.content)
else:
return None
<commit_msg>Use six.BytesIO for Python3 compatibility<commit_after>import base64
import requests
import six
class Camera(object):
def __init__(self, host):
self.host = host
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO/StringIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return six.BytesIO(result.content)
else:
return None
|
047351704c4cd4a3a0714f4e839f96bbc6c125bf | scripts/slave/chromium/test_mini_installer_wrapper.py | scripts/slave/chromium/test_mini_installer_wrapper.py | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
| #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
'-v',
'--config', mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
| Update mini_installer test wrapper script. | Update mini_installer test wrapper script.
This tracks changes made to the script in r286837.
BUG=264859,399511
R=robertshield@chromium.org
Review URL: https://codereview.chromium.org/437593008
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@286999 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
Update mini_installer test wrapper script.
This tracks changes made to the script in r286837.
BUG=264859,399511
R=robertshield@chromium.org
Review URL: https://codereview.chromium.org/437593008
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@286999 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
'-v',
'--config', mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
| <commit_before>#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
<commit_msg>Update mini_installer test wrapper script.
This tracks changes made to the script in r286837.
BUG=264859,399511
R=robertshield@chromium.org
Review URL: https://codereview.chromium.org/437593008
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@286999 0039d316-1c4b-4281-b951-d872f2087c98<commit_after> | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
'-v',
'--config', mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
| #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
Update mini_installer test wrapper script.
This tracks changes made to the script in r286837.
BUG=264859,399511
R=robertshield@chromium.org
Review URL: https://codereview.chromium.org/437593008
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@286999 0039d316-1c4b-4281-b951-d872f2087c98#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
'-v',
'--config', mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
| <commit_before>#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
<commit_msg>Update mini_installer test wrapper script.
This tracks changes made to the script in r286837.
BUG=264859,399511
R=robertshield@chromium.org
Review URL: https://codereview.chromium.org/437593008
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@286999 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper script for src/chrome/test/mini_installer/test_installer.py.
"""
import optparse
import os
import sys
from slave import build_directory
from common import chromium_utils
def main():
parser = optparse.OptionParser()
parser.add_option('--target', help='Release or Debug')
options, args = parser.parse_args()
assert not args
mini_installer_dir = os.path.join('src', 'chrome', 'test', 'mini_installer')
mini_installer_tests_config = os.path.join(
mini_installer_dir, 'config', 'config.config')
return chromium_utils.RunCommand([
sys.executable,
os.path.join(mini_installer_dir, 'test_installer.py'),
'-v',
'--config', mini_installer_tests_config,
'--build-dir', build_directory.GetBuildOutputDirectory(),
'--target', options.target,
'--force-clean',
])
if '__main__' == __name__:
sys.exit(main())
|
c2792efbb7c3b74c18ffede21b53adc42d887423 | social_website_django_angular/social_website_django_angular/urls.py | social_website_django_angular/social_website_django_angular/urls.py | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index')
]
| """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
url('^.*$', IndexView.as_view(), name='index')
]
| Add login endpoint to URLs | Add login endpoint to URLs
| Python | mit | tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index')
]
Add login endpoint to URLs | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
url('^.*$', IndexView.as_view(), name='index')
]
| <commit_before>"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index')
]
<commit_msg>Add login endpoint to URLs<commit_after> | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
url('^.*$', IndexView.as_view(), name='index')
]
| """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index')
]
Add login endpoint to URLs"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
url('^.*$', IndexView.as_view(), name='index')
]
| <commit_before>"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index')
]
<commit_msg>Add login endpoint to URLs<commit_after>"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework_nested import routers
from social_website_django_angular.views import IndexView
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
url('^.*$', IndexView.as_view(), name='index')
]
|
9616ba8659aab6b60d95ea7e07699e258fb436e6 | openprovider/modules/__init__.py | openprovider/modules/__init__.py | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
| # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
| Implement an Optional Element function | Implement an Optional Element function
| Python | mit | AntagonistHQ/openprovider.py | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
Implement an Optional Element function | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
| <commit_before># coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
<commit_msg>Implement an Optional Element function<commit_after> | # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
| # coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
Implement an Optional Element function# coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
| <commit_before># coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
<commit_msg>Implement an Optional Element function<commit_after># coding=utf-8
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
|
3b5094b86414a70460a54600d1cf7959fffea240 | nisl/io/tests/test_nifti_masker.py | nisl/io/tests/test_nifti_masker.py | """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
| """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
from nose.tools import assert_true, assert_false
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
def test_nan():
data = np.ones((9, 9, 9))
data[0] = np.nan
data[:, 0] = np.nan
data[:, :, 0] = np.nan
data[-1] = np.nan
data[:, -1] = np.nan
data[:, :, -1] = np.nan
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
mask = masker.mask_.get_data()
assert_true(mask[1:-1, 1:-1, 1:-1].all())
assert_false(mask[0].any())
assert_false(mask[:, 0].any())
assert_false(mask[:, :, 0].any())
assert_false(mask[-1].any())
assert_false(mask[:, -1].any())
assert_false(mask[:, :, -1].any())
| Add test for NaN input values | Add test for NaN input values
| Python | bsd-3-clause | abenicho/isvr | """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
Add test for NaN input values | """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
from nose.tools import assert_true, assert_false
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
def test_nan():
data = np.ones((9, 9, 9))
data[0] = np.nan
data[:, 0] = np.nan
data[:, :, 0] = np.nan
data[-1] = np.nan
data[:, -1] = np.nan
data[:, :, -1] = np.nan
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
mask = masker.mask_.get_data()
assert_true(mask[1:-1, 1:-1, 1:-1].all())
assert_false(mask[0].any())
assert_false(mask[:, 0].any())
assert_false(mask[:, :, 0].any())
assert_false(mask[-1].any())
assert_false(mask[:, -1].any())
assert_false(mask[:, :, -1].any())
| <commit_before>"""
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
<commit_msg>Add test for NaN input values<commit_after> | """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
from nose.tools import assert_true, assert_false
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
def test_nan():
data = np.ones((9, 9, 9))
data[0] = np.nan
data[:, 0] = np.nan
data[:, :, 0] = np.nan
data[-1] = np.nan
data[:, -1] = np.nan
data[:, :, -1] = np.nan
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
mask = masker.mask_.get_data()
assert_true(mask[1:-1, 1:-1, 1:-1].all())
assert_false(mask[0].any())
assert_false(mask[:, 0].any())
assert_false(mask[:, :, 0].any())
assert_false(mask[-1].any())
assert_false(mask[:, -1].any())
assert_false(mask[:, :, -1].any())
| """
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
Add test for NaN input values"""
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
from nose.tools import assert_true, assert_false
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
def test_nan():
data = np.ones((9, 9, 9))
data[0] = np.nan
data[:, 0] = np.nan
data[:, :, 0] = np.nan
data[-1] = np.nan
data[:, -1] = np.nan
data[:, :, -1] = np.nan
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
mask = masker.mask_.get_data()
assert_true(mask[1:-1, 1:-1, 1:-1].all())
assert_false(mask[0].any())
assert_false(mask[:, 0].any())
assert_false(mask[:, :, 0].any())
assert_false(mask[-1].any())
assert_false(mask[:, -1].any())
assert_false(mask[:, :, -1].any())
| <commit_before>"""
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
<commit_msg>Add test for NaN input values<commit_after>"""
Test the nifti_masker module
"""
# Author: Gael Varoquaux
# License: simplified BSD
from nose.tools import assert_true, assert_false
import numpy as np
from nibabel import Nifti1Image
from ..nifti_masker import NiftiMasker
def test_auto_mask():
data = np.ones((9, 9, 9))
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
def test_nan():
data = np.ones((9, 9, 9))
data[0] = np.nan
data[:, 0] = np.nan
data[:, :, 0] = np.nan
data[-1] = np.nan
data[:, -1] = np.nan
data[:, :, -1] = np.nan
data[3:-3, 3:-3, 3:-3] = 10
img = Nifti1Image(data, np.eye(4))
masker = NiftiMasker()
masker.fit(img)
mask = masker.mask_.get_data()
assert_true(mask[1:-1, 1:-1, 1:-1].all())
assert_false(mask[0].any())
assert_false(mask[:, 0].any())
assert_false(mask[:, :, 0].any())
assert_false(mask[-1].any())
assert_false(mask[:, -1].any())
assert_false(mask[:, :, -1].any())
|
a9796c68c24c3e8a059c54aad6eee2d0b61a9041 | test/psyco.py | test/psyco.py | import _psyco
import sys
ticks = 0
depth = 10
funcs = {}
def f(frame, event, arg):
if event != 'call': return
c = frame.f_code.co_code
fn = frame.f_code.co_name
g = frame.f_globals
if not funcs.has_key(c):
funcs[c] = 1
if funcs[c] != None:
funcs[c] = funcs[c] + 1
if funcs[c] > ticks and g.has_key(fn):
g[fn] = _psyco.proxy(g[fn], depth)
funcs[c] = None
print 'psyco rebinding function:', fn
sys.setprofile(f)
| import _psyco
_psyco.selective(1) # Argument is number of invocations before rebinding
# import sys
# ticks = 0
# depth = 10
# funcs = {}
# def f(frame, event, arg):
# if event != 'call': return
# print type(frame.f_globals)
# c = frame.f_code.co_code
# fn = frame.f_code.co_name
# g = frame.f_globals
# if not funcs.has_key(c):
# funcs[c] = 1
# if funcs[c] != None:
# funcs[c] = funcs[c] + 1
# if funcs[c] > ticks and g.has_key(fn):
# g[fn] = _psyco.proxy(g[fn], depth)
# funcs[c] = None
# print 'psyco rebinding function:', fn
# sys.setprofile(f)
| Use c-version of the selective compilation | Use c-version of the selective compilation
| Python | mit | tonysimpson/Ni,tonysimpson/Ni,tonysimpson/Ni,tonysimpson/Ni,tonysimpson/Ni | import _psyco
import sys
ticks = 0
depth = 10
funcs = {}
def f(frame, event, arg):
if event != 'call': return
c = frame.f_code.co_code
fn = frame.f_code.co_name
g = frame.f_globals
if not funcs.has_key(c):
funcs[c] = 1
if funcs[c] != None:
funcs[c] = funcs[c] + 1
if funcs[c] > ticks and g.has_key(fn):
g[fn] = _psyco.proxy(g[fn], depth)
funcs[c] = None
print 'psyco rebinding function:', fn
sys.setprofile(f)
Use c-version of the selective compilation | import _psyco
_psyco.selective(1) # Argument is number of invocations before rebinding
# import sys
# ticks = 0
# depth = 10
# funcs = {}
# def f(frame, event, arg):
# if event != 'call': return
# print type(frame.f_globals)
# c = frame.f_code.co_code
# fn = frame.f_code.co_name
# g = frame.f_globals
# if not funcs.has_key(c):
# funcs[c] = 1
# if funcs[c] != None:
# funcs[c] = funcs[c] + 1
# if funcs[c] > ticks and g.has_key(fn):
# g[fn] = _psyco.proxy(g[fn], depth)
# funcs[c] = None
# print 'psyco rebinding function:', fn
# sys.setprofile(f)
| <commit_before>import _psyco
import sys
ticks = 0
depth = 10
funcs = {}
def f(frame, event, arg):
if event != 'call': return
c = frame.f_code.co_code
fn = frame.f_code.co_name
g = frame.f_globals
if not funcs.has_key(c):
funcs[c] = 1
if funcs[c] != None:
funcs[c] = funcs[c] + 1
if funcs[c] > ticks and g.has_key(fn):
g[fn] = _psyco.proxy(g[fn], depth)
funcs[c] = None
print 'psyco rebinding function:', fn
sys.setprofile(f)
<commit_msg>Use c-version of the selective compilation<commit_after> | import _psyco
_psyco.selective(1) # Argument is number of invocations before rebinding
# import sys
# ticks = 0
# depth = 10
# funcs = {}
# def f(frame, event, arg):
# if event != 'call': return
# print type(frame.f_globals)
# c = frame.f_code.co_code
# fn = frame.f_code.co_name
# g = frame.f_globals
# if not funcs.has_key(c):
# funcs[c] = 1
# if funcs[c] != None:
# funcs[c] = funcs[c] + 1
# if funcs[c] > ticks and g.has_key(fn):
# g[fn] = _psyco.proxy(g[fn], depth)
# funcs[c] = None
# print 'psyco rebinding function:', fn
# sys.setprofile(f)
| import _psyco
import sys
ticks = 0
depth = 10
funcs = {}
def f(frame, event, arg):
if event != 'call': return
c = frame.f_code.co_code
fn = frame.f_code.co_name
g = frame.f_globals
if not funcs.has_key(c):
funcs[c] = 1
if funcs[c] != None:
funcs[c] = funcs[c] + 1
if funcs[c] > ticks and g.has_key(fn):
g[fn] = _psyco.proxy(g[fn], depth)
funcs[c] = None
print 'psyco rebinding function:', fn
sys.setprofile(f)
Use c-version of the selective compilationimport _psyco
_psyco.selective(1) # Argument is number of invocations before rebinding
# import sys
# ticks = 0
# depth = 10
# funcs = {}
# def f(frame, event, arg):
# if event != 'call': return
# print type(frame.f_globals)
# c = frame.f_code.co_code
# fn = frame.f_code.co_name
# g = frame.f_globals
# if not funcs.has_key(c):
# funcs[c] = 1
# if funcs[c] != None:
# funcs[c] = funcs[c] + 1
# if funcs[c] > ticks and g.has_key(fn):
# g[fn] = _psyco.proxy(g[fn], depth)
# funcs[c] = None
# print 'psyco rebinding function:', fn
# sys.setprofile(f)
| <commit_before>import _psyco
import sys
ticks = 0
depth = 10
funcs = {}
def f(frame, event, arg):
if event != 'call': return
c = frame.f_code.co_code
fn = frame.f_code.co_name
g = frame.f_globals
if not funcs.has_key(c):
funcs[c] = 1
if funcs[c] != None:
funcs[c] = funcs[c] + 1
if funcs[c] > ticks and g.has_key(fn):
g[fn] = _psyco.proxy(g[fn], depth)
funcs[c] = None
print 'psyco rebinding function:', fn
sys.setprofile(f)
<commit_msg>Use c-version of the selective compilation<commit_after>import _psyco
_psyco.selective(1) # Argument is number of invocations before rebinding
# import sys
# ticks = 0
# depth = 10
# funcs = {}
# def f(frame, event, arg):
# if event != 'call': return
# print type(frame.f_globals)
# c = frame.f_code.co_code
# fn = frame.f_code.co_name
# g = frame.f_globals
# if not funcs.has_key(c):
# funcs[c] = 1
# if funcs[c] != None:
# funcs[c] = funcs[c] + 1
# if funcs[c] > ticks and g.has_key(fn):
# g[fn] = _psyco.proxy(g[fn], depth)
# funcs[c] = None
# print 'psyco rebinding function:', fn
# sys.setprofile(f)
|
a9f9fc75411aededcb768adf32cc26efd64fe976 | sevenbridges/models/compound/tasks/__init__.py | sevenbridges/models/compound/tasks/__init__.py | from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
if item['class'].lower() in ('file', 'directory'):
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
data.update({k: item[k] for k in item if k != 'path'})
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
| from sevenbridges.models.enums import FileApiFormats
from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
file_class_list = [
FileApiFormats.FILE.lower(),
FileApiFormats.FOLDER.lower()
]
if item['class'].lower() in file_class_list:
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
# map class to type
if item['class'].lower() == FileApiFormats.FOLDER.lower():
data['type'] = 'folder'
else:
data['type'] = 'file'
# map cwl 1 file name
if 'basename' in item:
data['name'] = item['basename']
data.update(
{k: item[k] for k in item if k not in ['path', 'basename']}
)
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
| Add support for cwl1 task outputs so the name is preloaded. Add preloaded file type for task outputs. | Add support for cwl1 task outputs so the name is preloaded.
Add preloaded file type for task outputs.
| Python | apache-2.0 | sbg/sevenbridges-python | from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
if item['class'].lower() in ('file', 'directory'):
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
data.update({k: item[k] for k in item if k != 'path'})
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
Add support for cwl1 task outputs so the name is preloaded.
Add preloaded file type for task outputs. | from sevenbridges.models.enums import FileApiFormats
from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
file_class_list = [
FileApiFormats.FILE.lower(),
FileApiFormats.FOLDER.lower()
]
if item['class'].lower() in file_class_list:
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
# map class to type
if item['class'].lower() == FileApiFormats.FOLDER.lower():
data['type'] = 'folder'
else:
data['type'] = 'file'
# map cwl 1 file name
if 'basename' in item:
data['name'] = item['basename']
data.update(
{k: item[k] for k in item if k not in ['path', 'basename']}
)
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
| <commit_before>from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
if item['class'].lower() in ('file', 'directory'):
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
data.update({k: item[k] for k in item if k != 'path'})
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
<commit_msg>Add support for cwl1 task outputs so the name is preloaded.
Add preloaded file type for task outputs.<commit_after> | from sevenbridges.models.enums import FileApiFormats
from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
file_class_list = [
FileApiFormats.FILE.lower(),
FileApiFormats.FOLDER.lower()
]
if item['class'].lower() in file_class_list:
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
# map class to type
if item['class'].lower() == FileApiFormats.FOLDER.lower():
data['type'] = 'folder'
else:
data['type'] = 'file'
# map cwl 1 file name
if 'basename' in item:
data['name'] = item['basename']
data.update(
{k: item[k] for k in item if k not in ['path', 'basename']}
)
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
| from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
if item['class'].lower() in ('file', 'directory'):
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
data.update({k: item[k] for k in item if k != 'path'})
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
Add support for cwl1 task outputs so the name is preloaded.
Add preloaded file type for task outputs.from sevenbridges.models.enums import FileApiFormats
from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
file_class_list = [
FileApiFormats.FILE.lower(),
FileApiFormats.FOLDER.lower()
]
if item['class'].lower() in file_class_list:
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
# map class to type
if item['class'].lower() == FileApiFormats.FOLDER.lower():
data['type'] = 'folder'
else:
data['type'] = 'file'
# map cwl 1 file name
if 'basename' in item:
data['name'] = item['basename']
data.update(
{k: item[k] for k in item if k not in ['path', 'basename']}
)
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
| <commit_before>from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
if item['class'].lower() in ('file', 'directory'):
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
data.update({k: item[k] for k in item if k != 'path'})
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
<commit_msg>Add support for cwl1 task outputs so the name is preloaded.
Add preloaded file type for task outputs.<commit_after>from sevenbridges.models.enums import FileApiFormats
from sevenbridges.models.file import File
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
file_class_list = [
FileApiFormats.FILE.lower(),
FileApiFormats.FOLDER.lower()
]
if item['class'].lower() in file_class_list:
_secondary_files = []
for _file in item.get('secondaryFiles', []):
_secondary_files.append({'id': _file['path']})
data = {
'id': item['path']
}
# map class to type
if item['class'].lower() == FileApiFormats.FOLDER.lower():
data['type'] = 'folder'
else:
data['type'] = 'file'
# map cwl 1 file name
if 'basename' in item:
data['name'] = item['basename']
data.update(
{k: item[k] for k in item if k not in ['path', 'basename']}
)
if _secondary_files:
data.update({
'_secondary_files': _secondary_files,
'fetched': True
})
return File(api=api, **data)
else:
return item
|
72382916560d275a0bb456ab4d5bd0e63e95cff4 | css_updater/git/webhook/handler.py | css_updater/git/webhook/handler.py | """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
| """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
@property
def url(self: Handler) -> str:
"""returns url to github repository"""
return self.data["repository"]["html_url"]
| Add function to return URL | Add function to return URL
| Python | mit | neoliberal/css-updater | """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
Add function to return URL | """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
@property
def url(self: Handler) -> str:
"""returns url to github repository"""
return self.data["repository"]["html_url"]
| <commit_before>"""handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
<commit_msg>Add function to return URL<commit_after> | """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
@property
def url(self: Handler) -> str:
"""returns url to github repository"""
return self.data["repository"]["html_url"]
| """handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
Add function to return URL"""handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
@property
def url(self: Handler) -> str:
"""returns url to github repository"""
return self.data["repository"]["html_url"]
| <commit_before>"""handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
<commit_msg>Add function to return URL<commit_after>"""handles webhook"""
from typing import Any, List, Dict
class Handler(object):
"""wraps webhook data"""
def __init__(self: Handler, data: Dict[str, Any]) -> None:
self.data: Dict[str, Any] = data
@property
def head_commit(self: Handler) -> Dict[str, Any]:
"""returns head_commit for convienent access"""
return self.data["head_commit"]
@property
def timestamp(self: Handler) -> str:
"""returns timestamp of the head commit"""
return self.head_commit["timestamp"]
@property
def changed_files(self: Handler) -> List[str]:
"""returns added or changed files"""
return self.head_commit["added"] + self.head_commit["modified"]
@property
def removed_files(self: Handler) -> List[str]:
"""returns removed files"""
return self.head_commit["removed"]
@property
def commits(self: Handler) -> List[Dict[str, Any]]:
"""returns commits"""
return self.data["commits"]
@property
def author(self: Handler) -> str:
"""returns author of head commit"""
return self.head_commit["author"]["username"]
@property
def branch(self: Handler) -> str:
"""returns the branch the commit was pushed to"""
return self.data["ref"].split('/')[-1]
@property
def url(self: Handler) -> str:
"""returns url to github repository"""
return self.data["repository"]["html_url"]
|
e3c413e9642a026dba20c91ae8865c4e193ada5b | tests/create_service_test.py | tests/create_service_test.py | from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
| from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
| Remove an aborted test and add a docstring explaining why this test-less testcase is still here. | Remove an aborted test and add a docstring explaining why this test-less testcase is still here.
| Python | apache-2.0 | Yelp/paasta,Yelp/paasta,somic/paasta,gstarnberger/paasta,somic/paasta,gstarnberger/paasta | from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
Remove an aborted test and add a docstring explaining why this test-less testcase is still here. | from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
| <commit_before>from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
<commit_msg>Remove an aborted test and add a docstring explaining why this test-less testcase is still here.<commit_after> | from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
| from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
Remove an aborted test and add a docstring explaining why this test-less testcase is still here.from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
| <commit_before>from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
def test_append_raises_when_file_dne(self):
self.srw._append()
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
<commit_msg>Remove an aborted test and add a docstring explaining why this test-less testcase is still here.<commit_after>from mock import Mock
import testify as T
import create_service
class SrvReaderWriterTestCase(T.TestCase):
"""I bailed out of this test, but I'll leave this here for now as an
example of how to interact with the Srv* classes."""
@T.setup
def init_service(self):
paths = create_service.paths.SrvPathBuilder("fake_srvpathbuilder")
self.srw = create_service.SrvReaderWriter(paths)
class ValidateOptionsTestCase(T.TestCase):
def test_enable_puppet_requires_puppet_root(self):
parser = Mock()
options = Mock()
options.enable_puppet = True
options.puppet_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
def test_enable_nagios_requires_nagios_root(self):
parser = Mock()
options = Mock()
options.enable_nagios = True
options.nagios_root = None
with T.assert_raises(SystemExit):
create_service.validate_options(parser, options)
if __name__ == "__main__":
T.run()
|
fa7856c152c0f9866f4a3befd507bb7693c350df | runserver.py | runserver.py | #!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=True)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
| #!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=False)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
| Disable reloader. It messes with plugins. | Disable reloader. It messes with plugins.
| Python | bsd-3-clause | rescrv/firmant | #!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=True)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
Disable reloader. It messes with plugins. | #!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=False)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
| <commit_before>#!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=True)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
<commit_msg>Disable reloader. It messes with plugins.<commit_after> | #!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=False)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
| #!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=True)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
Disable reloader. It messes with plugins.#!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=False)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
| <commit_before>#!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=True)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
<commit_msg>Disable reloader. It messes with plugins.<commit_after>#!/usr/bin/python
from optparse import OptionParser
from sys import stderr
import pytz
from werkzeug import script
from werkzeug.script import make_runserver
from firmant.wsgi import Application
from firmant.utils import mod_to_dict
from firmant.utils import get_module
parser = OptionParser()
parser.add_option('-s', '--settings',
dest='settings', type='string', default='settings',
help='the settings module to use for the test server.')
parser.add_option('-p', '--port',
dest='port', type='int', default='8080',
help='the port on which to run the test server.')
parser.add_option('-H', '--host',
dest='host', type='string', default='',
help='the host to which the server should bind.')
(options, args) = parser.parse_args()
try:
settings = mod_to_dict(get_module(options.settings))
except ImportError:
stderr.write('Please specify a settings module that can be imported.\n')
exit(1)
def make_app():
return Application(settings)
action_runserver = script.make_runserver(make_app, use_reloader=False)
if __name__ == '__main__':
print 'Starting local WSGI Server'
print 'Please do not use this server for production'
script.run()
|
a0eaad7d4d4426c9d497409a6699929c71afeea7 | opps/views/generic/detail.py | opps/views/generic/detail.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
names = []
domain_folder = self.get_template_folder()
names.append(u'{}/{}/{}.html'.format(
domain_folder, self.long_slug, self.slug))
names.append(u'{}/{}.html'.format(domain_folder, self.long_slug))
try:
names = names + super(DetailView, self).get_template_names()
except ImproperlyConfigured:
pass
return names
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
| Fix opps template engine (name list) on DetailView | Fix opps template engine (name list) on DetailView
| Python | mit | jeanmask/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
names = []
domain_folder = self.get_template_folder()
names.append(u'{}/{}/{}.html'.format(
domain_folder, self.long_slug, self.slug))
names.append(u'{}/{}.html'.format(domain_folder, self.long_slug))
try:
names = names + super(DetailView, self).get_template_names()
except ImproperlyConfigured:
pass
return names
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
Fix opps template engine (name list) on DetailView | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
names = []
domain_folder = self.get_template_folder()
names.append(u'{}/{}/{}.html'.format(
domain_folder, self.long_slug, self.slug))
names.append(u'{}/{}.html'.format(domain_folder, self.long_slug))
try:
names = names + super(DetailView, self).get_template_names()
except ImproperlyConfigured:
pass
return names
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
<commit_msg>Fix opps template engine (name list) on DetailView<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
names = []
domain_folder = self.get_template_folder()
names.append(u'{}/{}/{}.html'.format(
domain_folder, self.long_slug, self.slug))
names.append(u'{}/{}.html'.format(domain_folder, self.long_slug))
try:
names = names + super(DetailView, self).get_template_names()
except ImproperlyConfigured:
pass
return names
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
Fix opps template engine (name list) on DetailView#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
names = []
domain_folder = self.get_template_folder()
names.append(u'{}/{}/{}.html'.format(
domain_folder, self.long_slug, self.slug))
names.append(u'{}/{}.html'.format(domain_folder, self.long_slug))
try:
names = names + super(DetailView, self).get_template_names()
except ImproperlyConfigured:
pass
return names
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
<commit_msg>Fix opps template engine (name list) on DetailView<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
|
9f69c886a1b5d75444e2efcfa29ce636d000b0a0 | microbower/__init__.py | microbower/__init__.py |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
|
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
if not os.path.isdir(bowerrc['directory']):
os.makedirs(bowerrc['directory'])
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
| Make the destination directory if it does not exist | Make the destination directory if it does not exist
| Python | isc | zenhack/microbower |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
Make the destination directory if it does not exist |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
if not os.path.isdir(bowerrc['directory']):
os.makedirs(bowerrc['directory'])
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
| <commit_before>
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
<commit_msg>Make the destination directory if it does not exist<commit_after> |
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
if not os.path.isdir(bowerrc['directory']):
os.makedirs(bowerrc['directory'])
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
|
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
Make the destination directory if it does not exist
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
if not os.path.isdir(bowerrc['directory']):
os.makedirs(bowerrc['directory'])
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
| <commit_before>
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
<commit_msg>Make the destination directory if it does not exist<commit_after>
from subprocess import check_call
import urllib
import json
import os
import os.path
def install():
with open('.bowerrc') as f:
bowerrc = json.load(f)
with open('bower.json') as f:
bower_json = json.load(f)
registry = 'https://bower.herokuapp.com'
topdir = os.path.abspath(os.curdir)
for pkg in bower_json['dependencies'].keys():
req = urllib.urlopen('%s/packages/%s' % (registry, pkg))
info = json.load(req)
if not os.path.isdir(bowerrc['directory']):
os.makedirs(bowerrc['directory'])
os.chdir(bowerrc['directory'])
check_call(['git', 'clone', info['url']])
os.chdir(pkg)
install()
os.chdir(topdir)
|
28afd50b0243cedf0796b57600bfbb5845623843 | warehouse/database/mixins.py | warehouse/database/mixins.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue())
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue(for_update=True))
| Make the FetchedValue marked as for_update | Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631
| Python | bsd-2-clause | davidfischer/warehouse | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue())
Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631 | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue(for_update=True))
| <commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue())
<commit_msg>Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631<commit_after> | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue(for_update=True))
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue())
Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue(for_update=True))
| <commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue())
<commit_msg>Make the FetchedValue marked as for_update
SQLAlchemy is currently unable to determine between a FetchedValue
inside of a server_default and one inside of a server_onupdate
causing the one in server_onupdate to override the func.now()
in server_default.
See: http://www.sqlalchemy.org/trac/ticket/2631<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import text
from warehouse import db
from warehouse.database.schema import TableDDL
class UUIDPrimaryKeyMixin(object):
id = db.Column(pg.UUID(as_uuid=True),
primary_key=True, server_default=text("uuid_generate_v4()"))
class TimeStampedMixin(object):
__table_args__ = (
TableDDL("""
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.modified = now();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER update_%(table)s_modtime
BEFORE UPDATE
ON %(table)s
FOR EACH ROW
EXECUTE PROCEDURE update_modified_column();
"""),
)
created = db.Column(db.DateTime, nullable=False, server_default=func.now())
modified = db.Column(db.DateTime, nullable=False,
server_default=func.now(),
server_onupdate=FetchedValue(for_update=True))
|
059125f04430dd525205fe9b4331ac87c5556d8c | thumbor_cloud_storage/loaders/cloud_storage_loader.py | thumbor_cloud_storage/loaders/cloud_storage_loader.py | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
callback(blob.download_as_string())
| from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
if blob:
callback(blob.download_as_string())
else:
callback(blob)
| Return None on missing object | Return None on missing object
| Python | mit | Superbalist/thumbor-cloud-storage | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
callback(blob.download_as_string())
Return None on missing object | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
if blob:
callback(blob.download_as_string())
else:
callback(blob)
| <commit_before>from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
callback(blob.download_as_string())
<commit_msg>Return None on missing object<commit_after> | from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
if blob:
callback(blob.download_as_string())
else:
callback(blob)
| from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
callback(blob.download_as_string())
Return None on missing objectfrom tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
if blob:
callback(blob.download_as_string())
else:
callback(blob)
| <commit_before>from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
callback(blob.download_as_string())
<commit_msg>Return None on missing object<commit_after>from tornado.concurrent import return_future
from gcloud import storage
from collections import defaultdict
buckets = defaultdict(dict)
@return_future
def load(context, path, callback):
bucket_id = context.config.get("CLOUD_STORAGE_BUCKET_ID")
project_id = context.config.get("CLOUD_STORAGE_PROJECT_ID")
bucket = buckets[project_id].get(bucket_id, None)
if bucket is None:
client = storage.Client(project_id)
bucket = client.get_bucket(bucket_id)
buckets[project_id][bucket_id] = bucket
blob = bucket.get_blob(path)
if blob:
callback(blob.download_as_string())
else:
callback(blob)
|
5497d37337ae16b31b3cc9eba39d143c7a6adeca | hr_employee_service_contract/migrations/12.0.1.0.0/pre-migration.py | hr_employee_service_contract/migrations/12.0.1.0.0/pre-migration.py | # Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date;
WHERE initial_employment_date IS NOT NULL;
"""
)
| # Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date
WHERE initial_employment_date IS NOT NULL;
"""
)
| Fix bad syntax in query | Fix bad syntax in query
the query is not correct because of semicolon
| Python | agpl-3.0 | OCA/hr,OCA/hr,OCA/hr | # Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date;
WHERE initial_employment_date IS NOT NULL;
"""
)
Fix bad syntax in query
the query is not correct because of semicolon | # Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date
WHERE initial_employment_date IS NOT NULL;
"""
)
| <commit_before># Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date;
WHERE initial_employment_date IS NOT NULL;
"""
)
<commit_msg>Fix bad syntax in query
the query is not correct because of semicolon<commit_after> | # Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date
WHERE initial_employment_date IS NOT NULL;
"""
)
| # Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date;
WHERE initial_employment_date IS NOT NULL;
"""
)
Fix bad syntax in query
the query is not correct because of semicolon# Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date
WHERE initial_employment_date IS NOT NULL;
"""
)
| <commit_before># Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date;
WHERE initial_employment_date IS NOT NULL;
"""
)
<commit_msg>Fix bad syntax in query
the query is not correct because of semicolon<commit_after># Copyright 2019 Eficent <http://www.eficent.com>
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
if openupgrade.column_exists(cr, 'hr_employee', 'initial_employment_date'):
openupgrade.logged_query(
cr, """
UPDATE hr_employee
SET service_hire_date = initial_employment_date
WHERE initial_employment_date IS NOT NULL;
"""
)
|
0d261edf436fac06d8a8bd35fba34e1773aee460 | alexandria/__init__.py | alexandria/__init__.py | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
| import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
| Check for some required settings | Check for some required settings
| Python | isc | cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
Check for some required settings | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
| <commit_before>import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
<commit_msg>Check for some required settings<commit_after> | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
| import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
Check for some required settingsimport logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
| <commit_before>import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
<commit_msg>Check for some required settings<commit_after>import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
config.add_static_view('static', 'static', cache_max_age=3600)
|
1265221d0300ff214cef12dc244f745c7f2ec316 | tests/core/ast_transforms/test_basic_sanity.py | tests/core/ast_transforms/test_basic_sanity.py |
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
if __name__ == '__main__':
import pytest
pytest.main()
|
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def zero(x):
return 0
def child_faker(x):
return 42
child_faker.__name__ = 'child'
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_square_to_zero():
original = parent(2)
assert original == 16
result = parent(2, child=zero)
assert result == 0
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_with_faked_child():
# maliciously faking a function's name should not affect the result
# this can also happen when using decorators
assert child_faker.__name__ == child.__name__
original = parent(1)
assert original == 4
result = parent(1, child=child_faker)
assert result == 42
final = parent(1)
assert final == 4
if __name__ == '__main__':
import pytest
pytest.main()
| Add a failing, coverage-increasing test | Add a failing, coverage-increasing test
| Python | mit | dwillmer/fastats,fastats/fastats |
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
if __name__ == '__main__':
import pytest
pytest.main()
Add a failing, coverage-increasing test |
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def zero(x):
return 0
def child_faker(x):
return 42
child_faker.__name__ = 'child'
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_square_to_zero():
original = parent(2)
assert original == 16
result = parent(2, child=zero)
assert result == 0
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_with_faked_child():
# maliciously faking a function's name should not affect the result
# this can also happen when using decorators
assert child_faker.__name__ == child.__name__
original = parent(1)
assert original == 4
result = parent(1, child=child_faker)
assert result == 42
final = parent(1)
assert final == 4
if __name__ == '__main__':
import pytest
pytest.main()
| <commit_before>
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
if __name__ == '__main__':
import pytest
pytest.main()
<commit_msg>Add a failing, coverage-increasing test<commit_after> |
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def zero(x):
return 0
def child_faker(x):
return 42
child_faker.__name__ = 'child'
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_square_to_zero():
original = parent(2)
assert original == 16
result = parent(2, child=zero)
assert result == 0
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_with_faked_child():
# maliciously faking a function's name should not affect the result
# this can also happen when using decorators
assert child_faker.__name__ == child.__name__
original = parent(1)
assert original == 4
result = parent(1, child=child_faker)
assert result == 42
final = parent(1)
assert final == 4
if __name__ == '__main__':
import pytest
pytest.main()
|
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
if __name__ == '__main__':
import pytest
pytest.main()
Add a failing, coverage-increasing test
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def zero(x):
return 0
def child_faker(x):
return 42
child_faker.__name__ = 'child'
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_square_to_zero():
original = parent(2)
assert original == 16
result = parent(2, child=zero)
assert result == 0
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_with_faked_child():
# maliciously faking a function's name should not affect the result
# this can also happen when using decorators
assert child_faker.__name__ == child.__name__
original = parent(1)
assert original == 4
result = parent(1, child=child_faker)
assert result == 42
final = parent(1)
assert final == 4
if __name__ == '__main__':
import pytest
pytest.main()
| <commit_before>
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
if __name__ == '__main__':
import pytest
pytest.main()
<commit_msg>Add a failing, coverage-increasing test<commit_after>
from fastats.core.decorator import fs
from tests import cube
def child(x):
return x * x
@fs
def parent(a):
b = 2 * a
result = child(b)
return result
def quad(x):
return cube(x) * x
def zero(x):
return 0
def child_faker(x):
return 42
child_faker.__name__ = 'child'
def test_child_transform_square_to_cube_execution():
original = parent(2)
assert original == 16
result = parent(2, child=cube)
assert result == 64
final = parent(2)
assert final == 16
def test_child_transform_square_to_quadruple():
original = parent(2)
assert original == 16
result = parent(2, child=quad)
assert result == 256
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_square_to_zero():
original = parent(2)
assert original == 16
result = parent(2, child=zero)
assert result == 0
final_two = parent(2)
assert final_two == 16
final = parent(3)
assert final == 36
def test_child_transform_with_faked_child():
# maliciously faking a function's name should not affect the result
# this can also happen when using decorators
assert child_faker.__name__ == child.__name__
original = parent(1)
assert original == 4
result = parent(1, child=child_faker)
assert result == 42
final = parent(1)
assert final == 4
if __name__ == '__main__':
import pytest
pytest.main()
|
fbe3644bf58f29150ada009951691425571429d4 | moocng/eco_api/urls.py | moocng/eco_api/urls.py | # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
| # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w.]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
| Fix courses by user url | Fix courses by user url
| Python | apache-2.0 | GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng,GeographicaGS/moocng | # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
Fix courses by user url | # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w.]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
| <commit_before># -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
<commit_msg>Fix courses by user url<commit_after> | # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w.]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
| # -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
Fix courses by user url# -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w.]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
| <commit_before># -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
<commit_msg>Fix courses by user url<commit_after># -*- coding: utf-8 -*-
# Copyright 2012-2013 UNED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import include, patterns, url
from django.views.generic import RedirectView
urlpatterns = patterns(
'moocng.eco_api.views',
url(r'^oai/$', 'ListRecords', name='ListRecords'),
url(r'^heartbeat', 'heartbeat', name='heartbeat'),
url(r'^users/(?P<id>[-\w.]+)/courses', 'courses_by_users', name='heartbeat'),
url(r'^teachers/(?P<id>[-\w]+)/', 'teacher', name='heartbeat'),
url(r'^tasks/(?P<id>[-\w]+)/', 'tasks_by_course', name='tasks_by_course')
)
|
2a46eecd0fbd13dd03610b7bbace6cf84466f455 | mysite/search/tests.py | mysite/search/tests.py | import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
# FIXME: This should test for 1 to 10, not 0 to 10
response = self.client.get('/search/')
self.assertContains(response, '0 to 10')
| import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
response = self.client.get('/search/')
self.failUnlessEqual(response.context['start'], 1)
self.failUnlessEqual(response.context['end'], 10)
| Use the response.context to check the provided start and end | Use the response.context to check the provided start and end
| Python | agpl-3.0 | Changaco/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,onceuponatimeforever/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,openhatch/oh-mainline,willingc/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,heeraj123/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,vipul-sharma20/oh-mainline,jledbetter/openhatch,willingc/oh-mainline,Changaco/oh-mainline,openhatch/oh-mainline,SnappleCap/oh-mainline,ehashman/oh-mainline,openhatch/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,onceuponatimeforever/oh-mainline,Changaco/oh-mainline,ehashman/oh-mainline,jledbetter/openhatch,onceuponatimeforever/oh-mainline,campbe13/openhatch,waseem18/oh-mainline,eeshangarg/oh-mainline,moijes12/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,moijes12/oh-mainline,eeshangarg/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,moijes12/oh-mainline,nirmeshk/oh-mainline,nirmeshk/oh-mainline,nirmeshk/oh-mainline,nirmeshk/oh-mainline,heeraj123/oh-mainline,heeraj123/oh-mainline,ojengwa/oh-mainline,SnappleCap/oh-mainline,ojengwa/oh-mainline,onceuponatimeforever/oh-mainline,waseem18/oh-mainline,eeshangarg/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,jledbetter/openhatch,ojengwa/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,willingc/oh-mainline,vipul-sharma20/oh-mainline,Changaco/oh-mainline,eeshangarg/oh-mainline,ehashman/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,moijes12/oh-mainline,jledbetter/openhatch,campbe13/openhatch,Changaco/oh-mainline,jledbetter/openhatch | import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
# FIXME: This should test for 1 to 10, not 0 to 10
response = self.client.get('/search/')
self.assertContains(response, '0 to 10')
Use the response.context to check the provided start and end | import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
response = self.client.get('/search/')
self.failUnlessEqual(response.context['start'], 1)
self.failUnlessEqual(response.context['end'], 10)
| <commit_before>import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
# FIXME: This should test for 1 to 10, not 0 to 10
response = self.client.get('/search/')
self.assertContains(response, '0 to 10')
<commit_msg>Use the response.context to check the provided start and end<commit_after> | import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
response = self.client.get('/search/')
self.failUnlessEqual(response.context['start'], 1)
self.failUnlessEqual(response.context['end'], 10)
| import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
# FIXME: This should test for 1 to 10, not 0 to 10
response = self.client.get('/search/')
self.assertContains(response, '0 to 10')
Use the response.context to check the provided start and endimport django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
response = self.client.get('/search/')
self.failUnlessEqual(response.context['start'], 1)
self.failUnlessEqual(response.context['end'], 10)
| <commit_before>import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
# FIXME: This should test for 1 to 10, not 0 to 10
response = self.client.get('/search/')
self.assertContains(response, '0 to 10')
<commit_msg>Use the response.context to check the provided start and end<commit_after>import django.test
from search.models import Project
class NonJavascriptSearch(django.test.TestCase):
fixtures = ['bugs-for-two-projects.json']
def testSearch(self):
response = self.client.get('/search/')
for n in range(1, 11):
self.assertContains(response, 'Title #%d' % n)
self.assertContains(response, 'Description #%d' % n)
def testMatchingBugsFromMtoN(self):
response = self.client.get('/search/')
self.failUnlessEqual(response.context['start'], 1)
self.failUnlessEqual(response.context['end'], 10)
|
b22b292ec2b839d611738928f41c79723146ea15 | readthedocs/core/migrations/0005_migrate-old-passwords.py | readthedocs/core/migrations/0005_migrate-old-passwords.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.set_unusable_password()
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.password = make_password(None)
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
| Migrate old passwords without "set_unusable_password" | Migrate old passwords without "set_unusable_password"
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.set_unusable_password()
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
Migrate old passwords without "set_unusable_password" | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.password = make_password(None)
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.set_unusable_password()
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
<commit_msg>Migrate old passwords without "set_unusable_password"<commit_after> | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.password = make_password(None)
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.set_unusable_password()
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
Migrate old passwords without "set_unusable_password"# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.password = make_password(None)
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.set_unusable_password()
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
<commit_msg>Migrate old passwords without "set_unusable_password"<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-11 17:28
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.hashers import make_password
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
old_password_patterns = (
'sha1$',
# RTD's production database doesn't have any of these
# but they are included for completeness
'md5$',
'crypt$',
)
for pattern in old_password_patterns:
users = User.objects.filter(password__startswith=pattern)
for user in users:
user.password = make_password(None)
user.save()
class Migration(migrations.Migration):
dependencies = [
('core', '0004_ad-opt-out'),
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.RunPython(forwards_func),
]
|
d70360601669f9e58072cd121de79896690471fd | buildlet/datastore/tests/test_inmemory.py | buildlet/datastore/tests/test_inmemory.py | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
| import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
class TestDataStoreNestableInMemoryAutoValue(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemoryAutoValue
| Fix and add tests for datastore.inmemory | Fix and add tests for datastore.inmemory
| Python | bsd-3-clause | tkf/buildlet | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
Fix and add tests for datastore.inmemory | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
class TestDataStoreNestableInMemoryAutoValue(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemoryAutoValue
| <commit_before>import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
<commit_msg>Fix and add tests for datastore.inmemory<commit_after> | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
class TestDataStoreNestableInMemoryAutoValue(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemoryAutoValue
| import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
Fix and add tests for datastore.inmemoryimport unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
class TestDataStoreNestableInMemoryAutoValue(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemoryAutoValue
| <commit_before>import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
<commit_msg>Fix and add tests for datastore.inmemory<commit_after>import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
def test_set_get_singleton(self):
obj = object()
self.ds.set(obj)
self.assertTrue(self.ds.get() is obj)
class TestDataStreamInMemory(MixInStreamTestCase, unittest.TestCase):
dstype = DataStreamInMemory
class TestDataStoreNestableInMemory(MixInNestableTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemory
class TestDataStoreNestableInMemoryAutoValue(MixInNestableAutoValueTestCase,
unittest.TestCase):
dstype = DataStoreNestableInMemoryAutoValue
|
eba8a0796242d18807e1cace97bd476386ade0aa | functions.py | functions.py | import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
import requests
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["shares"]
| import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
try:
return adict["shares"]
except:
pass
| Put in a try for shares function | Put in a try for shares function
| Python | mit | miklevin/pipulate,miklevin/pipulate,whofman/my-pipulate,whofman/my-pipulate,miklevin/pipulate,whofman/my-pipulate | import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
import requests
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["shares"]
Put in a try for shares function | import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
try:
return adict["shares"]
except:
pass
| <commit_before>import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
import requests
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["shares"]
<commit_msg>Put in a try for shares function<commit_after> | import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
try:
return adict["shares"]
except:
pass
| import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
import requests
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["shares"]
Put in a try for shares functionimport requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
try:
return adict["shares"]
except:
pass
| <commit_before>import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
import requests
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["shares"]
<commit_msg>Put in a try for shares function<commit_after>import requests
def tweets(url):
api = "http://urls.api.twitter.com/1/urls/count.json?url="
respobj = requests.get(api + url)
adict = respobj.json()
return adict["count"]
def plusses(url):
api = "https://clients6.google.com/rpc"
jobj = '''{
"method":"pos.plusones.get",
"id":"p",
"params":{
"nolog":true,
"id":"%s",
"source":"widget",
"userId":"@viewer",
"groupId":"@self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
}''' % (url)
respobj = requests.post(api, jobj)
adict = respobj.json()
return adict['result']['metadata']['globalCounts']['count']
def shares(url):
api = "http://graph.facebook.com/?id="
respobj = requests.get(api + url)
adict = respobj.json()
try:
return adict["shares"]
except:
pass
|
c048b42e7eac68f0e7ab300efab5f414227c0a21 | readthedocs/tastyapi/slum.py | readthedocs/tastyapi/slum.py | import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'http://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
| import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'https://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
| Fix http->https for the API | Fix http->https for the API
| Python | mit | KamranMackey/readthedocs.org,SteveViss/readthedocs.org,dirn/readthedocs.org,agjohnson/readthedocs.org,raven47git/readthedocs.org,attakei/readthedocs-oauth,sils1297/readthedocs.org,safwanrahman/readthedocs.org,d0ugal/readthedocs.org,agjohnson/readthedocs.org,espdev/readthedocs.org,raven47git/readthedocs.org,singingwolfboy/readthedocs.org,espdev/readthedocs.org,clarkperkins/readthedocs.org,Carreau/readthedocs.org,singingwolfboy/readthedocs.org,nikolas/readthedocs.org,istresearch/readthedocs.org,sils1297/readthedocs.org,mrshoki/readthedocs.org,takluyver/readthedocs.org,raven47git/readthedocs.org,gjtorikian/readthedocs.org,tddv/readthedocs.org,cgourlay/readthedocs.org,espdev/readthedocs.org,LukasBoersma/readthedocs.org,kenwang76/readthedocs.org,pombredanne/readthedocs.org,attakei/readthedocs-oauth,mhils/readthedocs.org,wijerasa/readthedocs.org,pombredanne/readthedocs.org,kenwang76/readthedocs.org,attakei/readthedocs-oauth,ojii/readthedocs.org,GovReady/readthedocs.org,GovReady/readthedocs.org,takluyver/readthedocs.org,emawind84/readthedocs.org,stevepiercy/readthedocs.org,atsuyim/readthedocs.org,royalwang/readthedocs.org,safwanrahman/readthedocs.org,kenshinthebattosai/readthedocs.org,raven47git/readthedocs.org,d0ugal/readthedocs.org,VishvajitP/readthedocs.org,atsuyim/readthedocs.org,wanghaven/readthedocs.org,hach-que/readthedocs.org,sunnyzwh/readthedocs.org,mrshoki/readthedocs.org,mhils/readthedocs.org,atsuyim/readthedocs.org,SteveViss/readthedocs.org,soulshake/readthedocs.org,wijerasa/readthedocs.org,VishvajitP/readthedocs.org,ojii/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,michaelmcandrew/readthedocs.org,michaelmcandrew/readthedocs.org,fujita-shintaro/readthedocs.org,kdkeyser/readthedocs.org,rtfd/readthedocs.org,sunnyzwh/readthedocs.org,asampat3090/readthedocs.org,royalwang/readthedocs.org,asampat3090/readthedocs.org,royalwang/readthedocs.org,LukasBoersma/readthedocs.org,nyergler/pythonslides,KamranMackey/readthedocs.org,ojii/readthedocs.org,attakei/readthedocs-oauth,espdev/readthedocs.org,nikolas/readthedocs.org,KamranMackey/readthedocs.org,titiushko/readthedocs.org,singingwolfboy/readthedocs.org,dirn/readthedocs.org,Carreau/readthedocs.org,d0ugal/readthedocs.org,fujita-shintaro/readthedocs.org,mrshoki/readthedocs.org,wijerasa/readthedocs.org,kenwang76/readthedocs.org,CedarLogic/readthedocs.org,Tazer/readthedocs.org,LukasBoersma/readthedocs.org,techtonik/readthedocs.org,laplaceliu/readthedocs.org,rtfd/readthedocs.org,takluyver/readthedocs.org,GovReady/readthedocs.org,Carreau/readthedocs.org,emawind84/readthedocs.org,Tazer/readthedocs.org,hach-que/readthedocs.org,sils1297/readthedocs.org,royalwang/readthedocs.org,takluyver/readthedocs.org,SteveViss/readthedocs.org,davidfischer/readthedocs.org,kenwang76/readthedocs.org,clarkperkins/readthedocs.org,fujita-shintaro/readthedocs.org,laplaceliu/readthedocs.org,singingwolfboy/readthedocs.org,techtonik/readthedocs.org,mhils/readthedocs.org,mhils/readthedocs.org,jerel/readthedocs.org,cgourlay/readthedocs.org,istresearch/readthedocs.org,tddv/readthedocs.org,safwanrahman/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,CedarLogic/readthedocs.org,LukasBoersma/readthedocs.org,sid-kap/readthedocs.org,jerel/readthedocs.org,jerel/readthedocs.org,fujita-shintaro/readthedocs.org,davidfischer/readthedocs.org,soulshake/readthedocs.org,hach-que/readthedocs.org,sils1297/readthedocs.org,CedarLogic/readthedocs.org,ojii/readthedocs.org,GovReady/readthedocs.org,stevepiercy/readthedocs.org,kdkeyser/readthedocs.org,espdev/readthedocs.org,techtonik/readthedocs.org,clarkperkins/readthedocs.org,gjtorikian/readthedocs.org,wanghaven/readthedocs.org,kenshinthebattosai/readthedocs.org,michaelmcandrew/readthedocs.org,sunnyzwh/readthedocs.org,d0ugal/readthedocs.org,istresearch/readthedocs.org,wanghaven/readthedocs.org,wanghaven/readthedocs.org,gjtorikian/readthedocs.org,CedarLogic/readthedocs.org,VishvajitP/readthedocs.org,laplaceliu/readthedocs.org,jerel/readthedocs.org,dirn/readthedocs.org,rtfd/readthedocs.org,stevepiercy/readthedocs.org,kdkeyser/readthedocs.org,gjtorikian/readthedocs.org,soulshake/readthedocs.org,emawind84/readthedocs.org,clarkperkins/readthedocs.org,laplaceliu/readthedocs.org,mrshoki/readthedocs.org,sunnyzwh/readthedocs.org,sid-kap/readthedocs.org,SteveViss/readthedocs.org,Carreau/readthedocs.org,nyergler/pythonslides,techtonik/readthedocs.org,emawind84/readthedocs.org,michaelmcandrew/readthedocs.org,soulshake/readthedocs.org,safwanrahman/readthedocs.org,stevepiercy/readthedocs.org,cgourlay/readthedocs.org,asampat3090/readthedocs.org,VishvajitP/readthedocs.org,hach-que/readthedocs.org,kdkeyser/readthedocs.org,nyergler/pythonslides,wijerasa/readthedocs.org,nikolas/readthedocs.org,rtfd/readthedocs.org,kenshinthebattosai/readthedocs.org,titiushko/readthedocs.org,davidfischer/readthedocs.org,Tazer/readthedocs.org,istresearch/readthedocs.org,nyergler/pythonslides,nikolas/readthedocs.org,davidfischer/readthedocs.org,cgourlay/readthedocs.org,titiushko/readthedocs.org,titiushko/readthedocs.org,asampat3090/readthedocs.org,dirn/readthedocs.org,Tazer/readthedocs.org,agjohnson/readthedocs.org,sid-kap/readthedocs.org,agjohnson/readthedocs.org,KamranMackey/readthedocs.org,pombredanne/readthedocs.org | import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'http://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
Fix http->https for the API | import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'https://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
| <commit_before>import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'http://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
<commit_msg>Fix http->https for the API<commit_after> | import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'https://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
| import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'http://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
Fix http->https for the APIimport slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'https://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
| <commit_before>import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'http://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
<commit_msg>Fix http->https for the API<commit_after>import slumber
import json
import logging
from django.conf import settings
log = logging.getLogger(__name__)
USER = getattr(settings, 'SLUMBER_USERNAME', None)
PASS = getattr(settings, 'SLUMBER_PASSWORD', None)
API_HOST = getattr(settings, 'SLUMBER_API_HOST', 'https://readthedocs.org')
if USER and PASS:
log.debug("Using slumber with user %s, pointed at %s" % (USER, API_HOST))
api = slumber.API(base_url='%s/api/v1/' % API_HOST, auth=(USER, PASS))
else:
log.warning("SLUMBER_USERNAME/PASSWORD settings are not set")
api = slumber.API(base_url='%s/api/v1/' % API_HOST)
|
a54be407e4b18250f24a256fe6d615f25d42a7ee | pubrunner/snakemake.py | pubrunner/snakemake.py |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags = "--cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
|
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags += " --cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
| Fix for non-DRMAA cluster run | Fix for non-DRMAA cluster run
| Python | mit | jakelever/pubrunner,jakelever/pubrunner |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags = "--cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
Fix for non-DRMAA cluster run |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags += " --cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
| <commit_before>
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags = "--cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
<commit_msg>Fix for non-DRMAA cluster run<commit_after> |
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags += " --cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
|
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags = "--cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
Fix for non-DRMAA cluster run
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags += " --cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
| <commit_before>
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags = "--cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
<commit_msg>Fix for non-DRMAA cluster run<commit_after>
import pubrunner
import os
import shlex
import subprocess
def launchSnakemake(snakeFilePath,useCluster=True,parameters={}):
globalSettings = pubrunner.getGlobalSettings()
clusterFlags = ""
if useCluster and "cluster" in globalSettings:
clusterSettings = globalSettings["cluster"]
jobs = 1
if "jobs" in globalSettings["cluster"]:
jobs = int(globalSettings["cluster"]["jobs"])
clusterFlags = "--jobs %d --latency-wait 60" % jobs
if "drmaa" in clusterSettings and clusterSettings["drmaa"] == True:
clusterFlags += ' --drmaa'
elif "options" in clusterSettings:
clusterFlags += " --cluster '%s'" % clusterSettings["options"]
else:
raise RuntimeError("Cluster must either have drmaa = true or provide options (e.g. using qsub)")
makecommand = "snakemake %s --nolock -s %s" % (clusterFlags,snakeFilePath)
env = os.environ.copy()
env.update(parameters)
retval = subprocess.call(shlex.split(makecommand),env=env)
if retval != 0:
raise RuntimeError("Snake make call FAILED (file:%s)" % snakeFilePath)
|
2cfe6e6c9284dfffba2943a8562e38844b6ba089 | temba/campaigns/migrations/0015_campaignevent_message_new.py | temba/campaigns/migrations/0015_campaignevent_message_new.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
event.message_new = {event.flow.base_language: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
base_lang = event.flow.base_language or 'base'
event.message_new = {base_lang: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
| Fix migration to work with flows with no base_language | Fix migration to work with flows with no base_language
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
event.message_new = {event.flow.base_language: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
Fix migration to work with flows with no base_language | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
base_lang = event.flow.base_language or 'base'
event.message_new = {base_lang: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
event.message_new = {event.flow.base_language: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
<commit_msg>Fix migration to work with flows with no base_language<commit_after> | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
base_lang = event.flow.base_language or 'base'
event.message_new = {base_lang: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
event.message_new = {event.flow.base_language: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
Fix migration to work with flows with no base_language# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
base_lang = event.flow.base_language or 'base'
event.message_new = {base_lang: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
event.message_new = {event.flow.base_language: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
<commit_msg>Fix migration to work with flows with no base_language<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals
import json
import temba.utils.models
from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations
def populate_message_new(apps, schema_editor):
CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))
for event in events:
try:
event.message_new = json.loads(event.message)
except Exception:
base_lang = event.flow.base_language or 'base'
event.message_new = {base_lang: event.message}
event.save(update_fields=('message_new',))
if events:
print("Converted %d campaign events" % len(events))
class Migration(migrations.Migration):
dependencies = [
('campaigns', '0014_auto_20170228_0837'),
]
operations = [
HStoreExtension(),
migrations.AddField(
model_name='campaignevent',
name='message_new',
field=temba.utils.models.TranslatableField(max_length=640, null=True),
),
migrations.RunPython(populate_message_new)
]
|
b2addc724a35c3859e8982ddecff180b6e2ec9df | exercises/control_movement.py | exercises/control_movement.py | """Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
#rueda_izquierda = raw_input("Velocidad izquierda: ")
#rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
| """Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
# rueda_izquierda = raw_input("Velocidad izquierda: ")
# rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
| Correct style of wheels exercise | Correct style of wheels exercise
| Python | mit | AliGhahraei/nao-classroom | """Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
#rueda_izquierda = raw_input("Velocidad izquierda: ")
#rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
Correct style of wheels exercise | """Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
# rueda_izquierda = raw_input("Velocidad izquierda: ")
# rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
| <commit_before>"""Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
#rueda_izquierda = raw_input("Velocidad izquierda: ")
#rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
<commit_msg> Correct style of wheels exercise<commit_after> | """Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
# rueda_izquierda = raw_input("Velocidad izquierda: ")
# rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
| """Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
#rueda_izquierda = raw_input("Velocidad izquierda: ")
#rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
Correct style of wheels exercise"""Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
# rueda_izquierda = raw_input("Velocidad izquierda: ")
# rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
| <commit_before>"""Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
#rueda_izquierda = raw_input("Velocidad izquierda: ")
#rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
<commit_msg> Correct style of wheels exercise<commit_after>"""Simple exercise file where the kid must write code.
Control the LED light in the finch robot with this small exercise. The code
doesn't run as it is because a kid is supposed to complete the exercise first.
NAO will open this file in an editor.
"""
from exercises.finch.finch import Finch
from time import sleep
finch = Finch()
###############################################################################
# Write your code here. Your code defines the speed of the wheels and the
# duration of their movement
# CODE: rueda_izquierda = 0.5, rueda_derecha = 0, tiempo = 5
rueda_izquierda =
rueda_derecha =
tiempo =
###############################################################################
# Ahora pide al usuario que ingrese las velocidades
# rueda_izquierda = raw_input("Velocidad izquierda: ")
# rueda_derecha = raw_input("Velocidad derecha: ")
finch.wheels(rueda_izquierda, rueda_derecha)
sleep(tiempo)
finch.wheels(0, 0)
|
53de65c29fe4bc3961258bb160210c32ddfaeae4 | django/website/contacts/tests/test_validators.py | django/website/contacts/tests/test_validators.py | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
| from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
def test_calling_year_to_now_with_non_integer_throws_value_error(self):
self.assertRaises(ValidationError, year_to_now, 'a')
self.assertRaises(ValidationError, year_to_now, '1900.1')
| Add test for year_to_now with non-integer values | Add test for year_to_now with non-integer values | Python | agpl-3.0 | aptivate/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana,daniell/kashana,daniell/kashana,daniell/kashana,aptivate/kashana,daniell/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
Add test for year_to_now with non-integer values | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
def test_calling_year_to_now_with_non_integer_throws_value_error(self):
self.assertRaises(ValidationError, year_to_now, 'a')
self.assertRaises(ValidationError, year_to_now, '1900.1')
| <commit_before>from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
<commit_msg>Add test for year_to_now with non-integer values<commit_after> | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
def test_calling_year_to_now_with_non_integer_throws_value_error(self):
self.assertRaises(ValidationError, year_to_now, 'a')
self.assertRaises(ValidationError, year_to_now, '1900.1')
| from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
Add test for year_to_now with non-integer valuesfrom datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
def test_calling_year_to_now_with_non_integer_throws_value_error(self):
self.assertRaises(ValidationError, year_to_now, 'a')
self.assertRaises(ValidationError, year_to_now, '1900.1')
| <commit_before>from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
<commit_msg>Add test for year_to_now with non-integer values<commit_after>from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from contacts.validators import year_to_now
today = date.today()
this_year = today.year
class ValidatorTests(TestCase):
def test_year_to_now(self):
self.assertRaises(ValidationError, year_to_now, 1899)
self.assertRaises(ValidationError, year_to_now, '1899')
self.assertRaises(ValidationError, year_to_now, this_year)
self.assertRaises(ValidationError, year_to_now, this_year + 3)
self.assertIsNone(year_to_now(1900))
self.assertIsNone(year_to_now(this_year - 1))
def test_calling_year_to_now_with_non_integer_throws_value_error(self):
self.assertRaises(ValidationError, year_to_now, 'a')
self.assertRaises(ValidationError, year_to_now, '1900.1')
|
43ca79dbd2067ba9733bf43f81b43aa048bbd900 | seaweb_project/jobs/serializers.py | seaweb_project/jobs/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
| from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
| Implement validation for structure and topology files. | Implement validation for structure and topology
files. | Python | mit | grollins/sea-web-django | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
Implement validation for structure and topology
files. | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
| <commit_before>from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
<commit_msg>Implement validation for structure and topology
files.<commit_after> | from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
| from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
Implement validation for structure and topology
files.from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
| <commit_before>from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
<commit_msg>Implement validation for structure and topology
files.<commit_after>from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
|
cf7e1c52a0242814cf9e621a62414252110765a2 | feincms/content/rss/models.py | feincms/content/rss/models.py | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.save()
| from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
last_updated = models.DateTimeField(_('Last updated'), blank=True, null=True)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.last_updated = datetime.now()
self.save()
| Add last_updated field to RSSContent | Add last_updated field to RSSContent
| Python | bsd-3-clause | joshuajonah/feincms,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/django-content-editor,feincms/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,feincms/feincms,pjdelport/feincms,hgrimelid/feincms,mjl/feincms,joshuajonah/feincms,mjl/feincms,hgrimelid/feincms,michaelkuty/feincms,feincms/feincms,nickburlett/feincms,mjl/feincms,matthiask/django-content-editor,joshuajonah/feincms,pjdelport/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/feincms2-content,michaelkuty/feincms,joshuajonah/feincms,matthiask/feincms2-content,nickburlett/feincms,pjdelport/feincms,hgrimelid/feincms | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.save()
Add last_updated field to RSSContent | from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
last_updated = models.DateTimeField(_('Last updated'), blank=True, null=True)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.last_updated = datetime.now()
self.save()
| <commit_before>from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.save()
<commit_msg>Add last_updated field to RSSContent<commit_after> | from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
last_updated = models.DateTimeField(_('Last updated'), blank=True, null=True)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.last_updated = datetime.now()
self.save()
| from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.save()
Add last_updated field to RSSContentfrom datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
last_updated = models.DateTimeField(_('Last updated'), blank=True, null=True)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.last_updated = datetime.now()
self.save()
| <commit_before>from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.save()
<commit_msg>Add last_updated field to RSSContent<commit_after>from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
last_updated = models.DateTimeField(_('Last updated'), blank=True, null=True)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.last_updated = datetime.now()
self.save()
|
e13c6ab9e5e14b457439cefd1ebc9de7facd6ddb | sacredboard/tests/app/test_sacredboard.py | sacredboard/tests/app/test_sacredboard.py | from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.3.3"
| from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.4.0"
| Increase version number to 0.4.0 - fix | Increase version number to 0.4.0 - fix
| Python | mit | chovanecm/sacredboard,chovanecm/sacredboard,chovanecm/sacredboard | from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.3.3"
Increase version number to 0.4.0 - fix | from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.4.0"
| <commit_before>from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.3.3"
<commit_msg>Increase version number to 0.4.0 - fix<commit_after> | from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.4.0"
| from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.3.3"
Increase version number to 0.4.0 - fixfrom unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.4.0"
| <commit_before>from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.3.3"
<commit_msg>Increase version number to 0.4.0 - fix<commit_after>from unittest import TestCase
from sacredboard.app.sacredboard import Sacredboard
class TestSacredboard(TestCase):
def test_get_version(self):
assert Sacredboard.get_version() == "0.4.0"
|
ac0f3c39c471efc9981382acbdb0bb8f9d1cf52e | categories/__init__.py | categories/__init__.py | __version_info__ = {
'major': 1,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| __version_info__ = {
'major': 1,
'minor': 7,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| Update the version to 1.7.1 | Update the version to 1.7.1
| Python | apache-2.0 | callowayproject/django-categories,callowayproject/django-categories,callowayproject/django-categories | __version_info__ = {
'major': 1,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
Update the version to 1.7.1 | __version_info__ = {
'major': 1,
'minor': 7,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| <commit_before>__version_info__ = {
'major': 1,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
<commit_msg>Update the version to 1.7.1<commit_after> | __version_info__ = {
'major': 1,
'minor': 7,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| __version_info__ = {
'major': 1,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
Update the version to 1.7.1__version_info__ = {
'major': 1,
'minor': 7,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
| <commit_before>__version_info__ = {
'major': 1,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
<commit_msg>Update the version to 1.7.1<commit_after>__version_info__ = {
'major': 1,
'minor': 7,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
|
df9dd41cfd7140a266f41296024c4e6ba59f25ec | server/plugins/cryptstatus/cryptstatus.py | server/plugins/cryptstatus/cryptstatus.py | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.Meta.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
| import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
| Fix missed plugin code update. | Fix missed plugin code update.
This `Meta` business is from an earlier draft.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.Meta.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
Fix missed plugin code update.
This `Meta` business is from an earlier draft. | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
| <commit_before>import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.Meta.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
<commit_msg>Fix missed plugin code update.
This `Meta` business is from an earlier draft.<commit_after> | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
| import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.Meta.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
Fix missed plugin code update.
This `Meta` business is from an earlier draft.import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
| <commit_before>import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
class Meta:
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.Meta.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
<commit_msg>Fix missed plugin code update.
This `Meta` business is from an earlier draft.<commit_after>import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Status'
def get_context(self, machine, **kwargs):
context = defaultdict(str)
context['title'] = self.description
crypt_url = utils.get_setting('crypt_url', None).rstrip()
if crypt_url:
try:
verify = settings.ROOT_CA
except AttributeError:
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
try:
response = requests.get(request_url, verify=verify)
if response.status_code == requests.codes.ok:
output = response.json()
# Have template link to machine info page rather
# than Crypt root.
machine_url = '{}/info/{}'.format(crypt_url, machine.serial)
except RequestException:
# Either there was an error or the machine hasn't been
# seen.
output = None
machine_url = crypt_url
if output:
context['escrowed'] = output['escrowed']
if output['escrowed']:
context['date_escrowed'] = parse_datetime(output['date_escrowed'])
context['crypt_url'] = machine_url
return context
|
dd4c35272db9ec7161fd83fc8fb346877f9b74a7 | spyder_unittest/backend/tests/__init__.py | spyder_unittest/backend/tests/__init__.py | # -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# noqa: D104
| Add copyright notice, skip docstring checks | Add copyright notice, skip docstring checks | Python | mit | jitseniesen/spyder-unittest | Add copyright notice, skip docstring checks | # -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# noqa: D104
| <commit_before><commit_msg>Add copyright notice, skip docstring checks<commit_after> | # -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# noqa: D104
| Add copyright notice, skip docstring checks# -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# noqa: D104
| <commit_before><commit_msg>Add copyright notice, skip docstring checks<commit_after># -*- coding: utf-8 -*-
#
# Copyright © 2017 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# noqa: D104
| |
7a5161739b9348e577f484143e56a37f327104c6 | src/gramcore/transformations/geometric.py | src/gramcore/transformations/geometric.py | """
"""
def resize(parameters):
pass
def rotate(parameters):
pass
| """Geometric transformations on arrays. They are more useful in the context
that these arrays are in fact images.
"""
from skimage import transform
def resize(parameters):
"""Resizes input to match a certain size.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#resize
:param parameters['data'][0]: array to resize
:type parameters['data'][0]: numpy.array
:param parameters['output_shape']: size of the output
:type parameters['data'][1]: tuple
:return: numpy.array
"""
return transform.resize(parameters['data'][0], parameters['output_shape'])
def rotate(parameters):
"""Rotates input anti-clockwise around its center.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#rotate
:param parameters['data'][0]: array to rotate
:type parameters['data'][0]: numpy.array
:param parameters['angle']: rotation angle in degrees
:type parameters['angle']: float
:param parameters['resize']: expand
:type parameters['resize']: bool
:return: numpy.array
"""
| Add initial resize and rotate, no tests yet | Add initial resize and rotate, no tests yet
| Python | mit | cpsaltis/pythogram-core | """
"""
def resize(parameters):
pass
def rotate(parameters):
pass
Add initial resize and rotate, no tests yet | """Geometric transformations on arrays. They are more useful in the context
that these arrays are in fact images.
"""
from skimage import transform
def resize(parameters):
"""Resizes input to match a certain size.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#resize
:param parameters['data'][0]: array to resize
:type parameters['data'][0]: numpy.array
:param parameters['output_shape']: size of the output
:type parameters['data'][1]: tuple
:return: numpy.array
"""
return transform.resize(parameters['data'][0], parameters['output_shape'])
def rotate(parameters):
"""Rotates input anti-clockwise around its center.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#rotate
:param parameters['data'][0]: array to rotate
:type parameters['data'][0]: numpy.array
:param parameters['angle']: rotation angle in degrees
:type parameters['angle']: float
:param parameters['resize']: expand
:type parameters['resize']: bool
:return: numpy.array
"""
| <commit_before>"""
"""
def resize(parameters):
pass
def rotate(parameters):
pass
<commit_msg>Add initial resize and rotate, no tests yet<commit_after> | """Geometric transformations on arrays. They are more useful in the context
that these arrays are in fact images.
"""
from skimage import transform
def resize(parameters):
"""Resizes input to match a certain size.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#resize
:param parameters['data'][0]: array to resize
:type parameters['data'][0]: numpy.array
:param parameters['output_shape']: size of the output
:type parameters['data'][1]: tuple
:return: numpy.array
"""
return transform.resize(parameters['data'][0], parameters['output_shape'])
def rotate(parameters):
"""Rotates input anti-clockwise around its center.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#rotate
:param parameters['data'][0]: array to rotate
:type parameters['data'][0]: numpy.array
:param parameters['angle']: rotation angle in degrees
:type parameters['angle']: float
:param parameters['resize']: expand
:type parameters['resize']: bool
:return: numpy.array
"""
| """
"""
def resize(parameters):
pass
def rotate(parameters):
pass
Add initial resize and rotate, no tests yet"""Geometric transformations on arrays. They are more useful in the context
that these arrays are in fact images.
"""
from skimage import transform
def resize(parameters):
"""Resizes input to match a certain size.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#resize
:param parameters['data'][0]: array to resize
:type parameters['data'][0]: numpy.array
:param parameters['output_shape']: size of the output
:type parameters['data'][1]: tuple
:return: numpy.array
"""
return transform.resize(parameters['data'][0], parameters['output_shape'])
def rotate(parameters):
"""Rotates input anti-clockwise around its center.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#rotate
:param parameters['data'][0]: array to rotate
:type parameters['data'][0]: numpy.array
:param parameters['angle']: rotation angle in degrees
:type parameters['angle']: float
:param parameters['resize']: expand
:type parameters['resize']: bool
:return: numpy.array
"""
| <commit_before>"""
"""
def resize(parameters):
pass
def rotate(parameters):
pass
<commit_msg>Add initial resize and rotate, no tests yet<commit_after>"""Geometric transformations on arrays. They are more useful in the context
that these arrays are in fact images.
"""
from skimage import transform
def resize(parameters):
"""Resizes input to match a certain size.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#resize
:param parameters['data'][0]: array to resize
:type parameters['data'][0]: numpy.array
:param parameters['output_shape']: size of the output
:type parameters['data'][1]: tuple
:return: numpy.array
"""
return transform.resize(parameters['data'][0], parameters['output_shape'])
def rotate(parameters):
"""Rotates input anti-clockwise around its center.
Check http://scikit-image.org/docs/dev/api/skimage.transform.html#rotate
:param parameters['data'][0]: array to rotate
:type parameters['data'][0]: numpy.array
:param parameters['angle']: rotation angle in degrees
:type parameters['angle']: float
:param parameters['resize']: expand
:type parameters['resize']: bool
:return: numpy.array
"""
|
8433fe04ad1230329de2c209a8625cd4b36b63f8 | src/sentry/api/serializers/models/grouptagvalue.py | src/sentry/api/serializers/models/grouptagvalue.py | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
| from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def get_attrs(self, item_list, user):
assert len(set(i.key for i in item_list)) < 2
tagvalues = dict(
(t.value, t)
for t in TagValue.objects.filter(
project=item_list[0].project,
key=item_list[0].key,
value__in=[i.value for i in item_list]
)
)
result = {}
for item in item_list:
result[item] = {
'name': tagvalues[item.value].get_label(),
}
return result
def serialize(self, obj, attrs, user):
d = {
'name': attrs['name'],
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
| Implement labels on group tag values | Implement labels on group tag values
| Python | bsd-3-clause | gencer/sentry,drcapulet/sentry,vperron/sentry,pauloschilling/sentry,kevinlondon/sentry,ifduyue/sentry,zenefits/sentry,JamesMura/sentry,jean/sentry,fotinakis/sentry,gencer/sentry,ngonzalvez/sentry,gg7/sentry,mvaled/sentry,JTCunning/sentry,alexm92/sentry,hongliang5623/sentry,Kryz/sentry,JackDanger/sentry,gg7/sentry,TedaLIEz/sentry,imankulov/sentry,vperron/sentry,imankulov/sentry,felixbuenemann/sentry,mvaled/sentry,Natim/sentry,BayanGroup/sentry,wong2/sentry,ewdurbin/sentry,wujuguang/sentry,jean/sentry,beeftornado/sentry,JTCunning/sentry,beeftornado/sentry,pauloschilling/sentry,ifduyue/sentry,BuildingLink/sentry,Natim/sentry,gencer/sentry,mitsuhiko/sentry,alexm92/sentry,songyi199111/sentry,kevinlondon/sentry,JackDanger/sentry,kevinastone/sentry,jean/sentry,beeftornado/sentry,fuziontech/sentry,kevinlondon/sentry,looker/sentry,JackDanger/sentry,mitsuhiko/sentry,fotinakis/sentry,1tush/sentry,boneyao/sentry,JamesMura/sentry,mvaled/sentry,korealerts1/sentry,zenefits/sentry,BuildingLink/sentry,BuildingLink/sentry,felixbuenemann/sentry,JamesMura/sentry,korealerts1/sentry,ifduyue/sentry,daevaorn/sentry,ngonzalvez/sentry,TedaLIEz/sentry,fotinakis/sentry,JTCunning/sentry,daevaorn/sentry,boneyao/sentry,zenefits/sentry,TedaLIEz/sentry,nicholasserra/sentry,jean/sentry,drcapulet/sentry,songyi199111/sentry,mvaled/sentry,BuildingLink/sentry,kevinastone/sentry,alexm92/sentry,BayanGroup/sentry,daevaorn/sentry,BuildingLink/sentry,gencer/sentry,drcapulet/sentry,wong2/sentry,looker/sentry,nicholasserra/sentry,JamesMura/sentry,kevinastone/sentry,wujuguang/sentry,fotinakis/sentry,jean/sentry,boneyao/sentry,fuziontech/sentry,imankulov/sentry,daevaorn/sentry,mvaled/sentry,vperron/sentry,gencer/sentry,looker/sentry,wong2/sentry,Natim/sentry,1tush/sentry,korealerts1/sentry,zenefits/sentry,zenefits/sentry,nicholasserra/sentry,ewdurbin/sentry,looker/sentry,Kryz/sentry,Kryz/sentry,mvaled/sentry,felixbuenemann/sentry,gg7/sentry,ifduyue/sentry,hongliang5623/sentry,looker/sentry,pauloschilling/sentry,ewdurbin/sentry,fuziontech/sentry,songyi199111/sentry,JamesMura/sentry,BayanGroup/sentry,1tush/sentry,hongliang5623/sentry,ngonzalvez/sentry,ifduyue/sentry,wujuguang/sentry | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
Implement labels on group tag values | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def get_attrs(self, item_list, user):
assert len(set(i.key for i in item_list)) < 2
tagvalues = dict(
(t.value, t)
for t in TagValue.objects.filter(
project=item_list[0].project,
key=item_list[0].key,
value__in=[i.value for i in item_list]
)
)
result = {}
for item in item_list:
result[item] = {
'name': tagvalues[item.value].get_label(),
}
return result
def serialize(self, obj, attrs, user):
d = {
'name': attrs['name'],
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
| <commit_before>from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
<commit_msg>Implement labels on group tag values<commit_after> | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def get_attrs(self, item_list, user):
assert len(set(i.key for i in item_list)) < 2
tagvalues = dict(
(t.value, t)
for t in TagValue.objects.filter(
project=item_list[0].project,
key=item_list[0].key,
value__in=[i.value for i in item_list]
)
)
result = {}
for item in item_list:
result[item] = {
'name': tagvalues[item.value].get_label(),
}
return result
def serialize(self, obj, attrs, user):
d = {
'name': attrs['name'],
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
| from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
Implement labels on group tag valuesfrom __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def get_attrs(self, item_list, user):
assert len(set(i.key for i in item_list)) < 2
tagvalues = dict(
(t.value, t)
for t in TagValue.objects.filter(
project=item_list[0].project,
key=item_list[0].key,
value__in=[i.value for i in item_list]
)
)
result = {}
for item in item_list:
result[item] = {
'name': tagvalues[item.value].get_label(),
}
return result
def serialize(self, obj, attrs, user):
d = {
'name': attrs['name'],
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
| <commit_before>from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
<commit_msg>Implement labels on group tag values<commit_after>from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import GroupTagValue, TagValue
@register(GroupTagValue)
class GroupTagValueSerializer(Serializer):
def get_attrs(self, item_list, user):
assert len(set(i.key for i in item_list)) < 2
tagvalues = dict(
(t.value, t)
for t in TagValue.objects.filter(
project=item_list[0].project,
key=item_list[0].key,
value__in=[i.value for i in item_list]
)
)
result = {}
for item in item_list:
result[item] = {
'name': tagvalues[item.value].get_label(),
}
return result
def serialize(self, obj, attrs, user):
d = {
'name': attrs['name'],
'key': obj.key,
'value': obj.value,
'count': obj.times_seen,
'lastSeen': obj.last_seen,
'firstSeen': obj.first_seen,
}
return d
|
a222d268ec1c12466db48bbfcd58d8ecf2907805 | echo_server.py | echo_server.py | import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
self.connection, self.addr = self.socket.accept()
words = self.connection.recv(32)
if words:
self.connection.sendall(unicode(words))
self.connection.close()
self.socket.close()
break
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
| import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
request = []
self.connection, self.addr = self.socket.accept()
while True:
buffer_ = self.connection.recv(32)
if buffer_:
request.append(buffer_)
else:
break
self.connection.sendall(" ".join(request))
self.connection.close()
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
| Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests | Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests
| Python | mit | jefrailey/network_tools | import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
self.connection, self.addr = self.socket.accept()
words = self.connection.recv(32)
if words:
self.connection.sendall(unicode(words))
self.connection.close()
self.socket.close()
break
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests | import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
request = []
self.connection, self.addr = self.socket.accept()
while True:
buffer_ = self.connection.recv(32)
if buffer_:
request.append(buffer_)
else:
break
self.connection.sendall(" ".join(request))
self.connection.close()
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
| <commit_before>import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
self.connection, self.addr = self.socket.accept()
words = self.connection.recv(32)
if words:
self.connection.sendall(unicode(words))
self.connection.close()
self.socket.close()
break
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
<commit_msg>Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests<commit_after> | import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
request = []
self.connection, self.addr = self.socket.accept()
while True:
buffer_ = self.connection.recv(32)
if buffer_:
request.append(buffer_)
else:
break
self.connection.sendall(" ".join(request))
self.connection.close()
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
| import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
self.connection, self.addr = self.socket.accept()
words = self.connection.recv(32)
if words:
self.connection.sendall(unicode(words))
self.connection.close()
self.socket.close()
break
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
Update EchoServer to keep connection open until client shutsdown connection in order to collect all requestsimport socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
request = []
self.connection, self.addr = self.socket.accept()
while True:
buffer_ = self.connection.recv(32)
if buffer_:
request.append(buffer_)
else:
break
self.connection.sendall(" ".join(request))
self.connection.close()
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
| <commit_before>import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
self.connection, self.addr = self.socket.accept()
words = self.connection.recv(32)
if words:
self.connection.sendall(unicode(words))
self.connection.close()
self.socket.close()
break
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
<commit_msg>Update EchoServer to keep connection open until client shutsdown connection in order to collect all requests<commit_after>import socket
class EchoServer(object):
"""a simple EchoServer"""
def __init__(self, ip=u'127.0.0.1', port=50000, backlog=5):
self.ip = ip
self.port = port
self.backlog = backlog
self.socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
self.socket.bind((self.ip, self.port))
self.socket.listen(self.backlog)
def start_listening(self):
while True:
request = []
self.connection, self.addr = self.socket.accept()
while True:
buffer_ = self.connection.recv(32)
if buffer_:
request.append(buffer_)
else:
break
self.connection.sendall(" ".join(request))
self.connection.close()
if __name__ == "__main__":
server = EchoServer()
server.start_listening()
|
67c291b6acf0943a55626be8d40e7134012f9271 | entity/hero.py | entity/hero.py | #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 1
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
| #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 3
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
print self.life
| Modify Hero :: Life + 2 | Modify Hero :: Life + 2
| Python | unlicense | Bobbyshow/Avoid | #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 1
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
Modify Hero :: Life + 2 | #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 3
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
print self.life
| <commit_before>#-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 1
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
<commit_msg>Modify Hero :: Life + 2<commit_after> | #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 3
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
print self.life
| #-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 1
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
Modify Hero :: Life + 2#-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 3
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
print self.life
| <commit_before>#-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 1
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
<commit_msg>Modify Hero :: Life + 2<commit_after>#-*- coding: utf-8 -*-
from lib.base_entity import BaseEntity
from lib.base_animation import BaseAnimation
from pygame.locals import K_UP as UP
class HeroAnimation(BaseAnimation):
"""Custom class Animation : HeroAnimation
"""
WIDTH_SPRITE = 31
HEIGHT_SPRITE = 31
def get_sprite(self, move_direction):
direction_num = move_direction - UP
frame = self.subsurface(
self.frame * self.WIDTH_SPRITE,
direction_num * self.HEIGHT_SPRITE,
self.WIDTH_SPRITE,
self.HEIGHT_SPRITE
).convert_alpha()
return frame
class Hero(BaseEntity):
"""Custom class Entity : Hero
Entity for the player. Represents the player
and player's move
"""
def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img)
self.life = 3
def init_animation(self, max_frame, max_frame_delay, img):
return HeroAnimation(max_frame, max_frame_delay, img)
def is_alive(self):
"""Return true if player is alive"""
return self.life > 0
def lose_life(self):
self.life = self.life - 1
print self.life
|
d1bae39247a1184f7d61fa015897103af2069703 | pinax/notifications/urls.py | pinax/notifications/urls.py | from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
| from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
| Make compatible with Django 1.9 | Make compatible with Django 1.9
| Python | mit | pinax/pinax-notifications,pinax/pinax-notifications | from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
Make compatible with Django 1.9 | from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
| <commit_before>from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
<commit_msg>Make compatible with Django 1.9<commit_after> | from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
| from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
Make compatible with Django 1.9from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
| <commit_before>from django.conf.urls import patterns, url
from .views import NoticeSettingsView
urlpatterns = patterns(
"",
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
)
<commit_msg>Make compatible with Django 1.9<commit_after>from django.conf.urls import url
from .views import NoticeSettingsView
urlpatterns = [
url(r"^settings/$", NoticeSettingsView.as_view(), name="notification_notice_settings"),
]
|
bf343f88ee1eb16bb1268bc70ecb03f25ab338cf | Sketches/RJL/Util/DataSource.py | Sketches/RJL/Util/DataSource.py | from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
self.send(producerFinished(), "signal")
| from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
yield 1
self.send(producerFinished(), "signal")
return
if __name__ == "__main__":
from Kamaelia.Util.PipelineComponent import pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
pipeline(
DataSource( ["hello", " ", "there", " ", "how", " ", "are", " ", "you", " ", "today\r\n", "?", "!"] ),
ConsoleEchoer()
).run()
| Work around a minor bug in ConsoleEchoer - yield before sending a complete message. | Work around a minor bug in ConsoleEchoer - yield before sending a
complete message.
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
self.send(producerFinished(), "signal")
Work around a minor bug in ConsoleEchoer - yield before sending a
complete message. | from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
yield 1
self.send(producerFinished(), "signal")
return
if __name__ == "__main__":
from Kamaelia.Util.PipelineComponent import pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
pipeline(
DataSource( ["hello", " ", "there", " ", "how", " ", "are", " ", "you", " ", "today\r\n", "?", "!"] ),
ConsoleEchoer()
).run()
| <commit_before>from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
self.send(producerFinished(), "signal")
<commit_msg>Work around a minor bug in ConsoleEchoer - yield before sending a
complete message.<commit_after> | from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
yield 1
self.send(producerFinished(), "signal")
return
if __name__ == "__main__":
from Kamaelia.Util.PipelineComponent import pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
pipeline(
DataSource( ["hello", " ", "there", " ", "how", " ", "are", " ", "you", " ", "today\r\n", "?", "!"] ),
ConsoleEchoer()
).run()
| from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
self.send(producerFinished(), "signal")
Work around a minor bug in ConsoleEchoer - yield before sending a
complete message.from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
yield 1
self.send(producerFinished(), "signal")
return
if __name__ == "__main__":
from Kamaelia.Util.PipelineComponent import pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
pipeline(
DataSource( ["hello", " ", "there", " ", "how", " ", "are", " ", "you", " ", "today\r\n", "?", "!"] ),
ConsoleEchoer()
).run()
| <commit_before>from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
self.send(producerFinished(), "signal")
<commit_msg>Work around a minor bug in ConsoleEchoer - yield before sending a
complete message.<commit_after>from Axon.Component import component
from Axon.Ipc import producerFinished, shutdownMicroprocess, shutdown
class DataSource(component):
def __init__(self, messages):
super(DataSource, self).__init__()
self.messages = messages
def main(self):
while len(self.messages) > 0:
yield 1
self.send(self.messages.pop(0), "outbox")
yield 1
self.send(producerFinished(), "signal")
return
if __name__ == "__main__":
from Kamaelia.Util.PipelineComponent import pipeline
from Kamaelia.Util.Console import ConsoleReader, ConsoleEchoer
pipeline(
DataSource( ["hello", " ", "there", " ", "how", " ", "are", " ", "you", " ", "today\r\n", "?", "!"] ),
ConsoleEchoer()
).run()
|
dc140f6c7bc6fe03ec60a5b1029d7bc7463d2a0e | pydarkstar/scrubbing/scrubber.py | pydarkstar/scrubbing/scrubber.py | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
handle = urlopen(url)
handle = handle.read()
break
except:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
| from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
| Add support for absolute URL in request | Add support for absolute URL in request
| Python | mit | AdamGagorik/pydarkstar | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
handle = urlopen(url)
handle = handle.read()
break
except:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
Add support for absolute URL in request | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
| <commit_before>from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
handle = urlopen(url)
handle = handle.read()
break
except:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
<commit_msg>Add support for absolute URL in request<commit_after> | from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
| from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
handle = urlopen(url)
handle = handle.read()
break
except:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
Add support for absolute URL in requestfrom ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
| <commit_before>from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import logging
import time
from urllib.request import urlopen
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
handle = urlopen(url)
handle = handle.read()
break
except:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
<commit_msg>Add support for absolute URL in request<commit_after>from ..darkobject import DarkObject
from bs4 import BeautifulSoup
import requests
import logging
import time
class Scrubber(DarkObject):
def __init__(self):
super(Scrubber, self).__init__()
def scrub(self):
"""
Get item metadata.
"""
return {}
# noinspection PyBroadException
@staticmethod
def soup(url, absolute: bool = False, **kwargs):
"""
Open URL and create tag soup.
:param url: website string
:type url: str
:param absolute: perform double get request to find absolute url
:type absolute: bool
"""
handle = ''
max_tries = 10
for i in range(max_tries):
# noinspection PyPep8
try:
if absolute:
url = requests.get(url).url
handle = requests.get(url, params=kwargs).text
break
except Exception:
logging.exception('urlopen failed (attempt %d)', i + 1)
if i == max_tries - 1:
logging.error('the maximum urlopen attempts have been reached')
raise
time.sleep(1)
s = BeautifulSoup(handle, features='html5lib')
return s
if __name__ == '__main__':
pass
|
fbd49474eb9d0d80874048964ca08295e8c040cb | webwatcher/fetcher/simple.py | webwatcher/fetcher/simple.py | import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True)
else:
return response.text
| import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True, sort_keys=True)
else:
return response.text
| Sort keys in JSON fetcher for consistent results | Sort keys in JSON fetcher for consistent results | Python | mit | kibitzr/kibitzr,kibitzr/kibitzr | import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True)
else:
return response.text
Sort keys in JSON fetcher for consistent results | import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True, sort_keys=True)
else:
return response.text
| <commit_before>import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True)
else:
return response.text
<commit_msg>Sort keys in JSON fetcher for consistent results<commit_after> | import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True, sort_keys=True)
else:
return response.text
| import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True)
else:
return response.text
Sort keys in JSON fetcher for consistent resultsimport json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True, sort_keys=True)
else:
return response.text
| <commit_before>import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True)
else:
return response.text
<commit_msg>Sort keys in JSON fetcher for consistent results<commit_after>import json
import requests
def simple(conf):
url = conf['url']
output_format = conf.get('format', 'html')
response = requests.get(url)
if output_format == 'json':
return json.dumps(response.json(), indent=True, sort_keys=True)
else:
return response.text
|
3b8269857b1370e550664b47a20af30427992204 | kolibri/core/test/test_key_urls.py | kolibri/core/test/test_key_urls.py | from __future__ import absolute_import, print_function, unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.test_api import FacilityFactory
from kolibri.auth.test.helpers import create_superuser, provision_device
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:setupwizardplugin:setupwizard'))
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.helpers import create_superuser
from kolibri.auth.test.helpers import provision_device
from kolibri.auth.test.test_api import FacilityFactory
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
url = reverse('kolibri:setupwizardplugin:setupwizard')
self.assertTrue('<meta http-equiv="refresh" content="0;URL=\'{url}\'" />'.format(url=url) in response.content)
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
| Update KolibriTagNavigationTestCase to handle new redirect method | Update KolibriTagNavigationTestCase to handle new redirect method
| Python | mit | learningequality/kolibri,lyw07/kolibri,indirectlylit/kolibri,benjaoming/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,DXCanas/kolibri,benjaoming/kolibri,learningequality/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,indirectlylit/kolibri,DXCanas/kolibri,benjaoming/kolibri,indirectlylit/kolibri,benjaoming/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,lyw07/kolibri,DXCanas/kolibri | from __future__ import absolute_import, print_function, unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.test_api import FacilityFactory
from kolibri.auth.test.helpers import create_superuser, provision_device
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:setupwizardplugin:setupwizard'))
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
Update KolibriTagNavigationTestCase to handle new redirect method | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.helpers import create_superuser
from kolibri.auth.test.helpers import provision_device
from kolibri.auth.test.test_api import FacilityFactory
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
url = reverse('kolibri:setupwizardplugin:setupwizard')
self.assertTrue('<meta http-equiv="refresh" content="0;URL=\'{url}\'" />'.format(url=url) in response.content)
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
| <commit_before>from __future__ import absolute_import, print_function, unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.test_api import FacilityFactory
from kolibri.auth.test.helpers import create_superuser, provision_device
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:setupwizardplugin:setupwizard'))
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
<commit_msg>Update KolibriTagNavigationTestCase to handle new redirect method<commit_after> | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.helpers import create_superuser
from kolibri.auth.test.helpers import provision_device
from kolibri.auth.test.test_api import FacilityFactory
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
url = reverse('kolibri:setupwizardplugin:setupwizard')
self.assertTrue('<meta http-equiv="refresh" content="0;URL=\'{url}\'" />'.format(url=url) in response.content)
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
| from __future__ import absolute_import, print_function, unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.test_api import FacilityFactory
from kolibri.auth.test.helpers import create_superuser, provision_device
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:setupwizardplugin:setupwizard'))
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
Update KolibriTagNavigationTestCase to handle new redirect methodfrom __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.helpers import create_superuser
from kolibri.auth.test.helpers import provision_device
from kolibri.auth.test.test_api import FacilityFactory
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
url = reverse('kolibri:setupwizardplugin:setupwizard')
self.assertTrue('<meta http-equiv="refresh" content="0;URL=\'{url}\'" />'.format(url=url) in response.content)
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
| <commit_before>from __future__ import absolute_import, print_function, unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.test_api import FacilityFactory
from kolibri.auth.test.helpers import create_superuser, provision_device
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:setupwizardplugin:setupwizard'))
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
<commit_msg>Update KolibriTagNavigationTestCase to handle new redirect method<commit_after>from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.auth.test.helpers import create_superuser
from kolibri.auth.test.helpers import provision_device
from kolibri.auth.test.test_api import FacilityFactory
DUMMY_PASSWORD = "password"
class KolibriTagNavigationTestCase(APITestCase):
def test_redirect_to_setup_wizard(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
url = reverse('kolibri:setupwizardplugin:setupwizard')
self.assertTrue('<meta http-equiv="refresh" content="0;URL=\'{url}\'" />'.format(url=url) in response.content)
def test_redirect_root_to_user_if_not_logged_in(self):
provision_device()
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:user:user'))
def test_redirect_root_to_learn_if_logged_in(self):
facility = FacilityFactory.create()
do = create_superuser(facility)
provision_device()
self.client.login(username=do.username, password=DUMMY_PASSWORD)
response = self.client.get("/")
self.assertEqual(response.status_code, 302)
self.assertEqual(response.get("location"), reverse('kolibri:learnplugin:learn'))
|
1a4f8b2565b0e6ccdef8eba8982633825ddd978c | telemetry/telemetry/core/profile_types.py | telemetry/telemetry/core/profile_types.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/content_scripts10',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
| # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
| Use correct profile for power_user. | [Telemetry] Use correct profile for power_user.
TEST=None
BUG=None
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/12775015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@188294 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | sahiljain/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,catapult-project/catapult-csm,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/content_scripts10',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
[Telemetry] Use correct profile for power_user.
TEST=None
BUG=None
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/12775015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@188294 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
| <commit_before># Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/content_scripts10',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
<commit_msg>[Telemetry] Use correct profile for power_user.
TEST=None
BUG=None
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/12775015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@188294 0039d316-1c4b-4281-b951-d872f2087c98<commit_after> | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
| # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/content_scripts10',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
[Telemetry] Use correct profile for power_user.
TEST=None
BUG=None
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/12775015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@188294 0039d316-1c4b-4281-b951-d872f2087c98# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
| <commit_before># Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/content_scripts10',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
<commit_msg>[Telemetry] Use correct profile for power_user.
TEST=None
BUG=None
NOTRY=True
Review URL: https://chromiumcodereview.appspot.com/12775015
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@188294 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest',
}
PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
def GetProfileDir(profile_type):
path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/')))
assert os.path.exists(path)
return path
|
c07e2bbbeb513429fc6ef4a5efba5cae71cac214 | autostew_back/tests/test_assets/settings_no_plugins.py | autostew_back/tests/test_assets/settings_no_plugins.py | import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 1
full_update_period = 5
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
| import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 0
full_update_period = 0
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
| Set sleep times to zero for tests | Set sleep times to zero for tests
| Python | agpl-3.0 | Autostew/autostew,Autostew/autostew,Autostew/autostew | import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 1
full_update_period = 5
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
Set sleep times to zero for tests | import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 0
full_update_period = 0
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
| <commit_before>import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 1
full_update_period = 5
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
<commit_msg>Set sleep times to zero for tests<commit_after> | import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 0
full_update_period = 0
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
| import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 1
full_update_period = 5
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
Set sleep times to zero for testsimport logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 0
full_update_period = 0
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
| <commit_before>import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 1
full_update_period = 5
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
<commit_msg>Set sleep times to zero for tests<commit_after>import logging
from autostew_back.tests.test_assets import prl_s4_r2_zolder_casual
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('django.db.backends').setLevel(logging.INFO)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.INFO)
class SettingsWithoutPlugins:
host_name = "TestHost"
server_name = "TestServer"
config_file = "server.cfg"
url = "http://localhost:9000"
event_poll_period = 0
full_update_period = 0
setup_rotation = [
prl_s4_r2_zolder_casual
]
plugins = []
|
de7043594786780a29d5451f5ec21132634ec878 | wsgiproxy/requests_client.py | wsgiproxy/requests_client.py | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = requests.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
| # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
if session is None:
session = requests.sessions.Session()
self.session = session
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = self.session.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
| Allow custom session object for the requests backend. | Allow custom session object for the requests backend.
| Python | mit | gawel/WSGIProxy2 | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = requests.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
Allow custom session object for the requests backend. | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
if session is None:
session = requests.sessions.Session()
self.session = session
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = self.session.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
| <commit_before># -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = requests.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
<commit_msg>Allow custom session object for the requests backend.<commit_after> | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
if session is None:
session = requests.sessions.Session()
self.session = session
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = self.session.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
| # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = requests.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
Allow custom session object for the requests backend.# -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
if session is None:
session = requests.sessions.Session()
self.session = session
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = self.session.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
| <commit_before># -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = requests.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
<commit_msg>Allow custom session object for the requests backend.<commit_after># -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
if session is None:
session = requests.sessions.Session()
self.session = session
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = self.session.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
|
d8a4cfcf50462050d186d086733ee9cbb2a2ec3b | imhotep_jsl/plugin.py | imhotep_jsl/plugin.py | from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
| from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
| Update for api change with linter_configs. | Update for api change with linter_configs.
| Python | mit | hayes/imhotep_jsl | from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
Update for api change with linter_configs. | from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
| <commit_before>from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
<commit_msg>Update for api change with linter_configs.<commit_after> | from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
| from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
Update for api change with linter_configs.from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
| <commit_before>from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
<commit_msg>Update for api change with linter_configs.<commit_after>from imhotep.tools import Tool
from collections import defaultdict
import re
class JSL(Tool):
regex = re.compile(
r'^(?P<type>[WE]) '
r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$')
def invoke(self, dirname, filenames=set(), linter_configs=set()):
retval = defaultdict(lambda: defaultdict(list))
if len(filenames) == 0:
cmd = 'find %s -name "*.js" | xargs jsl' % dirname
else:
js_files = []
for filename in filenames:
if '.js' in filename:
js_files.append("%s/%s" % (dirname, filename))
cmd = 'jsl %s' % ' '.join(js_files)
output = self.executor(cmd)
for line in output.split('\n'):
match = self.regex.search(line)
if match is None:
continue
message = '%s: %s' % (match.group('type'), match.group('message'))
filename = match.group('filename')[len(dirname) + 1:]
retval[filename][match.group('line_number')].append(message)
return retval
|
e89602fec93ca86c3952b4bf33ee7151bfe2e6b0 | emission/analysis/classification/cleaning/speed_outlier_detection.py | emission/analysis/classification/cleaning/speed_outlier_detection.py | # Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR):
self.multiplier = multiplier
def get_threshold(self, with_speeds_df):
quartile_vals = with_speeds_df.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99):
self.quantile = quantile
def get_threshold(self, with_speeds_df):
return with_speeds_df.speed.quantile(self.quantile)
| # Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR, ignore_zeros = False):
self.multiplier = multiplier
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
quartile_vals = df_to_use.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99, ignore_zeros = False):
self.quantile = quantile
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
return df_to_use.speed.quantile(self.quantile)
| Support an option to ignore zeros while calculating thresholds | Support an option to ignore zeros while calculating thresholds
Based on the results, the default should be to ignore
| Python | bsd-3-clause | shankari/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,joshzarrabi/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,joshzarrabi/e-mission-server,joshzarrabi/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server | # Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR):
self.multiplier = multiplier
def get_threshold(self, with_speeds_df):
quartile_vals = with_speeds_df.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99):
self.quantile = quantile
def get_threshold(self, with_speeds_df):
return with_speeds_df.speed.quantile(self.quantile)
Support an option to ignore zeros while calculating thresholds
Based on the results, the default should be to ignore | # Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR, ignore_zeros = False):
self.multiplier = multiplier
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
quartile_vals = df_to_use.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99, ignore_zeros = False):
self.quantile = quantile
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
return df_to_use.speed.quantile(self.quantile)
| <commit_before># Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR):
self.multiplier = multiplier
def get_threshold(self, with_speeds_df):
quartile_vals = with_speeds_df.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99):
self.quantile = quantile
def get_threshold(self, with_speeds_df):
return with_speeds_df.speed.quantile(self.quantile)
<commit_msg>Support an option to ignore zeros while calculating thresholds
Based on the results, the default should be to ignore<commit_after> | # Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR, ignore_zeros = False):
self.multiplier = multiplier
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
quartile_vals = df_to_use.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99, ignore_zeros = False):
self.quantile = quantile
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
return df_to_use.speed.quantile(self.quantile)
| # Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR):
self.multiplier = multiplier
def get_threshold(self, with_speeds_df):
quartile_vals = with_speeds_df.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99):
self.quantile = quantile
def get_threshold(self, with_speeds_df):
return with_speeds_df.speed.quantile(self.quantile)
Support an option to ignore zeros while calculating thresholds
Based on the results, the default should be to ignore# Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR, ignore_zeros = False):
self.multiplier = multiplier
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
quartile_vals = df_to_use.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99, ignore_zeros = False):
self.quantile = quantile
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
return df_to_use.speed.quantile(self.quantile)
| <commit_before># Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR):
self.multiplier = multiplier
def get_threshold(self, with_speeds_df):
quartile_vals = with_speeds_df.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99):
self.quantile = quantile
def get_threshold(self, with_speeds_df):
return with_speeds_df.speed.quantile(self.quantile)
<commit_msg>Support an option to ignore zeros while calculating thresholds
Based on the results, the default should be to ignore<commit_after># Techniques for outlier detection of speeds. Each of these returns a speed threshold that
# can be used with outlier detection techniques.
# Standard imports
import logging
logging.basicConfig(level=logging.DEBUG)
class BoxplotOutlier(object):
MINOR = 1.5
MAJOR = 3
def __init__(self, multiplier = MAJOR, ignore_zeros = False):
self.multiplier = multiplier
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
quartile_vals = df_to_use.quantile([0.25, 0.75]).speed
logging.debug("quartile values are %s" % quartile_vals)
iqr = quartile_vals.iloc[1] - quartile_vals.iloc[0]
logging.debug("iqr %s" % iqr)
return quartile_vals.iloc[1] + self.multiplier * iqr
class SimpleQuartileOutlier(object):
def __init__(self, quantile = 0.99, ignore_zeros = False):
self.quantile = quantile
self.ignore_zeros = ignore_zeros
def get_threshold(self, with_speeds_df):
if self.ignore_zeros:
df_to_use = with_speeds_df[with_speeds_df.speed > 0]
else:
df_to_use = with_speeds_df
return df_to_use.speed.quantile(self.quantile)
|
35fb8c91bac3d68d255223b20dbbfd84ab34b3b1 | quant/ichimoku/ichimoku_test.py | quant/ichimoku/ichimoku_test.py | import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration)
#print(str(n)+" days ago:\n"+str(ndays_ago))
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df,ichimoku(df['close']),title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected) | import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
MAX_ROLLING = 100
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration+MAX_ROLLING)
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df[MAX_ROLLING:],ichimoku(df['close'])[MAX_ROLLING:],title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)
| Add the missing data for ichimoku with additional data fed | Add the missing data for ichimoku with additional data fed
| Python | apache-2.0 | yunfeiz/py_learnt | import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration)
#print(str(n)+" days ago:\n"+str(ndays_ago))
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df,ichimoku(df['close']),title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)Add the missing data for ichimoku with additional data fed | import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
MAX_ROLLING = 100
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration+MAX_ROLLING)
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df[MAX_ROLLING:],ichimoku(df['close'])[MAX_ROLLING:],title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)
| <commit_before>import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration)
#print(str(n)+" days ago:\n"+str(ndays_ago))
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df,ichimoku(df['close']),title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)<commit_msg>Add the missing data for ichimoku with additional data fed<commit_after> | import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
MAX_ROLLING = 100
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration+MAX_ROLLING)
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df[MAX_ROLLING:],ichimoku(df['close'])[MAX_ROLLING:],title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)
| import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration)
#print(str(n)+" days ago:\n"+str(ndays_ago))
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df,ichimoku(df['close']),title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)Add the missing data for ichimoku with additional data fedimport pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
MAX_ROLLING = 100
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration+MAX_ROLLING)
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df[MAX_ROLLING:],ichimoku(df['close'])[MAX_ROLLING:],title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)
| <commit_before>import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration)
#print(str(n)+" days ago:\n"+str(ndays_ago))
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df,ichimoku(df['close']),title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)<commit_msg>Add the missing data for ichimoku with additional data fed<commit_after>import pandas as pd
import numpy as np
import os
#from ta import ichimoku
from util import get_data, plot_data
from pandas import DataFrame, Series
from technical_analysis import ichimoku
from datetime import datetime, timedelta,date
import os
import time
import sys
import getopt,argparse
MAX_ROLLING = 100
def test_run(stock='000725'):
duration = 360
#now=datetime.now()
today=date.today()
ndays_ago=today-timedelta(duration+MAX_ROLLING)
start_date=str(ndays_ago)
end_date =str(today)
df = get_data(stock,start_date, end_date)
plot_data(df[MAX_ROLLING:],ichimoku(df['close'])[MAX_ROLLING:],title=stock)
def usage():
print (sys.argv[0] + ' -s stock id')
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], "s:")
stock_list=''
single_stock=False
stock_selected="002281"
for op, value in opts:
if op == '-s':
stock_selected = value
elif op == '-h':
usage()
sys.exit()
test_run(stock_selected)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.