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
9a5905a42eebcc3b4dadc3f772ba7d9d6b25af63
setup.py
setup.py
from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest'], } )
from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest', 'ipython'], } )
Install ipython in development environment
Install ipython in development environment
Python
mit
Turbasen/turbasen.py
from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest'], } ) Install ipython in development environment
from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest', 'ipython'], } )
<commit_before>from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest'], } ) <commit_msg>Install ipython in development environment<commit_after>
from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest', 'ipython'], } )
from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest'], } ) Install ipython in development environmentfrom setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest', 'ipython'], } )
<commit_before>from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest'], } ) <commit_msg>Install ipython in development environment<commit_after>from setuptools import setup name = 'turbasen' VERSION = '2.4.6' setup( name=name, packages=[name], version=VERSION, description='Client for Nasjonal Turbase REST API', long_description='See https://github.com/Turbasen/turbasen.py/blob/master/README.md', author='Ali Kaafarani', author_email='ali.kaafarani@dnt.no', url='https://github.com/Turbasen/turbasen.py', download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION), keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'], license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: Norwegian', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], install_requires=['requests>=2.9,<2.10'], extras_require={ 'dev': ['pytest', 'ipython'], } )
1cda2d235000e33d3325f313edc424d06e5bacc9
setup.py
setup.py
from setuptools import setup setup( name='tattle', version='0.1', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], )
from setuptools import setup setup( name='tattle', version='0.1.0', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], )
Update tattle version to 0.1.0
Update tattle version to 0.1.0 Previous version number was 0.1
Python
apache-2.0
cloudify-cosmo/tattle
from setuptools import setup setup( name='tattle', version='0.1', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], ) Update tattle version to 0.1.0 Previous version number was 0.1
from setuptools import setup setup( name='tattle', version='0.1.0', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], )
<commit_before>from setuptools import setup setup( name='tattle', version='0.1', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], ) <commit_msg>Update tattle version to 0.1.0 Previous version number was 0.1<commit_after>
from setuptools import setup setup( name='tattle', version='0.1.0', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], )
from setuptools import setup setup( name='tattle', version='0.1', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], ) Update tattle version to 0.1.0 Previous version number was 0.1from setuptools import setup setup( name='tattle', version='0.1.0', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], )
<commit_before>from setuptools import setup setup( name='tattle', version='0.1', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], ) <commit_msg>Update tattle version to 0.1.0 Previous version number was 0.1<commit_after>from setuptools import setup setup( name='tattle', version='0.1.0', packages=[ 'tattle', ], install_requires=[ 'requests>=2.7.0', 'pyyaml>=3.11' ], )
178434bc869bf8884a29fbf622570d0d8661a675
setup.py
setup.py
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.0', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.1', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
Fix link to spec in README
Fix link to spec in README
Python
bsd-2-clause
anossov/openrtb,gsakkis/openrtb
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.0', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), ) Fix link to spec in README
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.1', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
<commit_before>from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.0', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), ) <commit_msg>Fix link to spec in README<commit_after>
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.1', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.0', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), ) Fix link to spec in READMEfrom setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.1', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
<commit_before>from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.0', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), ) <commit_msg>Fix link to spec in README<commit_after>from setuptools import setup import codecs def readme(fn): with codecs.open(fn, encoding='utf-8') as f: return f.read() setup(name='openrtb', version='0.1.1', packages=[ 'openrtb', ], author='Pavel Anossov', author_email='anossov@gmail.com', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries', ], url='https://github.com/anossov/openrtb', license='BSD', description='A set of classes implementing OpenRTB 2.2 and OpenRTB Mobile specifications', long_description=readme('README.rst'), )
3f298ed994506a54068ec8cec6fd028a0b0e8699
setup.py
setup.py
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
Remove download URL since Github doesn't get his act together. Damnit
Remove download URL since Github doesn't get his act together. Damnit git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f> --HG-- extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077a
Python
bsd-3-clause
gbezyuk/django-robots,pbs/django-robots,jscott1971/django-robots,jezdez/django-robots,jazzband/django-robots,jezdez/django-robots,freakboy3742/django-robots,pbs/django-robots,philippeowagner/django-robots,philippeowagner/django-robots,amitu/django-robots,jazzband/django-robots,freakboy3742/django-robots,pbs/django-robots,amitu/django-robots,gbezyuk/django-robots,jscott1971/django-robots
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] ) Remove download URL since Github doesn't get his act together. Damnit git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f> --HG-- extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077a
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
<commit_before>from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] ) <commit_msg>Remove download URL since Github doesn't get his act together. Damnit git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f> --HG-- extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077a<commit_after>
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] ) Remove download URL since Github doesn't get his act together. Damnit git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f> --HG-- extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077afrom distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
<commit_before>from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] ) <commit_msg>Remove download URL since Github doesn't get his act together. Damnit git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f> --HG-- extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077a<commit_after>from distutils.core import setup setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://code.google.com/p/django-robots/', packages=['robots'], package_dir={'dbtemplates': 'dbtemplates'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] )
adc79737e1932724fa38533ecf67a65bf77a6dc8
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], )
#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
Fix compiling flags for darwin.
Fix compiling flags for darwin. The OpenBLAS formula is keg-only, which means it was not symlinked into /usr/local. Thus, we need to add the build variables manually. Also, the library is named as openblas, which means `-llapack` and `-llapacke` will cause library not found error.
Python
bsd-2-clause
ntucllab/libact,ntucllab/libact,ntucllab/libact
#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], ) Fix compiling flags for darwin. The OpenBLAS formula is keg-only, which means it was not symlinked into /usr/local. Thus, we need to add the build variables manually. Also, the library is named as openblas, which means `-llapack` and `-llapacke` will cause library not found error.
#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
<commit_before>#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], ) <commit_msg>Fix compiling flags for darwin. The OpenBLAS formula is keg-only, which means it was not symlinked into /usr/local. Thus, we need to add the build variables manually. Also, the library is named as openblas, which means `-llapack` and `-llapacke` will cause library not found error.<commit_after>
#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], ) Fix compiling flags for darwin. The OpenBLAS formula is keg-only, which means it was not symlinked into /usr/local. Thus, we need to add the build variables manually. Also, the library is named as openblas, which means `-llapack` and `-llapacke` will cause library not found error.#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
<commit_before>#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=['-llapacke -llapack -lblas'], extra_compile_args=['-std=c11'], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ), ], ) <commit_msg>Fix compiling flags for darwin. The OpenBLAS formula is keg-only, which means it was not symlinked into /usr/local. Thus, we need to add the build variables manually. Also, the library is named as openblas, which means `-llapack` and `-llapacke` will cause library not found error.<commit_after>#!/usr/bin/env python from distutils.core import setup, Extension import numpy.distutils import sys if sys.platform == 'darwin': print("Platform Detection: Mac OS X. Link to openblas...") extra_link_args = ['-L/usr/local/opt/openblas/lib -lopenblas'] include_dirs = (numpy.distutils.misc_util.get_numpy_include_dirs() + ['/usr/local/opt/openblas/include']) else: # assume linux otherwise, unless we support Windows in the future... print("Platform Detection: Linux. Link to liblapacke...") extra_link_args = ['-llapacke -llapack -lblas'] include_dirs = numpy.distutils.misc_util.get_numpy_include_dirs() setup( name='Libact', version='0.1.0', description='Active learning package', long_description='Active learning package', author='LSC', author_email='this@is.email', url='http://www.csie.ntu.edu.tw/~htlin/', packages=[ 'libact.base', 'libact.models', 'libact.labelers', 'libact.query_strategies', ], package_dir={ 'libact.base': 'libact/base', 'libact.models': 'libact/models', 'libact.labelers': 'libact/labelers', 'libact.query_strategies': 'libact/query_strategies', }, ext_modules=[ Extension( "libact.query_strategies._variance_reduction", ["libact/query_strategies/variance_reduction.c"], extra_link_args=extra_link_args, extra_compile_args=['-std=c11'], include_dirs=include_dirs, ), ], )
19e7aa3269adacd6ff5f0974ddd957b468ebd0ca
slack.py
slack.py
import requests import json import time import sys _token = "xxxxxxx" _domain = "xxxxxxx" def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete")
import requests import json import time import sys file = open('token.txt', 'r') _token = file.readline() file.close() file = open('domain.txt', 'r') _domain = file.readline() def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete")
Change about read "token" & "domain"
Change about read "token" & "domain"
Python
mit
Rick-Kota/Slack_file_Delete
import requests import json import time import sys _token = "xxxxxxx" _domain = "xxxxxxx" def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete") Change about read "token" & "domain"
import requests import json import time import sys file = open('token.txt', 'r') _token = file.readline() file.close() file = open('domain.txt', 'r') _domain = file.readline() def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete")
<commit_before>import requests import json import time import sys _token = "xxxxxxx" _domain = "xxxxxxx" def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete") <commit_msg>Change about read "token" & "domain"<commit_after>
import requests import json import time import sys file = open('token.txt', 'r') _token = file.readline() file.close() file = open('domain.txt', 'r') _domain = file.readline() def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete")
import requests import json import time import sys _token = "xxxxxxx" _domain = "xxxxxxx" def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete") Change about read "token" & "domain"import requests import json import time import sys file = open('token.txt', 'r') _token = file.readline() file.close() file = open('domain.txt', 'r') _domain = file.readline() def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete")
<commit_before>import requests import json import time import sys _token = "xxxxxxx" _domain = "xxxxxxx" def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete") <commit_msg>Change about read "token" & "domain"<commit_after>import requests import json import time import sys file = open('token.txt', 'r') _token = file.readline() file.close() file = open('domain.txt', 'r') _domain = file.readline() def del_time(Day): Set_time = str(int(time.time())-Day*86400) return Set_time def files_list(Day): Del_time = del_time(Day) files_list_url = "https://slack.com/api/files.list" data = { "token": _token, "ts_to": Del_time, "count":1000 } response = requests.post(files_list_url,data) if response.json()["ok"] == 0: print("Error_exit(around API's argument)") sys.exit() return response.json()["files"] def delete(): return if __name__ == '__main__': while 1: files = files_list(0) if len(files) == 0: print ("No files") break for f in files: print ("Deleting file " + f["name"] + "...") delete_url = "https://slack.com/api/files.delete" data = { "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1" } requests.post(delete_url, data) print ("complete")
3068939373b864995827b938b669b9493e6a680d
app/settings/prod.py
app/settings/prod.py
import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = ['agendaodonto.herokuapp.com'] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None
import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = [ 'backend.agendaodonto.com' ] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None
Update allowed hosts to the new domain
fix: Update allowed hosts to the new domain
Python
agpl-3.0
agendaodonto/server,agendaodonto/server
import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = ['agendaodonto.herokuapp.com'] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None fix: Update allowed hosts to the new domain
import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = [ 'backend.agendaodonto.com' ] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None
<commit_before>import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = ['agendaodonto.herokuapp.com'] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None <commit_msg>fix: Update allowed hosts to the new domain<commit_after>
import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = [ 'backend.agendaodonto.com' ] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None
import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = ['agendaodonto.herokuapp.com'] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None fix: Update allowed hosts to the new domainimport dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = [ 'backend.agendaodonto.com' ] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None
<commit_before>import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = ['agendaodonto.herokuapp.com'] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None <commit_msg>fix: Update allowed hosts to the new domain<commit_after>import dj_database_url from .default import * DEBUG = False SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', None) ALLOWED_HOSTS = [ 'backend.agendaodonto.com' ] DATABASES = {'default': dj_database_url.config()} CORS_ORIGIN_WHITELIST = ( 'agendaodonto.com', 'backend.agendaodonto.com', ) DJOSER['DOMAIN'] = 'agendaodonto.com' # Celery Settings CELERY_BROKER_URL = os.getenv('RABBITMQ_URL', None) CELERY_BROKER_HEARTBEAT = None
e331f5cd1c921ca35c6184c00fbd36929cb92b90
src/tenyksddate/main.py
src/tenyksddate/main.py
from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main()
import datetime from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'], 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def handle_date(self, data, match): year = int(match.groupdict()['year']) month = int(match.groupdict()['month']) day = int(match.groupdict()['day']) self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main()
Add lookup for an arbitrary date
Add lookup for an arbitrary date In the form “mm dd yyyy”.
Python
mit
kyleterry/tenyks-contrib,cblgh/tenyks-contrib,colby/tenyks-contrib
from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main() Add lookup for an arbitrary date In the form “mm dd yyyy”.
import datetime from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'], 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def handle_date(self, data, match): year = int(match.groupdict()['year']) month = int(match.groupdict()['month']) day = int(match.groupdict()['day']) self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main()
<commit_before>from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main() <commit_msg>Add lookup for an arbitrary date In the form “mm dd yyyy”.<commit_after>
import datetime from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'], 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def handle_date(self, data, match): year = int(match.groupdict()['year']) month = int(match.groupdict()['month']) day = int(match.groupdict()['day']) self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main()
from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main() Add lookup for an arbitrary date In the form “mm dd yyyy”.import datetime from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'], 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def handle_date(self, data, match): year = int(match.groupdict()['year']) month = int(match.groupdict()['month']) day = int(match.groupdict()['day']) self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main()
<commit_before>from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main() <commit_msg>Add lookup for an arbitrary date In the form “mm dd yyyy”.<commit_after>import datetime from tenyksservice import TenyksService, run_service from ddate.base import DDate class DiscordianDate(TenyksService): direct_only = True irc_message_filters = { 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'], 'today': [r'^(?i)(ddate|discordian)'] } def __init__(self, *args, **kwargs): super(DiscordianDate, self).__init__(*args, **kwargs) def handle_today(self, data, match): self.send(str(DDate()), data) def handle_date(self, data, match): year = int(match.groupdict()['year']) month = int(match.groupdict()['month']) day = int(match.groupdict()['day']) self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data) def main(): run_service(DiscordianDate) if __name__ == '__main__': main()
9ad378244cf8ca8a28b01ae1c7e166dbeff9a3fb
odoo/addons/test_main_flows/__manifest__.py
odoo/addons/test_main_flows/__manifest__.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, }
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
Revert "[FIX] test_main_flows: missing dependency to run it in a browser"
Revert "[FIX] test_main_flows: missing dependency to run it in a browser" This reverts commit 58e914425033a9604885fb0cdd7de1a6a144c4da.
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, } Revert "[FIX] test_main_flows: missing dependency to run it in a browser" This reverts commit 58e914425033a9604885fb0cdd7de1a6a144c4da.
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
<commit_before># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, } <commit_msg>Revert "[FIX] test_main_flows: missing dependency to run it in a browser" This reverts commit 58e914425033a9604885fb0cdd7de1a6a144c4da.<commit_after>
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, } Revert "[FIX] test_main_flows: missing dependency to run it in a browser" This reverts commit 58e914425033a9604885fb0cdd7de1a6a144c4da.# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
<commit_before># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account_accountant'], 'data': [ 'views/templates.xml', ], 'installable': True, } <commit_msg>Revert "[FIX] test_main_flows: missing dependency to run it in a browser" This reverts commit 58e914425033a9604885fb0cdd7de1a6a144c4da.<commit_after># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most important actions. """, 'depends': ['web_tour', 'crm', 'sale_timesheet', 'purchase', 'mrp', 'account'], 'data': [ 'views/templates.xml', ], 'installable': True, }
91147e838348b576d760cb2f3966e2c64b930e2e
swift/dedupe/killall.py
swift/dedupe/killall.py
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf')
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') os.system('rm /etc/swift/*.db -rf')
Change the position. use proxy-server to do dedupe instead of object-server
Change the position. use proxy-server to do dedupe instead of object-server
Python
apache-2.0
mjwtom/swift,mjwtom/swift
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') Change the position. use proxy-server to do dedupe instead of object-server
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') os.system('rm /etc/swift/*.db -rf')
<commit_before>#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') <commit_msg>Change the position. use proxy-server to do dedupe instead of object-server<commit_after>
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') os.system('rm /etc/swift/*.db -rf')
#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') Change the position. use proxy-server to do dedupe instead of object-server#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') os.system('rm /etc/swift/*.db -rf')
<commit_before>#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') <commit_msg>Change the position. use proxy-server to do dedupe instead of object-server<commit_after>#!/usr/bin/python __author__ = 'mjwtom' import os os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') os.system('ps -aux | grep swift-object-server | grep -v grep | cut -c 9-15 | xargs kill -s 9') # remove the database file os.system('rm ~/*.db -rf') os.system('rm /etc/swift/*.db -rf')
ac854703ac8ae2e9ab1b9fb2475f9fcb11df8721
pysc2/agents/base_agent.py
pysc2/agents/base_agent.py
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def setup(self, obs_spec, action_spec): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, [])
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def __init__(self): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = None self.action_spec = None def setup(self, obs_spec, action_spec): self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, [])
Define instance attributes on __init__.
Define instance attributes on __init__. PySC2: Import of refs/pull/48/head PiperOrigin-RevId: 166837442
Python
apache-2.0
deepmind/pysc2
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def setup(self, obs_spec, action_spec): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, []) Define instance attributes on __init__. PySC2: Import of refs/pull/48/head PiperOrigin-RevId: 166837442
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def __init__(self): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = None self.action_spec = None def setup(self, obs_spec, action_spec): self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, [])
<commit_before># Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def setup(self, obs_spec, action_spec): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, []) <commit_msg>Define instance attributes on __init__. PySC2: Import of refs/pull/48/head PiperOrigin-RevId: 166837442<commit_after>
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def __init__(self): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = None self.action_spec = None def setup(self, obs_spec, action_spec): self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, [])
# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def setup(self, obs_spec, action_spec): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, []) Define instance attributes on __init__. PySC2: Import of refs/pull/48/head PiperOrigin-RevId: 166837442# Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def __init__(self): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = None self.action_spec = None def setup(self, obs_spec, action_spec): self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, [])
<commit_before># Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def setup(self, obs_spec, action_spec): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, []) <commit_msg>Define instance attributes on __init__. PySC2: Import of refs/pull/48/head PiperOrigin-RevId: 166837442<commit_after># Copyright 2017 Google Inc. All Rights Reserved. # # 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. """A base agent to write custom scripted agents.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from pysc2.lib import actions class BaseAgent(object): """A base agent to write custom scripted agents.""" def __init__(self): self.reward = 0 self.episodes = 0 self.steps = 0 self.obs_spec = None self.action_spec = None def setup(self, obs_spec, action_spec): self.obs_spec = obs_spec self.action_spec = action_spec def reset(self): self.episodes += 1 def step(self, obs): self.steps += 1 self.reward += obs.reward return actions.FunctionCall(0, [])
856bdb5219b233769dc2529772d8489c20fb1efc
reddit_adzerk/adzerkads.py
reddit_adzerk/adzerkads.py
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.adzerk_url.format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
Use protocol relative adzerk url
Use protocol relative adzerk url
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main" Use protocol relative adzerk url
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.adzerk_url.format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
<commit_before>from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main" <commit_msg>Use protocol relative adzerk url<commit_after>
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.adzerk_url.format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main" Use protocol relative adzerk urlfrom urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.adzerk_url.format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
<commit_before>from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.config[url_key].format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main" <commit_msg>Use protocol relative adzerk url<commit_after>from urllib import quote from pylons import tmpl_context as c from pylons import app_globals as g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) site_name = getattr(c.site, "analytics_name", c.site.name) # adzerk reporting is easier when not using a space in the tag if isinstance(c.site, DefaultSR): site_name = FRONTPAGE_NAME self.ad_url = g.adzerk_url.format( subreddit=quote(site_name.lower()), origin=c.request_origin, loggedin="loggedin" if c.user_is_loggedin else "loggedout", ) self.frame_id = "ad_main"
485f04f0e396444dbb5635b21202b2cd2e0612ff
src/webapp/admin/login.py
src/webapp/admin/login.py
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.path return redirect(url_for(".login")) return nufun
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.script_root + request.path return redirect(url_for(".login")) return nufun
Fix redirect generation for reverse proxied solutions
Fix redirect generation for reverse proxied solutions
Python
bsd-3-clause
janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.path return redirect(url_for(".login")) return nufun Fix redirect generation for reverse proxied solutions
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.script_root + request.path return redirect(url_for(".login")) return nufun
<commit_before>from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.path return redirect(url_for(".login")) return nufun <commit_msg>Fix redirect generation for reverse proxied solutions<commit_after>
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.script_root + request.path return redirect(url_for(".login")) return nufun
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.path return redirect(url_for(".login")) return nufun Fix redirect generation for reverse proxied solutionsfrom datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.script_root + request.path return redirect(url_for(".login")) return nufun
<commit_before>from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.path return redirect(url_for(".login")) return nufun <commit_msg>Fix redirect generation for reverse proxied solutions<commit_after>from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.script_root + request.path return redirect(url_for(".login")) return nufun
1ad3bf1093dd6b336dfc45c51dc608f04b355631
wafer/talks/tests/test_wafer_basic_talks.py
wafer/talks/tests/test_wafer_basic_talks.py
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talk.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') Talk.objects.create( title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 def test_filter_talk(): """Create a second user and check some filters""" from django.contrib.auth.models import User User.objects.create_user('james', 'best@wafer.test', 'johnpassword') assert User.objects.filter(contact_talks__isnull=False).count() == 1 assert User.objects.filter(contact_talks__isnull=True).count() == 1 def test_multiple_talks(): """Add more talks""" from wafer.talks.models import Talk from django.contrib.auth.models import User user1 = User.objects.filter(username='john').get() user2 = User.objects.filter(username='james').get() Talk.objects.create( title="This is a another test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user1.id) assert len([x.title for x in user1.contact_talks.all()]) == 2 assert len([x.title for x in user2.contact_talks.all()]) == 0 Talk.objects.create( title="This is a third test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user2.id) assert len([x.title for x in user2.contact_talks.all()]) == 1
Add some more simple tests
Add some more simple tests
Python
isc
CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talk.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 Add some more simple tests
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') Talk.objects.create( title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 def test_filter_talk(): """Create a second user and check some filters""" from django.contrib.auth.models import User User.objects.create_user('james', 'best@wafer.test', 'johnpassword') assert User.objects.filter(contact_talks__isnull=False).count() == 1 assert User.objects.filter(contact_talks__isnull=True).count() == 1 def test_multiple_talks(): """Add more talks""" from wafer.talks.models import Talk from django.contrib.auth.models import User user1 = User.objects.filter(username='john').get() user2 = User.objects.filter(username='james').get() Talk.objects.create( title="This is a another test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user1.id) assert len([x.title for x in user1.contact_talks.all()]) == 2 assert len([x.title for x in user2.contact_talks.all()]) == 0 Talk.objects.create( title="This is a third test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user2.id) assert len([x.title for x in user2.contact_talks.all()]) == 1
<commit_before># This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talk.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 <commit_msg>Add some more simple tests<commit_after>
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') Talk.objects.create( title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 def test_filter_talk(): """Create a second user and check some filters""" from django.contrib.auth.models import User User.objects.create_user('james', 'best@wafer.test', 'johnpassword') assert User.objects.filter(contact_talks__isnull=False).count() == 1 assert User.objects.filter(contact_talks__isnull=True).count() == 1 def test_multiple_talks(): """Add more talks""" from wafer.talks.models import Talk from django.contrib.auth.models import User user1 = User.objects.filter(username='john').get() user2 = User.objects.filter(username='james').get() Talk.objects.create( title="This is a another test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user1.id) assert len([x.title for x in user1.contact_talks.all()]) == 2 assert len([x.title for x in user2.contact_talks.all()]) == 0 Talk.objects.create( title="This is a third test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user2.id) assert len([x.title for x in user2.contact_talks.all()]) == 1
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talk.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 Add some more simple tests# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') Talk.objects.create( title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 def test_filter_talk(): """Create a second user and check some filters""" from django.contrib.auth.models import User User.objects.create_user('james', 'best@wafer.test', 'johnpassword') assert User.objects.filter(contact_talks__isnull=False).count() == 1 assert User.objects.filter(contact_talks__isnull=True).count() == 1 def test_multiple_talks(): """Add more talks""" from wafer.talks.models import Talk from django.contrib.auth.models import User user1 = User.objects.filter(username='john').get() user2 = User.objects.filter(username='james').get() Talk.objects.create( title="This is a another test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user1.id) assert len([x.title for x in user1.contact_talks.all()]) == 2 assert len([x.title for x in user2.contact_talks.all()]) == 0 Talk.objects.create( title="This is a third test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user2.id) assert len([x.title for x in user2.contact_talks.all()]) == 1
<commit_before># This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talk.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 <commit_msg>Add some more simple tests<commit_after># This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talk user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') Talk.objects.create( title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1 def test_filter_talk(): """Create a second user and check some filters""" from django.contrib.auth.models import User User.objects.create_user('james', 'best@wafer.test', 'johnpassword') assert User.objects.filter(contact_talks__isnull=False).count() == 1 assert User.objects.filter(contact_talks__isnull=True).count() == 1 def test_multiple_talks(): """Add more talks""" from wafer.talks.models import Talk from django.contrib.auth.models import User user1 = User.objects.filter(username='john').get() user2 = User.objects.filter(username='james').get() Talk.objects.create( title="This is a another test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user1.id) assert len([x.title for x in user1.contact_talks.all()]) == 2 assert len([x.title for x in user2.contact_talks.all()]) == 0 Talk.objects.create( title="This is a third test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user2.id) assert len([x.title for x in user2.contact_talks.all()]) == 1
1cf1da043ceab767d9d0dbdbed62c2f1c5ff36e9
test_http.py
test_http.py
from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000)
from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000) def test_close_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() s.close_socket() assert s._socket is None
Add tests for closing a socket
Add tests for closing a socket
Python
mit
jefrailey/network_tools
from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000)Add tests for closing a socket
from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000) def test_close_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() s.close_socket() assert s._socket is None
<commit_before>from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000)<commit_msg>Add tests for closing a socket<commit_after>
from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000) def test_close_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() s.close_socket() assert s._socket is None
from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000)Add tests for closing a socketfrom http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000) def test_close_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() s.close_socket() assert s._socket is None
<commit_before>from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000)<commit_msg>Add tests for closing a socket<commit_after>from http_server import HttpServer import socket def test_200_ok(): s = HttpServer() assert s.ok() == "HTTP/1.1 200 OK" def test_200_ok_byte(): s = HttpServer() assert isinstance(s.ok(), bytes) def test_socket_is_socket(): s = HttpServer() s.open_socket() assert isinstance(s._socket, socket.socket) def test_open_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() assert s._socket.getsockname() == ('127.0.0.1', 50000) def test_close_socket(): s = HttpServer(ip=u'127.0.0.1', port=50000, backlog=5) s.open_socket() s.close_socket() assert s._socket is None
8cd922488ffa3363f140ba156e1e5a011d89545d
tfr/files.py
tfr/files.py
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
Fix the quantization factor for writing.
Fix the quantization factor for writing.
Python
mit
bzamecnik/tfr,bzamecnik/tfr
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1) Fix the quantization factor for writing.
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
<commit_before>import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1) <commit_msg>Fix the quantization factor for writing.<commit_after>
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1) Fix the quantization factor for writing.import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
<commit_before>import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1) <commit_msg>Fix the quantization factor for writing.<commit_after>import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a WAV file. Samples are assumed to be in the [-1; 1] range and converted to signed 16-bit integers. ''' samples = normalize(samples) if should_normalize else samples wavfile.write(filename, fs, np.int16(samples * factor)) def load_wav(filename, factor=(1 / (((2**15)))), mono_mix=True): ''' Reads samples from a WAV file. Samples are assumed to be signed 16-bit integers and are converted to [-1; 1] range. It returns a tuple of sampling frequency and actual samples. ''' fs, samples = wavfile.read(filename) samples = samples * factor if mono_mix: samples = to_mono(samples) return samples, fs def to_mono(samples): if samples.ndim == 1: return samples else: return samples.mean(axis=-1)
5def645c7bceaca3da3e76fec136c82b4ae848e3
UIP.py
UIP.py
import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0)
import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
Add flag options for flush and offline modes
Add flag options for flush and offline modes Fixes #65
Python
agpl-3.0
Aniq55/UIP,nemaniarjun/UIP,mohitshaw/UIP,akshatnitd/UIP,VK10/UIP,VK10/UIP,nemaniarjun/UIP,Aniq55/UIP,NIT-dgp/UIP,DarkSouL11/UIP,hackrush01/UIP,NIT-dgp/UIP,hassi2016/UIP
import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0) Add flag options for flush and offline modes Fixes #65
import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
<commit_before>import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0) <commit_msg>Add flag options for flush and offline modes Fixes #65<commit_after>
import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0) Add flag options for flush and offline modes Fixes #65import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
<commit_before>import sys from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") try: offline = False if len(sys.argv) > 1 and str(sys.argv[1]) == '--offline': print("You have choosen to run UIP in offline mode.") offline = True else: print("UIP will now connect to internet and download images" " from reddit.") scheduler(offline) except KeyboardInterrupt: sys.exit(0) <commit_msg>Add flag options for flush and offline modes Fixes #65<commit_after>import sys, argparse, os, shutil from uiplib.constants import CURR_DIR, PICS_FOLDER from uiplib.scheduler import scheduler if __name__ == "__main__": print("Hey this is UIP! you can use it to download" " images from reddit and also to schedule the setting of these" " images as your desktop wallpaper.") parser = argparse.ArgumentParser() parser.add_argument("--offline", action="store_true", help="Runs UIP in offline mode.") parser.add_argument("--flush", action="store_true", help="Delete all downloaded wallpapers" " and downloads new ones. " "When combined with --offline," " deletes the wallpapers and exits.") args = parser.parse_args() try: if args.offline: print("You have choosen to run UIP in offline mode.") if args.flush: print("Deleting all downloaded wallpapers...") try: shutil.rmtree(os.path.join(CURR_DIR, PICS_FOLDER)) os.mkdir(os.path.join(CURR_DIR, PICS_FOLDER)) except FileNotFoundError: pass if not args.offline: print("UIP will now connect to internet and download images" " from reddit.") scheduler(args.offline) except KeyboardInterrupt: sys.exit(0)
a3c52c84da93c3e3007fa291213b97fd7d5b0e8f
tests.py
tests.py
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
Add twitter API functionality test
Add twitter API functionality test
Python
mit
jayelm/twittersa,jayelm/twittersa
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main() Add twitter API functionality test
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
<commit_before>""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main() <commit_msg>Add twitter API functionality test<commit_after>
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main() Add twitter API functionality test""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
<commit_before>""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main() <commit_msg>Add twitter API functionality test<commit_after>""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() def tearDown(self): pass def test_twitter_api(self): """Test to make sure the API is getting tweets""" tweets = TwitterSA.api.search(q='hello') assert tweets and len(tweets) def test_invalid_search_query(self): """Test for invalid search queries""" rv = self.app.get('/search?q=') assert 'Invalid search query' in rv.data rv = self.app.get('/search?nonsense=nonsense') assert 'Invalid search query' in rv.data def test_invalid_user_id(self): """Test for invalid user ids""" rv = self.app.get('/user?uid=') assert 'Invalid user id' in rv.data rv = self.app.get('/user?nonsense=nonsense') assert 'Invalid user id' in rv.data if __name__ == '__main__': unittest.main()
5f16929b405ea12a430a22fdd02a547d6b7e28a5
tests.py
tests.py
from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'})
from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) def test_add_page(self): self.login() self.assertEqual(Page.objects.count(), 2) post = {'title': 'NewTitle', 'content': 'NewContent'} r = self.client.post('/wiki/add/', post, follow=True) self.assertRedirects(r, '/wiki')
Add test for adding a page
Add test for adding a page
Python
mit
plumdog/mainstay_wiki
from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) Add test for adding a page
from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) def test_add_page(self): self.login() self.assertEqual(Page.objects.count(), 2) post = {'title': 'NewTitle', 'content': 'NewContent'} r = self.client.post('/wiki/add/', post, follow=True) self.assertRedirects(r, '/wiki')
<commit_before>from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) <commit_msg>Add test for adding a page<commit_after>
from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) def test_add_page(self): self.login() self.assertEqual(Page.objects.count(), 2) post = {'title': 'NewTitle', 'content': 'NewContent'} r = self.client.post('/wiki/add/', post, follow=True) self.assertRedirects(r, '/wiki')
from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) Add test for adding a pagefrom django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) def test_add_page(self): self.login() self.assertEqual(Page.objects.count(), 2) post = {'title': 'NewTitle', 'content': 'NewContent'} r = self.client.post('/wiki/add/', post, follow=True) self.assertRedirects(r, '/wiki')
<commit_before>from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) <commit_msg>Add test for adding a page<commit_after>from django.test import TestCase from django.contrib.auth.models import User from mainstay.test_utils import MainstayTest from .models import Page class WikiTestCase(MainstayTest): fixtures = MainstayTest.fixtures + ['wiki_pages'] def test_user_loaded(self): user = User.objects.get() self.assertEqual(user.username, 'admin') self.assertEqual(user.is_superuser, True) def test_pages_loaded(self): pages = Page.objects.all() self.assertEqual(len(pages), 2) def test_page_view(self): self.login() r = self.client.get('/wiki/page/TestPage') def test_page_with_link(self): self.login() r = self.client.get('/wiki/page/PageWithLink') self.assertInHTML('<a href="/wiki/page/TestPage">TestPage</a>', r.content.decode('utf-8')) def test_search(self): self.login() r = self.client.get('/wiki/search/page') results = r.context['results'] self.assertEqual({r.title for r in results}, {'TestPage', 'PageWithLink'}) r = self.client.get('/wiki/search/withlink') results = r.context['results'] self.assertEqual({r.title for r in results}, {'PageWithLink'}) def test_add_page(self): self.login() self.assertEqual(Page.objects.count(), 2) post = {'title': 'NewTitle', 'content': 'NewContent'} r = self.client.post('/wiki/add/', post, follow=True) self.assertRedirects(r, '/wiki')
d2cfadb8100859521c9423ae8ace95cf074fed05
src/submodules/sm_stats.py
src/submodules/sm_stats.py
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and block log. """ DEPTH = 1 import config site = config.site class JuniorCollector(): def __init__(self,user): self.user = user def raw(self): return {'sample':site.Pages['Example']}
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and log events. """ DEPTH = 1 import config site = config.site import dateutil.parser from collections import Counter class JuniorCollector(): def __init__(self,user): self.user = user self.process() def process(self): results = {} # Basic data basedata = site.users([self.user],prop='registration|editcount|gender').next() results['gender'] = basedata['gender'] if 'gender' in basedata else 'unknown' results['editcount'] = basedata['editcount'] results['registration'] = dateutil.parser.parse(basedata['registration']) # User rights changes rightsevents = site.logevents(title="User:"+self.user,dir='newer',type='rights') rightschanges = [] for event in rightsevents: if event['action'] == 'rights': new = Counter(event['rights']['new'].split(', ')) old = Counter(event['rights']['old'].split(', ')) diff = new-old if len(list(diff.elements())) > 0: rightschanges.append({'change':'add','rights':list(diff.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) diff2 = old-new if len(list(diff2.elements())) > 0: rightschanges.append({'change':'remove','rights':list(diff2.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) results['rightschanges'] = rightschanges #!todo block log self.results = results def raw(self): return self.results
Add basic data parsing, userrights changes
Add basic data parsing, userrights changes
Python
mit
theopolisme/wikitimeline
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and block log. """ DEPTH = 1 import config site = config.site class JuniorCollector(): def __init__(self,user): self.user = user def raw(self): return {'sample':site.Pages['Example']} Add basic data parsing, userrights changes
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and log events. """ DEPTH = 1 import config site = config.site import dateutil.parser from collections import Counter class JuniorCollector(): def __init__(self,user): self.user = user self.process() def process(self): results = {} # Basic data basedata = site.users([self.user],prop='registration|editcount|gender').next() results['gender'] = basedata['gender'] if 'gender' in basedata else 'unknown' results['editcount'] = basedata['editcount'] results['registration'] = dateutil.parser.parse(basedata['registration']) # User rights changes rightsevents = site.logevents(title="User:"+self.user,dir='newer',type='rights') rightschanges = [] for event in rightsevents: if event['action'] == 'rights': new = Counter(event['rights']['new'].split(', ')) old = Counter(event['rights']['old'].split(', ')) diff = new-old if len(list(diff.elements())) > 0: rightschanges.append({'change':'add','rights':list(diff.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) diff2 = old-new if len(list(diff2.elements())) > 0: rightschanges.append({'change':'remove','rights':list(diff2.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) results['rightschanges'] = rightschanges #!todo block log self.results = results def raw(self): return self.results
<commit_before> #!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and block log. """ DEPTH = 1 import config site = config.site class JuniorCollector(): def __init__(self,user): self.user = user def raw(self): return {'sample':site.Pages['Example']} <commit_msg>Add basic data parsing, userrights changes<commit_after>
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and log events. """ DEPTH = 1 import config site = config.site import dateutil.parser from collections import Counter class JuniorCollector(): def __init__(self,user): self.user = user self.process() def process(self): results = {} # Basic data basedata = site.users([self.user],prop='registration|editcount|gender').next() results['gender'] = basedata['gender'] if 'gender' in basedata else 'unknown' results['editcount'] = basedata['editcount'] results['registration'] = dateutil.parser.parse(basedata['registration']) # User rights changes rightsevents = site.logevents(title="User:"+self.user,dir='newer',type='rights') rightschanges = [] for event in rightsevents: if event['action'] == 'rights': new = Counter(event['rights']['new'].split(', ')) old = Counter(event['rights']['old'].split(', ')) diff = new-old if len(list(diff.elements())) > 0: rightschanges.append({'change':'add','rights':list(diff.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) diff2 = old-new if len(list(diff2.elements())) > 0: rightschanges.append({'change':'remove','rights':list(diff2.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) results['rightschanges'] = rightschanges #!todo block log self.results = results def raw(self): return self.results
#!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and block log. """ DEPTH = 1 import config site = config.site class JuniorCollector(): def __init__(self,user): self.user = user def raw(self): return {'sample':site.Pages['Example']} Add basic data parsing, userrights changes #!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and log events. """ DEPTH = 1 import config site = config.site import dateutil.parser from collections import Counter class JuniorCollector(): def __init__(self,user): self.user = user self.process() def process(self): results = {} # Basic data basedata = site.users([self.user],prop='registration|editcount|gender').next() results['gender'] = basedata['gender'] if 'gender' in basedata else 'unknown' results['editcount'] = basedata['editcount'] results['registration'] = dateutil.parser.parse(basedata['registration']) # User rights changes rightsevents = site.logevents(title="User:"+self.user,dir='newer',type='rights') rightschanges = [] for event in rightsevents: if event['action'] == 'rights': new = Counter(event['rights']['new'].split(', ')) old = Counter(event['rights']['old'].split(', ')) diff = new-old if len(list(diff.elements())) > 0: rightschanges.append({'change':'add','rights':list(diff.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) diff2 = old-new if len(list(diff2.elements())) > 0: rightschanges.append({'change':'remove','rights':list(diff2.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) results['rightschanges'] = rightschanges #!todo block log self.results = results def raw(self): return self.results
<commit_before> #!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and block log. """ DEPTH = 1 import config site = config.site class JuniorCollector(): def __init__(self,user): self.user = user def raw(self): return {'sample':site.Pages['Example']} <commit_msg>Add basic data parsing, userrights changes<commit_after> #!/usr/bin/env python """ Returns basic statistics about the user, including edit count, creation date, and log events. """ DEPTH = 1 import config site = config.site import dateutil.parser from collections import Counter class JuniorCollector(): def __init__(self,user): self.user = user self.process() def process(self): results = {} # Basic data basedata = site.users([self.user],prop='registration|editcount|gender').next() results['gender'] = basedata['gender'] if 'gender' in basedata else 'unknown' results['editcount'] = basedata['editcount'] results['registration'] = dateutil.parser.parse(basedata['registration']) # User rights changes rightsevents = site.logevents(title="User:"+self.user,dir='newer',type='rights') rightschanges = [] for event in rightsevents: if event['action'] == 'rights': new = Counter(event['rights']['new'].split(', ')) old = Counter(event['rights']['old'].split(', ')) diff = new-old if len(list(diff.elements())) > 0: rightschanges.append({'change':'add','rights':list(diff.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) diff2 = old-new if len(list(diff2.elements())) > 0: rightschanges.append({'change':'remove','rights':list(diff2.elements()),'comment':event['comment'],'timestamp':event['timestamp']}) results['rightschanges'] = rightschanges #!todo block log self.results = results def raw(self): return self.results
c7150bf227edf78d716fe4e09b3a073d9b0cfc1e
fmriprep/workflows/bold/tests/test_utils.py
fmriprep/workflows/bold/tests/test_utils.py
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) def test_masking(input_fname, expected_fname): enhance_and_skullstrip_bold_wf = init_enhance_and_skullstrip_bold_wf() enhance_and_skullstrip_bold_wf.inputs.inputnode.in_file = input_fname res = enhance_and_skullstrip_bold_wf.run() combine_masks = [node for node in res.nodes if node.name == 'combine_masks'][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.skip def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
Use bold_reference_wf to generate reference before enhancing
TEST: Use bold_reference_wf to generate reference before enhancing
Python
bsd-3-clause
poldracklab/preprocessing-workflow,poldracklab/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep,oesteban/fmriprep,oesteban/fmriprep,oesteban/preprocessing-workflow,poldracklab/fmriprep,poldracklab/fmriprep,oesteban/preprocessing-workflow
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) def test_masking(input_fname, expected_fname): enhance_and_skullstrip_bold_wf = init_enhance_and_skullstrip_bold_wf() enhance_and_skullstrip_bold_wf.inputs.inputnode.in_file = input_fname res = enhance_and_skullstrip_bold_wf.run() combine_masks = [node for node in res.nodes if node.name == 'combine_masks'][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname TEST: Use bold_reference_wf to generate reference before enhancing
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.skip def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
<commit_before>''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) def test_masking(input_fname, expected_fname): enhance_and_skullstrip_bold_wf = init_enhance_and_skullstrip_bold_wf() enhance_and_skullstrip_bold_wf.inputs.inputnode.in_file = input_fname res = enhance_and_skullstrip_bold_wf.run() combine_masks = [node for node in res.nodes if node.name == 'combine_masks'][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname <commit_msg>TEST: Use bold_reference_wf to generate reference before enhancing<commit_after>
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.skip def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) def test_masking(input_fname, expected_fname): enhance_and_skullstrip_bold_wf = init_enhance_and_skullstrip_bold_wf() enhance_and_skullstrip_bold_wf.inputs.inputnode.in_file = input_fname res = enhance_and_skullstrip_bold_wf.run() combine_masks = [node for node in res.nodes if node.name == 'combine_masks'][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname TEST: Use bold_reference_wf to generate reference before enhancing''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.skip def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
<commit_before>''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) def test_masking(input_fname, expected_fname): enhance_and_skullstrip_bold_wf = init_enhance_and_skullstrip_bold_wf() enhance_and_skullstrip_bold_wf.inputs.inputnode.in_file = input_fname res = enhance_and_skullstrip_bold_wf.run() combine_masks = [node for node in res.nodes if node.name == 'combine_masks'][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname <commit_msg>TEST: Use bold_reference_wf to generate reference before enhancing<commit_after>''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.skip def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
b742bd2ba0a2dd18c614ddb72dc09ef091a81717
takeyourmeds/api/views.py
takeyourmeds/api/views.py
from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder, ReminderTime class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for time in req.data.get('times', []): ReminderTime.objects.create( reminder=obj, cronstring=time, ) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"})
from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for x in req.data.get('times', []): obj.times.create(cronstring=x) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"})
Use related_name etc to avoid code
Use related_name etc to avoid code Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
Python
mit
takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web
from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder, ReminderTime class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for time in req.data.get('times', []): ReminderTime.objects.create( reminder=obj, cronstring=time, ) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"}) Use related_name etc to avoid code Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for x in req.data.get('times', []): obj.times.create(cronstring=x) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"})
<commit_before>from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder, ReminderTime class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for time in req.data.get('times', []): ReminderTime.objects.create( reminder=obj, cronstring=time, ) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"}) <commit_msg>Use related_name etc to avoid code Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk><commit_after>
from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for x in req.data.get('times', []): obj.times.create(cronstring=x) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"})
from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder, ReminderTime class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for time in req.data.get('times', []): ReminderTime.objects.create( reminder=obj, cronstring=time, ) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"}) Use related_name etc to avoid code Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for x in req.data.get('times', []): obj.times.create(cronstring=x) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"})
<commit_before>from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder, ReminderTime class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for time in req.data.get('times', []): ReminderTime.objects.create( reminder=obj, cronstring=time, ) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"}) <commit_msg>Use related_name etc to avoid code Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk><commit_after>from rest_framework import serializers, viewsets from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated from takeyourmeds.reminder.models import Reminder class ReminderTimeField(serializers.RelatedField): def to_representation(self, model): return model.cronstring class ReminderSerializer(serializers.ModelSerializer): times = ReminderTimeField(many=True, read_only=True) def create(self, data): req = self.context['request'] data['user_id'] = req.user.pk obj = super(ReminderSerializer, self).create(data) for x in req.data.get('times', []): obj.times.create(cronstring=x) return obj class Meta: model = Reminder fields = ( 'times', 'message', 'audiourl', 'telnumber', ) class ReminderViewSet(viewsets.ModelViewSet): queryset = Reminder.objects.all() serializer_class = ReminderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Reminder.objects.filter(user=self.request.user) @api_view(('POST',)) def trigger_now(request): # FIXME: Move parameter to urlconf pk = request.data.get('id') reminder = Reminder.objects.get(pk=pk) reminder.dispatch_task() return Response({'message': "Triggered"})
d3a0c400e50d34b9829b05d26eef5eac878aa091
enhanced_cbv/views/list.py
enhanced_cbv/views/list.py
from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(self.request.GET, queryset=self.get_base_queryset()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """
from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_filter_set_kwargs(self): """ Returns the keyword arguments for instanciating the filterset. """ return { 'data': self.request.GET, 'queryset': self.get_base_queryset(), } def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(**self.get_filter_set_kwargs()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """
Add get_filter_set_kwargs for instanciating FilterSet with additional arguments
Add get_filter_set_kwargs for instanciating FilterSet with additional arguments
Python
bsd-3-clause
rasca/django-enhanced-cbv,matuu/django-enhanced-cbv,matuu/django-enhanced-cbv,rasca/django-enhanced-cbv
from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(self.request.GET, queryset=self.get_base_queryset()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """ Add get_filter_set_kwargs for instanciating FilterSet with additional arguments
from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_filter_set_kwargs(self): """ Returns the keyword arguments for instanciating the filterset. """ return { 'data': self.request.GET, 'queryset': self.get_base_queryset(), } def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(**self.get_filter_set_kwargs()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """
<commit_before>from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(self.request.GET, queryset=self.get_base_queryset()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """ <commit_msg>Add get_filter_set_kwargs for instanciating FilterSet with additional arguments<commit_after>
from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_filter_set_kwargs(self): """ Returns the keyword arguments for instanciating the filterset. """ return { 'data': self.request.GET, 'queryset': self.get_base_queryset(), } def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(**self.get_filter_set_kwargs()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """
from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(self.request.GET, queryset=self.get_base_queryset()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """ Add get_filter_set_kwargs for instanciating FilterSet with additional argumentsfrom django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_filter_set_kwargs(self): """ Returns the keyword arguments for instanciating the filterset. """ return { 'data': self.request.GET, 'queryset': self.get_base_queryset(), } def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(**self.get_filter_set_kwargs()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """
<commit_before>from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(self.request.GET, queryset=self.get_base_queryset()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """ <commit_msg>Add get_filter_set_kwargs for instanciating FilterSet with additional arguments<commit_after>from django.core.exceptions import ImproperlyConfigured from django.views.generic import ListView class ListFilteredMixin(object): """ Mixin that adds support for django-filter """ filter_set = None def get_filter_set(self): if self.filter_set: return self.filter_set else: raise ImproperlyConfigured( "ListFilterMixin requires either a definition of " "'filter_set' or an implementation of 'get_filter()'") def get_filter_set_kwargs(self): """ Returns the keyword arguments for instanciating the filterset. """ return { 'data': self.request.GET, 'queryset': self.get_base_queryset(), } def get_base_queryset(self): """ We can decided to either alter the queryset before or after applying the FilterSet """ return super(ListFilteredMixin, self).get_queryset() def get_constructed_filter(self): # We need to store the instantiated FilterSet cause we use it in # get_queryset and in get_context_data if getattr(self, 'constructed_filter', None): return self.constructed_filter else: f = self.get_filter_set()(**self.get_filter_set_kwargs()) self.constructed_filter = f return f def get_queryset(self): return self.get_constructed_filter().qs def get_context_data(self, **kwargs): kwargs.update({'filter': self.get_constructed_filter()}) return super(ListFilteredMixin, self).get_context_data(**kwargs) class ListFilteredView(ListFilteredMixin, ListView): """ A list view that can be filtered by django-filter """
c6eac58dcddde575dbc919edb71661b4a443cc29
shallow_appify/_version.py
shallow_appify/_version.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 3) __version__ = '.'.join(map(str, __version_info__))
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 4) __version__ = '.'.join(map(str, __version_info__))
Increase the version number to `0.4.4`
Increase the version number to `0.4.4`
Python
mit
IngoHeimbach/shallow-appify
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 3) __version__ = '.'.join(map(str, __version_info__)) Increase the version number to `0.4.4`
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 4) __version__ = '.'.join(map(str, __version_info__))
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 3) __version__ = '.'.join(map(str, __version_info__)) <commit_msg>Increase the version number to `0.4.4`<commit_after>
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 4) __version__ = '.'.join(map(str, __version_info__))
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 3) __version__ = '.'.join(map(str, __version_info__)) Increase the version number to `0.4.4`# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 4) __version__ = '.'.join(map(str, __version_info__))
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 3) __version__ = '.'.join(map(str, __version_info__)) <commit_msg>Increase the version number to `0.4.4`<commit_after># -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __version_info__ = (0, 4, 4) __version__ = '.'.join(map(str, __version_info__))
4a8c608c545b67f9dc1f436c82e0d83a55e168e9
scripts/database/common.py
scripts/database/common.py
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
Add default port to database connection script
Add default port to database connection script The default port is used if the ~/.catmaid-db file doesn't contain it. This fixes #454.
Python
agpl-3.0
fzadow/CATMAID,htem/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password) Add default port to database connection script The default port is used if the ~/.catmaid-db file doesn't contain it. This fixes #454.
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
<commit_before>import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password) <commit_msg>Add default port to database connection script The default port is used if the ~/.catmaid-db file doesn't contain it. This fixes #454.<commit_after>
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password) Add default port to database connection script The default port is used if the ~/.catmaid-db file doesn't contain it. This fixes #454.import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
<commit_before>import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password) <commit_msg>Add default port to database connection script The default port is used if the ~/.catmaid-db file doesn't contain it. This fixes #454.<commit_after>import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost port: 5432 database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_port = conf['port'] if 'port' in conf else 5432 db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, port=db_port, database=db_database, user=db_username, password=db_password)
523dc5d2ab15b0e092f7c73d5a38ba90c8753338
custom/icds_reports/__init__.py
custom/icds_reports/__init__.py
from django.apps import AppConfig class ICDSReportsAppConfig(AppConfig): name = 'custom.icds_reports' def ready(self): import custom.icds_reports.reports.reports # noqa default_app_config = 'custom.icds_reports.ICDSReportsAppConfig'
Make sure reports are loaded so location_safe is applied
Make sure reports are loaded so location_safe is applied
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
Make sure reports are loaded so location_safe is applied
from django.apps import AppConfig class ICDSReportsAppConfig(AppConfig): name = 'custom.icds_reports' def ready(self): import custom.icds_reports.reports.reports # noqa default_app_config = 'custom.icds_reports.ICDSReportsAppConfig'
<commit_before><commit_msg>Make sure reports are loaded so location_safe is applied<commit_after>
from django.apps import AppConfig class ICDSReportsAppConfig(AppConfig): name = 'custom.icds_reports' def ready(self): import custom.icds_reports.reports.reports # noqa default_app_config = 'custom.icds_reports.ICDSReportsAppConfig'
Make sure reports are loaded so location_safe is appliedfrom django.apps import AppConfig class ICDSReportsAppConfig(AppConfig): name = 'custom.icds_reports' def ready(self): import custom.icds_reports.reports.reports # noqa default_app_config = 'custom.icds_reports.ICDSReportsAppConfig'
<commit_before><commit_msg>Make sure reports are loaded so location_safe is applied<commit_after>from django.apps import AppConfig class ICDSReportsAppConfig(AppConfig): name = 'custom.icds_reports' def ready(self): import custom.icds_reports.reports.reports # noqa default_app_config = 'custom.icds_reports.ICDSReportsAppConfig'
1431f45e6b605e54f1ec341114b53ae047e48be7
token_names.py
token_names.py
INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF, OPEN, CLOSE, BANG, ASSIGN, SEMI, ID = ( 'INTEGER', 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE', 'LPAREN', 'RPAREN', 'EOF', 'OPEN', 'CLOSE', 'BANG', 'ASSIGN', 'SEMI', 'ID' )
ASSIGN = 'ASSIGN' BANG = 'BANG' CLOSE = 'CLOSE' DIVIDE = 'DIVIDE' EOF = 'EOF' ID = 'ID' INTEGER = 'INTEGER' LPAREN = 'LPAREN' MINUS = 'MINUS' MULTIPLY = 'MULTIPLY' OPEN = 'OPEN' PLUS = 'PLUS' RPAREN = 'RPAREN' SEMI = 'SEMI'
Fix token names format for readability.
Fix token names format for readability.
Python
mit
doubledherin/my_compiler
INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF, OPEN, CLOSE, BANG, ASSIGN, SEMI, ID = ( 'INTEGER', 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE', 'LPAREN', 'RPAREN', 'EOF', 'OPEN', 'CLOSE', 'BANG', 'ASSIGN', 'SEMI', 'ID' ) Fix token names format for readability.
ASSIGN = 'ASSIGN' BANG = 'BANG' CLOSE = 'CLOSE' DIVIDE = 'DIVIDE' EOF = 'EOF' ID = 'ID' INTEGER = 'INTEGER' LPAREN = 'LPAREN' MINUS = 'MINUS' MULTIPLY = 'MULTIPLY' OPEN = 'OPEN' PLUS = 'PLUS' RPAREN = 'RPAREN' SEMI = 'SEMI'
<commit_before>INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF, OPEN, CLOSE, BANG, ASSIGN, SEMI, ID = ( 'INTEGER', 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE', 'LPAREN', 'RPAREN', 'EOF', 'OPEN', 'CLOSE', 'BANG', 'ASSIGN', 'SEMI', 'ID' ) <commit_msg>Fix token names format for readability.<commit_after>
ASSIGN = 'ASSIGN' BANG = 'BANG' CLOSE = 'CLOSE' DIVIDE = 'DIVIDE' EOF = 'EOF' ID = 'ID' INTEGER = 'INTEGER' LPAREN = 'LPAREN' MINUS = 'MINUS' MULTIPLY = 'MULTIPLY' OPEN = 'OPEN' PLUS = 'PLUS' RPAREN = 'RPAREN' SEMI = 'SEMI'
INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF, OPEN, CLOSE, BANG, ASSIGN, SEMI, ID = ( 'INTEGER', 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE', 'LPAREN', 'RPAREN', 'EOF', 'OPEN', 'CLOSE', 'BANG', 'ASSIGN', 'SEMI', 'ID' ) Fix token names format for readability.ASSIGN = 'ASSIGN' BANG = 'BANG' CLOSE = 'CLOSE' DIVIDE = 'DIVIDE' EOF = 'EOF' ID = 'ID' INTEGER = 'INTEGER' LPAREN = 'LPAREN' MINUS = 'MINUS' MULTIPLY = 'MULTIPLY' OPEN = 'OPEN' PLUS = 'PLUS' RPAREN = 'RPAREN' SEMI = 'SEMI'
<commit_before>INTEGER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, EOF, OPEN, CLOSE, BANG, ASSIGN, SEMI, ID = ( 'INTEGER', 'PLUS', 'MINUS', 'MULTIPLY', 'DIVIDE', 'LPAREN', 'RPAREN', 'EOF', 'OPEN', 'CLOSE', 'BANG', 'ASSIGN', 'SEMI', 'ID' ) <commit_msg>Fix token names format for readability.<commit_after>ASSIGN = 'ASSIGN' BANG = 'BANG' CLOSE = 'CLOSE' DIVIDE = 'DIVIDE' EOF = 'EOF' ID = 'ID' INTEGER = 'INTEGER' LPAREN = 'LPAREN' MINUS = 'MINUS' MULTIPLY = 'MULTIPLY' OPEN = 'OPEN' PLUS = 'PLUS' RPAREN = 'RPAREN' SEMI = 'SEMI'
9ce01dc752d62c62eb8b276698f7cf2d6bc5707f
transaction.py
transaction.py
import signature class Transaction: def __init__(self, data, signature): self.data = data self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.signature) def sign_transaction(data, key): return Transaction(data, signature.sign(key, data))
import signature class Transaction: def __init__(self, data, author, signature): self.data = data self.author = author self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.author) def get_data(self): return self.data def get_author(self): return self.author def get_signature(self): return self.signature def sign_transaction(data, key): return Transaction(data, signature.sign(key, data), signature.key_to_string(key.publickey()))
Add author public key info to Transaction class
Add author public key info to Transaction class
Python
mit
jake-billings/research-blockchain
import signature class Transaction: def __init__(self, data, signature): self.data = data self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.signature) def sign_transaction(data, key): return Transaction(data, signature.sign(key, data)) Add author public key info to Transaction class
import signature class Transaction: def __init__(self, data, author, signature): self.data = data self.author = author self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.author) def get_data(self): return self.data def get_author(self): return self.author def get_signature(self): return self.signature def sign_transaction(data, key): return Transaction(data, signature.sign(key, data), signature.key_to_string(key.publickey()))
<commit_before>import signature class Transaction: def __init__(self, data, signature): self.data = data self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.signature) def sign_transaction(data, key): return Transaction(data, signature.sign(key, data)) <commit_msg>Add author public key info to Transaction class<commit_after>
import signature class Transaction: def __init__(self, data, author, signature): self.data = data self.author = author self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.author) def get_data(self): return self.data def get_author(self): return self.author def get_signature(self): return self.signature def sign_transaction(data, key): return Transaction(data, signature.sign(key, data), signature.key_to_string(key.publickey()))
import signature class Transaction: def __init__(self, data, signature): self.data = data self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.signature) def sign_transaction(data, key): return Transaction(data, signature.sign(key, data)) Add author public key info to Transaction classimport signature class Transaction: def __init__(self, data, author, signature): self.data = data self.author = author self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.author) def get_data(self): return self.data def get_author(self): return self.author def get_signature(self): return self.signature def sign_transaction(data, key): return Transaction(data, signature.sign(key, data), signature.key_to_string(key.publickey()))
<commit_before>import signature class Transaction: def __init__(self, data, signature): self.data = data self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.signature) def sign_transaction(data, key): return Transaction(data, signature.sign(key, data)) <commit_msg>Add author public key info to Transaction class<commit_after>import signature class Transaction: def __init__(self, data, author, signature): self.data = data self.author = author self.signature = signature def get_string(self): return '%s (%s)' % (self.data, self.author) def get_data(self): return self.data def get_author(self): return self.author def get_signature(self): return self.signature def sign_transaction(data, key): return Transaction(data, signature.sign(key, data), signature.key_to_string(key.publickey()))
b44dc164e6dd1e9a07f460c2be07829744029cea
server/tests/test_admin.py
server/tests/test_admin.py
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'}
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
Remove endpoint from test (it has been removed in lieu of User admin).
Remove endpoint from test (it has been removed in lieu of User admin).
Python
apache-2.0
sheagcraig/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'} Remove endpoint from test (it has been removed in lieu of User admin).
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
<commit_before>"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'} <commit_msg>Remove endpoint from test (it has been removed in lieu of User admin).<commit_after>
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'} Remove endpoint from test (it has been removed in lieu of User admin)."""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
<commit_before>"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory', 'userprofile'} <commit_msg>Remove endpoint from test (it has been removed in lieu of User admin).<commit_after>"""General functional tests for the Server admin.""" from sal.test_utils import AdminTestCase class ServerAdminTest(AdminTestCase): """Test the admin site is configured to have all expected views.""" admin_endpoints = { 'apikey', 'businessunit', 'condition', 'fact', 'historicalfact', 'installedupdate', 'machinedetailplugin', 'machinegroup', 'machine', 'pendingappleupdate', 'pendingupdate', 'pluginscriptrow', 'pluginscriptsubmission', 'plugin', 'report', 'salsetting', 'updatehistoryitem', 'updatehistory'}
76bbaa5e0208e5c28747fff09388cd52ef63f6f5
blackjax/__init__.py
blackjax/__init__.py
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "pathfinder", # variational inference "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
Add `pathfinder` to the library namespace
Add `pathfinder` to the library namespace
Python
apache-2.0
blackjax-devs/blackjax
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"] Add `pathfinder` to the library namespace
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "pathfinder", # variational inference "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
<commit_before>from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"] <commit_msg>Add `pathfinder` to the library namespace<commit_after>
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "pathfinder", # variational inference "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"] Add `pathfinder` to the library namespacefrom .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "pathfinder", # variational inference "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
<commit_before>from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"] <commit_msg>Add `pathfinder` to the library namespace<commit_after>from .diagnostics import effective_sample_size as ess from .diagnostics import potential_scale_reduction as rhat from .kernels import ( adaptive_tempered_smc, elliptical_slice, ghmc, hmc, irmh, mala, meads, mgrad_gaussian, nuts, orbital_hmc, pathfinder, pathfinder_adaptation, rmh, sghmc, sgld, tempered_smc, window_adaptation, ) from .optimizers import dual_averaging, lbfgs __all__ = [ "dual_averaging", # optimizers "lbfgs", "hmc", # mcmc "mala", "mgrad_gaussian", "nuts", "orbital_hmc", "rmh", "irmh", "elliptical_slice", "ghmc", "meads", "sgld", # stochastic gradient mcmc "sghmc", "window_adaptation", # mcmc adaptation "pathfinder_adaptation", "adaptive_tempered_smc", # smc "tempered_smc", "pathfinder", # variational inference "ess", # diagnostics "rhat", ] from . import _version __version__ = _version.get_versions()["version"]
f48a9f088e383eb77c40b0196552590dc654cea7
test/mbed_gt_cli.py
test/mbed_gt_cli.py
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_print_version(self): version = mbed_greentea_cli.print_version(verbose=False) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_greentea_version(self): version = mbed_greentea_cli.get_greentea_version() self.assertIs(type(version), str) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) def get_hello_string(self): version = mbed_greentea_cli.get_greentea_version() hello_string = mbed_greentea_cli.get_hello_string() self.assertIs(type(version), str) self.assertIs(type(hello_string), str) self.assertIn(version, hello_string) if __name__ == '__main__': unittest.main()
Add unit tests to mbed-greentea version printing API
Add unit tests to mbed-greentea version printing API
Python
apache-2.0
ARMmbed/greentea
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_print_version(self): version = mbed_greentea_cli.print_version(verbose=False) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) if __name__ == '__main__': unittest.main() Add unit tests to mbed-greentea version printing API
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_greentea_version(self): version = mbed_greentea_cli.get_greentea_version() self.assertIs(type(version), str) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) def get_hello_string(self): version = mbed_greentea_cli.get_greentea_version() hello_string = mbed_greentea_cli.get_hello_string() self.assertIs(type(version), str) self.assertIs(type(hello_string), str) self.assertIn(version, hello_string) if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_print_version(self): version = mbed_greentea_cli.print_version(verbose=False) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) if __name__ == '__main__': unittest.main() <commit_msg>Add unit tests to mbed-greentea version printing API<commit_after>
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_greentea_version(self): version = mbed_greentea_cli.get_greentea_version() self.assertIs(type(version), str) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) def get_hello_string(self): version = mbed_greentea_cli.get_greentea_version() hello_string = mbed_greentea_cli.get_hello_string() self.assertIs(type(version), str) self.assertIs(type(hello_string), str) self.assertIn(version, hello_string) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_print_version(self): version = mbed_greentea_cli.print_version(verbose=False) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) if __name__ == '__main__': unittest.main() Add unit tests to mbed-greentea version printing API#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_greentea_version(self): version = mbed_greentea_cli.get_greentea_version() self.assertIs(type(version), str) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) def get_hello_string(self): version = mbed_greentea_cli.get_greentea_version() hello_string = mbed_greentea_cli.get_hello_string() self.assertIs(type(version), str) self.assertIs(type(hello_string), str) self.assertIn(version, hello_string) if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_print_version(self): version = mbed_greentea_cli.print_version(verbose=False) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) if __name__ == '__main__': unittest.main() <commit_msg>Add unit tests to mbed-greentea version printing API<commit_after>#!/usr/bin/env python """ mbed SDK Copyright (c) 2011-2015 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest from mbed_greentea import mbed_greentea_cli class GreenteaCliFunctionality(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_get_greentea_version(self): version = mbed_greentea_cli.get_greentea_version() self.assertIs(type(version), str) a, b, c = version.split('.') self.assertEqual(a.isdigit(), True) self.assertEqual(b.isdigit(), True) self.assertEqual(c.isdigit(), True) def get_hello_string(self): version = mbed_greentea_cli.get_greentea_version() hello_string = mbed_greentea_cli.get_hello_string() self.assertIs(type(version), str) self.assertIs(type(hello_string), str) self.assertIn(version, hello_string) if __name__ == '__main__': unittest.main()
80a55580806f19e9e57d86a03768664caf35d54b
ci/generate_pipeline_yml.py
ci/generate_pipeline_yml.py
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
Comment out our one breaking example from pipeline
Comment out our one breaking example from pipeline
Python
apache-2.0
cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml" Comment out our one breaking example from pipeline
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
<commit_before>#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml" <commit_msg>Comment out our one breaking example from pipeline<commit_after>
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml" Comment out our one breaking example from pipeline#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
<commit_before>#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] tiles = [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml" <commit_msg>Comment out our one breaking example from pipeline<commit_after>#!/usr/bin/env python import os from jinja2 import Template clusters = ['1-12', '2-0', '2-1', '2-2'] # Commenting out this as we only have one example and it breaks tiles = [] # [d for d in os.listdir('../examples') if os.path.isdir(os.path.join('../examples', d))] with open('pipeline.yml.jinja2', 'r') as f: t = Template(f.read()); with open('pipeline.yml', 'w') as f: f.write(t.render(clusters=clusters, tiles=tiles)) print "Successfully generated pipeline.yml"
6bca7b628af7b5f57c4d7090008369eb2cde9d46
rest/views.py
rest/views.py
import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer
import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() sound._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer
Make sure to rename the sound file to its checksum
Make sure to rename the sound file to its checksum
Python
bsd-3-clause
Soundphy/soundphy
import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer Make sure to rename the sound file to its checksum
import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() sound._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer
<commit_before>import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer <commit_msg>Make sure to rename the sound file to its checksum<commit_after>
import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() sound._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer
import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer Make sure to rename the sound file to its checksumimport hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() sound._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer
<commit_before>import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer <commit_msg>Make sure to rename the sound file to its checksum<commit_after>import hashlib from rest.models import Sound from rest_framework import generics from rest.serializers import SoundListCreateSerializer from rest.serializers import SoundRetrieveUpdateDestroySerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication def hashfile(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.digest() class SoundList(generics.ListCreateAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundListCreateSerializer def perform_create(self, serializer): sound = self.request.FILES['sound'] codec = sound.content_type.split('/')[-1] size = sound._size duration = 0.0 # TODO sha1 = hashfile(sound.file, hashlib.sha1()).hex() sound._name = sha1 # TODO: validate calculated parameters before saving # TODO: if file already uploaded, do not save serializer.save(codec=codec, size=size, duration=duration, sha1=sha1) class SoundDetail(generics.RetrieveUpdateDestroyAPIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) queryset = Sound.objects.all() serializer_class = SoundRetrieveUpdateDestroySerializer
f9c3e4b95cb38f5aff5bad6692ac4fe469f5444d
test/spambl_test.py
test/spambl_test.py
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest class DNSBLTest(unittest.TestCase): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from spambl import DNSBL class DNSBLTest(unittest.TestCase): @classmethod def setUpClass(cls): code_item_class = {1: 'Class #1', 2: 'Class #2'} query_suffix = 'query.suffix' cls.dnsbl = DNSBL('test.dnsbl', query_suffix, code_item_class, True, True) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
Add setUpClass method to DNSBLTest
Add setUpClass method to DNSBLTest This method is used to set up a common instance of DNSBL for testing
Python
mit
piotr-rusin/spam-lists
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest class DNSBLTest(unittest.TestCase): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()Add setUpClass method to DNSBLTest This method is used to set up a common instance of DNSBL for testing
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from spambl import DNSBL class DNSBLTest(unittest.TestCase): @classmethod def setUpClass(cls): code_item_class = {1: 'Class #1', 2: 'Class #2'} query_suffix = 'query.suffix' cls.dnsbl = DNSBL('test.dnsbl', query_suffix, code_item_class, True, True) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
<commit_before>#!/usr/bin/python # -*- coding: utf-8 -*- import unittest class DNSBLTest(unittest.TestCase): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()<commit_msg>Add setUpClass method to DNSBLTest This method is used to set up a common instance of DNSBL for testing<commit_after>
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from spambl import DNSBL class DNSBLTest(unittest.TestCase): @classmethod def setUpClass(cls): code_item_class = {1: 'Class #1', 2: 'Class #2'} query_suffix = 'query.suffix' cls.dnsbl = DNSBL('test.dnsbl', query_suffix, code_item_class, True, True) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest class DNSBLTest(unittest.TestCase): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()Add setUpClass method to DNSBLTest This method is used to set up a common instance of DNSBL for testing#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from spambl import DNSBL class DNSBLTest(unittest.TestCase): @classmethod def setUpClass(cls): code_item_class = {1: 'Class #1', 2: 'Class #2'} query_suffix = 'query.suffix' cls.dnsbl = DNSBL('test.dnsbl', query_suffix, code_item_class, True, True) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
<commit_before>#!/usr/bin/python # -*- coding: utf-8 -*- import unittest class DNSBLTest(unittest.TestCase): pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()<commit_msg>Add setUpClass method to DNSBLTest This method is used to set up a common instance of DNSBL for testing<commit_after>#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from spambl import DNSBL class DNSBLTest(unittest.TestCase): @classmethod def setUpClass(cls): code_item_class = {1: 'Class #1', 2: 'Class #2'} query_suffix = 'query.suffix' cls.dnsbl = DNSBL('test.dnsbl', query_suffix, code_item_class, True, True) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
e4c5f68da949683232b520796b380e8b8f2163c7
test/tiles/bigwig_test.py
test/tiles/bigwig_test.py
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') tileset_info = hgbi.tileset_info(filename) # print('tileset_info', tileset_info)
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) tileset_info = hgbi.tileset_info(filename) assert len(tileset_info['aggregation_modes']) == 4 assert tileset_info['aggregation_modes']['mean'] assert tileset_info['aggregation_modes']['min'] assert tileset_info['aggregation_modes']['max'] assert tileset_info['aggregation_modes']['std']
Test for bigWig aggregation modes
Test for bigWig aggregation modes
Python
mit
hms-dbmi/clodius,hms-dbmi/clodius
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') tileset_info = hgbi.tileset_info(filename) # print('tileset_info', tileset_info) Test for bigWig aggregation modes
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) tileset_info = hgbi.tileset_info(filename) assert len(tileset_info['aggregation_modes']) == 4 assert tileset_info['aggregation_modes']['mean'] assert tileset_info['aggregation_modes']['min'] assert tileset_info['aggregation_modes']['max'] assert tileset_info['aggregation_modes']['std']
<commit_before>import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') tileset_info = hgbi.tileset_info(filename) # print('tileset_info', tileset_info) <commit_msg>Test for bigWig aggregation modes<commit_after>
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) tileset_info = hgbi.tileset_info(filename) assert len(tileset_info['aggregation_modes']) == 4 assert tileset_info['aggregation_modes']['mean'] assert tileset_info['aggregation_modes']['min'] assert tileset_info['aggregation_modes']['max'] assert tileset_info['aggregation_modes']['std']
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') tileset_info = hgbi.tileset_info(filename) # print('tileset_info', tileset_info) Test for bigWig aggregation modesimport clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) tileset_info = hgbi.tileset_info(filename) assert len(tileset_info['aggregation_modes']) == 4 assert tileset_info['aggregation_modes']['mean'] assert tileset_info['aggregation_modes']['min'] assert tileset_info['aggregation_modes']['max'] assert tileset_info['aggregation_modes']['std']
<commit_before>import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') tileset_info = hgbi.tileset_info(filename) # print('tileset_info', tileset_info) <commit_msg>Test for bigWig aggregation modes<commit_after>import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.max']) assert meanval[0][1]['max_value'] > minval[0][1]['max_value'] assert maxval[0][1]['max_value'] > meanval[0][1]['max_value'] def test_tileset_info(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) tileset_info = hgbi.tileset_info(filename) assert len(tileset_info['aggregation_modes']) == 4 assert tileset_info['aggregation_modes']['mean'] assert tileset_info['aggregation_modes']['min'] assert tileset_info['aggregation_modes']['max'] assert tileset_info['aggregation_modes']['std']
60db7d52b2e3138eaedd87619d49ab8f6b422367
metakernel/magics/tests/test_spell_magic.py
metakernel/magics/tests/test_spell_magic.py
from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print "ok" """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel)
from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print("ok") """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel)
Make spell test Python3 compatible
Make spell test Python3 compatible
Python
bsd-3-clause
Calysto/metakernel
from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print "ok" """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel) Make spell test Python3 compatible
from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print("ok") """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel)
<commit_before> from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print "ok" """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel) <commit_msg>Make spell test Python3 compatible<commit_after>
from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print("ok") """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel)
from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print "ok" """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel) Make spell test Python3 compatible from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print("ok") """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel)
<commit_before> from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print "ok" """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel) <commit_msg>Make spell test Python3 compatible<commit_after> from metakernel.tests.utils import (get_kernel, get_log_text, EvalKernel, clear_log_text) def test_spell_magic(): kernel = get_kernel(EvalKernel) kernel.do_execute("""%%spell testme print("ok") """, False) kernel.do_execute("%spell testme", False) text = get_log_text(kernel) assert "ok" in text, text clear_log_text(kernel) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" in text, text clear_log_text(kernel) kernel.do_execute("%spell -d testme", False) kernel.do_execute("%spell -l learned", False) text = get_log_text(kernel) assert "testme" not in text, text clear_log_text(kernel)
23de595bdf9d87dc4841138b6ae284faeda4b856
banner/forms.py
banner/forms.py
from django import forms from django.utils.translation import ugettext as _ class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), )
from django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from jmbo.admin import ModelBaseAdminForm from banner.styles import BANNER_STYLE_CLASSES class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) class BannerAdminForm(ModelBaseAdminForm): def __init__(self, *args, **kwargs): super(BannerAdminForm, self).__init__(*args, **kwargs) # Custom the style field layout choices = [] self.fields["style"].widget = forms.widgets.RadioSelect() for klass in BANNER_STYLE_CLASSES: image_path = getattr(klass, "image_path", None) image_markup = "" if image_path: image_markup = \ "<img src=\"%s%s\" style=\"max-width: 128px;\" />" \ % (settings.STATIC_URL.rstrip("/"), image_path) choices.append(( klass.__name__, mark_safe("%s%s" % (image_markup, klass.__name__)) )) self.fields["style"].widget.choices = choices
Use custom form for Banner model because style is a special case
Use custom form for Banner model because style is a special case
Python
bsd-3-clause
praekelt/jmbo-banner,praekelt/jmbo-banner
from django import forms from django.utils.translation import ugettext as _ class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) Use custom form for Banner model because style is a special case
from django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from jmbo.admin import ModelBaseAdminForm from banner.styles import BANNER_STYLE_CLASSES class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) class BannerAdminForm(ModelBaseAdminForm): def __init__(self, *args, **kwargs): super(BannerAdminForm, self).__init__(*args, **kwargs) # Custom the style field layout choices = [] self.fields["style"].widget = forms.widgets.RadioSelect() for klass in BANNER_STYLE_CLASSES: image_path = getattr(klass, "image_path", None) image_markup = "" if image_path: image_markup = \ "<img src=\"%s%s\" style=\"max-width: 128px;\" />" \ % (settings.STATIC_URL.rstrip("/"), image_path) choices.append(( klass.__name__, mark_safe("%s%s" % (image_markup, klass.__name__)) )) self.fields["style"].widget.choices = choices
<commit_before>from django import forms from django.utils.translation import ugettext as _ class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) <commit_msg>Use custom form for Banner model because style is a special case<commit_after>
from django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from jmbo.admin import ModelBaseAdminForm from banner.styles import BANNER_STYLE_CLASSES class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) class BannerAdminForm(ModelBaseAdminForm): def __init__(self, *args, **kwargs): super(BannerAdminForm, self).__init__(*args, **kwargs) # Custom the style field layout choices = [] self.fields["style"].widget = forms.widgets.RadioSelect() for klass in BANNER_STYLE_CLASSES: image_path = getattr(klass, "image_path", None) image_markup = "" if image_path: image_markup = \ "<img src=\"%s%s\" style=\"max-width: 128px;\" />" \ % (settings.STATIC_URL.rstrip("/"), image_path) choices.append(( klass.__name__, mark_safe("%s%s" % (image_markup, klass.__name__)) )) self.fields["style"].widget.choices = choices
from django import forms from django.utils.translation import ugettext as _ class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) Use custom form for Banner model because style is a special casefrom django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from jmbo.admin import ModelBaseAdminForm from banner.styles import BANNER_STYLE_CLASSES class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) class BannerAdminForm(ModelBaseAdminForm): def __init__(self, *args, **kwargs): super(BannerAdminForm, self).__init__(*args, **kwargs) # Custom the style field layout choices = [] self.fields["style"].widget = forms.widgets.RadioSelect() for klass in BANNER_STYLE_CLASSES: image_path = getattr(klass, "image_path", None) image_markup = "" if image_path: image_markup = \ "<img src=\"%s%s\" style=\"max-width: 128px;\" />" \ % (settings.STATIC_URL.rstrip("/"), image_path) choices.append(( klass.__name__, mark_safe("%s%s" % (image_markup, klass.__name__)) )) self.fields["style"].widget.choices = choices
<commit_before>from django import forms from django.utils.translation import ugettext as _ class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) <commit_msg>Use custom form for Banner model because style is a special case<commit_after>from django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from jmbo.admin import ModelBaseAdminForm from banner.styles import BANNER_STYLE_CLASSES class ImportForm(forms.Form): csv_file = forms.FileField( required=True, label=_('CSV File'), help_text=_('CSV File containing import data.') ) def __init__(self, model, *args, **kwargs): super(ImportForm, self).__init__(*args, **kwargs) self.fieldsets = ( (_('Import'), {'fields': ('csv_file', )}), ) class BannerAdminForm(ModelBaseAdminForm): def __init__(self, *args, **kwargs): super(BannerAdminForm, self).__init__(*args, **kwargs) # Custom the style field layout choices = [] self.fields["style"].widget = forms.widgets.RadioSelect() for klass in BANNER_STYLE_CLASSES: image_path = getattr(klass, "image_path", None) image_markup = "" if image_path: image_markup = \ "<img src=\"%s%s\" style=\"max-width: 128px;\" />" \ % (settings.STATIC_URL.rstrip("/"), image_path) choices.append(( klass.__name__, mark_safe("%s%s" % (image_markup, klass.__name__)) )) self.fields["style"].widget.choices = choices
204ee81fcb12e03f4a9d02b336709e6c79c6872c
rx/linq/observable/bufferwithtimeorcount.py
rx/linq/observable/bufferwithtimeorcount.py
from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable())
from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler=None): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable())
Align buffer_with_time_or_count signature with doc
Align buffer_with_time_or_count signature with doc According to docs, `buffer_with_time_or_count` has an optional scheduler parameter but in reality it's mandatory. Let's make it optional for real as passing `None` as third argument all the time is a bit inconvenient.
Python
mit
ReactiveX/RxPY,ReactiveX/RxPY
from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable()) Align buffer_with_time_or_count signature with doc According to docs, `buffer_with_time_or_count` has an optional scheduler parameter but in reality it's mandatory. Let's make it optional for real as passing `None` as third argument all the time is a bit inconvenient.
from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler=None): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable())
<commit_before>from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable()) <commit_msg>Align buffer_with_time_or_count signature with doc According to docs, `buffer_with_time_or_count` has an optional scheduler parameter but in reality it's mandatory. Let's make it optional for real as passing `None` as third argument all the time is a bit inconvenient.<commit_after>
from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler=None): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable())
from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable()) Align buffer_with_time_or_count signature with doc According to docs, `buffer_with_time_or_count` has an optional scheduler parameter but in reality it's mandatory. Let's make it optional for real as passing `None` as third argument all the time is a bit inconvenient.from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler=None): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable())
<commit_before>from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable()) <commit_msg>Align buffer_with_time_or_count signature with doc According to docs, `buffer_with_time_or_count` has an optional scheduler parameter but in reality it's mandatory. Let's make it optional for real as passing `None` as third argument all the time is a bit inconvenient.<commit_after>from rx import Observable from rx.concurrency import timeout_scheduler from rx.internal import extensionmethod @extensionmethod(Observable) def buffer_with_time_or_count(self, timespan, count, scheduler=None): """Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. # 5s or 50 items in an array 1 - res = source.buffer_with_time_or_count(5000, 50) # 5s or 50 items in an array 2 - res = source.buffer_with_time_or_count(5000, 50, Scheduler.timeout) Keyword arguments: timespan -- Maximum time length of a buffer. count -- Maximum element count of a buffer. scheduler -- [Optional] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. Returns an observable sequence of buffers. """ scheduler = scheduler or timeout_scheduler return self.window_with_time_or_count(timespan, count, scheduler) \ .flat_map(lambda x: x.to_iterable())
65bfede8d8739699e57ddd4f66049ac0374d1a8d
ydf/instructions.py
ydf/instructions.py
""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL'
""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ import collections import functools from ydf import meta __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' def get_instructions(): """ Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`. """ instructions = collections.defaultdict(dict) for func in (value for key, value in globals().items() if meta.is_instruction(value)): instructions[func.instruction_name][func.instruction_type] = func return instructions def instruction(name, type, desc): """ Decorate a function to indicate that it is responsible for converting a python type to a Docker instruction. :param name: Name of docker instruction :param type: Type of python object it can convert :param desc: Short description of expected format for the python object. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return '{} {}'.format(name, func(*args, **kwargs)) wrapper.instruction_name = name wrapper.instruction_type = type wrapper.instruction_desc = desc return wrapper return decorator
Add @instruction decorator to mark module level funcs as handlers.
Add @instruction decorator to mark module level funcs as handlers.
Python
apache-2.0
ahawker/ydf
""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' Add @instruction decorator to mark module level funcs as handlers.
""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ import collections import functools from ydf import meta __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' def get_instructions(): """ Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`. """ instructions = collections.defaultdict(dict) for func in (value for key, value in globals().items() if meta.is_instruction(value)): instructions[func.instruction_name][func.instruction_type] = func return instructions def instruction(name, type, desc): """ Decorate a function to indicate that it is responsible for converting a python type to a Docker instruction. :param name: Name of docker instruction :param type: Type of python object it can convert :param desc: Short description of expected format for the python object. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return '{} {}'.format(name, func(*args, **kwargs)) wrapper.instruction_name = name wrapper.instruction_type = type wrapper.instruction_desc = desc return wrapper return decorator
<commit_before>""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' <commit_msg>Add @instruction decorator to mark module level funcs as handlers.<commit_after>
""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ import collections import functools from ydf import meta __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' def get_instructions(): """ Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`. """ instructions = collections.defaultdict(dict) for func in (value for key, value in globals().items() if meta.is_instruction(value)): instructions[func.instruction_name][func.instruction_type] = func return instructions def instruction(name, type, desc): """ Decorate a function to indicate that it is responsible for converting a python type to a Docker instruction. :param name: Name of docker instruction :param type: Type of python object it can convert :param desc: Short description of expected format for the python object. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return '{} {}'.format(name, func(*args, **kwargs)) wrapper.instruction_name = name wrapper.instruction_type = type wrapper.instruction_desc = desc return wrapper return decorator
""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' Add @instruction decorator to mark module level funcs as handlers.""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ import collections import functools from ydf import meta __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' def get_instructions(): """ Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`. """ instructions = collections.defaultdict(dict) for func in (value for key, value in globals().items() if meta.is_instruction(value)): instructions[func.instruction_name][func.instruction_type] = func return instructions def instruction(name, type, desc): """ Decorate a function to indicate that it is responsible for converting a python type to a Docker instruction. :param name: Name of docker instruction :param type: Type of python object it can convert :param desc: Short description of expected format for the python object. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return '{} {}'.format(name, func(*args, **kwargs)) wrapper.instruction_name = name wrapper.instruction_type = type wrapper.instruction_desc = desc return wrapper return decorator
<commit_before>""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' <commit_msg>Add @instruction decorator to mark module level funcs as handlers.<commit_after>""" ydf/instructions ~~~~~~~~~~~~~~~~ Convert objects parsed from YAML to those that represent Dockerfile instructions. """ import collections import functools from ydf import meta __all__ = [] FROM = 'FROM' RUN = 'RUN' CMD = 'CMD' LABEL = 'LABEL' EXPOSE = 'EXPOSE' ENV = 'ENV' ADD = 'ADD' COPY = 'COPY' ENTRYPOINT = 'ENTRYPOINT' VOLUME = 'VOLUME' USER = 'USER' WORKDIR = 'WORKDIR' ARG = 'ARG' ONBUILD = 'ONBUILD' STOPSIGNAL = 'STOPSIGNAL' HEALTHCHECK = 'HEALTHCHECK' SHELL = 'SHELL' def get_instructions(): """ Get all functions within this module that are decorated with :func:`~ydf.instructions.instruction`. """ instructions = collections.defaultdict(dict) for func in (value for key, value in globals().items() if meta.is_instruction(value)): instructions[func.instruction_name][func.instruction_type] = func return instructions def instruction(name, type, desc): """ Decorate a function to indicate that it is responsible for converting a python type to a Docker instruction. :param name: Name of docker instruction :param type: Type of python object it can convert :param desc: Short description of expected format for the python object. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return '{} {}'.format(name, func(*args, **kwargs)) wrapper.instruction_name = name wrapper.instruction_type = type wrapper.instruction_desc = desc return wrapper return decorator
a0391649f2982f3dcb2ca251f0803095879b01fe
tests/test_leaky_state.py
tests/test_leaky_state.py
import spylon.spark.launcher as sparklauncher import os def test_set_spark_property(): c = sparklauncher.SparkConfiguration() c.driver_memory = "4g" def test_spark_driver_memory(): c = sparklauncher.SparkConfiguration() c.conf.spark.driver.memory = "5g" c._set_environment_variables() assert '--driver-memory 5g' in os.environ['PYSPARK_SUBMIT_ARGS']
Add test that exposes leaky state
Add test that exposes leaky state
Python
bsd-3-clause
MaxPoint/spylon
Add test that exposes leaky state
import spylon.spark.launcher as sparklauncher import os def test_set_spark_property(): c = sparklauncher.SparkConfiguration() c.driver_memory = "4g" def test_spark_driver_memory(): c = sparklauncher.SparkConfiguration() c.conf.spark.driver.memory = "5g" c._set_environment_variables() assert '--driver-memory 5g' in os.environ['PYSPARK_SUBMIT_ARGS']
<commit_before><commit_msg>Add test that exposes leaky state<commit_after>
import spylon.spark.launcher as sparklauncher import os def test_set_spark_property(): c = sparklauncher.SparkConfiguration() c.driver_memory = "4g" def test_spark_driver_memory(): c = sparklauncher.SparkConfiguration() c.conf.spark.driver.memory = "5g" c._set_environment_variables() assert '--driver-memory 5g' in os.environ['PYSPARK_SUBMIT_ARGS']
Add test that exposes leaky stateimport spylon.spark.launcher as sparklauncher import os def test_set_spark_property(): c = sparklauncher.SparkConfiguration() c.driver_memory = "4g" def test_spark_driver_memory(): c = sparklauncher.SparkConfiguration() c.conf.spark.driver.memory = "5g" c._set_environment_variables() assert '--driver-memory 5g' in os.environ['PYSPARK_SUBMIT_ARGS']
<commit_before><commit_msg>Add test that exposes leaky state<commit_after>import spylon.spark.launcher as sparklauncher import os def test_set_spark_property(): c = sparklauncher.SparkConfiguration() c.driver_memory = "4g" def test_spark_driver_memory(): c = sparklauncher.SparkConfiguration() c.conf.spark.driver.memory = "5g" c._set_environment_variables() assert '--driver-memory 5g' in os.environ['PYSPARK_SUBMIT_ARGS']
39bd25ffa9a90fb4dbbd63321eeee4acd84b8781
tests/test_movingfiles.py
tests/test_movingfiles.py
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """ """ conf = """ {"move_files_enable": true, "move_files_desination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) def test_dynamic_destination(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "tv/%(seriesname)s/season %(seasonnumber)d/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['tv/Scrubs/season 1/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
Add more complex move_file test
Add more complex move_file test
Python
unlicense
lahwaacz/tvnamer,m42e/tvnamer,dbr/tvnamer
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """ """ conf = """ {"move_files_enable": true, "move_files_desination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) Add more complex move_file test
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) def test_dynamic_destination(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "tv/%(seriesname)s/season %(seasonnumber)d/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['tv/Scrubs/season 1/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
<commit_before>#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """ """ conf = """ {"move_files_enable": true, "move_files_desination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) <commit_msg>Add more complex move_file test<commit_after>
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) def test_dynamic_destination(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "tv/%(seriesname)s/season %(seasonnumber)d/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['tv/Scrubs/season 1/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """ """ conf = """ {"move_files_enable": true, "move_files_desination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) Add more complex move_file test#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) def test_dynamic_destination(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "tv/%(seriesname)s/season %(seasonnumber)d/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['tv/Scrubs/season 1/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
<commit_before>#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """ """ conf = """ {"move_files_enable": true, "move_files_desination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) <commit_msg>Add more complex move_file test<commit_after>#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Tests moving renamed files """ from functional_runner import run_tvnamer, verify_out_data def test_simple_realtive_move(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "test/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['test/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files) def test_dynamic_destination(): """Move file to simple relative static dir """ conf = """ {"move_files_enable": true, "move_files_destination": "tv/%(seriesname)s/season %(seasonnumber)d/", "batch": true} """ out_data = run_tvnamer( with_files = ['scrubs.s01e01.avi'], with_config = conf, with_input = "") expected_files = ['tv/Scrubs/season 1/Scrubs - [01x01] - My First Day.avi'] verify_out_data(out_data, expected_files)
a7c78d0abb2ce3b44c8db67b12d658bed960306f
tests/types/test_arrow.py
tests/types/test_arrow.py
from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013
from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 def test_utc(self): time = arrow.arrow.utcnow() article = self.Article(created_at=time) self.session.add(article) assert article.created_at == time self.session.commit() assert article.created_at == time def test_other_tz(self): time = arrow.arrow.utcnow() local = time.to('US/Pacific') article = self.Article(created_at=local) self.session.add(article) assert article.created_at == time == local self.session.commit() assert article.created_at == time
Add tz tests for ArrowType
Add tz tests for ArrowType
Python
bsd-3-clause
joshfriend/sqlalchemy-utils,tonyseek/sqlalchemy-utils,tonyseek/sqlalchemy-utils,rmoorman/sqlalchemy-utils,marrybird/sqlalchemy-utils,cheungpat/sqlalchemy-utils,joshfriend/sqlalchemy-utils,JackWink/sqlalchemy-utils,konstantinoskostis/sqlalchemy-utils,spoqa/sqlalchemy-utils
from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 Add tz tests for ArrowType
from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 def test_utc(self): time = arrow.arrow.utcnow() article = self.Article(created_at=time) self.session.add(article) assert article.created_at == time self.session.commit() assert article.created_at == time def test_other_tz(self): time = arrow.arrow.utcnow() local = time.to('US/Pacific') article = self.Article(created_at=local) self.session.add(article) assert article.created_at == time == local self.session.commit() assert article.created_at == time
<commit_before>from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 <commit_msg>Add tz tests for ArrowType<commit_after>
from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 def test_utc(self): time = arrow.arrow.utcnow() article = self.Article(created_at=time) self.session.add(article) assert article.created_at == time self.session.commit() assert article.created_at == time def test_other_tz(self): time = arrow.arrow.utcnow() local = time.to('US/Pacific') article = self.Article(created_at=local) self.session.add(article) assert article.created_at == time == local self.session.commit() assert article.created_at == time
from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 Add tz tests for ArrowTypefrom datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 def test_utc(self): time = arrow.arrow.utcnow() article = self.Article(created_at=time) self.session.add(article) assert article.created_at == time self.session.commit() assert article.created_at == time def test_other_tz(self): time = arrow.arrow.utcnow() local = time.to('US/Pacific') article = self.Article(created_at=local) self.session.add(article) assert article.created_at == time == local self.session.commit() assert article.created_at == time
<commit_before>from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 <commit_msg>Add tz tests for ArrowType<commit_after>from datetime import datetime from pytest import mark import sqlalchemy as sa from sqlalchemy_utils.types import arrow from tests import TestCase @mark.skipif('arrow.arrow is None') class TestArrowDateTimeType(TestCase): def create_models(self): class Article(self.Base): __tablename__ = 'article' id = sa.Column(sa.Integer, primary_key=True) created_at = sa.Column(arrow.ArrowType) self.Article = Article def test_parameter_processing(self): article = self.Article( created_at=arrow.arrow.get(datetime(2000, 11, 1)) ) self.session.add(article) self.session.commit() article = self.session.query(self.Article).first() assert article.created_at.datetime def test_string_coercion(self): article = self.Article( created_at='1367900664' ) assert article.created_at.year == 2013 def test_utc(self): time = arrow.arrow.utcnow() article = self.Article(created_at=time) self.session.add(article) assert article.created_at == time self.session.commit() assert article.created_at == time def test_other_tz(self): time = arrow.arrow.utcnow() local = time.to('US/Pacific') article = self.Article(created_at=local) self.session.add(article) assert article.created_at == time == local self.session.commit() assert article.created_at == time
a29d4c9ea531552886734b3217a18c2128ddc233
byceps/util/money.py
byceps/util/money.py
""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
Use `locale.format_string` to format monetary amounts
Use `locale.format_string` to format monetary amounts Previously used `locale.format` is deprecated as of Python 3.7 and suggests to use `format_string` instead.
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES) Use `locale.format_string` to format monetary amounts Previously used `locale.format` is deprecated as of Python 3.7 and suggests to use `format_string` instead.
""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
<commit_before>""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES) <commit_msg>Use `locale.format_string` to format monetary amounts Previously used `locale.format` is deprecated as of Python 3.7 and suggests to use `format_string` instead.<commit_after>
""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES) Use `locale.format_string` to format monetary amounts Previously used `locale.format` is deprecated as of Python 3.7 and suggests to use `format_string` instead.""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
<commit_before>""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES) <commit_msg>Use `locale.format_string` to format monetary amounts Previously used `locale.format` is deprecated as of Python 3.7 and suggests to use `format_string` instead.<commit_after>""" byceps.util.money ~~~~~~~~~~~~~~~~~ Handle monetary amounts. :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
7a5083163f86833d81a41de8f0448292e2c31d75
tools/db/copy_chunk_of_nonpartitioned_sentences_to_partitions.py
tools/db/copy_chunk_of_nonpartitioned_sentences_to_partitions.py
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 100 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 10 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
Reduce story sentences chunk size
Reduce story sentences chunk size For whatever reason 100k never finishes copying a chunk.
Python
agpl-3.0
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 100 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions) Reduce story sentences chunk size For whatever reason 100k never finishes copying a chunk.
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 10 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
<commit_before>#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 100 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions) <commit_msg>Reduce story sentences chunk size For whatever reason 100k never finishes copying a chunk.<commit_after>
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 10 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 100 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions) Reduce story sentences chunk size For whatever reason 100k never finishes copying a chunk.#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 10 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
<commit_before>#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 100 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions) <commit_msg>Reduce story sentences chunk size For whatever reason 100k never finishes copying a chunk.<commit_after>#!/usr/bin/env python3 from mediawords.db import connect_to_db from mediawords.util.log import create_logger from mediawords.util.process import run_alone log = create_logger(__name__) def copy_chunk_of_nonpartitioned_sentences_to_partitions(): """Copy a chunk of sentences from "story_sentences_nonpartitioned" to "story_sentences_partitioned".""" stories_chunk_size = 10 * 1000 while True: log.info("Copying sentences of {} stories to a partitioned table...".format(stories_chunk_size)) db = connect_to_db() db.query( 'SELECT copy_chunk_of_nonpartitioned_sentences_to_partitions(%(stories_chunk_size)s)', {'stories_chunk_size': stories_chunk_size} ) db.disconnect() log.info("Copied sentences of {} stories.".format(stories_chunk_size)) if __name__ == '__main__': run_alone(copy_chunk_of_nonpartitioned_sentences_to_partitions)
eb78719ad6bd8d3d2d5f1160c9fe8d300d867ee3
isthatanearthquake/urls.py
isthatanearthquake/urls.py
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('quakes.urls')), )
Include URLs from the quake project.
Include URLs from the quake project.
Python
bsd-3-clause
adamfast/isthatanearthquake
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) Include URLs from the quake project.
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('quakes.urls')), )
<commit_before>from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Include URLs from the quake project.<commit_after>
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('quakes.urls')), )
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) Include URLs from the quake project.from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('quakes.urls')), )
<commit_before>from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Include URLs from the quake project.<commit_after>from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'isthatanearthquake.views.home', name='home'), # url(r'^isthatanearthquake/', include('isthatanearthquake.foo.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('quakes.urls')), )
b2b5b82632e1feee76ee9d4f6a9a070b350114b7
vim_turing_machine/machines/merge_business_hours/encode_hours.py
vim_turing_machine/machines/merge_business_hours/encode_hours.py
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants import BLANK_CHARACTER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return BLANK_CHARACTER + result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
Remove blank space at beginning
Remove blank space at beginning
Python
mit
ealter/vim_turing_machine,ealter/vim_turing_machine
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants import BLANK_CHARACTER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return BLANK_CHARACTER + result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin))) Remove blank space at beginning
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
<commit_before>"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants import BLANK_CHARACTER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return BLANK_CHARACTER + result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin))) <commit_msg>Remove blank space at beginning<commit_after>
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants import BLANK_CHARACTER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return BLANK_CHARACTER + result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin))) Remove blank space at beginning"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
<commit_before>"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants import BLANK_CHARACTER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return BLANK_CHARACTER + result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin))) <commit_msg>Remove blank space at beginning<commit_after>"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BITS_PER_NUMBER): result = '' for (begin, end) in hours: result += encode_in_x_bits(begin, num_bits) result += encode_in_x_bits(end, num_bits) return result def encode_in_x_bits(number, num_bits): encoded = '{:b}'.format(number) assert len(encoded) <= num_bits # Add leading zeros return '0' * (num_bits - len(encoded)) + encoded if __name__ == '__main__': print(encode_hours(json.load(sys.stdin)))
1bd287d3f6f7545e47364832a824e7380c6609e8
web/core/api/resources.py
web/core/api/resources.py
import tastypie.resources import tastypie.authentication import django.db.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.owner = django.db.models.User.objects.get(pk=bundle.request.user.id) return bundle
import tastypie.resources import tastypie.authentication import tastypie.fields import django.contrib.auth.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.author = django.contrib.auth.models.User.objects.get(pk=bundle.request.user.id) return bundle def deserialize(self, request, data, format=None): if not format: format = request.META.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(FileResource, self).deserialize(request, data, format)
Allow files to be uploaded through the TastyPie API
Allow files to be uploaded through the TastyPie API
Python
bsd-3-clause
ambientsound/rsync,ambientsound/rsync,ambientsound/rsync,ambientsound/rsync
import tastypie.resources import tastypie.authentication import django.db.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.owner = django.db.models.User.objects.get(pk=bundle.request.user.id) return bundle Allow files to be uploaded through the TastyPie API
import tastypie.resources import tastypie.authentication import tastypie.fields import django.contrib.auth.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.author = django.contrib.auth.models.User.objects.get(pk=bundle.request.user.id) return bundle def deserialize(self, request, data, format=None): if not format: format = request.META.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(FileResource, self).deserialize(request, data, format)
<commit_before>import tastypie.resources import tastypie.authentication import django.db.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.owner = django.db.models.User.objects.get(pk=bundle.request.user.id) return bundle <commit_msg>Allow files to be uploaded through the TastyPie API<commit_after>
import tastypie.resources import tastypie.authentication import tastypie.fields import django.contrib.auth.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.author = django.contrib.auth.models.User.objects.get(pk=bundle.request.user.id) return bundle def deserialize(self, request, data, format=None): if not format: format = request.META.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(FileResource, self).deserialize(request, data, format)
import tastypie.resources import tastypie.authentication import django.db.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.owner = django.db.models.User.objects.get(pk=bundle.request.user.id) return bundle Allow files to be uploaded through the TastyPie APIimport tastypie.resources import tastypie.authentication import tastypie.fields import django.contrib.auth.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.author = django.contrib.auth.models.User.objects.get(pk=bundle.request.user.id) return bundle def deserialize(self, request, data, format=None): if not format: format = request.META.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(FileResource, self).deserialize(request, data, format)
<commit_before>import tastypie.resources import tastypie.authentication import django.db.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.owner = django.db.models.User.objects.get(pk=bundle.request.user.id) return bundle <commit_msg>Allow files to be uploaded through the TastyPie API<commit_after>import tastypie.resources import tastypie.authentication import tastypie.fields import django.contrib.auth.models import web.core.models import web.core.api.authorization class FileResource(tastypie.resources.ModelResource): class Meta: queryset = web.core.models.File.objects.all() allowed_methods = ['get', 'post'] always_return_data = True authentication = tastypie.authentication.MultiAuthentication( tastypie.authentication.SessionAuthentication(), tastypie.authentication.ApiKeyAuthentication() ) authorization = web.core.api.authorization.UserObjectsOnlyAuthorization() def hydrate(self, bundle, request=None): bundle.obj.author = django.contrib.auth.models.User.objects.get(pk=bundle.request.user.id) return bundle def deserialize(self, request, data, format=None): if not format: format = request.META.get('CONTENT_TYPE', 'application/json') if format == 'application/x-www-form-urlencoded': return request.POST if format.startswith('multipart'): data = request.POST.copy() data.update(request.FILES) return data return super(FileResource, self).deserialize(request, data, format)
edc296184db9d11dc160035541af2fa7c37f7e4b
twominutejournal/errors.py
twominutejournal/errors.py
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message): super().__init__() self.message = message
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message: str): super().__init__() self.message = message
Add type annotation to EntryAlreadyExistsError
Add type annotation to EntryAlreadyExistsError
Python
mit
tjmcginnis/tmj
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message): super().__init__() self.message = message Add type annotation to EntryAlreadyExistsError
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message: str): super().__init__() self.message = message
<commit_before>"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message): super().__init__() self.message = message <commit_msg>Add type annotation to EntryAlreadyExistsError<commit_after>
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message: str): super().__init__() self.message = message
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message): super().__init__() self.message = message Add type annotation to EntryAlreadyExistsError"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message: str): super().__init__() self.message = message
<commit_before>"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message): super().__init__() self.message = message <commit_msg>Add type annotation to EntryAlreadyExistsError<commit_after>"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """ def __init__(self, message: str): super().__init__() self.message = message
f90cd0883a9a9301f359c7a238aba223756c6765
klustakwik2/numerics/cylib/compute_cluster_masks.py
klustakwik2/numerics/cylib/compute_cluster_masks.py
from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.num_special_clusters)
from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.clusters.dtype.type(kk.num_special_clusters))
Fix for some version of py64 on win64
Fix for some version of py64 on win64
Python
bsd-3-clause
benvermaercke/klustakwik2,kwikteam/klustakwik2
from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.num_special_clusters) Fix for some version of py64 on win64
from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.clusters.dtype.type(kk.num_special_clusters))
<commit_before>from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.num_special_clusters) <commit_msg>Fix for some version of py64 on win64<commit_after>
from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.clusters.dtype.type(kk.num_special_clusters))
from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.num_special_clusters) Fix for some version of py64 on win64from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.clusters.dtype.type(kk.num_special_clusters))
<commit_before>from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.num_special_clusters) <commit_msg>Fix for some version of py64 on win64<commit_after>from .compute_cluster_masks_cy import doaccum __all__ = ['accumulate_cluster_mask_sum'] def accumulate_cluster_mask_sum(kk, cluster_mask_sum): data = kk.data doaccum(kk.clusters, data.unmasked, data.unmasked_start, data.unmasked_end, data.masks, data.values_start, data.values_end, cluster_mask_sum, kk.clusters.dtype.type(kk.num_special_clusters))
cf3ff4d78a9a64c0c0e8d274ca36f68e9290b463
tests/seattle_benchmark.py
tests/seattle_benchmark.py
## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() print "Done: " + str((et - t) * 1000.0) + " -- raw JSON in: " + str((ett - tt) * 1000.0) fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() for x in range(100): run_tests(data)
## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() read_delta = (et - t) * 1000.0 print "Done: " + str(read_delta) + " -- raw JSON in: " + str((ett - tt) * 1000.0) return read_delta fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() runs = 100 deltas = [run_tests(data) for x in range(runs)] print "\nMean: "+str(sum(deltas)/runs)
Update Seattle to print the mean at the end
Update Seattle to print the mean at the end
Python
apache-2.0
cognitect/transit-python,cognitect/transit-python,dand-oss/transit-python,dand-oss/transit-python
## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() print "Done: " + str((et - t) * 1000.0) + " -- raw JSON in: " + str((ett - tt) * 1000.0) fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() for x in range(100): run_tests(data) Update Seattle to print the mean at the end
## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() read_delta = (et - t) * 1000.0 print "Done: " + str(read_delta) + " -- raw JSON in: " + str((ett - tt) * 1000.0) return read_delta fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() runs = 100 deltas = [run_tests(data) for x in range(runs)] print "\nMean: "+str(sum(deltas)/runs)
<commit_before>## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() print "Done: " + str((et - t) * 1000.0) + " -- raw JSON in: " + str((ett - tt) * 1000.0) fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() for x in range(100): run_tests(data) <commit_msg>Update Seattle to print the mean at the end<commit_after>
## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() read_delta = (et - t) * 1000.0 print "Done: " + str(read_delta) + " -- raw JSON in: " + str((ett - tt) * 1000.0) return read_delta fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() runs = 100 deltas = [run_tests(data) for x in range(runs)] print "\nMean: "+str(sum(deltas)/runs)
## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() print "Done: " + str((et - t) * 1000.0) + " -- raw JSON in: " + str((ett - tt) * 1000.0) fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() for x in range(100): run_tests(data) Update Seattle to print the mean at the end## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() read_delta = (et - t) * 1000.0 print "Done: " + str(read_delta) + " -- raw JSON in: " + str((ett - tt) * 1000.0) return read_delta fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() runs = 100 deltas = [run_tests(data) for x in range(runs)] print "\nMean: "+str(sum(deltas)/runs)
<commit_before>## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() print "Done: " + str((et - t) * 1000.0) + " -- raw JSON in: " + str((ett - tt) * 1000.0) fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() for x in range(100): run_tests(data) <commit_msg>Update Seattle to print the mean at the end<commit_after>## Copyright (c) Cognitect, Inc. ## All rights reserved. from transit.reader import JsonUnmarshaler import json import time from StringIO import StringIO def run_tests(data): datas = StringIO(data) t = time.time() JsonUnmarshaler().load(datas) et = time.time() datas = StringIO(data) tt = time.time() json.load(datas) ett = time.time() read_delta = (et - t) * 1000.0 print "Done: " + str(read_delta) + " -- raw JSON in: " + str((ett - tt) * 1000.0) return read_delta fd = open("../transit/seattle-data0.tjs", 'r') data = fd.read() fd.close() runs = 100 deltas = [run_tests(data) for x in range(runs)] print "\nMean: "+str(sum(deltas)/runs)
f5543f10208ed4eef9d0f1a0a208e03e72709f40
windpowerlib/wind_farm.py
windpowerlib/wind_farm.py
""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates, power_curve=None, power_output=None): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = power_curve self.power_output = power_output # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve
""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = None self.power_output = None # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve
Change parameters power_curve and power_output to attributes
Change parameters power_curve and power_output to attributes
Python
mit
wind-python/windpowerlib
""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates, power_curve=None, power_output=None): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = power_curve self.power_output = power_output # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve Change parameters power_curve and power_output to attributes
""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = None self.power_output = None # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve
<commit_before>""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates, power_curve=None, power_output=None): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = power_curve self.power_output = power_output # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve <commit_msg>Change parameters power_curve and power_output to attributes<commit_after>
""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = None self.power_output = None # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve
""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates, power_curve=None, power_output=None): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = power_curve self.power_output = power_output # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve Change parameters power_curve and power_output to attributes""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = None self.power_output = None # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve
<commit_before>""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates, power_curve=None, power_output=None): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = power_curve self.power_output = power_output # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve <commit_msg>Change parameters power_curve and power_output to attributes<commit_after>""" The ``wind_farm`` module contains the class WindFarm that implements a wind farm in the windpowerlib and functions needed for the modelling of a wind farm. """ __copyright__ = "Copyright oemof developer group" __license__ = "GPLv3" import numpy as np class WindFarm(object): """ def __init__(self, wind_farm_name, wind_turbine_fleet, coordinates): self.wind_farm_name = wind_farm_name self.wind_turbine_fleet = wind_turbine_fleet self.coordinates = coordinates self.power_curve = None self.power_output = None # def wind_park_p_curve(self): # p_curve = np.sum([self.wind_turbines[i].power_curve # for i in range(len(self.wind_turbines))], axis=0) # return p_curve
b2b7975d635eea81fc370f07758564a7e28d3e65
tools/bots/ddc_tests.py
tools/bots/ddc_tests.py
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # TODO(vsm): Our bots do not have node / npm installed. # These mirror pkg/dev_compiler/tool/browser_test.sh. # bot.RunProcess(['npm', 'install']) # bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
Disable npm steps on DDC bot for now
Disable npm steps on DDC bot for now This will only regression test compilation (no running of generated code), but that appears to work. R=leafp@google.com Review-Url: https://codereview.chromium.org/2646493003 .
Python
bsd-3-clause
dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'}) Disable npm steps on DDC bot for now This will only regression test compilation (no running of generated code), but that appears to work. R=leafp@google.com Review-Url: https://codereview.chromium.org/2646493003 .
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # TODO(vsm): Our bots do not have node / npm installed. # These mirror pkg/dev_compiler/tool/browser_test.sh. # bot.RunProcess(['npm', 'install']) # bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
<commit_before>#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'}) <commit_msg>Disable npm steps on DDC bot for now This will only regression test compilation (no running of generated code), but that appears to work. R=leafp@google.com Review-Url: https://codereview.chromium.org/2646493003 .<commit_after>
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # TODO(vsm): Our bots do not have node / npm installed. # These mirror pkg/dev_compiler/tool/browser_test.sh. # bot.RunProcess(['npm', 'install']) # bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'}) Disable npm steps on DDC bot for now This will only regression test compilation (no running of generated code), but that appears to work. R=leafp@google.com Review-Url: https://codereview.chromium.org/2646493003 .#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # TODO(vsm): Our bots do not have node / npm installed. # These mirror pkg/dev_compiler/tool/browser_test.sh. # bot.RunProcess(['npm', 'install']) # bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
<commit_before>#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'}) <commit_msg>Disable npm steps on DDC bot for now This will only regression test compilation (no running of generated code), but that appears to work. R=leafp@google.com Review-Url: https://codereview.chromium.org/2646493003 .<commit_after>#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. 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 import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # TODO(vsm): Our bots do not have node / npm installed. # These mirror pkg/dev_compiler/tool/browser_test.sh. # bot.RunProcess(['npm', 'install']) # bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
3b4af27a5e6a13e384852d31108449aa60f30fa2
tools/gdb/gdb_chrome.py
tools/gdb/gdb_chrome.py
#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] def lookup_function(val): typ = str(val.type) if typ == 'string16': return String16Printer(val) elif typ == 'GURL': return GURLPrinter(val) return None gdb.pretty_printers.append(lookup_function)
#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] class FilePathPrinter(object): def __init__(self, val): self.val = val def to_string(self): return self.val['path_']['_M_dataplus']['_M_p'] def lookup_function(val): type_to_printer = { 'string16': String16Printer, 'GURL': GURLPrinter, 'FilePath': FilePathPrinter, } printer = type_to_printer.get(str(val.type), None) if printer: return printer(val) return None gdb.pretty_printers.append(lookup_function)
Add FilePath to the gdb pretty printers.
Add FilePath to the gdb pretty printers. Review URL: http://codereview.chromium.org/6621017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76956 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,gavinp/chromium
#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] def lookup_function(val): typ = str(val.type) if typ == 'string16': return String16Printer(val) elif typ == 'GURL': return GURLPrinter(val) return None gdb.pretty_printers.append(lookup_function) Add FilePath to the gdb pretty printers. Review URL: http://codereview.chromium.org/6621017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76956 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] class FilePathPrinter(object): def __init__(self, val): self.val = val def to_string(self): return self.val['path_']['_M_dataplus']['_M_p'] def lookup_function(val): type_to_printer = { 'string16': String16Printer, 'GURL': GURLPrinter, 'FilePath': FilePathPrinter, } printer = type_to_printer.get(str(val.type), None) if printer: return printer(val) return None gdb.pretty_printers.append(lookup_function)
<commit_before>#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] def lookup_function(val): typ = str(val.type) if typ == 'string16': return String16Printer(val) elif typ == 'GURL': return GURLPrinter(val) return None gdb.pretty_printers.append(lookup_function) <commit_msg>Add FilePath to the gdb pretty printers. Review URL: http://codereview.chromium.org/6621017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76956 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] class FilePathPrinter(object): def __init__(self, val): self.val = val def to_string(self): return self.val['path_']['_M_dataplus']['_M_p'] def lookup_function(val): type_to_printer = { 'string16': String16Printer, 'GURL': GURLPrinter, 'FilePath': FilePathPrinter, } printer = type_to_printer.get(str(val.type), None) if printer: return printer(val) return None gdb.pretty_printers.append(lookup_function)
#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] def lookup_function(val): typ = str(val.type) if typ == 'string16': return String16Printer(val) elif typ == 'GURL': return GURLPrinter(val) return None gdb.pretty_printers.append(lookup_function) Add FilePath to the gdb pretty printers. Review URL: http://codereview.chromium.org/6621017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76956 0039d316-1c4b-4281-b951-d872f2087c98#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] class FilePathPrinter(object): def __init__(self, val): self.val = val def to_string(self): return self.val['path_']['_M_dataplus']['_M_p'] def lookup_function(val): type_to_printer = { 'string16': String16Printer, 'GURL': GURLPrinter, 'FilePath': FilePathPrinter, } printer = type_to_printer.get(str(val.type), None) if printer: return printer(val) return None gdb.pretty_printers.append(lookup_function)
<commit_before>#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] def lookup_function(val): typ = str(val.type) if typ == 'string16': return String16Printer(val) elif typ == 'GURL': return GURLPrinter(val) return None gdb.pretty_printers.append(lookup_function) <commit_msg>Add FilePath to the gdb pretty printers. Review URL: http://codereview.chromium.org/6621017 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@76956 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>#!/usr/bin/python # Copyright (c) 2011 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. """GDB support for Chrome types. Add this to your gdb by amending your ~/.gdbinit as follows: python import sys sys.path.insert(0, "/path/to/tools/gdb/") import gdb_chrome This module relies on the WebKit gdb module already existing in your Python path. """ import gdb import webkit class String16Printer(webkit.StringPrinter): def to_string(self): return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p']) class GURLPrinter(webkit.StringPrinter): def to_string(self): return self.val['spec_'] class FilePathPrinter(object): def __init__(self, val): self.val = val def to_string(self): return self.val['path_']['_M_dataplus']['_M_p'] def lookup_function(val): type_to_printer = { 'string16': String16Printer, 'GURL': GURLPrinter, 'FilePath': FilePathPrinter, } printer = type_to_printer.get(str(val.type), None) if printer: return printer(val) return None gdb.pretty_printers.append(lookup_function)
ece6799fce381c5047c510f3db0303ff62195cc6
datapipe/targets/objects.py
datapipe/targets/objects.py
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def checksum(self): digest = super(PyTarget, self).checksum() if not self._obj is None: m = hashlib.sha1() m.update(digest.encode()) m.update(joblib.hash(self._obj).encode()) return m.hexdigest() else: return digest def is_damaged(self): if not self._obj is None: return False stored = self.stored() if stored and not stored._obj is None: self._obj = stored._obj return False return True
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def is_damaged(self): stored = self.stored() if stored: if self._obj is None: self._obj = stored._obj return stored._obj is None else: return joblib.hash(self._obj) == joblib.hash(stored._obj) else: return self._obj is None
Fix up to date checks for PyTarget
Fix up to date checks for PyTarget
Python
mit
ibab/datapipe
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def checksum(self): digest = super(PyTarget, self).checksum() if not self._obj is None: m = hashlib.sha1() m.update(digest.encode()) m.update(joblib.hash(self._obj).encode()) return m.hexdigest() else: return digest def is_damaged(self): if not self._obj is None: return False stored = self.stored() if stored and not stored._obj is None: self._obj = stored._obj return False return True Fix up to date checks for PyTarget
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def is_damaged(self): stored = self.stored() if stored: if self._obj is None: self._obj = stored._obj return stored._obj is None else: return joblib.hash(self._obj) == joblib.hash(stored._obj) else: return self._obj is None
<commit_before>from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def checksum(self): digest = super(PyTarget, self).checksum() if not self._obj is None: m = hashlib.sha1() m.update(digest.encode()) m.update(joblib.hash(self._obj).encode()) return m.hexdigest() else: return digest def is_damaged(self): if not self._obj is None: return False stored = self.stored() if stored and not stored._obj is None: self._obj = stored._obj return False return True <commit_msg>Fix up to date checks for PyTarget<commit_after>
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def is_damaged(self): stored = self.stored() if stored: if self._obj is None: self._obj = stored._obj return stored._obj is None else: return joblib.hash(self._obj) == joblib.hash(stored._obj) else: return self._obj is None
from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def checksum(self): digest = super(PyTarget, self).checksum() if not self._obj is None: m = hashlib.sha1() m.update(digest.encode()) m.update(joblib.hash(self._obj).encode()) return m.hexdigest() else: return digest def is_damaged(self): if not self._obj is None: return False stored = self.stored() if stored and not stored._obj is None: self._obj = stored._obj return False return True Fix up to date checks for PyTargetfrom ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def is_damaged(self): stored = self.stored() if stored: if self._obj is None: self._obj = stored._obj return stored._obj is None else: return joblib.hash(self._obj) == joblib.hash(stored._obj) else: return self._obj is None
<commit_before>from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def checksum(self): digest = super(PyTarget, self).checksum() if not self._obj is None: m = hashlib.sha1() m.update(digest.encode()) m.update(joblib.hash(self._obj).encode()) return m.hexdigest() else: return digest def is_damaged(self): if not self._obj is None: return False stored = self.stored() if stored and not stored._obj is None: self._obj = stored._obj return False return True <commit_msg>Fix up to date checks for PyTarget<commit_after>from ..target import Target import hashlib import dill import joblib class PyTarget(Target): def __init__(self, name, obj=None): self._name = name self._obj = obj super(PyTarget, self).__init__() if not obj is None: self.set(obj) def identifier(self): return self._name def get(self): return self._obj def set(self, obj): self._obj = obj def is_damaged(self): stored = self.stored() if stored: if self._obj is None: self._obj = stored._obj return stored._obj is None else: return joblib.hash(self._obj) == joblib.hash(stored._obj) else: return self._obj is None
13c0d58f1625c11f041a23ef442c86370cd41f1c
src/ros_sdp/sdp_publisher.py
src/ros_sdp/sdp_publisher.py
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep() def main(): pub = SDPPublisher() while not rospy.is_shutdown(): pub.step() if __name__ == "__main__": main()
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep()
Remove tester code in publisher
Remove tester code in publisher
Python
mit
edran/ros_sdp
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep() def main(): pub = SDPPublisher() while not rospy.is_shutdown(): pub.step() if __name__ == "__main__": main() Remove tester code in publisher
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep()
<commit_before>import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep() def main(): pub = SDPPublisher() while not rospy.is_shutdown(): pub.step() if __name__ == "__main__": main() <commit_msg>Remove tester code in publisher<commit_after>
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep()
import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep() def main(): pub = SDPPublisher() while not rospy.is_shutdown(): pub.step() if __name__ == "__main__": main() Remove tester code in publisherimport os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep()
<commit_before>import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep() def main(): pub = SDPPublisher() while not rospy.is_shutdown(): pub.step() if __name__ == "__main__": main() <commit_msg>Remove tester code in publisher<commit_after>import os import rospy from std_msgs.msg import String # Don't do this in your code, mkay? :) fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) class SDPPublisher(object): def __init__(self): self.pub = rospy.Publisher('sdp_ros_fib', String, queue_size=10) self.counter = 1 self.r = rospy.Rate(1) # Hz def step(self): nfib = fib(self.counter) self.pub(String("Fibonacci number #%d = %d" % (self.counter, nfib))) self.counter += 1 self.r.sleep()
74fa1bf956952df4cddd7420610475725a473831
userkit/__init__.py
userkit/__init__.py
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) @classmethod def version(cls): return cls.api_version
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager from logs import LogsManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) self.logs = LogsManager(self._rq) @classmethod def version(cls): return cls.api_version
Add LogsManager to UserKit constructor
Add LogsManager to UserKit constructor
Python
mit
workpail/userkit-python
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) @classmethod def version(cls): return cls.api_version Add LogsManager to UserKit constructor
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager from logs import LogsManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) self.logs = LogsManager(self._rq) @classmethod def version(cls): return cls.api_version
<commit_before>from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) @classmethod def version(cls): return cls.api_version <commit_msg>Add LogsManager to UserKit constructor<commit_after>
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager from logs import LogsManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) self.logs = LogsManager(self._rq) @classmethod def version(cls): return cls.api_version
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) @classmethod def version(cls): return cls.api_version Add LogsManager to UserKit constructorfrom requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager from logs import LogsManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) self.logs = LogsManager(self._rq) @classmethod def version(cls): return cls.api_version
<commit_before>from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) @classmethod def version(cls): return cls.api_version <commit_msg>Add LogsManager to UserKit constructor<commit_after>from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager from logs import LogsManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) self.logs = LogsManager(self._rq) @classmethod def version(cls): return cls.api_version
a038657aab5896394ba4e0c8f6b07d2620d5061a
perimeter/management/commands/list_access_tokens.py
perimeter/management/commands/list_access_tokens.py
# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): logger.info(u"Listing all tokens:") for token in AccessToken.objects.all(): print (token)
# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): print (u"Listing all tokens:") for token in AccessToken.objects.all(): print (token)
Fix lingering logging statement in management command
Fix lingering logging statement in management command
Python
mit
yunojuno/django-perimeter,yunojuno/django-perimeter
# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): logger.info(u"Listing all tokens:") for token in AccessToken.objects.all(): print (token) Fix lingering logging statement in management command
# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): print (u"Listing all tokens:") for token in AccessToken.objects.all(): print (token)
<commit_before># -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): logger.info(u"Listing all tokens:") for token in AccessToken.objects.all(): print (token) <commit_msg>Fix lingering logging statement in management command<commit_after>
# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): print (u"Listing all tokens:") for token in AccessToken.objects.all(): print (token)
# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): logger.info(u"Listing all tokens:") for token in AccessToken.objects.all(): print (token) Fix lingering logging statement in management command# -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): print (u"Listing all tokens:") for token in AccessToken.objects.all(): print (token)
<commit_before># -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): logger.info(u"Listing all tokens:") for token in AccessToken.objects.all(): print (token) <commit_msg>Fix lingering logging statement in management command<commit_after># -*- coding: utf-8 -*- """Management command to list all active tokens.""" from django.core.management.base import BaseCommand from optparse import make_option from perimeter.models import AccessToken class Command(BaseCommand): help = "List all active tokens." def handle(self, *args, **options): print (u"Listing all tokens:") for token in AccessToken.objects.all(): print (token)
221cfd23efde8d0ccc096da57aa95ad44c3a83a0
django/generate_fixtures.py
django/generate_fixtures.py
from django.core.management.base import BaseCommand, CommandError from {{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%}
from django.core.management.base import BaseCommand, CommandError from {{{ project }}}.{{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%}
Use proper relative path in django commands file
Use proper relative path in django commands file
Python
apache-2.0
christabor/Skaffold,christabor/Skaffold
from django.core.management.base import BaseCommand, CommandError from {{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%} Use proper relative path in django commands file
from django.core.management.base import BaseCommand, CommandError from {{{ project }}}.{{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%}
<commit_before>from django.core.management.base import BaseCommand, CommandError from {{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%} <commit_msg>Use proper relative path in django commands file<commit_after>
from django.core.management.base import BaseCommand, CommandError from {{{ project }}}.{{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%}
from django.core.management.base import BaseCommand, CommandError from {{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%} Use proper relative path in django commands filefrom django.core.management.base import BaseCommand, CommandError from {{{ project }}}.{{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%}
<commit_before>from django.core.management.base import BaseCommand, CommandError from {{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%} <commit_msg>Use proper relative path in django commands file<commit_after>from django.core.management.base import BaseCommand, CommandError from {{{ project }}}.{{{ app_name }}} import model_factories MAX_RECORDS = 10 class Command(BaseCommand): help = 'Adds all fixture data.' def handle(self, *args, **options): for _ in xrange(MAX_RECORDS):{%% for model_name in all_models %%}{%% set model_name = model_name|capitalize %%} model_factories.{{{ model_name }}}Factory(){%% endfor %%}
b01a1c3b03c5d87c3fbf13d06c72849da2bab12e
web/django/emca/urls.py
web/django/emca/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), )
Remove admin interface from emca.
Remove admin interface from emca.
Python
apache-2.0
openconnectome/open-connectome,openconnectome/open-connectome,neurodata/ndstore,openconnectome/open-connectome,neurodata/ndstore,openconnectome/open-connectome,neurodata/ndstore,openconnectome/open-connectome,openconnectome/open-connectome,neurodata/ndstore
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), url(r'^admin/', include(admin.site.urls)), ) Remove admin interface from emca.
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), )
<commit_before>from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Remove admin interface from emca.<commit_after>
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), url(r'^admin/', include(admin.site.urls)), ) Remove admin interface from emca.from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), )
<commit_before>from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Remove admin interface from emca.<commit_after>from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('emca.views', # test url(r'^$', 'index'), # catmaid url(r'^catmaid/(?P<webargs>\w+/.*)$', 'catmaid'), # fetch ids (with predicates) url(r'(?P<webargs>^\w+/list/[\w,/]*)$', 'listObjects'), # batch fetch RAMON url(r'(?P<webargs>^\w+/objects/[\w,/]*)$', 'getObjects'), # get project information url(r'(?P<webargs>^\w+/projinfo/[\w,/]*)$', 'projinfo'), # get services url(r'(?P<webargs>^\w+/(xy|xz|yz|hdf5|npz|id|ids|xyanno||xzanno|yzanno)/[\w,/]+)$', 'emcaget'), # the post services url(r'(?P<webargs>^\w+/(npvoxels|npdense)/[\w,/]+)$', 'annopost'), # HDF5 interfaces url(r'(?P<webargs>^\w+/[\d+/]?[\w,/]*)$', 'annotation'), )
d3de354717fdb15d6e883f38d87eba4806fd5cc7
wafer/pages/urls.py
wafer/pages/urls.py
from django.conf.urls import patterns, url, include from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url('^index(?:\.html)?/?$', RedirectView.as_view( url=get_script_prefix(), permanent=True, query_string=True)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), )
from django.conf.urls import patterns, url, include from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), )
Drop index redirect, no longer needed
Drop index redirect, no longer needed
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
from django.conf.urls import patterns, url, include from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url('^index(?:\.html)?/?$', RedirectView.as_view( url=get_script_prefix(), permanent=True, query_string=True)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), ) Drop index redirect, no longer needed
from django.conf.urls import patterns, url, include from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), )
<commit_before>from django.conf.urls import patterns, url, include from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url('^index(?:\.html)?/?$', RedirectView.as_view( url=get_script_prefix(), permanent=True, query_string=True)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), ) <commit_msg>Drop index redirect, no longer needed<commit_after>
from django.conf.urls import patterns, url, include from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), )
from django.conf.urls import patterns, url, include from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url('^index(?:\.html)?/?$', RedirectView.as_view( url=get_script_prefix(), permanent=True, query_string=True)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), ) Drop index redirect, no longer neededfrom django.conf.urls import patterns, url, include from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), )
<commit_before>from django.conf.urls import patterns, url, include from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url('^index(?:\.html)?/?$', RedirectView.as_view( url=get_script_prefix(), permanent=True, query_string=True)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), ) <commit_msg>Drop index redirect, no longer needed<commit_after>from django.conf.urls import patterns, url, include from rest_framework import routers from wafer.pages.views import PageViewSet router = routers.DefaultRouter() router.register(r'pages', PageViewSet) urlpatterns = patterns( 'wafer.pages.views', url(r'^api/', include(router.urls)), url(r'^(?:(.+)/)?$', 'slug', name='wafer_page'), )
925864a916e5c06b58cac1caa3f2bac5907bbbd3
grader/grader/grade/__init__.py
grader/grader/grade/__init__.py
'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') #NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli)
'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') # NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli)
Fix a flake style issue
Fix a flake style issue
Python
mit
redkyn/grader,grade-it/grader,redkyn/grader
'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') #NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli) Fix a flake style issue
'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') # NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli)
<commit_before>'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') #NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli) <commit_msg>Fix a flake style issue<commit_after>
'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') # NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli)
'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') #NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli) Fix a flake style issue'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') # NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli)
<commit_before>'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') #NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli) <commit_msg>Fix a flake style issue<commit_after>'''TODO: Grade package docs ''' from grader.grade.main import grade from docker import Client help = "Grade assignments" def setup_parser(parser): parser.add_argument('folder', metavar='folder', help='Folder of tarballs or assignment folders.') parser.add_argument('--image', default='5201', help='Docker image for assignments.') # NOTE: This could be done with volumes. Is that better..? parser.add_argument('--extra', default=None, help='Extra files to copy into container (tarball).') parser.add_argument('--force', action='store_true', default=False, help='Force removal of conflicting containers ' 'even if their image doesn\'t match.') parser.set_defaults(run=run) def run(args): # Connect up with docker cli = Client(base_url='unix://var/run/docker.sock') grade(args, cli)
ea0f0f13b5d91c991e593792eee721f5fb7717b8
core/enso/plugins.py
core/enso/plugins.py
# TODO: Add documentation for this module. import logging import atexit import enso.config _plugins = [] def install( eventManager ): eventManager.registerResponder( _init, "init" ) atexit.register( _shutdown ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() _plugins.append( (module, moduleName) ) except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName ) def _shutdown(): for module, moduleName in _plugins: try: module.unload() except: logging.warn( "Error while unloading plugin '%s'." % moduleName ) raise logging.info( "Unloaded plugin '%s'." % moduleName ) _plugins[:] = []
# TODO: Add documentation for this module. import logging import enso.config def install( eventManager ): eventManager.registerResponder( _init, "init" ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName )
Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler.
Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler. git-svn-id: b6fd099cd3d97ba56ca68c4d1ea7aaa6a131ba03@17 8b7adc99-b347-0410-ae0a-d9e86c8d69b5
Python
bsd-3-clause
roderyc/enso,roderyc/enso,roderyc/enso
# TODO: Add documentation for this module. import logging import atexit import enso.config _plugins = [] def install( eventManager ): eventManager.registerResponder( _init, "init" ) atexit.register( _shutdown ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() _plugins.append( (module, moduleName) ) except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName ) def _shutdown(): for module, moduleName in _plugins: try: module.unload() except: logging.warn( "Error while unloading plugin '%s'." % moduleName ) raise logging.info( "Unloaded plugin '%s'." % moduleName ) _plugins[:] = [] Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler. git-svn-id: b6fd099cd3d97ba56ca68c4d1ea7aaa6a131ba03@17 8b7adc99-b347-0410-ae0a-d9e86c8d69b5
# TODO: Add documentation for this module. import logging import enso.config def install( eventManager ): eventManager.registerResponder( _init, "init" ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName )
<commit_before># TODO: Add documentation for this module. import logging import atexit import enso.config _plugins = [] def install( eventManager ): eventManager.registerResponder( _init, "init" ) atexit.register( _shutdown ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() _plugins.append( (module, moduleName) ) except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName ) def _shutdown(): for module, moduleName in _plugins: try: module.unload() except: logging.warn( "Error while unloading plugin '%s'." % moduleName ) raise logging.info( "Unloaded plugin '%s'." % moduleName ) _plugins[:] = [] <commit_msg>Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler. git-svn-id: b6fd099cd3d97ba56ca68c4d1ea7aaa6a131ba03@17 8b7adc99-b347-0410-ae0a-d9e86c8d69b5<commit_after>
# TODO: Add documentation for this module. import logging import enso.config def install( eventManager ): eventManager.registerResponder( _init, "init" ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName )
# TODO: Add documentation for this module. import logging import atexit import enso.config _plugins = [] def install( eventManager ): eventManager.registerResponder( _init, "init" ) atexit.register( _shutdown ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() _plugins.append( (module, moduleName) ) except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName ) def _shutdown(): for module, moduleName in _plugins: try: module.unload() except: logging.warn( "Error while unloading plugin '%s'." % moduleName ) raise logging.info( "Unloaded plugin '%s'." % moduleName ) _plugins[:] = [] Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler. git-svn-id: b6fd099cd3d97ba56ca68c4d1ea7aaa6a131ba03@17 8b7adc99-b347-0410-ae0a-d9e86c8d69b5# TODO: Add documentation for this module. import logging import enso.config def install( eventManager ): eventManager.registerResponder( _init, "init" ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName )
<commit_before># TODO: Add documentation for this module. import logging import atexit import enso.config _plugins = [] def install( eventManager ): eventManager.registerResponder( _init, "init" ) atexit.register( _shutdown ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() _plugins.append( (module, moduleName) ) except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName ) def _shutdown(): for module, moduleName in _plugins: try: module.unload() except: logging.warn( "Error while unloading plugin '%s'." % moduleName ) raise logging.info( "Unloaded plugin '%s'." % moduleName ) _plugins[:] = [] <commit_msg>Change to plugin interface: unload() is no longer part of the protocol, and any unloading a plugin needs to do can just be done by registering an atexit handler. git-svn-id: b6fd099cd3d97ba56ca68c4d1ea7aaa6a131ba03@17 8b7adc99-b347-0410-ae0a-d9e86c8d69b5<commit_after># TODO: Add documentation for this module. import logging import enso.config def install( eventManager ): eventManager.registerResponder( _init, "init" ) def _init(): for moduleName in enso.config.PLUGINS: try: # Import the module; most of this code was taken from the # Python Library Reference documentation for __import__(). module = __import__( moduleName, {}, {}, [], 0 ) components = moduleName.split( "." ) for component in components[1:]: module = getattr( module, component ) module.load() except: logging.warn( "Error while loading plugin '%s'." % moduleName ) raise logging.info( "Loaded plugin '%s'." % moduleName )
013154d359570d591f9315b10c738616d9cddb49
loqusdb/build_models/profile_variant.py
loqusdb/build_models/profile_variant.py
import logging import json from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ if ID CAF exists in INFO column, return the allele frequency for the alt allele. The CAF INFO tag from dbSNP is a Comma delimited list of allele frequencies based on 1000Genomes. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ if not variant.INFO.get('CAF'): return None maf_list = json.loads(variant.INFO.get('CAF')) return maf_list[1] def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant
import logging from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get('MAF') def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant
Change from CAF to MAF tag when looking for MAF in vcf file
Change from CAF to MAF tag when looking for MAF in vcf file
Python
mit
moonso/loqusdb
import logging import json from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ if ID CAF exists in INFO column, return the allele frequency for the alt allele. The CAF INFO tag from dbSNP is a Comma delimited list of allele frequencies based on 1000Genomes. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ if not variant.INFO.get('CAF'): return None maf_list = json.loads(variant.INFO.get('CAF')) return maf_list[1] def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant Change from CAF to MAF tag when looking for MAF in vcf file
import logging from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get('MAF') def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant
<commit_before>import logging import json from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ if ID CAF exists in INFO column, return the allele frequency for the alt allele. The CAF INFO tag from dbSNP is a Comma delimited list of allele frequencies based on 1000Genomes. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ if not variant.INFO.get('CAF'): return None maf_list = json.loads(variant.INFO.get('CAF')) return maf_list[1] def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant <commit_msg>Change from CAF to MAF tag when looking for MAF in vcf file<commit_after>
import logging from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get('MAF') def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant
import logging import json from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ if ID CAF exists in INFO column, return the allele frequency for the alt allele. The CAF INFO tag from dbSNP is a Comma delimited list of allele frequencies based on 1000Genomes. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ if not variant.INFO.get('CAF'): return None maf_list = json.loads(variant.INFO.get('CAF')) return maf_list[1] def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant Change from CAF to MAF tag when looking for MAF in vcf fileimport logging from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get('MAF') def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant
<commit_before>import logging import json from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ if ID CAF exists in INFO column, return the allele frequency for the alt allele. The CAF INFO tag from dbSNP is a Comma delimited list of allele frequencies based on 1000Genomes. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ if not variant.INFO.get('CAF'): return None maf_list = json.loads(variant.INFO.get('CAF')) return maf_list[1] def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant <commit_msg>Change from CAF to MAF tag when looking for MAF in vcf file<commit_after>import logging from loqusdb.models import ProfileVariant from .variant import get_variant_id LOG = logging.getLogger(__name__) def get_maf(variant): """ Gets the MAF (minor allele frequency) tag from the info field for the variant. Args: variant (cyvcf2.Variant) Returns: maf (float): Minor allele frequency """ return variant.INFO.get('MAF') def build_profile_variant(variant): """Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant) """ chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column = variant.ID ) return profile_variant
0ab4a593781dea4bf7c2f631a88f906f4aa7e329
swift/obj/dedupe/fp_index.py
swift/obj/dedupe/fp_index.py
__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main()
__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() ''' def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() '''
Use database to detect the duplication. But the md5 value does not match. Need to add some code here
Use database to detect the duplication. But the md5 value does not match. Need to add some code here
Python
apache-2.0
mjwtom/swift,mjwtom/swift
__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() Use database to detect the duplication. But the md5 value does not match. Need to add some code here
__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() ''' def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() '''
<commit_before>__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() <commit_msg>Use database to detect the duplication. But the md5 value does not match. Need to add some code here<commit_after>
__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() ''' def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() '''
__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() Use database to detect the duplication. But the md5 value does not match. Need to add some code here__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() ''' def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() '''
<commit_before>__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() <commit_msg>Use database to detect the duplication. But the md5 value does not match. Need to add some code here<commit_after>__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''') def insert(self, key, value): data = (key, value) self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data) self.conn.commit() def lookup(self, key): data = (key,) self.c.execute('SELECT value FROM fp_index WHERE key=?', data) return self.c.fetchone() ''' def testinsert(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() fp.insert(str, str) def testselect(): fp = fp_index('/home/mjwtom/mydb.db') for i in range(0, 100): str = i.__str__() c = fp.lookup(str) for row in c: print row if __name__ == '__main__': unittest.main() '''
e951dde14f65e188118c2eb9e8825d317ada488a
yunity/groups/models.py
yunity/groups/models.py
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL)
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
Add related name for group member
Add related name for group member
Python
agpl-3.0
yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL) Add related name for group member
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
<commit_before>from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL) <commit_msg>Add related name for group member<commit_after>
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL) Add related name for group memberfrom django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
<commit_before>from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL) <commit_msg>Add related name for group member<commit_after>from django.db.models import TextField, ManyToManyField from yunity.base.base_models import BaseModel, LocationModel from config import settings class Group(BaseModel, LocationModel): name = TextField() description = TextField(null=True) members = ManyToManyField(settings.AUTH_USER_MODEL, related_name='groups')
f33bd2f80076c192796da5015228d44dce638fee
users/migrations/0002_initial_admin_user.py
users/migrations/0002_initial_admin_user.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex@smith.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex.smith@example.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ]
Change default admin email to alex.smith@example.com
Change default admin email to alex.smith@example.com
Python
mit
magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex@smith.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ] Change default admin email to alex.smith@example.com
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex.smith@example.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex@smith.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ] <commit_msg>Change default admin email to alex.smith@example.com<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex.smith@example.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex@smith.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ] Change default admin email to alex.smith@example.com# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex.smith@example.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex@smith.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ] <commit_msg>Change default admin email to alex.smith@example.com<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password def create_users(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. User = apps.get_model('users', 'User') User.objects.create( date_joined='2012-10-09T21:42:23Z', email='alex.smith@example.com', first_name='Alex', is_active=True, is_staff=True, is_superuser=True, last_name='Smith', password=make_password('codigofuente'), ) class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.RunPython(create_users), ]
b3525570929ba47c10d9d08696876c39487f7000
test/mitmproxy/contentviews/test_xml_html.py
test/mitmproxy/contentviews/test_xml_html.py
import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open(path.replace(".", "-formatted.")) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected
import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open("-formatted.".join(path.rsplit(".", 1))) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected
Fix test_format_xml with dot in path
Fix test_format_xml with dot in path When the path contains dot ".", replacing all dots will generate a non-exist result and raises a FileNotFoundError. Replacing only the last dot fixes this.
Python
mit
ujjwal96/mitmproxy,MatthewShao/mitmproxy,cortesi/mitmproxy,ddworken/mitmproxy,vhaupert/mitmproxy,cortesi/mitmproxy,mitmproxy/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,mhils/mitmproxy,xaxa89/mitmproxy,zlorb/mitmproxy,mitmproxy/mitmproxy,ujjwal96/mitmproxy,zlorb/mitmproxy,cortesi/mitmproxy,mhils/mitmproxy,mitmproxy/mitmproxy,ddworken/mitmproxy,MatthewShao/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mitmproxy,MatthewShao/mitmproxy,ddworken/mitmproxy,vhaupert/mitmproxy,mhils/mitmproxy,vhaupert/mitmproxy,zlorb/mitmproxy,xaxa89/mitmproxy,vhaupert/mitmproxy,xaxa89/mitmproxy,cortesi/mitmproxy,zlorb/mitmproxy,mitmproxy/mitmproxy,Kriechi/mitmproxy,mhils/mitmproxy,mitmproxy/mitmproxy,xaxa89/mitmproxy,MatthewShao/mitmproxy,ujjwal96/mitmproxy,StevenVanAcker/mitmproxy,StevenVanAcker/mitmproxy,ujjwal96/mitmproxy,ddworken/mitmproxy,Kriechi/mitmproxy,StevenVanAcker/mitmproxy
import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open(path.replace(".", "-formatted.")) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected Fix test_format_xml with dot in path When the path contains dot ".", replacing all dots will generate a non-exist result and raises a FileNotFoundError. Replacing only the last dot fixes this.
import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open("-formatted.".join(path.rsplit(".", 1))) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected
<commit_before>import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open(path.replace(".", "-formatted.")) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected <commit_msg>Fix test_format_xml with dot in path When the path contains dot ".", replacing all dots will generate a non-exist result and raises a FileNotFoundError. Replacing only the last dot fixes this.<commit_after>
import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open("-formatted.".join(path.rsplit(".", 1))) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected
import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open(path.replace(".", "-formatted.")) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected Fix test_format_xml with dot in path When the path contains dot ".", replacing all dots will generate a non-exist result and raises a FileNotFoundError. Replacing only the last dot fixes this.import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open("-formatted.".join(path.rsplit(".", 1))) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected
<commit_before>import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open(path.replace(".", "-formatted.")) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected <commit_msg>Fix test_format_xml with dot in path When the path contains dot ".", replacing all dots will generate a non-exist result and raises a FileNotFoundError. Replacing only the last dot fixes this.<commit_after>import pytest from mitmproxy.contentviews import xml_html from mitmproxy.test import tutils from . import full_eval data = tutils.test_data.push("mitmproxy/contentviews/test_xml_html_data/") def test_simple(): v = full_eval(xml_html.ViewXmlHtml()) assert v(b"foo") == ('XML', [[('text', 'foo')]]) assert v(b"<html></html>") == ('HTML', [[('text', '<html></html>')]]) @pytest.mark.parametrize("filename", [ "simple.html", "cdata.xml", "comment.xml", "inline.html", ]) def test_format_xml(filename): path = data.path(filename) with open(path) as f: input = f.read() with open("-formatted.".join(path.rsplit(".", 1))) as f: expected = f.read() tokens = xml_html.tokenize(input) assert xml_html.format_xml(tokens) == expected
a12c61d5e86f10d0f0b310c9204d56d2defd8f8d
src/monitors/checks/http-get-statuscode/__init__.py
src/monitors/checks/http-get-statuscode/__init__.py
#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except: return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: return True else: return False
#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] logger = kwargs['logger'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except Exception as e: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'had an exception: {2}'.format(url, jdata['cid'], e) logger.error(line) return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Successful'.format(url, jdata['cid']) logger.info(line) return True else: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Failure'.format(url, jdata['cid']) logger.info(line) return False
Add logging to http-get-statuscode monitor for docs example
Add logging to http-get-statuscode monitor for docs example
Python
unknown
codecakes/cloudroutes-service,dethos/cloudroutes-service,rbramwell/runbook,rbramwell/runbook,dethos/cloudroutes-service,rbramwell/runbook,madflojo/cloudroutes-service,Runbook/runbook,asm-products/cloudroutes-service,codecakes/cloudroutes-service,madflojo/cloudroutes-service,Runbook/runbook,madflojo/cloudroutes-service,Runbook/runbook,dethos/cloudroutes-service,madflojo/cloudroutes-service,rbramwell/runbook,asm-products/cloudroutes-service,asm-products/cloudroutes-service,asm-products/cloudroutes-service,codecakes/cloudroutes-service,dethos/cloudroutes-service,Runbook/runbook,codecakes/cloudroutes-service
#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except: return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: return True else: return False Add logging to http-get-statuscode monitor for docs example
#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] logger = kwargs['logger'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except Exception as e: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'had an exception: {2}'.format(url, jdata['cid'], e) logger.error(line) return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Successful'.format(url, jdata['cid']) logger.info(line) return True else: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Failure'.format(url, jdata['cid']) logger.info(line) return False
<commit_before>#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except: return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: return True else: return False <commit_msg>Add logging to http-get-statuscode monitor for docs example<commit_after>
#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] logger = kwargs['logger'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except Exception as e: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'had an exception: {2}'.format(url, jdata['cid'], e) logger.error(line) return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Successful'.format(url, jdata['cid']) logger.info(line) return True else: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Failure'.format(url, jdata['cid']) logger.info(line) return False
#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except: return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: return True else: return False Add logging to http-get-statuscode monitor for docs example#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] logger = kwargs['logger'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except Exception as e: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'had an exception: {2}'.format(url, jdata['cid'], e) logger.error(line) return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Successful'.format(url, jdata['cid']) logger.info(line) return True else: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Failure'.format(url, jdata['cid']) logger.info(line) return False
<commit_before>#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except: return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: return True else: return False <commit_msg>Add logging to http-get-statuscode monitor for docs example<commit_after>#!/usr/bin/python ###################################################################### # Cloud Routes Availability Manager: http-get-statuscode module # ------------------------------------------------------------------ # This is a moduel for performing http get based health checks. # This will return true if no errors or false if there are errors # ------------------------------------------------------------------ # Version: Alpha.20140618 # Original Author: Benjamin J. Cane - madflojo@cloudrout.es # Contributors: # - your name here ###################################################################### import requests def check(**kwargs): """ Perform a http get request and validate the return code """ jdata = kwargs['jdata'] logger = kwargs['logger'] headers = {'host': jdata['data']['host']} timeout = 3.00 url = jdata['data']['url'] try: result = requests.get( url, timeout=timeout, headers=headers, verify=False) except Exception as e: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'had an exception: {2}'.format(url, jdata['cid'], e) logger.error(line) return False rcode = str(result.status_code) if rcode in jdata['data']['codes']: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Successful'.format(url, jdata['cid']) logger.info(line) return True else: line = 'http-get-statuscode: Reqeust to {0} sent for monitor {1} - ' \ 'Failure'.format(url, jdata['cid']) logger.info(line) return False
c73d24259a6aa198d749fba097999ba2c18bd6da
website/addons/figshare/settings/defaults.py
website/addons/figshare/settings/defaults.py
API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings.
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]
Python
apache-2.0
mattclark/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,jnayak1/osf.io,SSJohns/osf.io,revanthkolli/osf.io,kch8qx/osf.io,amyshi188/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,revanthkolli/osf.io,jinluyuan/osf.io,cldershem/osf.io,KAsante95/osf.io,lamdnhan/osf.io,caseyrygt/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,caneruguz/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,zachjanicki/osf.io,emetsger/osf.io,ckc6cz/osf.io,kwierman/osf.io,GageGaskins/osf.io,KAsante95/osf.io,DanielSBrown/osf.io,adlius/osf.io,hmoco/osf.io,erinspace/osf.io,bdyetton/prettychart,ticklemepierce/osf.io,baylee-d/osf.io,mluke93/osf.io,ckc6cz/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,crcresearch/osf.io,haoyuchen1992/osf.io,lamdnhan/osf.io,SSJohns/osf.io,reinaH/osf.io,himanshuo/osf.io,petermalcolm/osf.io,ZobairAlijan/osf.io,dplorimer/osf,Ghalko/osf.io,mluke93/osf.io,GaryKriebel/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,leb2dg/osf.io,acshi/osf.io,chrisseto/osf.io,alexschiller/osf.io,mluo613/osf.io,mluo613/osf.io,arpitar/osf.io,amyshi188/osf.io,caseyrygt/osf.io,lamdnhan/osf.io,Ghalko/osf.io,barbour-em/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,Nesiehr/osf.io,rdhyee/osf.io,petermalcolm/osf.io,cosenal/osf.io,crcresearch/osf.io,felliott/osf.io,zkraime/osf.io,ticklemepierce/osf.io,barbour-em/osf.io,zkraime/osf.io,mluke93/osf.io,emetsger/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,Nesiehr/osf.io,reinaH/osf.io,aaxelb/osf.io,danielneis/osf.io,mluke93/osf.io,bdyetton/prettychart,emetsger/osf.io,fabianvf/osf.io,amyshi188/osf.io,dplorimer/osf,acshi/osf.io,KAsante95/osf.io,bdyetton/prettychart,brandonPurvis/osf.io,danielneis/osf.io,asanfilippo7/osf.io,jolene-esposito/osf.io,felliott/osf.io,baylee-d/osf.io,billyhunt/osf.io,Nesiehr/osf.io,mluo613/osf.io,sloria/osf.io,RomanZWang/osf.io,icereval/osf.io,doublebits/osf.io,SSJohns/osf.io,kwierman/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,chrisseto/osf.io,himanshuo/osf.io,arpitar/osf.io,jnayak1/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,jinluyuan/osf.io,Johnetordoff/osf.io,jeffreyliu3230/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,petermalcolm/osf.io,acshi/osf.io,dplorimer/osf,erinspace/osf.io,jolene-esposito/osf.io,billyhunt/osf.io,bdyetton/prettychart,zkraime/osf.io,saradbowman/osf.io,abought/osf.io,abought/osf.io,zamattiac/osf.io,GageGaskins/osf.io,kushG/osf.io,sbt9uc/osf.io,reinaH/osf.io,ckc6cz/osf.io,adlius/osf.io,icereval/osf.io,lyndsysimon/osf.io,caseyrygt/osf.io,cosenal/osf.io,billyhunt/osf.io,sloria/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,jeffreyliu3230/osf.io,kch8qx/osf.io,pattisdr/osf.io,wearpants/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,caneruguz/osf.io,wearpants/osf.io,MerlinZhang/osf.io,himanshuo/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,doublebits/osf.io,doublebits/osf.io,samanehsan/osf.io,mluo613/osf.io,jmcarp/osf.io,zamattiac/osf.io,hmoco/osf.io,samchrisinger/osf.io,chennan47/osf.io,sbt9uc/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,lamdnhan/osf.io,jolene-esposito/osf.io,hmoco/osf.io,revanthkolli/osf.io,himanshuo/osf.io,ticklemepierce/osf.io,HalcyonChimera/osf.io,TomHeatwole/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,lyndsysimon/osf.io,arpitar/osf.io,samanehsan/osf.io,abought/osf.io,jinluyuan/osf.io,binoculars/osf.io,reinaH/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,jmcarp/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,kushG/osf.io,caneruguz/osf.io,laurenrevere/osf.io,cldershem/osf.io,mattclark/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,samanehsan/osf.io,rdhyee/osf.io,cldershem/osf.io,mfraezz/osf.io,aaxelb/osf.io,mfraezz/osf.io,saradbowman/osf.io,emetsger/osf.io,acshi/osf.io,caseyrygt/osf.io,kushG/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,HarryRybacki/osf.io,Nesiehr/osf.io,leb2dg/osf.io,billyhunt/osf.io,baylee-d/osf.io,Ghalko/osf.io,RomanZWang/osf.io,sbt9uc/osf.io,leb2dg/osf.io,mattclark/osf.io,chennan47/osf.io,jmcarp/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,jnayak1/osf.io,zamattiac/osf.io,amyshi188/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,sloria/osf.io,lyndsysimon/osf.io,hmoco/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,KAsante95/osf.io,sbt9uc/osf.io,dplorimer/osf,lyndsysimon/osf.io,arpitar/osf.io,mfraezz/osf.io,kch8qx/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,binoculars/osf.io,ckc6cz/osf.io,njantrania/osf.io,fabianvf/osf.io,pattisdr/osf.io,caseyrollins/osf.io,kushG/osf.io,zachjanicki/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,chrisseto/osf.io,mfraezz/osf.io,jinluyuan/osf.io,jeffreyliu3230/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,doublebits/osf.io,crcresearch/osf.io,rdhyee/osf.io,GaryKriebel/osf.io,binoculars/osf.io,felliott/osf.io,GaryKriebel/osf.io,HarryRybacki/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,jeffreyliu3230/osf.io,kwierman/osf.io,asanfilippo7/osf.io,abought/osf.io,MerlinZhang/osf.io,samanehsan/osf.io,wearpants/osf.io,acshi/osf.io,fabianvf/osf.io,alexschiller/osf.io,cslzchen/osf.io,MerlinZhang/osf.io,kwierman/osf.io,wearpants/osf.io,adlius/osf.io,revanthkolli/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,mluo613/osf.io,caneruguz/osf.io,felliott/osf.io,caseyrollins/osf.io,zamattiac/osf.io,zkraime/osf.io,kch8qx/osf.io,doublebits/osf.io,jmcarp/osf.io,Ghalko/osf.io,barbour-em/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,cosenal/osf.io,cosenal/osf.io,TomHeatwole/osf.io,njantrania/osf.io,adlius/osf.io,GageGaskins/osf.io,njantrania/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,icereval/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,danielneis/osf.io,KAsante95/osf.io,njantrania/osf.io,jolene-esposito/osf.io,ZobairAlijan/osf.io
API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000 Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]
CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
<commit_before>API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000 <commit_msg>Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]<commit_after>
CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000 Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
<commit_before>API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000 <commit_msg>Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]<commit_after>CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
24c5cd9916b7fe81d3a57fc612132a070367756f
challenges/c7.py
challenges/c7.py
from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac455' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html')
from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac4556' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html')
Fix incorrect hash in URL
Fix incorrect hash in URL
Python
mit
GunshipPenguin/billionaire_challenge,GunshipPenguin/billionaire_challenge
from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac455' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html') Fix incorrect hash in URL
from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac4556' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html')
<commit_before>from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac455' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html') <commit_msg>Fix incorrect hash in URL<commit_after>
from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac4556' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html')
from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac455' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html') Fix incorrect hash in URLfrom challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac4556' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html')
<commit_before>from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac455' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html') <commit_msg>Fix incorrect hash in URL<commit_after>from challenge import Challenge import flask class c7(Challenge): ''' Challenge 7 Satoshi Base58 Encoding ''' def __init__(self): super() self._id = '3aed4348ed11e6adf1b54885b297078070ac4556' self._hints = {1: 'Base58 Encoding'} def get_response(self, app): return app.send_static_file('c7/index.html')
e81e25f1d97ef4f141e392bda736aaa6a37aadf5
chatbot/botui.py
chatbot/botui.py
import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor def bot_ui(): data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt') td = TokenizedData(seq_length=10, data_file=data_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui()
import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def bot_ui(): dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle') td = TokenizedData(seq_length=10, dict_file=dict_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') print("Welcome to Chat with ChatLearner!") print("Type exit and press enter to end the conversation.") # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: if sentence.strip() == 'exit': print("Thank you for using ChatLearner. Bye.") break dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui()
Optimize the UI and allow the user to exit the program smoothly.
Optimize the UI and allow the user to exit the program smoothly.
Python
apache-2.0
bshao001/ChatLearner,bshao001/ChatLearner,bshao001/ChatLearner,bshao001/ChatLearner
import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor def bot_ui(): data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt') td = TokenizedData(seq_length=10, data_file=data_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui() Optimize the UI and allow the user to exit the program smoothly.
import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def bot_ui(): dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle') td = TokenizedData(seq_length=10, dict_file=dict_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') print("Welcome to Chat with ChatLearner!") print("Type exit and press enter to end the conversation.") # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: if sentence.strip() == 'exit': print("Thank you for using ChatLearner. Bye.") break dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui()
<commit_before>import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor def bot_ui(): data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt') td = TokenizedData(seq_length=10, data_file=data_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui() <commit_msg>Optimize the UI and allow the user to exit the program smoothly.<commit_after>
import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def bot_ui(): dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle') td = TokenizedData(seq_length=10, dict_file=dict_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') print("Welcome to Chat with ChatLearner!") print("Type exit and press enter to end the conversation.") # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: if sentence.strip() == 'exit': print("Thank you for using ChatLearner. Bye.") break dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui()
import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor def bot_ui(): data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt') td = TokenizedData(seq_length=10, data_file=data_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui() Optimize the UI and allow the user to exit the program smoothly.import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def bot_ui(): dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle') td = TokenizedData(seq_length=10, dict_file=dict_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') print("Welcome to Chat with ChatLearner!") print("Type exit and press enter to end the conversation.") # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: if sentence.strip() == 'exit': print("Thank you for using ChatLearner. Bye.") break dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui()
<commit_before>import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor def bot_ui(): data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt') td = TokenizedData(seq_length=10, data_file=data_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui() <commit_msg>Optimize the UI and allow the user to exit the program smoothly.<commit_after>import numpy as np import os import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.tokenizeddata import TokenizedData from chatbot.botpredictor import BotPredictor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def bot_ui(): dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle') td = TokenizedData(seq_length=10, dict_file=dict_file) res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: predictor = BotPredictor(sess, td, res_dir, 'basic') print("Welcome to Chat with ChatLearner!") print("Type exit and press enter to end the conversation.") # Waiting from standard input. sys.stdout.write("> ") sys.stdout.flush() sentence = sys.stdin.readline() while sentence: if sentence.strip() == 'exit': print("Thank you for using ChatLearner. Bye.") break dec_outputs = predictor.predict(sentence) word_ids = [] for out in dec_outputs: word_ids.append(np.argmax(out)) print(td.word_ids_to_str(word_ids)) print("> ", end="") sys.stdout.flush() sentence = sys.stdin.readline() if __name__ == "__main__": bot_ui()
66a68261fcc67abe7f87885edb5ff5b5ead68a45
diylang/evaluator.py
diylang/evaluator.py
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY")
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, \ is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY")
Break line in long line of imports.
Break line in long line of imports.
Python
bsd-3-clause
kvalle/diy-lang,kvalle/diy-lisp,kvalle/diy-lang,kvalle/diy-lisp,codecop/diy-lang,codecop/diy-lang
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY") Break line in long line of imports.
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, \ is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY")
<commit_before># -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY") <commit_msg>Break line in long line of imports.<commit_after>
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, \ is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY")
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY") Break line in long line of imports.# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, \ is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY")
<commit_before># -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY") <commit_msg>Break line in long line of imports.<commit_after># -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, \ is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for most of parts 2 through 6. A score of useful functions is provided for you, as per the above imports, making your work a bit easier. (We're supposed to get through this thing in a day, after all.) """ def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" raise NotImplementedError("DIY")
d7bd0ff21a32806459dcb45cea9c1d1faacc0f51
scraper/fedtext/spiders/tutorial_spider.py
scraper/fedtext/spiders/tutorial_spider.py
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): soup = BeautifulSoup(response.body_as_unicode(), 'html.parser') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] print(visible_texts)
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment from fedtext.items import FedTextItem class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): """ Callback method for parsing the response. Yields a FedTextItem. """ soup = BeautifulSoup(response.body_as_unicode(), 'lxml') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] item = FedTextItem() item['text_list'] = visible_texts yield item
Use a faster parser for bs4
Use a faster parser for bs4
Python
cc0-1.0
khandelwal/fedtext
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): soup = BeautifulSoup(response.body_as_unicode(), 'html.parser') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] print(visible_texts) Use a faster parser for bs4
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment from fedtext.items import FedTextItem class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): """ Callback method for parsing the response. Yields a FedTextItem. """ soup = BeautifulSoup(response.body_as_unicode(), 'lxml') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] item = FedTextItem() item['text_list'] = visible_texts yield item
<commit_before>import scrapy from bs4 import BeautifulSoup from bs4.element import Comment class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): soup = BeautifulSoup(response.body_as_unicode(), 'html.parser') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] print(visible_texts) <commit_msg>Use a faster parser for bs4<commit_after>
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment from fedtext.items import FedTextItem class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): """ Callback method for parsing the response. Yields a FedTextItem. """ soup = BeautifulSoup(response.body_as_unicode(), 'lxml') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] item = FedTextItem() item['text_list'] = visible_texts yield item
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): soup = BeautifulSoup(response.body_as_unicode(), 'html.parser') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] print(visible_texts) Use a faster parser for bs4import scrapy from bs4 import BeautifulSoup from bs4.element import Comment from fedtext.items import FedTextItem class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): """ Callback method for parsing the response. Yields a FedTextItem. """ soup = BeautifulSoup(response.body_as_unicode(), 'lxml') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] item = FedTextItem() item['text_list'] = visible_texts yield item
<commit_before>import scrapy from bs4 import BeautifulSoup from bs4.element import Comment class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): soup = BeautifulSoup(response.body_as_unicode(), 'html.parser') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] print(visible_texts) <commit_msg>Use a faster parser for bs4<commit_after>import scrapy from bs4 import BeautifulSoup from bs4.element import Comment from fedtext.items import FedTextItem class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the rendered sense), False otherwise. This returns False on empty strings """ if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif isinstance(element, Comment): return False else: return element.strip() def parse(self, response): """ Callback method for parsing the response. Yields a FedTextItem. """ soup = BeautifulSoup(response.body_as_unicode(), 'lxml') texts = soup.findAll(text=True) visible_texts = [t.strip() for t in texts if self.visible(t)] item = FedTextItem() item['text_list'] = visible_texts yield item
a2bcee39ae1b40848bdddefb1b5d5ed05b847c55
mysite/search/tasks/__init__.py
mysite/search/tasks/__init__.py
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs)
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() class GrabGnomeLoveBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab GNOME Love bugs") mysite.customs.bugtrackers.gnome_love.grab() tasks.register(GrabMiroBugs) tasks.register(GrabGnomeLoveBugs) tasks.register(GrabLaunchpadBugs)
Add a task to grab GNOME love bugs.
Add a task to grab GNOME love bugs.
Python
agpl-3.0
sudheesh001/oh-mainline,openhatch/oh-mainline,Changaco/oh-mainline,campbe13/openhatch,onceuponatimeforever/oh-mainline,onceuponatimeforever/oh-mainline,eeshangarg/oh-mainline,nirmeshk/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,willingc/oh-mainline,moijes12/oh-mainline,onceuponatimeforever/oh-mainline,moijes12/oh-mainline,Changaco/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,nirmeshk/oh-mainline,jledbetter/openhatch,ojengwa/oh-mainline,willingc/oh-mainline,moijes12/oh-mainline,nirmeshk/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,vipul-sharma20/oh-mainline,ojengwa/oh-mainline,heeraj123/oh-mainline,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline,heeraj123/oh-mainline,heeraj123/oh-mainline,SnappleCap/oh-mainline,vipul-sharma20/oh-mainline,jledbetter/openhatch,moijes12/oh-mainline,willingc/oh-mainline,ehashman/oh-mainline,campbe13/openhatch,Changaco/oh-mainline,mzdaniel/oh-mainline,ehashman/oh-mainline,waseem18/oh-mainline,jledbetter/openhatch,mzdaniel/oh-mainline,ojengwa/oh-mainline,vipul-sharma20/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,ehashman/oh-mainline,SnappleCap/oh-mainline,waseem18/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,SnappleCap/oh-mainline,moijes12/oh-mainline,onceuponatimeforever/oh-mainline,mzdaniel/oh-mainline,jledbetter/openhatch,mzdaniel/oh-mainline,Changaco/oh-mainline,heeraj123/oh-mainline,nirmeshk/oh-mainline,heeraj123/oh-mainline,eeshangarg/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,openhatch/oh-mainline,SnappleCap/oh-mainline,ehashman/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,Changaco/oh-mainline,openhatch/oh-mainline,jledbetter/openhatch,openhatch/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,ehashman/oh-mainline
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs) Add a task to grab GNOME love bugs.
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() class GrabGnomeLoveBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab GNOME Love bugs") mysite.customs.bugtrackers.gnome_love.grab() tasks.register(GrabMiroBugs) tasks.register(GrabGnomeLoveBugs) tasks.register(GrabLaunchpadBugs)
<commit_before>from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs) <commit_msg>Add a task to grab GNOME love bugs.<commit_after>
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() class GrabGnomeLoveBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab GNOME Love bugs") mysite.customs.bugtrackers.gnome_love.grab() tasks.register(GrabMiroBugs) tasks.register(GrabGnomeLoveBugs) tasks.register(GrabLaunchpadBugs)
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs) Add a task to grab GNOME love bugs.from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() class GrabGnomeLoveBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab GNOME Love bugs") mysite.customs.bugtrackers.gnome_love.grab() tasks.register(GrabMiroBugs) tasks.register(GrabGnomeLoveBugs) tasks.register(GrabLaunchpadBugs)
<commit_before>from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() tasks.register(GrabMiroBugs) tasks.register(GrabLaunchpadBugs) <commit_msg>Add a task to grab GNOME love bugs.<commit_after>from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) for lp_project in lpproj2ohproj: openhatch_proj = lpproj2ohproj[lp_project] logger.info("Started to grab lp.net bugs for %s into %s" % ( lp_project, openhatch_proj)) grab_lp_bugs(lp_project=lp_project, openhatch_project=openhatch_proj) class GrabMiroBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab Miro bitesized bugs") mysite.customs.miro.grab_miro_bugs() class GrabGnomeLoveBugs(PeriodicTask): run_every = timedelta(days=1) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Started to grab GNOME Love bugs") mysite.customs.bugtrackers.gnome_love.grab() tasks.register(GrabMiroBugs) tasks.register(GrabGnomeLoveBugs) tasks.register(GrabLaunchpadBugs)
155952fa8db51184314f1922bb2f041bfdefcaa7
harp/settings/production.py
harp/settings/production.py
from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp/static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp"
from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp_static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp"
Change static to new webfaction application
Change static to new webfaction application
Python
mit
msampaio/harpa,msampaio/harpa,msampaio/harpa
from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp/static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp" Change static to new webfaction application
from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp_static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp"
<commit_before>from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp/static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp" <commit_msg>Change static to new webfaction application<commit_after>
from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp_static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp"
from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp/static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp" Change static to new webfaction applicationfrom __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp_static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp"
<commit_before>from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp/static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp" <commit_msg>Change static to new webfaction application<commit_after>from __future__ import absolute_import from .base import * import json from django.core.exceptions import ImproperlyConfigured def get_secret(): try: with open(join(DJANGO_ROOT, "serverconf.json")) as conf_file: return json.load(conf_file) except KeyError: raise ImproperlyConfigured("Create a proper serverconf.json") # Leave this commented, only use in an emergency ;-) # DEBUG = True # TEMPLATE_DEBUG = DEBUG SERVER_CONF = get_secret() ALLOWED_HOSTS = ["harp.genosmus.com"] SECRET_KEY = SERVER_CONF['secret-key'] STATIC_ROOT = '/home/genos/webapps/harp_static/' EMAIL_HOST = 'smtp.webfaction.com' EMAIL_HOST_USER = 'genos' EMAIL_HOST_PASSWORD = SERVER_CONF['email-password'] DEFAULT_FROM_EMAIL = 'genos@genosmus.com' SERVER_EMAIL = 'genos@genosmus.com' DEALER_PATH = "/home/genos/webapps/harp/harp"
fe2fdd17dcf05e7464e9b5cdeccbf7e884c0ee38
cob/subsystems/models_subsystem.py
cob/subsystems/models_subsystem.py
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
Make COB_DATABASE_URI environment variable override existing settings
Make COB_DATABASE_URI environment variable override existing settings
Python
bsd-3-clause
getweber/weber-cli
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load() Make COB_DATABASE_URI environment variable override existing settings
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
<commit_before>import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load() <commit_msg>Make COB_DATABASE_URI environment variable override existing settings<commit_after>
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load() Make COB_DATABASE_URI environment variable override existing settingsimport os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
<commit_before>import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): database_uri = os.environ.get('COB_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', database_uri) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load() <commit_msg>Make COB_DATABASE_URI environment variable override existing settings<commit_after>import os import logbook from .base import SubsystemBase from ..ctx import context from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy _logger = logbook.Logger(__name__) class ModelsSubsystem(SubsystemBase): NAME = 'models' def activate(self, flask_app): env_override = os.environ.get('COB_DATABASE_URI') if env_override: flask_app.config['SQLALCHEMY_DATABASE_URI'] = env_override else: flask_app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///{}'.format(os.path.join(self.project.root, '.cob', 'db.sqlite'))) context.db = SQLAlchemy(flask_app) Migrate(flask_app, context.db).init_app(flask_app) super(ModelsSubsystem, self).activate(flask_app) def has_migrations(self): return os.path.isdir(os.path.join(self.project.root, 'migrations')) def configure_grain(self, grain, flask_app): # pylint: disable=unused-argument _logger.trace('Found models: {m.path}', grain) grain.load()
b4687eb7fda33323cad8d42f9819a3ee223d3822
web/config/local_settings.py
web/config/local_settings.py
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
import os import json, requests from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') elif os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME"): rancher_carbonlink_service_url = "http://rancher-metadata/2015-12-19/services/%s/containers" % os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME") r = requests.get(rancher_carbonlink_service_url, headers={"Accept": "application/json"}).json() r = map(lambda x: x["primary_ip"] + ":80", r) CLUSTER_SERVERS = [str(x) for x in r] if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
Add graphite cluster discovery support using rancher
Add graphite cluster discovery support using rancher
Python
apache-2.0
Banno/graphite-setup,Banno/graphite-setup,Banno/graphite-setup
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now()) Add graphite cluster discovery support using rancher
import os import json, requests from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') elif os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME"): rancher_carbonlink_service_url = "http://rancher-metadata/2015-12-19/services/%s/containers" % os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME") r = requests.get(rancher_carbonlink_service_url, headers={"Accept": "application/json"}).json() r = map(lambda x: x["primary_ip"] + ":80", r) CLUSTER_SERVERS = [str(x) for x in r] if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
<commit_before>import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now()) <commit_msg>Add graphite cluster discovery support using rancher<commit_after>
import os import json, requests from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') elif os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME"): rancher_carbonlink_service_url = "http://rancher-metadata/2015-12-19/services/%s/containers" % os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME") r = requests.get(rancher_carbonlink_service_url, headers={"Accept": "application/json"}).json() r = map(lambda x: x["primary_ip"] + ":80", r) CLUSTER_SERVERS = [str(x) for x in r] if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now()) Add graphite cluster discovery support using rancherimport os import json, requests from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') elif os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME"): rancher_carbonlink_service_url = "http://rancher-metadata/2015-12-19/services/%s/containers" % os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME") r = requests.get(rancher_carbonlink_service_url, headers={"Accept": "application/json"}).json() r = map(lambda x: x["primary_ip"] + ":80", r) CLUSTER_SERVERS = [str(x) for x in r] if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
<commit_before>import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now()) <commit_msg>Add graphite cluster discovery support using rancher<commit_after>import os import json, requests from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') elif os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME"): rancher_carbonlink_service_url = "http://rancher-metadata/2015-12-19/services/%s/containers" % os.getenv("RANCHER_GRAPHITE_CLUSTER_SERVICE_NAME") r = requests.get(rancher_carbonlink_service_url, headers={"Accept": "application/json"}).json() r = map(lambda x: x["primary_ip"] + ":80", r) CLUSTER_SERVERS = [str(x) for x in r] if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
1c482edbc29d008a8de9a0762c1a85027de083cc
src/spz/test/test_views.py
src/spz/test/test_views.py
# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200
# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
Remove build_assets from test since test client will neither interprete css nor javascript
Remove build_assets from test since test client will neither interprete css nor javascript
Python
mit
spz-signup/spz-signup
# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200 Remove build_assets from test since test client will neither interprete css nor javascript
# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
<commit_before># -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200 <commit_msg>Remove build_assets from test since test client will neither interprete css nor javascript<commit_after>
# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200 Remove build_assets from test since test client will neither interprete css nor javascript# -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
<commit_before># -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources from util.build_assets import build_assets @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() build_assets() yield client def test_startpage(client): assert client.get('/').status_code == 200 <commit_msg>Remove build_assets from test since test client will neither interprete css nor javascript<commit_after># -*- coding: utf-8 -*- """Tests the application views. """ import pytest from spz import app from util.init_db import recreate_tables, insert_resources @pytest.fixture def client(): client = app.test_client() recreate_tables() insert_resources() yield client def test_startpage(client): assert client.get('/').status_code == 200
0808e3f5897028a1f174e21200870e4be6fcad11
apps/quotes/admin.py
apps/quotes/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin)
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] list_editable = ['broadcast'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin)
Make broadcast editable for now.
Make broadcast editable for now.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin) Make broadcast editable for now.
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] list_editable = ['broadcast'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin)
<commit_before># -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin) <commit_msg>Make broadcast editable for now.<commit_after>
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] list_editable = ['broadcast'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin)
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin) Make broadcast editable for now.# -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] list_editable = ['broadcast'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin)
<commit_before># -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin) <commit_msg>Make broadcast editable for now.<commit_after># -*- coding: utf-8 -*- from django.contrib import admin from .models import Quote class QuoteAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('text', ('timestamp', 'subject'),)}), ('Metadata', {'fields': ('creator', 'broadcast', 'game')}) ) list_display = ['text', 'timestamp', 'subject', 'creator', 'broadcast', 'game'] list_editable = ['broadcast'] raw_id_fields = ['broadcast', 'game'] autocomplete_lookup_fields = {'fk': ['game']} admin.site.register(Quote, QuoteAdmin)
4a6449b806dc755fe3f9d18966c0420da2a4d0fc
devito/dle/manipulation.py
devito/dle/manipulation.py
import cgen as c from devito.codeprinter import ccode from devito.nodes import Element, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Element(c.Assign(ccode(k[indices]), ccode(v[indices])))) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations
from sympy import Eq from devito.codeprinter import ccode from devito.nodes import Expression, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Expression(Eq(k[indices], v[indices]), dtype=k.function.dtype)) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations
Use Expression, not Element, in copy_arrays
dle: Use Expression, not Element, in copy_arrays
Python
mit
opesci/devito,opesci/devito
import cgen as c from devito.codeprinter import ccode from devito.nodes import Element, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Element(c.Assign(ccode(k[indices]), ccode(v[indices])))) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations dle: Use Expression, not Element, in copy_arrays
from sympy import Eq from devito.codeprinter import ccode from devito.nodes import Expression, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Expression(Eq(k[indices], v[indices]), dtype=k.function.dtype)) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations
<commit_before>import cgen as c from devito.codeprinter import ccode from devito.nodes import Element, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Element(c.Assign(ccode(k[indices]), ccode(v[indices])))) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations <commit_msg>dle: Use Expression, not Element, in copy_arrays<commit_after>
from sympy import Eq from devito.codeprinter import ccode from devito.nodes import Expression, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Expression(Eq(k[indices], v[indices]), dtype=k.function.dtype)) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations
import cgen as c from devito.codeprinter import ccode from devito.nodes import Element, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Element(c.Assign(ccode(k[indices]), ccode(v[indices])))) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations dle: Use Expression, not Element, in copy_arraysfrom sympy import Eq from devito.codeprinter import ccode from devito.nodes import Expression, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Expression(Eq(k[indices], v[indices]), dtype=k.function.dtype)) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations
<commit_before>import cgen as c from devito.codeprinter import ccode from devito.nodes import Element, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Element(c.Assign(ccode(k[indices]), ccode(v[indices])))) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations <commit_msg>dle: Use Expression, not Element, in copy_arrays<commit_after>from sympy import Eq from devito.codeprinter import ccode from devito.nodes import Expression, Iteration from devito.visitors import MergeOuterIterations __all__ = ['compose_nodes', 'copy_arrays'] def compose_nodes(nodes): """Build an Iteration/Expression tree by nesting the nodes in ``nodes``.""" l = list(nodes) body = l.pop(-1) while l: handle = l.pop(-1) body = handle._rebuild(body, **handle.args_frozen) return body def copy_arrays(mapper): """Build an Iteration/Expression tree performing the copy ``k = v`` for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`.""" # Build the Iteration tree for the copy iterations = [] for k, v in mapper.items(): handle = [] indices = k.function.indices for i, j in zip(k.shape, indices): handle.append(Iteration([], dimension=j, limits=j.symbolic_size)) handle.append(Expression(Eq(k[indices], v[indices]), dtype=k.function.dtype)) iterations.append(compose_nodes(handle)) # Maybe some Iterations are mergeable iterations = MergeOuterIterations().visit(iterations) return iterations
ed0d2f78bee4c7082be99683d2905e308f526d0c
diapason/dub.py
diapason/dub.py
""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg',) if coding_format == 'mpeg': coding_format = 'mp3' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted
""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg', 'vorbis') if coding_format == 'mpeg': coding_format = 'mp3' if coding_format == 'vorbis': coding_format = 'ogg' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted
Allow converting WAV to vorbis as well
Allow converting WAV to vorbis as well
Python
bsd-3-clause
Soundphy/diapason
""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg',) if coding_format == 'mpeg': coding_format = 'mp3' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted Allow converting WAV to vorbis as well
""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg', 'vorbis') if coding_format == 'mpeg': coding_format = 'mp3' if coding_format == 'vorbis': coding_format = 'ogg' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted
<commit_before>""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg',) if coding_format == 'mpeg': coding_format = 'mp3' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted <commit_msg>Allow converting WAV to vorbis as well<commit_after>
""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg', 'vorbis') if coding_format == 'mpeg': coding_format = 'mp3' if coding_format == 'vorbis': coding_format = 'ogg' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted
""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg',) if coding_format == 'mpeg': coding_format = 'mp3' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted Allow converting WAV to vorbis as well""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg', 'vorbis') if coding_format == 'mpeg': coding_format = 'mp3' if coding_format == 'vorbis': coding_format = 'ogg' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted
<commit_before>""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg',) if coding_format == 'mpeg': coding_format = 'mp3' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted <commit_msg>Allow converting WAV to vorbis as well<commit_after>""" Dub module that can be used when ffmpeg is available to deal with different audio formats. """ from io import BytesIO from pydub import AudioSegment def convert_wav(wav, coding_format='mpeg', **kwargs): """ Convert a WAV file to other formats. """ assert coding_format in ('mpeg', 'vorbis') if coding_format == 'mpeg': coding_format = 'mp3' if coding_format == 'vorbis': coding_format = 'ogg' bitrate = kwargs.get('bitrate', None) converted = BytesIO() audio = AudioSegment.from_wav(wav) audio.export(converted, format=coding_format, bitrate=bitrate) return converted
20c6c985ea5f27a7badb18ecd7f6e6e6c4e250a0
avocado/export/__init__.py
avocado/export/__init__.py
from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters')
from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') # registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters')
Disable registration of the HTML exporter for now
Disable registration of the HTML exporter for now
Python
bsd-2-clause
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters') Disable registration of the HTML exporter for now
from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') # registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters')
<commit_before>from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters') <commit_msg>Disable registration of the HTML exporter for now<commit_after>
from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') # registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters')
from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters') Disable registration of the HTML exporter for nowfrom avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') # registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters')
<commit_before>from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters') <commit_msg>Disable registration of the HTML exporter for now<commit_after>from avocado.core import loader from avocado.conf import OPTIONAL_DEPS from _csv import CSVExporter from _sas import SASExporter from _r import RExporter from _json import JSONExporter from _html import HTMLExporter registry = loader.Registry(register_instance=False) registry.register(CSVExporter, 'csv') registry.register(SASExporter, 'sas') registry.register(RExporter, 'r') registry.register(JSONExporter, 'json') # registry.register(HTMLExporter, 'html') if OPTIONAL_DEPS['openpyxl']: from _excel import ExcelExporter registry.register(ExcelExporter, 'excel') loader.autodiscover('exporters')
01daa7448260552113aa68f18c215c192e95324e
editorsnotes/auth/forms.py
editorsnotes/auth/forms.py
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ('email', 'display_name',) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',)
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from rest_framework.authtoken.models import Token from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): create_token = forms.BooleanField(required=False) class Meta: model = User fields = ('display_name', 'email', 'create_token',) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['readonly'] = True try: token = Token.objects.get(user=self.instance) except Token.DoesNotExist: token = None self.EXISTING_TOKEN = token def clean_email(self): return self.instance.email def save(self): super(UserProfileForm, self).save() if self.cleaned_data['create_token']: Token.objects.filter(user=self.instance).delete() token, created = Token.objects.get_or_create(user=self.instance) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',)
Allow tokens to be created/changed on profile settings page
Allow tokens to be created/changed on profile settings page
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ('email', 'display_name',) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',) Allow tokens to be created/changed on profile settings page
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from rest_framework.authtoken.models import Token from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): create_token = forms.BooleanField(required=False) class Meta: model = User fields = ('display_name', 'email', 'create_token',) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['readonly'] = True try: token = Token.objects.get(user=self.instance) except Token.DoesNotExist: token = None self.EXISTING_TOKEN = token def clean_email(self): return self.instance.email def save(self): super(UserProfileForm, self).save() if self.cleaned_data['create_token']: Token.objects.filter(user=self.instance).delete() token, created = Token.objects.get_or_create(user=self.instance) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',)
<commit_before>from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ('email', 'display_name',) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',) <commit_msg>Allow tokens to be created/changed on profile settings page<commit_after>
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from rest_framework.authtoken.models import Token from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): create_token = forms.BooleanField(required=False) class Meta: model = User fields = ('display_name', 'email', 'create_token',) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['readonly'] = True try: token = Token.objects.get(user=self.instance) except Token.DoesNotExist: token = None self.EXISTING_TOKEN = token def clean_email(self): return self.instance.email def save(self): super(UserProfileForm, self).save() if self.cleaned_data['create_token']: Token.objects.filter(user=self.instance).delete() token, created = Token.objects.get_or_create(user=self.instance) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',)
from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ('email', 'display_name',) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',) Allow tokens to be created/changed on profile settings pagefrom django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from rest_framework.authtoken.models import Token from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): create_token = forms.BooleanField(required=False) class Meta: model = User fields = ('display_name', 'email', 'create_token',) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['readonly'] = True try: token = Token.objects.get(user=self.instance) except Token.DoesNotExist: token = None self.EXISTING_TOKEN = token def clean_email(self): return self.instance.email def save(self): super(UserProfileForm, self).save() if self.cleaned_data['create_token']: Token.objects.filter(user=self.instance).delete() token, created = Token.objects.get_or_create(user=self.instance) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',)
<commit_before>from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ('email', 'display_name',) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',) <commit_msg>Allow tokens to be created/changed on profile settings page<commit_after>from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from rest_framework.authtoken.models import Token from .models import User, Project class ENUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email', 'display_name') def clean_email(self): # Since User.email is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) class ENAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: if user.confirmed: raise forms.ValidationError('This account is inactive.') class UserProfileForm(forms.ModelForm): create_token = forms.BooleanField(required=False) class Meta: model = User fields = ('display_name', 'email', 'create_token',) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['readonly'] = True try: token = Token.objects.get(user=self.instance) except Token.DoesNotExist: token = None self.EXISTING_TOKEN = token def clean_email(self): return self.instance.email def save(self): super(UserProfileForm, self).save() if self.cleaned_data['create_token']: Token.objects.filter(user=self.instance).delete() token, created = Token.objects.get_or_create(user=self.instance) class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'slug', 'default_license',)
8c1b2f1fc71be754898bf962306c325538a589bf
contentdensity/textifai/views.py
contentdensity/textifai/views.py
from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) from .models import User def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} )
from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} ) def general_insights(request): """ View function for the general insights page of the site. """ return render( request, 'general-insights.html', context={}, )
Add view definition for the general-insights page
Add view definition for the general-insights page
Python
mit
CS326-important/space-deer,CS326-important/space-deer
from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) from .models import User def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} )Add view definition for the general-insights page
from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} ) def general_insights(request): """ View function for the general insights page of the site. """ return render( request, 'general-insights.html', context={}, )
<commit_before>from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) from .models import User def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} )<commit_msg>Add view definition for the general-insights page<commit_after>
from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} ) def general_insights(request): """ View function for the general insights page of the site. """ return render( request, 'general-insights.html', context={}, )
from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) from .models import User def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} )Add view definition for the general-insights pagefrom django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} ) def general_insights(request): """ View function for the general insights page of the site. """ return render( request, 'general-insights.html', context={}, )
<commit_before>from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) from .models import User def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} )<commit_msg>Add view definition for the general-insights page<commit_after>from django.shortcuts import render from .models import User, Text, Insight, Comment # Create your views here. def index(request): """ View function for the homepage of the site """ return render(request, 'index.html', context={}) def textinput(request): """ View function for the text input page of the site. """ return render( request, 'textinput.html', context={}, ) def featureoutput(request): """ View function for the feature output page of the site. """ mock_text = Text.objects.first() mock_insights = Insight.objects.filter(user=mock_text.user) return render( request, 'featureoutput.html', context={'mock_text': mock_text.content, 'mock_insights': mock_insights}, ) def account(request): """ View function for user accounts. """ username = User._meta.get_field('username') return render( request, "account.html", context={'username':username} ) def general_insights(request): """ View function for the general insights page of the site. """ return render( request, 'general-insights.html', context={}, )
0bbfa67be217b603ee551aac0098eca2e74f43f0
.bin/scripts/current_track.py
.bin/scripts/current_track.py
import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split(" ") if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[4]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main()
import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split() if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[2]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main()
Fix bug in current track
Fix bug in current track
Python
mit
iAmMrinal0/dotfiles,iAmMrinal0/dotfiles
import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split(" ") if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[4]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main() Fix bug in current track
import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split() if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[2]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main()
<commit_before>import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split(" ") if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[4]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main() <commit_msg>Fix bug in current track<commit_after>
import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split() if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[2]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main()
import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split(" ") if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[4]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main() Fix bug in current trackimport subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split() if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[2]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main()
<commit_before>import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split(" ") if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[4]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main() <commit_msg>Fix bug in current track<commit_after>import subprocess def main(): st = subprocess.getoutput("mpc") lin = st.split("\n") if len(lin) > 1: sn_status = lin[1] duration = lin[1].split() if "paused" in sn_status: print(lin[0].split("-")[-1] + " [paused]") elif "playing" in sn_status: print(lin[0].split("-")[-1] + " " + duration[2]) else: print("stopped") else: print("stopped") if __name__ == "__main__": main()
34df666a20b6dba1f84af63e640a8d1058f131a8
exam/asserts.py
exam/asserts.py
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %r != %r after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
Use repr for assert failure
Use repr for assert failure
Python
mit
Fluxx/exam,gterzian/exam,Fluxx/exam,gterzian/exam
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher Use repr for assert failure
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %r != %r after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
<commit_before>IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher <commit_msg>Use repr for assert failure<commit_after>
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %r != %r after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher Use repr for assert failureIRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %r != %r after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
<commit_before>IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher <commit_msg>Use repr for assert failure<commit_after>IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %r != %r after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
046ab8fc0f60b15ccdafcbb549c7de894ecd064e
putio_cli/commands/base.py
putio_cli/commands/base.py
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
Remove run method (useless) in Base class
Remove run method (useless) in Base class
Python
mit
jlejeune/putio-cli
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') Remove run method (useless) in Base class
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
<commit_before>"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') <commit_msg>Remove run method (useless) in Base class<commit_after>
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') Remove run method (useless) in Base class"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
<commit_before>"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') <commit_msg>Remove run method (useless) in Base class<commit_after>"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
101bcd388745cc790408c39b74ceaa11062bebbf
treeherder/client/setup.py
treeherder/client/setup.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Jonathan Eads', author_email='jeads@mozilla.com', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
Set author to 'Mozilla Automation and Testing Team'
Set author to 'Mozilla Automation and Testing Team'
Python
mpl-2.0
tojonmz/treeherder,avih/treeherder,edmorley/treeherder,sylvestre/treeherder,KWierso/treeherder,deathping1994/treeherder,tojonmz/treeherder,avih/treeherder,moijes12/treeherder,rail/treeherder,rail/treeherder,KWierso/treeherder,gbrmachado/treeherder,wlach/treeherder,avih/treeherder,parkouss/treeherder,deathping1994/treeherder,adusca/treeherder,tojonmz/treeherder,gbrmachado/treeherder,avih/treeherder,deathping1994/treeherder,akhileshpillai/treeherder,glenn124f/treeherder,akhileshpillai/treeherder,KWierso/treeherder,KWierso/treeherder,kapy2010/treeherder,rail/treeherder,sylvestre/treeherder,parkouss/treeherder,kapy2010/treeherder,wlach/treeherder,tojon/treeherder,moijes12/treeherder,tojonmz/treeherder,tojonmz/treeherder,tojonmz/treeherder,glenn124f/treeherder,jgraham/treeherder,akhileshpillai/treeherder,akhileshpillai/treeherder,adusca/treeherder,sylvestre/treeherder,vaishalitekale/treeherder,deathping1994/treeherder,wlach/treeherder,avih/treeherder,deathping1994/treeherder,glenn124f/treeherder,tojon/treeherder,kapy2010/treeherder,glenn124f/treeherder,vaishalitekale/treeherder,jgraham/treeherder,moijes12/treeherder,moijes12/treeherder,parkouss/treeherder,rail/treeherder,vaishalitekale/treeherder,jgraham/treeherder,tojon/treeherder,tojon/treeherder,jgraham/treeherder,adusca/treeherder,wlach/treeherder,kapy2010/treeherder,adusca/treeherder,parkouss/treeherder,parkouss/treeherder,akhileshpillai/treeherder,gbrmachado/treeherder,moijes12/treeherder,sylvestre/treeherder,vaishalitekale/treeherder,gbrmachado/treeherder,wlach/treeherder,adusca/treeherder,kapy2010/treeherder,gbrmachado/treeherder,akhileshpillai/treeherder,glenn124f/treeherder,edmorley/treeherder,rail/treeherder,vaishalitekale/treeherder,edmorley/treeherder,vaishalitekale/treeherder,sylvestre/treeherder,glenn124f/treeherder,moijes12/treeherder,rail/treeherder,deathping1994/treeherder,gbrmachado/treeherder,jgraham/treeherder,wlach/treeherder,sylvestre/treeherder,edmorley/treeherder,parkouss/treeherder,adusca/treeherder,jgraham/treeherder,avih/treeherder
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Jonathan Eads', author_email='jeads@mozilla.com', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], ) Set author to 'Mozilla Automation and Testing Team'
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Jonathan Eads', author_email='jeads@mozilla.com', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], ) <commit_msg>Set author to 'Mozilla Automation and Testing Team'<commit_after>
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Jonathan Eads', author_email='jeads@mozilla.com', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], ) Set author to 'Mozilla Automation and Testing Team'# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Jonathan Eads', author_email='jeads@mozilla.com', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], ) <commit_msg>Set author to 'Mozilla Automation and Testing Team'<commit_after># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.0' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
4e306441cbfab5f56eaedcd9af8f71f84e40467c
tests/pytests/unit/states/test_makeconf.py
tests/pytests/unit/states/test_makeconf.py
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret # 'absent' function tests: 1 def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
Move makeconf state tests to pytest
Move makeconf state tests to pytest
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret # 'absent' function tests: 1 def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret Move makeconf state tests to pytest
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
<commit_before>""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret # 'absent' function tests: 1 def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret <commit_msg>Move makeconf state tests to pytest<commit_after>
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret # 'absent' function tests: 1 def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret Move makeconf state tests to pytest""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
<commit_before>""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret # 'absent' function tests: 1 def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret <commit_msg>Move makeconf state tests to pytest<commit_after>""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.states.makeconf as makeconf from tests.support.mock import MagicMock, patch @pytest.fixture def configure_loader_modules(): return {makeconf: {}} def test_present(): """ Test to verify that the variable is in the ``make.conf`` and has the provided settings. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): comt = "Variable {} is already present in make.conf".format(name) ret.update({"comment": comt}) assert makeconf.present(name) == ret def test_absent(): """ Test to verify that the variable is not in the ``make.conf``. """ name = "makeopts" ret = {"name": name, "result": True, "comment": "", "changes": {}} mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): comt = "Variable {} is already absent from make.conf".format(name) ret.update({"comment": comt}) assert makeconf.absent(name) == ret
859722fea0ed205c1af37c43c211d2f2855d22fc
fonts/create.py
fonts/create.py
import fontforge fontforge.open('input.otf').save('termu.sfd')
import fontforge font = fontforge.open('input.otf') font.fontname = 'Termu-' + font.fontname font.familyname = 'Termu: ' + font.familyname font.fullname = 'Termu: ' + font.fullname font.save('termu.sfd')
Add "termu" to the name of the font
Add "termu" to the name of the font
Python
mit
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
import fontforge fontforge.open('input.otf').save('termu.sfd') Add "termu" to the name of the font
import fontforge font = fontforge.open('input.otf') font.fontname = 'Termu-' + font.fontname font.familyname = 'Termu: ' + font.familyname font.fullname = 'Termu: ' + font.fullname font.save('termu.sfd')
<commit_before>import fontforge fontforge.open('input.otf').save('termu.sfd') <commit_msg>Add "termu" to the name of the font<commit_after>
import fontforge font = fontforge.open('input.otf') font.fontname = 'Termu-' + font.fontname font.familyname = 'Termu: ' + font.familyname font.fullname = 'Termu: ' + font.fullname font.save('termu.sfd')
import fontforge fontforge.open('input.otf').save('termu.sfd') Add "termu" to the name of the fontimport fontforge font = fontforge.open('input.otf') font.fontname = 'Termu-' + font.fontname font.familyname = 'Termu: ' + font.familyname font.fullname = 'Termu: ' + font.fullname font.save('termu.sfd')
<commit_before>import fontforge fontforge.open('input.otf').save('termu.sfd') <commit_msg>Add "termu" to the name of the font<commit_after>import fontforge font = fontforge.open('input.otf') font.fontname = 'Termu-' + font.fontname font.familyname = 'Termu: ' + font.familyname font.fullname = 'Termu: ' + font.fullname font.save('termu.sfd')
53add68f6ceb1f326f8162a361cf442b741d7470
app/__init__.py
app/__init__.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() lm = LoginManager() oauth = OAuth() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oauth = OAuth() lm = LoginManager() lm.login_view = "views.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app
Set user loader and login view
Set user loader and login view
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() lm = LoginManager() oauth = OAuth() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return appSet user loader and login view
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oauth = OAuth() lm = LoginManager() lm.login_view = "views.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app
<commit_before>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() lm = LoginManager() oauth = OAuth() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app<commit_msg>Set user loader and login view<commit_after>
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oauth = OAuth() lm = LoginManager() lm.login_view = "views.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() lm = LoginManager() oauth = OAuth() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return appSet user loader and login viewfrom flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oauth = OAuth() lm = LoginManager() lm.login_view = "views.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app
<commit_before>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() lm = LoginManager() oauth = OAuth() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app<commit_msg>Set user loader and login view<commit_after>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oauth = OAuth() lm = LoginManager() lm.login_view = "views.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oauth.init_app(app) from app.views import views app.register_blueprint(views) return app
2ed812ddc50bd262aadd74e01f24c8346d7ec8f7
scripts/fix_country_ids.py
scripts/fix_country_ids.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. # # Not all the SU_A3 IDs match those used in the ISO_A3 standard. This script replaces non-matching IDs # with corresponding ISO_A3 values. For more details seeissue #12 https://github.com/yaph/d3-geomap/issues/12. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
Add more details about issue being fixed
Add more details about issue being fixed
Python
mit
elaOnMars/d3-geomap,yaph/d3-geomap,elaOnMars/d3-geomap,elaOnMars/d3-geomap,yaph/d3-geomap
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small Add more details about issue being fixed
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. # # Not all the SU_A3 IDs match those used in the ISO_A3 standard. This script replaces non-matching IDs # with corresponding ISO_A3 values. For more details seeissue #12 https://github.com/yaph/d3-geomap/issues/12. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small <commit_msg>Add more details about issue being fixed<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. # # Not all the SU_A3 IDs match those used in the ISO_A3 standard. This script replaces non-matching IDs # with corresponding ISO_A3 values. For more details seeissue #12 https://github.com/yaph/d3-geomap/issues/12. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small Add more details about issue being fixed#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. # # Not all the SU_A3 IDs match those used in the ISO_A3 standard. This script replaces non-matching IDs # with corresponding ISO_A3 values. For more details seeissue #12 https://github.com/yaph/d3-geomap/issues/12. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small <commit_msg>Add more details about issue being fixed<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. # # Not all the SU_A3 IDs match those used in the ISO_A3 standard. This script replaces non-matching IDs # with corresponding ISO_A3 values. For more details seeissue #12 https://github.com/yaph/d3-geomap/issues/12. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
bbe5494df123a2173200669768f4297578aea23b
cms/djangoapps/contentstore/views/xblock.py
cms/djangoapps/contentstore/views/xblock.py
""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype)
""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, select=settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype)
Fix XBlock class loading in local resource view
Fix XBlock class loading in local resource view Some XBlock classes were being (randomly) incorrectly loaded. This was due to an error in the way the XBlock.load_class method was called. Error was happening randomly because of the cache mechanism in the class loading method. (see PLUGIN_CACHE)
Python
agpl-3.0
itsjeyd/edx-platform,vikas1885/test1,ovnicraft/edx-platform,gymnasium/edx-platform,chand3040/cloud_that,zadgroup/edx-platform,solashirai/edx-platform,JCBarahona/edX,Ayub-Khan/edx-platform,don-github/edx-platform,MakeHer/edx-platform,jamesblunt/edx-platform,martynovp/edx-platform,SivilTaram/edx-platform,mcgachey/edx-platform,cpennington/edx-platform,ZLLab-Mooc/edx-platform,gsehub/edx-platform,xuxiao19910803/edx,ak2703/edx-platform,xuxiao19910803/edx,polimediaupv/edx-platform,appliedx/edx-platform,10clouds/edx-platform,atsolakid/edx-platform,Kalyzee/edx-platform,procangroup/edx-platform,polimediaupv/edx-platform,mbareta/edx-platform-ft,alexthered/kienhoc-platform,Stanford-Online/edx-platform,Edraak/edraak-platform,etzhou/edx-platform,Edraak/circleci-edx-platform,devs1991/test_edx_docmode,antoviaque/edx-platform,utecuy/edx-platform,xuxiao19910803/edx-platform,Softmotions/edx-platform,inares/edx-platform,chrisndodge/edx-platform,SivilTaram/edx-platform,zhenzhai/edx-platform,antoviaque/edx-platform,hamzehd/edx-platform,fly19890211/edx-platform,zofuthan/edx-platform,ovnicraft/edx-platform,alu042/edx-platform,knehez/edx-platform,doganov/edx-platform,Shrhawk/edx-platform,bitifirefly/edx-platform,mahendra-r/edx-platform,jbzdak/edx-platform,Stanford-Online/edx-platform,bigdatauniversity/edx-platform,rismalrv/edx-platform,procangroup/edx-platform,leansoft/edx-platform,kursitet/edx-platform,pepeportela/edx-platform,adoosii/edx-platform,adoosii/edx-platform,chrisndodge/edx-platform,caesar2164/edx-platform,xuxiao19910803/edx-platform,openfun/edx-platform,vikas1885/test1,jamesblunt/edx-platform,Stanford-Online/edx-platform,jzoldak/edx-platform,alu042/edx-platform,prarthitm/edxplatform,cognitiveclass/edx-platform,solashirai/edx-platform,lduarte1991/edx-platform,don-github/edx-platform,tiagochiavericosta/edx-platform,10clouds/edx-platform,synergeticsedx/deployment-wipro,pepeportela/edx-platform,J861449197/edx-platform,jzoldak/edx-platform,zhenzhai/edx-platform,xingyepei/edx-platform,BehavioralInsightsTeam/edx-platform,edx/edx-platform,waheedahmed/edx-platform,itsjeyd/edx-platform,ahmedaljazzar/edx-platform,ovnicraft/edx-platform,waheedahmed/edx-platform,motion2015/edx-platform,amir-qayyum-khan/edx-platform,mjirayu/sit_academy,Ayub-Khan/edx-platform,B-MOOC/edx-platform,zerobatu/edx-platform,kxliugang/edx-platform,ampax/edx-platform,kxliugang/edx-platform,deepsrijit1105/edx-platform,zubair-arbi/edx-platform,appliedx/edx-platform,Edraak/circleci-edx-platform,Livit/Livit.Learn.EdX,amir-qayyum-khan/edx-platform,jbassen/edx-platform,a-parhom/edx-platform,chand3040/cloud_that,kxliugang/edx-platform,wwj718/edx-platform,zubair-arbi/edx-platform,zofuthan/edx-platform,longmen21/edx-platform,adoosii/edx-platform,leansoft/edx-platform,etzhou/edx-platform,devs1991/test_edx_docmode,nanolearningllc/edx-platform-cypress,Edraak/circleci-edx-platform,zerobatu/edx-platform,wwj718/edx-platform,appliedx/edx-platform,JioEducation/edx-platform,ampax/edx-platform,knehez/edx-platform,halvertoluke/edx-platform,deepsrijit1105/edx-platform,Edraak/edx-platform,knehez/edx-platform,ubc/edx-platform,zerobatu/edx-platform,Semi-global/edx-platform,vikas1885/test1,teltek/edx-platform,openfun/edx-platform,mitocw/edx-platform,4eek/edx-platform,eduNEXT/edx-platform,chudaol/edx-platform,ubc/edx-platform,nanolearningllc/edx-platform-cypress,mbareta/edx-platform-ft,stvstnfrd/edx-platform,leansoft/edx-platform,zubair-arbi/edx-platform,mcgachey/edx-platform,arifsetiawan/edx-platform,antoviaque/edx-platform,knehez/edx-platform,appliedx/edx-platform,Shrhawk/edx-platform,BehavioralInsightsTeam/edx-platform,ZLLab-Mooc/edx-platform,nikolas/edx-platform,nagyistoce/edx-platform,EDUlib/edx-platform,JioEducation/edx-platform,shabab12/edx-platform,xinjiguaike/edx-platform,atsolakid/edx-platform,vasyarv/edx-platform,10clouds/edx-platform,benpatterson/edx-platform,zofuthan/edx-platform,Semi-global/edx-platform,a-parhom/edx-platform,arbrandes/edx-platform,jbassen/edx-platform,Kalyzee/edx-platform,nttks/edx-platform,prarthitm/edxplatform,tanmaykm/edx-platform,shurihell/testasia,pomegranited/edx-platform,playm2mboy/edx-platform,eduNEXT/edx-platform,Lektorium-LLC/edx-platform,4eek/edx-platform,mitocw/edx-platform,naresh21/synergetics-edx-platform,cecep-edu/edx-platform,chrisndodge/edx-platform,wwj718/edx-platform,itsjeyd/edx-platform,Ayub-Khan/edx-platform,chauhanhardik/populo,RPI-OPENEDX/edx-platform,romain-li/edx-platform,ahmadiga/min_edx,jamiefolsom/edx-platform,franosincic/edx-platform,B-MOOC/edx-platform,angelapper/edx-platform,chauhanhardik/populo_2,nanolearningllc/edx-platform-cypress-2,fintech-circle/edx-platform,arbrandes/edx-platform,etzhou/edx-platform,utecuy/edx-platform,jazkarta/edx-platform,zadgroup/edx-platform,jazkarta/edx-platform,ESOedX/edx-platform,doganov/edx-platform,deepsrijit1105/edx-platform,benpatterson/edx-platform,shurihell/testasia,tiagochiavericosta/edx-platform,xuxiao19910803/edx-platform,a-parhom/edx-platform,xuxiao19910803/edx,CourseTalk/edx-platform,SravanthiSinha/edx-platform,ak2703/edx-platform,B-MOOC/edx-platform,jbzdak/edx-platform,zadgroup/edx-platform,nagyistoce/edx-platform,stvstnfrd/edx-platform,xinjiguaike/edx-platform,Shrhawk/edx-platform,martynovp/edx-platform,zubair-arbi/edx-platform,JCBarahona/edX,atsolakid/edx-platform,teltek/edx-platform,inares/edx-platform,appsembler/edx-platform,ovnicraft/edx-platform,ahmadiga/min_edx,nikolas/edx-platform,Softmotions/edx-platform,jonathan-beard/edx-platform,jamiefolsom/edx-platform,hamzehd/edx-platform,miptliot/edx-platform,naresh21/synergetics-edx-platform,TeachAtTUM/edx-platform,4eek/edx-platform,CredoReference/edx-platform,ahmedaljazzar/edx-platform,ampax/edx-platform,atsolakid/edx-platform,Kalyzee/edx-platform,JCBarahona/edX,Softmotions/edx-platform,chand3040/cloud_that,jjmiranda/edx-platform,chudaol/edx-platform,franosincic/edx-platform,martynovp/edx-platform,openfun/edx-platform,Stanford-Online/edx-platform,louyihua/edx-platform,pabloborrego93/edx-platform,chauhanhardik/populo,nagyistoce/edx-platform,fly19890211/edx-platform,bitifirefly/edx-platform,RPI-OPENEDX/edx-platform,simbs/edx-platform,procangroup/edx-platform,pabloborrego93/edx-platform,arbrandes/edx-platform,CredoReference/edx-platform,vikas1885/test1,naresh21/synergetics-edx-platform,inares/edx-platform,ahmadio/edx-platform,jzoldak/edx-platform,motion2015/edx-platform,Lektorium-LLC/edx-platform,10clouds/edx-platform,shabab12/edx-platform,romain-li/edx-platform,msegado/edx-platform,ahmadio/edx-platform,ak2703/edx-platform,mahendra-r/edx-platform,doganov/edx-platform,4eek/edx-platform,Semi-global/edx-platform,hastexo/edx-platform,defance/edx-platform,edx-solutions/edx-platform,MakeHer/edx-platform,Livit/Livit.Learn.EdX,cecep-edu/edx-platform,mitocw/edx-platform,shubhdev/edxOnBaadal,romain-li/edx-platform,IONISx/edx-platform,jzoldak/edx-platform,jbzdak/edx-platform,AkA84/edx-platform,jjmiranda/edx-platform,edry/edx-platform,gsehub/edx-platform,motion2015/edx-platform,utecuy/edx-platform,kursitet/edx-platform,ampax/edx-platform,philanthropy-u/edx-platform,appsembler/edx-platform,IndonesiaX/edx-platform,ovnicraft/edx-platform,ubc/edx-platform,jamiefolsom/edx-platform,jolyonb/edx-platform,msegado/edx-platform,Endika/edx-platform,jazkarta/edx-platform,playm2mboy/edx-platform,leansoft/edx-platform,Edraak/edx-platform,doganov/edx-platform,inares/edx-platform,edry/edx-platform,gsehub/edx-platform,pomegranited/edx-platform,simbs/edx-platform,chauhanhardik/populo_2,rismalrv/edx-platform,xinjiguaike/edx-platform,fly19890211/edx-platform,caesar2164/edx-platform,motion2015/edx-platform,doismellburning/edx-platform,caesar2164/edx-platform,CourseTalk/edx-platform,Edraak/edraak-platform,mjirayu/sit_academy,Edraak/circleci-edx-platform,martynovp/edx-platform,playm2mboy/edx-platform,JioEducation/edx-platform,TeachAtTUM/edx-platform,tanmaykm/edx-platform,halvertoluke/edx-platform,philanthropy-u/edx-platform,deepsrijit1105/edx-platform,eduNEXT/edunext-platform,mbareta/edx-platform-ft,mahendra-r/edx-platform,edx-solutions/edx-platform,Softmotions/edx-platform,jonathan-beard/edx-platform,benpatterson/edx-platform,Ayub-Khan/edx-platform,halvertoluke/edx-platform,shashank971/edx-platform,ESOedX/edx-platform,waheedahmed/edx-platform,xinjiguaike/edx-platform,simbs/edx-platform,Edraak/edraak-platform,hamzehd/edx-platform,jamesblunt/edx-platform,cpennington/edx-platform,IONISx/edx-platform,angelapper/edx-platform,halvertoluke/edx-platform,jamiefolsom/edx-platform,philanthropy-u/edx-platform,shabab12/edx-platform,shashank971/edx-platform,marcore/edx-platform,RPI-OPENEDX/edx-platform,louyihua/edx-platform,Endika/edx-platform,AkA84/edx-platform,Kalyzee/edx-platform,chrisndodge/edx-platform,IONISx/edx-platform,jbassen/edx-platform,J861449197/edx-platform,JCBarahona/edX,analyseuc3m/ANALYSE-v1,cognitiveclass/edx-platform,utecuy/edx-platform,franosincic/edx-platform,vikas1885/test1,edry/edx-platform,ZLLab-Mooc/edx-platform,alexthered/kienhoc-platform,kmoocdev2/edx-platform,kursitet/edx-platform,amir-qayyum-khan/edx-platform,proversity-org/edx-platform,antoviaque/edx-platform,mcgachey/edx-platform,SravanthiSinha/edx-platform,kmoocdev2/edx-platform,ubc/edx-platform,bigdatauniversity/edx-platform,polimediaupv/edx-platform,EDUlib/edx-platform,IndonesiaX/edx-platform,pomegranited/edx-platform,don-github/edx-platform,jolyonb/edx-platform,ZLLab-Mooc/edx-platform,pepeportela/edx-platform,vasyarv/edx-platform,Shrhawk/edx-platform,CourseTalk/edx-platform,caesar2164/edx-platform,leansoft/edx-platform,cpennington/edx-platform,edry/edx-platform,edx-solutions/edx-platform,proversity-org/edx-platform,vasyarv/edx-platform,Edraak/edx-platform,martynovp/edx-platform,arifsetiawan/edx-platform,fintech-circle/edx-platform,solashirai/edx-platform,jolyonb/edx-platform,wwj718/edx-platform,pomegranited/edx-platform,defance/edx-platform,synergeticsedx/deployment-wipro,kmoocdev2/edx-platform,Lektorium-LLC/edx-platform,longmen21/edx-platform,philanthropy-u/edx-platform,jazztpt/edx-platform,ahmadiga/min_edx,zadgroup/edx-platform,etzhou/edx-platform,franosincic/edx-platform,chauhanhardik/populo_2,JioEducation/edx-platform,mahendra-r/edx-platform,UOMx/edx-platform,CredoReference/edx-platform,wwj718/edx-platform,zofuthan/edx-platform,TeachAtTUM/edx-platform,alu042/edx-platform,polimediaupv/edx-platform,B-MOOC/edx-platform,lduarte1991/edx-platform,utecuy/edx-platform,franosincic/edx-platform,edx/edx-platform,synergeticsedx/deployment-wipro,xingyepei/edx-platform,appliedx/edx-platform,kxliugang/edx-platform,SivilTaram/edx-platform,MakeHer/edx-platform,JCBarahona/edX,openfun/edx-platform,nttks/edx-platform,RPI-OPENEDX/edx-platform,zhenzhai/edx-platform,doganov/edx-platform,eduNEXT/edunext-platform,Kalyzee/edx-platform,nikolas/edx-platform,nanolearningllc/edx-platform-cypress-2,RPI-OPENEDX/edx-platform,shashank971/edx-platform,analyseuc3m/ANALYSE-v1,nanolearningllc/edx-platform-cypress,cecep-edu/edx-platform,ahmedaljazzar/edx-platform,arifsetiawan/edx-platform,TeachAtTUM/edx-platform,pabloborrego93/edx-platform,jbassen/edx-platform,xingyepei/edx-platform,chauhanhardik/populo_2,doismellburning/edx-platform,xuxiao19910803/edx,vasyarv/edx-platform,MakeHer/edx-platform,UOMx/edx-platform,mcgachey/edx-platform,arifsetiawan/edx-platform,raccoongang/edx-platform,devs1991/test_edx_docmode,shurihell/testasia,msegado/edx-platform,motion2015/edx-platform,benpatterson/edx-platform,appsembler/edx-platform,shubhdev/edxOnBaadal,naresh21/synergetics-edx-platform,devs1991/test_edx_docmode,cognitiveclass/edx-platform,nanolearningllc/edx-platform-cypress,Edraak/edx-platform,fintech-circle/edx-platform,chauhanhardik/populo,chauhanhardik/populo,gymnasium/edx-platform,cecep-edu/edx-platform,ferabra/edx-platform,chudaol/edx-platform,Endika/edx-platform,bigdatauniversity/edx-platform,J861449197/edx-platform,ahmedaljazzar/edx-platform,nagyistoce/edx-platform,Edraak/edraak-platform,marcore/edx-platform,fly19890211/edx-platform,miptliot/edx-platform,rismalrv/edx-platform,benpatterson/edx-platform,miptliot/edx-platform,analyseuc3m/ANALYSE-v1,gymnasium/edx-platform,defance/edx-platform,jonathan-beard/edx-platform,teltek/edx-platform,jazztpt/edx-platform,cecep-edu/edx-platform,tiagochiavericosta/edx-platform,chand3040/cloud_that,shurihell/testasia,proversity-org/edx-platform,inares/edx-platform,nikolas/edx-platform,ak2703/edx-platform,Softmotions/edx-platform,adoosii/edx-platform,xingyepei/edx-platform,bigdatauniversity/edx-platform,eduNEXT/edx-platform,J861449197/edx-platform,IndonesiaX/edx-platform,halvertoluke/edx-platform,Endika/edx-platform,stvstnfrd/edx-platform,cpennington/edx-platform,shashank971/edx-platform,Lektorium-LLC/edx-platform,chudaol/edx-platform,appsembler/edx-platform,edry/edx-platform,jamiefolsom/edx-platform,mcgachey/edx-platform,iivic/BoiseStateX,msegado/edx-platform,tiagochiavericosta/edx-platform,eduNEXT/edunext-platform,itsjeyd/edx-platform,kmoocdev2/edx-platform,atsolakid/edx-platform,lduarte1991/edx-platform,J861449197/edx-platform,ZLLab-Mooc/edx-platform,B-MOOC/edx-platform,nikolas/edx-platform,AkA84/edx-platform,Semi-global/edx-platform,shubhdev/edxOnBaadal,msegado/edx-platform,jolyonb/edx-platform,chauhanhardik/populo,hastexo/edx-platform,vasyarv/edx-platform,pomegranited/edx-platform,miptliot/edx-platform,knehez/edx-platform,chand3040/cloud_that,openfun/edx-platform,AkA84/edx-platform,iivic/BoiseStateX,raccoongang/edx-platform,Ayub-Khan/edx-platform,rismalrv/edx-platform,ferabra/edx-platform,cognitiveclass/edx-platform,procangroup/edx-platform,CourseTalk/edx-platform,devs1991/test_edx_docmode,shabab12/edx-platform,IONISx/edx-platform,romain-li/edx-platform,ak2703/edx-platform,zerobatu/edx-platform,gymnasium/edx-platform,IndonesiaX/edx-platform,BehavioralInsightsTeam/edx-platform,kmoocdev2/edx-platform,Shrhawk/edx-platform,gsehub/edx-platform,playm2mboy/edx-platform,hastexo/edx-platform,jazkarta/edx-platform,jbzdak/edx-platform,IndonesiaX/edx-platform,edx/edx-platform,SravanthiSinha/edx-platform,alexthered/kienhoc-platform,chauhanhardik/populo_2,louyihua/edx-platform,solashirai/edx-platform,bigdatauniversity/edx-platform,4eek/edx-platform,xuxiao19910803/edx-platform,hamzehd/edx-platform,devs1991/test_edx_docmode,solashirai/edx-platform,mbareta/edx-platform-ft,ahmadio/edx-platform,zadgroup/edx-platform,hastexo/edx-platform,jjmiranda/edx-platform,waheedahmed/edx-platform,nanolearningllc/edx-platform-cypress-2,proversity-org/edx-platform,alu042/edx-platform,lduarte1991/edx-platform,don-github/edx-platform,playm2mboy/edx-platform,iivic/BoiseStateX,tiagochiavericosta/edx-platform,raccoongang/edx-platform,bitifirefly/edx-platform,Edraak/circleci-edx-platform,eduNEXT/edx-platform,devs1991/test_edx_docmode,edx-solutions/edx-platform,SivilTaram/edx-platform,angelapper/edx-platform,CredoReference/edx-platform,arbrandes/edx-platform,nanolearningllc/edx-platform-cypress-2,arifsetiawan/edx-platform,shubhdev/edxOnBaadal,shurihell/testasia,ahmadiga/min_edx,nanolearningllc/edx-platform-cypress-2,xuxiao19910803/edx,SravanthiSinha/edx-platform,zerobatu/edx-platform,zofuthan/edx-platform,kxliugang/edx-platform,iivic/BoiseStateX,xuxiao19910803/edx-platform,nttks/edx-platform,longmen21/edx-platform,romain-li/edx-platform,longmen21/edx-platform,BehavioralInsightsTeam/edx-platform,don-github/edx-platform,Edraak/edx-platform,bitifirefly/edx-platform,ahmadiga/min_edx,jamesblunt/edx-platform,mitocw/edx-platform,alexthered/kienhoc-platform,hamzehd/edx-platform,SravanthiSinha/edx-platform,doismellburning/edx-platform,Livit/Livit.Learn.EdX,pabloborrego93/edx-platform,jonathan-beard/edx-platform,ferabra/edx-platform,fly19890211/edx-platform,marcore/edx-platform,SivilTaram/edx-platform,EDUlib/edx-platform,jjmiranda/edx-platform,a-parhom/edx-platform,analyseuc3m/ANALYSE-v1,synergeticsedx/deployment-wipro,polimediaupv/edx-platform,simbs/edx-platform,rismalrv/edx-platform,UOMx/edx-platform,angelapper/edx-platform,ubc/edx-platform,longmen21/edx-platform,jazkarta/edx-platform,ESOedX/edx-platform,simbs/edx-platform,zubair-arbi/edx-platform,eduNEXT/edunext-platform,Semi-global/edx-platform,MakeHer/edx-platform,defance/edx-platform,fintech-circle/edx-platform,stvstnfrd/edx-platform,amir-qayyum-khan/edx-platform,jazztpt/edx-platform,zhenzhai/edx-platform,pepeportela/edx-platform,nagyistoce/edx-platform,AkA84/edx-platform,shashank971/edx-platform,ferabra/edx-platform,marcore/edx-platform,xinjiguaike/edx-platform,jamesblunt/edx-platform,devs1991/test_edx_docmode,cognitiveclass/edx-platform,ESOedX/edx-platform,ferabra/edx-platform,raccoongang/edx-platform,nttks/edx-platform,alexthered/kienhoc-platform,shubhdev/edxOnBaadal,iivic/BoiseStateX,teltek/edx-platform,jonathan-beard/edx-platform,zhenzhai/edx-platform,tanmaykm/edx-platform,mjirayu/sit_academy,bitifirefly/edx-platform,mahendra-r/edx-platform,ahmadio/edx-platform,jbzdak/edx-platform,xingyepei/edx-platform,prarthitm/edxplatform,nttks/edx-platform,mjirayu/sit_academy,ahmadio/edx-platform,doismellburning/edx-platform,kursitet/edx-platform,doismellburning/edx-platform,jazztpt/edx-platform,jazztpt/edx-platform,etzhou/edx-platform,IONISx/edx-platform,mjirayu/sit_academy,edx/edx-platform,tanmaykm/edx-platform,adoosii/edx-platform,louyihua/edx-platform,EDUlib/edx-platform,kursitet/edx-platform,UOMx/edx-platform,prarthitm/edxplatform,Livit/Livit.Learn.EdX,jbassen/edx-platform,nanolearningllc/edx-platform-cypress,chudaol/edx-platform,waheedahmed/edx-platform
""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype) Fix XBlock class loading in local resource view Some XBlock classes were being (randomly) incorrectly loaded. This was due to an error in the way the XBlock.load_class method was called. Error was happening randomly because of the cache mechanism in the class loading method. (see PLUGIN_CACHE)
""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, select=settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype)
<commit_before>""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype) <commit_msg>Fix XBlock class loading in local resource view Some XBlock classes were being (randomly) incorrectly loaded. This was due to an error in the way the XBlock.load_class method was called. Error was happening randomly because of the cache mechanism in the class loading method. (see PLUGIN_CACHE)<commit_after>
""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, select=settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype)
""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype) Fix XBlock class loading in local resource view Some XBlock classes were being (randomly) incorrectly loaded. This was due to an error in the way the XBlock.load_class method was called. Error was happening randomly because of the cache mechanism in the class loading method. (see PLUGIN_CACHE)""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, select=settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype)
<commit_before>""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype) <commit_msg>Fix XBlock class loading in local resource view Some XBlock classes were being (randomly) incorrectly loaded. This was due to an error in the way the XBlock.load_class method was called. Error was happening randomly because of the cache mechanism in the class loading method. (see PLUGIN_CACHE)<commit_after>""" Views dedicated to rendering xblocks. """ from __future__ import absolute_import import logging import mimetypes from xblock.core import XBlock from django.conf import settings from django.http import Http404, HttpResponse log = logging.getLogger(__name__) def xblock_resource(request, block_type, uri): # pylint: disable=unused-argument """ Return a package resource for the specified XBlock. """ try: xblock_class = XBlock.load_class(block_type, select=settings.XBLOCK_SELECT_FUNCTION) content = xblock_class.open_local_resource(uri) except IOError: log.info('Failed to load xblock resource', exc_info=True) raise Http404 except Exception: # pylint: disable=broad-except log.error('Failed to load xblock resource', exc_info=True) raise Http404 mimetype, _ = mimetypes.guess_type(uri) return HttpResponse(content, mimetype=mimetype)
b38a55302540507c43f56ed9c9c6c55d3ea7be8f
backend/websocket_server.py
backend/websocket_server.py
import thread import json from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
import thread import json import time from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break else: time.sleep(0.5) return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
Fix high cpu usage through sleep
Fix high cpu usage through sleep
Python
mit
HPI-Hackathon/cartets,HPI-Hackathon/cartets,HPI-Hackathon/cartets
import thread import json from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever() Fix high cpu usage through sleep
import thread import json import time from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break else: time.sleep(0.5) return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
<commit_before>import thread import json from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever() <commit_msg>Fix high cpu usage through sleep<commit_after>
import thread import json import time from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break else: time.sleep(0.5) return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
import thread import json from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever() Fix high cpu usage through sleepimport thread import json import time from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break else: time.sleep(0.5) return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
<commit_before>import thread import json from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever() <commit_msg>Fix high cpu usage through sleep<commit_after>import thread import json import time from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer from game import Game def client_thread(game, conn, data): player = game.add_player(conn, data) while True: answer_data = game.wait_for_answer(player) if answer_data: conn.sendMessage(answer_data) request = conn.wait() print request # Thread loop ended conn.sendClose() class CartetsServer(WebSocket): def handleMessage(self): if not self.data: return {} try: data = json.loads(self.data.decode('utf-8')) value = data['action'] except Exception: data = {} value = '' if value == 'init': thread.start_new_thread(client_thread, (game, self, data)) # self.sendMessage(str(self.data)) return data def handleConnected(self): print self.address, 'connected' def handleClose(self): print self.address, 'closed' def wait(self): while True: data = self.handleMessage() if data: break else: time.sleep(0.5) return data game = Game() server = SimpleWebSocketServer('', 8080, CartetsServer) server.serveforever()
c00b673a03d1f52b0b92d0fec96a16ffc4985fd8
go/apps/urls.py
go/apps/urls.py
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), )
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbos.urls', namespace='jsbox')), )
Add template path and URLs.
Add template path and URLs.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), ) Add template path and URLs.
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbos.urls', namespace='jsbox')), )
<commit_before>from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), ) <commit_msg>Add template path and URLs.<commit_after>
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbos.urls', namespace='jsbox')), )
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), ) Add template path and URLs.from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbos.urls', namespace='jsbox')), )
<commit_before>from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), ) <commit_msg>Add template path and URLs.<commit_after>from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go.apps.bulk_message.urls', namespace='bulk_message')), url(r'^opt_out/', include('go.apps.opt_out.urls', namespace='opt_out')), url(r'^sequential_send/', include('go.apps.sequential_send.urls', namespace='sequential_send')), url(r'^subscription/', include('go.apps.subscription.urls', namespace='subscription')), url(r'^wikipedia_ussd/', include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')), url(r'^wikipedia_sms/', include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')), url(r'^jsbox/', include('go.apps.jsbos.urls', namespace='jsbox')), )
0137d5440f86a8f1424598beea4468ae8c68f985
demos/dlgr/demos/iterated_drawing/models.py
demos/dlgr/demos/iterated_drawing/models.py
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
Comment explaining random.choice() on 1-item list
Comment explaining random.choice() on 1-item list
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" }) Comment explaining random.choice() on 1-item list
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
<commit_before>from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" }) <commit_msg>Comment explaining random.choice() on 1-item list<commit_after>
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" }) Comment explaining random.choice() on 1-item listfrom dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
<commit_before>from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" }) <commit_msg>Comment explaining random.choice() on 1-item list<commit_after>from dallinger.nodes import Source import random import base64 import os import json class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = { "polymorphic_identity": "drawing_source" } def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = [ "owl.png", ] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = ( b"data:image/png;base64," + base64.b64encode(open(image_path, "rb").read()) ) return json.dumps({ "image": uri_encoded_image.decode('utf-8'), "sketch": u"" })
b5fc8db375e7273fb3b7cbb2318f57f141e25045
src/commoner/profiles/models.py
src/commoner/profiles/models.py
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p') homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p', blank=True, null=True) homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
Allow the photo to be blank.
Allow the photo to be blank.
Python
agpl-3.0
cc-archive/commoner,cc-archive/commoner
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p') homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) ) Allow the photo to be blank.
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p', blank=True, null=True) homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
<commit_before>import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p') homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) ) <commit_msg>Allow the photo to be blank.<commit_after>
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p', blank=True, null=True) homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p') homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) ) Allow the photo to be blank.import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p', blank=True, null=True) homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
<commit_before>import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p') homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) ) <commit_msg>Allow the photo to be blank.<commit_after>import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class CommonerProfile(models.Model): user = models.ForeignKey(User, unique=True) nickname = models.CharField(max_length=255, blank=True) photo = models.ImageField(upload_to='p', blank=True, null=True) homepage = models.URLField(max_length=255, blank=True) location = models.CharField(max_length=255, blank=True) story = models.TextField(blank=True) def __unicode__(self): if self.nickname: return u"%s (%s)" % (self.user.username, self.nickname) return self.user.username def display_name(self): return self.nickname or self.user.username def get_absolute_url(self, request=None): if request is None: return reverse('profile_view', args=(self.user.username, ) ) else: return urlparse.urljoin( getBaseURL(request), reverse('profile_view', args=(self.user.username, ) ) )
fc94ac89d2f602c381f4c882ec963995f3ce3043
cla_frontend/apps/core/context_processors.py
cla_frontend/apps/core/context_processors.py
from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '' } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context
from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '', 'socketio_server_url': settings.SOCKETIO_SERVER_URL } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context
Make socketio server url a global context variable in Django
Make socketio server url a global context variable in Django
Python
mit
ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend
from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '' } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context Make socketio server url a global context variable in Django
from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '', 'socketio_server_url': settings.SOCKETIO_SERVER_URL } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context
<commit_before>from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '' } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context <commit_msg>Make socketio server url a global context variable in Django<commit_after>
from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '', 'socketio_server_url': settings.SOCKETIO_SERVER_URL } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context
from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '' } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context Make socketio server url a global context variable in Djangofrom django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '', 'socketio_server_url': settings.SOCKETIO_SERVER_URL } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context
<commit_before>from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '' } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context <commit_msg>Make socketio server url a global context variable in Django<commit_after>from django.conf import settings def globals(request): context = { 'app_title': 'Civil Legal Advice', 'proposition_title': 'Civil Legal Advice', 'phase': 'alpha', 'product_type': 'service', 'feedback_url': '#', 'ga_id': '', 'raven_config_site': settings.RAVEN_CONFIG['site'] or '', 'socketio_server_url': settings.SOCKETIO_SERVER_URL } if hasattr(request, 'zone') and request.zone: context['app_base_template'] = '%s/base.html' % request.zone['name'] context['zone'] = request.zone return context
552996b1c135d17f14752e098e1d305d2971611a
follower/fetch_timeline.py
follower/fetch_timeline.py
#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter")
#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter")
Add empty line after imports
[R] Add empty line after imports
Python
mit
suchkultur/trumpeltier
#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter") [R] Add empty line after imports
#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter")
<commit_before>#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter") <commit_msg>[R] Add empty line after imports<commit_after>
#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter")
#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter") [R] Add empty line after imports#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter")
<commit_before>#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter") <commit_msg>[R] Add empty line after imports<commit_after>#!/usr/bin/env python3 """ Follow the white house rabbit This fetches tweets from an user and prints the full json output from the api. """ import os import sys import json from twython import Twython from twython import TwythonError CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') CONSUMER_SECRET_KEY = os.environ.get('TWITTER_CONSUMER_SECRET_KEY') ACCESS_TOKEN = os.environ.get('TWITTER_ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') def query(screen_name='realDonaldTrump'): # Requires Authentication as of Twitter API v1.1 twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET_KEY, \ ACCESS_TOKEN, ACCESS_TOKEN_SECRET) try: user_timeline = twitter.get_user_timeline(screen_name=screen_name, count=200) except TwythonError as e: print(e) print(json.dumps(user_timeline)) if __name__ == '__main__': try: query(sys.argv[1]) except IndexError as e: print("Missing Twitter user name as first parameter")
bbc0b5df6bd43588f3c85c1031d3efd4eb1ec6a7
tests/panels/test_cache.py
tests/panels/test_cache.py
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 5) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 4) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
Fix the number of cache calls expected in a test.
Fix the number of cache calls expected in a test.
Python
bsd-3-clause
spookylukey/django-debug-toolbar,megcunningham/django-debug-toolbar,spookylukey/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,sidja/django-debug-toolbar,peap/django-debug-toolbar,calvinpy/django-debug-toolbar,sidja/django-debug-toolbar,calvinpy/django-debug-toolbar,megcunningham/django-debug-toolbar,pevzi/django-debug-toolbar,seperman/django-debug-toolbar,stored/django-debug-toolbar,calvinpy/django-debug-toolbar,jazzband/django-debug-toolbar,Endika/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,pevzi/django-debug-toolbar,seperman/django-debug-toolbar,tim-schilling/django-debug-toolbar,peap/django-debug-toolbar,jazzband/django-debug-toolbar,guilhermetavares/django-debug-toolbar,spookylukey/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,megcunningham/django-debug-toolbar,tim-schilling/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,jazzband/django-debug-toolbar,barseghyanartur/django-debug-toolbar,stored/django-debug-toolbar,guilhermetavares/django-debug-toolbar,Endika/django-debug-toolbar,peap/django-debug-toolbar,pevzi/django-debug-toolbar,ChristosChristofidis/django-debug-toolbar,sidja/django-debug-toolbar,stored/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,barseghyanartur/django-debug-toolbar,barseghyanartur/django-debug-toolbar,tim-schilling/django-debug-toolbar,guilhermetavares/django-debug-toolbar,seperman/django-debug-toolbar,Endika/django-debug-toolbar
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 5) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2) Fix the number of cache calls expected in a test.
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 4) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
<commit_before># coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 5) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2) <commit_msg>Fix the number of cache calls expected in a test.<commit_after>
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 4) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 5) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2) Fix the number of cache calls expected in a test.# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 4) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
<commit_before># coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 5) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2) <commit_msg>Fix the number of cache calls expected in a test.<commit_after># coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 4) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)