commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
679ea714796fcf6f11c0f14301f95a37914fd653
setup.py
setup.py
from setuptools import setup, find_packages from hdx.utilities.path import script_dir_plus_file requirements = ['ckanapi', 'colorlog', 'ndg-httpsclient', 'pyasn1', 'pyOpenSSL', 'pyaml', 'requests', 'scraperwiki', 'typing' ] version_file = open(script_dir_plus_file('version.txt', requirements)) version = version_file.read().strip() setup( name='hdx-python-api', version=version, packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']), url='http://data.humdata.org/', license='PSF', author='Michael Rans', author_email='rans@email.com', description='HDX Python Library', install_requires=requirements, package_data={ # If any package contains *.yml files, include them: '': ['*.yml'], }, )
from setuptools import setup, find_packages from hdx.utilities.path import script_dir_plus_file def get_version(): version_file = open(script_dir_plus_file('version.txt', get_version)) return version_file.read().strip() requirements = ['ckanapi', 'colorlog', 'ndg-httpsclient', 'pyasn1', 'pyOpenSSL', 'pyaml', 'requests', 'scraperwiki', 'typing' ] setup( name='hdx-python-api', version=get_version(), packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']), url='http://data.humdata.org/', license='PSF', author='Michael Rans', author_email='rans@email.com', description='HDX Python Library', install_requires=requirements, package_data={ # If any package contains *.yml files, include them: '': ['*.yml'], }, )
Make download work using url filename Add user agent string
Make download work using url filename Add user agent string
Python
mit
OCHA-DAP/hdx-python-api
--- +++ @@ -1,6 +1,11 @@ from setuptools import setup, find_packages from hdx.utilities.path import script_dir_plus_file + + +def get_version(): + version_file = open(script_dir_plus_file('version.txt', get_version)) + return version_file.read().strip() requirements = ['ckanapi', 'colorlog', @@ -13,12 +18,9 @@ 'typing' ] -version_file = open(script_dir_plus_file('version.txt', requirements)) -version = version_file.read().strip() - setup( name='hdx-python-api', - version=version, + version=get_version(), packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']), url='http://data.humdata.org/', license='PSF',
a9c8d3331451deaaa6b156d73df951021705fd71
setup.py
setup.py
import setuptools REQUIREMENTS = [ "docopt==0.6.1", "feedparser==5.1.3", "jabberbot==0.15", "xmpppy==0.5.0rc1", ] if __name__ == "__main__": setuptools.setup( name="dudebot", version="0.0.6", author="Sujay Mansingh", author_email="sujay.mansingh@gmail.com", packages=setuptools.find_packages(), package_data={ "dudebot": ["README.rst"] }, scripts=[], url="https://github.com/sujaymansingh/dudebot", license="LICENSE.txt", description="A really simple framework for chatroom bots", long_description=open("README.rst").read(), install_requires=REQUIREMENTS )
import setuptools REQUIREMENTS = [ "docopt==0.6.1", "feedparser==5.1.3", "jabberbot==0.15", "xmpppy==0.5.0rc1", ] if __name__ == "__main__": setuptools.setup( name="dudebot", version="0.0.6", author="Sujay Mansingh", author_email="sujay.mansingh@gmail.com", packages=setuptools.find_packages(), package_data={ "dudebot": ["README.rst"] }, scripts=[], url="https://github.com/sujaymansingh/dudebot", license="LICENSE.txt", description="A really simple framework for chatroom bots", long_description="View the github page (https://github.com/sujaymansingh/dudebot) for more details.", install_requires=REQUIREMENTS )
Use a placeholder string instead of a README.
Use a placeholder string instead of a README. Until I work out why README.rst isn't being included, use this.
Python
bsd-2-clause
sujaymansingh/dudebot
--- +++ @@ -21,6 +21,6 @@ url="https://github.com/sujaymansingh/dudebot", license="LICENSE.txt", description="A really simple framework for chatroom bots", - long_description=open("README.rst").read(), + long_description="View the github page (https://github.com/sujaymansingh/dudebot) for more details.", install_requires=REQUIREMENTS )
8651c367d05798323e33066c520cf8e988937a78
setup.py
setup.py
#!/usr/bin/env python import sys, os sys.path.insert(0, os.path.join(os.getcwd(),'lib')) from distutils.core import setup import simpletal setup(name="SimpleTAL", version= simpletal.__version__, description="SimpleTAL is a stand alone Python implementation of the TAL, TALES and METAL specifications used in Zope to power HTML and XML templates.", author="Colin Stewart", author_email="colin@owlfish.com", url="http://www.owlfish.com/software/simpleTAL/index.html", packages=[ 'simpletal', ], package_dir = {'': 'lib'}, )
#!/usr/bin/env python import sys, os sys.path.insert(0, os.path.join(os.getcwd(),'lib')) from distutils.core import setup import simpletal setup(name="SimpleTAL", version= simpletal.__version__, description="SimpleTAL is a stand alone Python implementation of the TAL, TALES and METAL specifications used in Zope to power HTML and XML templates.", author="Colin Stewart", author_email="colin@owlfish.com", url="http://www.owlfish.com/software/simpleTAL/index.html", download_url="http://www.owlfish.com/software/simpleTAL/download.html", packages=[ 'simpletal', ], package_dir = {'': 'lib'}, )
Add download_url so the package can be located from PyPI.
Add download_url so the package can be located from PyPI.
Python
bsd-3-clause
g2p/SimpleTAL
--- +++ @@ -12,6 +12,7 @@ author="Colin Stewart", author_email="colin@owlfish.com", url="http://www.owlfish.com/software/simpleTAL/index.html", + download_url="http://www.owlfish.com/software/simpleTAL/download.html", packages=[ 'simpletal', ],
33f28ad9ba7c6eeec1f85be43863ea4c7b04128f
setup.py
setup.py
from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: General', ], keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', 'pegmatcher', ], )
from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: General', ], keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', 'pegmatcher', ], )
Add lpeg.c to _ppeg.c dependencies
Add lpeg.c to _ppeg.c dependencies
Python
mit
moreati/ppeg,moreati/ppeg
--- +++ @@ -20,7 +20,7 @@ keywords='parsing peg grammar regex', - ext_modules = [Extension('_ppeg', ['_ppeg.c']), + ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl',
e6e25b3d872d4812df8be0655eb582a301dfb51c
setup.py
setup.py
#!/usr/bin/env python """ Created by: Lee Bergstrand (2018) Description: Setup for installing pygenprop. """ from setuptools import setup setup(name='pygenprop', version='0.5', description='A python library for programmatic usage of EBI InterPro Genome Properties.', url='https://github.com/Micromeda/pygenprop', author='Lee Bergstrand', author_email='lee.h.bergstrand@gmail.com', license='Apache License 2.0', packages=['pygenprop'], install_requires=[ 'Cython>=0.29', 'pandas>=0.23.4', ], zip_safe=False)
#!/usr/bin/env python """ Created by: Lee Bergstrand (2018) Description: Setup for installing pygenprop. """ from setuptools import setup setup(name='pygenprop', version='0.5', description='A python library for programmatic usage of EBI InterPro Genome Properties.', url='https://github.com/Micromeda/pygenprop', author='Lee Bergstrand', author_email='lee.h.bergstrand@gmail.com', license='Apache License 2.0', packages=['pygenprop'], install_requires=[ 'Cython>=0.29', 'pandas>=0.23.4', 'sqlalchemy>=1.2.18' ], zip_safe=False)
Add sqlalchemy as a dependancy.
Add sqlalchemy as a dependancy.
Python
apache-2.0
LeeBergstrand/pygenprop
--- +++ @@ -19,5 +19,6 @@ install_requires=[ 'Cython>=0.29', 'pandas>=0.23.4', + 'sqlalchemy>=1.2.18' ], zip_safe=False)
6c1f071876334b12f0c2f753efd42b0cd7bea135
setup.py
setup.py
# coding=utf-8 # Copyright 2022 The Balloon Learning Environment Authors. # # 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. """Setup file for installing the BLE.""" import setuptools setuptools.setup( name='balloon_learning_environment', version='0.1.1', packages=setuptools.find_packages(), install_requires=[ 'absl-py', 'dopamine-rl >= 4.0.0', 'flax', 'gcsfs', 'gin-config', 'gym', 'opensimplex <= 0.3.0', 's2sphere', 'scikit-learn', 'tensorflow', 'tensorflow-datasets >= 4.4.0', 'tensorflow-probability', 'transitions', 'zarr', ], package_data={ '': ['*.msgpack', '*.pb', '*.gin'], }, python_requires='>=3.7', )
# coding=utf-8 # Copyright 2022 The Balloon Learning Environment Authors. # # 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. """Setup file for installing the BLE.""" import pathlib import setuptools current_directory = pathlib.Path(__file__).parent description = (current_directory / 'README.md').read_text() setuptools.setup( name='balloon_learning_environment', long_description=description, long_description_content_type='text/markdown', version='0.1.1', packages=setuptools.find_packages(), install_requires=[ 'absl-py', 'dopamine-rl >= 4.0.0', 'flax', 'gcsfs', 'gin-config', 'gym', 'opensimplex <= 0.3.0', 's2sphere', 'scikit-learn', 'tensorflow', 'tensorflow-datasets >= 4.4.0', 'tensorflow-probability', 'transitions', 'zarr', ], package_data={ '': ['*.msgpack', '*.pb', '*.gin'], }, python_requires='>=3.7', )
Include readme description in pypi.
Include readme description in pypi. PiperOrigin-RevId: 426375123
Python
apache-2.0
google/balloon-learning-environment
--- +++ @@ -14,10 +14,16 @@ # limitations under the License. """Setup file for installing the BLE.""" +import pathlib import setuptools + +current_directory = pathlib.Path(__file__).parent +description = (current_directory / 'README.md').read_text() setuptools.setup( name='balloon_learning_environment', + long_description=description, + long_description_content_type='text/markdown', version='0.1.1', packages=setuptools.find_packages(), install_requires=[
93bcfe8d79e5835649239840ec3d4fd63a3a2567
setup.py
setup.py
import os import sys from setuptools import setup from setuptools.dist import Distribution # Do this first, so setuptools installs cffi immediately before trying to do # the below import Distribution(dict(setup_requires='cffi')) # Set this so the imagemagick flags will get sniffed out. os.environ['SANPERA_BUILD'] = 'yes' from sanpera._api import ffi # Depend on backported libraries only if they don't already exist in the stdlib BACKPORTS = [] if sys.version_info < (3, 4): BACKPORTS.append('enum34') setup( name='sanpera', version='0.2pre', description='Image manipulation library, powered by ImageMagick', author='Eevee', author_email='eevee.sanpera@veekun.com', url='http://eevee.github.com/sanpera/', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Topic :: Software Development :: Libraries', ], packages=['sanpera'], package_data={ 'sanpera': ['_api.c', '_api.h'], }, install_requires=BACKPORTS + [ 'cffi', ], ext_modules=[ffi.verifier.get_extension()], ext_package='sanpera', )
import os import sys from setuptools import setup from setuptools.dist import Distribution # Do this first, so setuptools installs cffi immediately before trying to do # the below import Distribution(dict(setup_requires='cffi')) # Set this so the imagemagick flags will get sniffed out. os.environ['SANPERA_BUILD'] = 'yes' from sanpera._api import ffi # Depend on backported libraries only if they don't already exist in the stdlib BACKPORTS = [] if sys.version_info < (3, 4): BACKPORTS.append('enum34') setup( name='sanpera', version='0.2.dev1', description='Image manipulation library, powered by ImageMagick', author='Eevee', author_email='eevee.sanpera@veekun.com', url='http://eevee.github.com/sanpera/', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Topic :: Software Development :: Libraries', ], packages=['sanpera'], package_data={ 'sanpera': ['_api.c', '_api.h'], }, install_requires=BACKPORTS + [ 'cffi', ], ext_modules=[ffi.verifier.get_extension()], ext_package='sanpera', )
Make a PEP-386-compatible version number.
Make a PEP-386-compatible version number.
Python
isc
eevee/sanpera,eevee/sanpera
--- +++ @@ -21,7 +21,7 @@ setup( name='sanpera', - version='0.2pre', + version='0.2.dev1', description='Image manipulation library, powered by ImageMagick', author='Eevee', author_email='eevee.sanpera@veekun.com',
aca0e79216cc1e87bf70dd4cae042de8155f9893
setup.py
setup.py
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='consultants@pdx.edu', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'cas': [ 'django-cas-client>=1.2.0', ], 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=1.0.2', ], 'dev': [ 'django>=1.7,<1.9', 'flake8', 'ldap3', 'mock', 'model_mommy', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='consultants@pdx.edu', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'cas': [ 'django-cas-client>=1.2.0', ], 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=1.0.3', ], 'dev': [ 'django>=1.7,<1.9', 'flake8', 'ldap3', 'mock', 'model_mommy', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Upgrade ldap3 1.0.2 => 1.0.3
Upgrade ldap3 1.0.2 => 1.0.3
Python
mit
wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,PSU-OIT-ARC/django-arcutils
--- +++ @@ -32,7 +32,7 @@ ], 'ldap': [ 'certifi>=2015.11.20.1', - 'ldap3>=1.0.2', + 'ldap3>=1.0.3', ], 'dev': [ 'django>=1.7,<1.9',
2e56f7674191aca7a03ede8586f2e18abb617a0b
polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py
polling_stations/apps/addressbase/management/commands/import_cleaned_addresses.py
import os import glob from django.apps import apps from django.db import connection from django.core.management.base import BaseCommand class Command(BaseCommand): """ Turn off auto system check for all apps We will maunally run system checks only for the 'addressbase' and 'pollingstations' apps """ requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'cleaned_ab_path', help='The path to the folder containing the cleaned AddressBase CSVs' ) def handle(self, *args, **kwargs): """ Manually run system checks for the 'addressbase' and 'pollingstations' apps Management commands can ignore checks that only apply to the apps supporting the website part of the project """ self.check([ apps.get_app_config('addressbase'), apps.get_app_config('pollingstations') ]) glob_str = os.path.join( kwargs['cleaned_ab_path'], "*_cleaned.csv" ) for cleaned_file_path in glob.glob(glob_str): cleaned_file_path = os.path.abspath(cleaned_file_path) print(cleaned_file_path) cursor = connection.cursor() cursor.execute(""" COPY addressbase_address (UPRN,address,postcode,location) FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); """.format(cleaned_file_path))
import os import glob from django.apps import apps from django.db import connection from django.core.management.base import BaseCommand class Command(BaseCommand): """ Turn off auto system check for all apps We will maunally run system checks only for the 'addressbase' and 'pollingstations' apps """ requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'cleaned_ab_path', help='The path to the folder containing the cleaned AddressBase CSVs' ) def handle(self, *args, **kwargs): """ Manually run system checks for the 'addressbase' and 'pollingstations' apps Management commands can ignore checks that only apply to the apps supporting the website part of the project """ self.check([ apps.get_app_config('addressbase'), apps.get_app_config('pollingstations') ]) cursor = connection.cursor() print("clearing existing data..") cursor.execute("TRUNCATE TABLE addressbase_address;") cleaned_file_path = os.path.abspath(os.path.join( kwargs['cleaned_ab_path'], "addressbase_cleaned.csv" )) print("importing from %s.." % (cleaned_file_path)) cursor.execute(""" COPY addressbase_address (UPRN,address,postcode,location) FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); """.format(cleaned_file_path)) print("...done")
Truncate address table before import, only import from one file
Truncate address table before import, only import from one file
Python
bsd-3-clause
chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations
--- +++ @@ -33,16 +33,20 @@ apps.get_app_config('pollingstations') ]) - glob_str = os.path.join( + cursor = connection.cursor() + print("clearing existing data..") + cursor.execute("TRUNCATE TABLE addressbase_address;") + + cleaned_file_path = os.path.abspath(os.path.join( kwargs['cleaned_ab_path'], - "*_cleaned.csv" - ) - for cleaned_file_path in glob.glob(glob_str): - cleaned_file_path = os.path.abspath(cleaned_file_path) - print(cleaned_file_path) - cursor = connection.cursor() + "addressbase_cleaned.csv" + )) - cursor.execute(""" - COPY addressbase_address (UPRN,address,postcode,location) - FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); - """.format(cleaned_file_path)) + print("importing from %s.." % (cleaned_file_path)) + + cursor.execute(""" + COPY addressbase_address (UPRN,address,postcode,location) + FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); + """.format(cleaned_file_path)) + + print("...done")
eeb9f4c01bba1df8b3946a319c5d904711ee4a18
setup.py
setup.py
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.23', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.24', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Update requests requirement from <2.23,>=2.4.2 to >=2.4.2,<2.24
Update requests requirement from <2.23,>=2.4.2 to >=2.4.2,<2.24 Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version. - [Release notes](https://github.com/psf/requests/releases) - [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md) - [Commits](https://github.com/psf/requests/compare/v2.4.2...v2.23.0) Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
Python
apache-2.0
zooniverse/panoptes-python-client
--- +++ @@ -9,7 +9,7 @@ packages=find_packages(), include_package_data=True, install_requires=[ - 'requests>=2.4.2,<2.23', + 'requests>=2.4.2,<2.24', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7',
6d1ba5e05c68dfe03676cd5a572bdf9107c18cb5
setup.py
setup.py
from os.path import abspath, dirname, join, normpath from setuptools import find_packages, setup setup( # Basic package information: name = 'django-twilio', version = '0.2', packages = find_packages(), # Packaging options: zip_safe = False, include_package_data = True, # Package dependencies: install_requires = ['twilio==3.3.6', 'Django>=1.3.1'], # Metadata for PyPI: author = 'Randall Degges', author_email = 'rdegges@gmail.com', license = 'UNLICENSE', url = 'http://twilio.com/', keywords = 'twilio telephony call phone voip sms', description = 'A simple library for building twilio-powered Django webapps.', long_description = open(normpath(join(dirname(abspath(__file__)), 'README.md'))).read() )
from os.path import abspath, dirname, join, normpath from setuptools import find_packages, setup setup( # Basic package information: name = 'django-twilio', version = '0.2', packages = find_packages(), # Packaging options: zip_safe = False, include_package_data = True, # Package dependencies: install_requires = ['twilio>=3.3.6', 'Django>=1.3.1'], # Metadata for PyPI: author = 'Randall Degges', author_email = 'rdegges@gmail.com', license = 'UNLICENSE', url = 'http://twilio.com/', keywords = 'twilio telephony call phone voip sms', description = 'A simple library for building twilio-powered Django webapps.', long_description = open(normpath(join(dirname(abspath(__file__)), 'README.md'))).read() )
Allow use latest version on twilio-python library.
Allow use latest version on twilio-python library.
Python
unlicense
rdegges/django-twilio,aditweb/django-twilio
--- +++ @@ -15,7 +15,7 @@ include_package_data = True, # Package dependencies: - install_requires = ['twilio==3.3.6', 'Django>=1.3.1'], + install_requires = ['twilio>=3.3.6', 'Django>=1.3.1'], # Metadata for PyPI: author = 'Randall Degges',
3ebcbafdaff070b2157b5fb065da9a950ba58d1c
django_rq/settings.py
django_rq/settings.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .queues import get_unique_connection_configs SHOW_ADMIN_LINK = getattr(settings, 'RQ_SHOW_ADMIN_LINK', False) QUEUES = getattr(settings, 'RQ_QUEUES', None) if QUEUES is None: raise ImproperlyConfigured("You have to define RQ_QUEUES in settings.py") NAME = getattr(settings, 'RQ_NAME', 'default') BURST = getattr(settings, 'RQ_BURST', False) # All queues in list format so we can get them by index, includes failed queues QUEUES_LIST = [] for key, value in QUEUES.items(): QUEUES_LIST.append({'name': key, 'connection_config': value}) for config in get_unique_connection_configs(): QUEUES_LIST.append({'name': 'failed', 'connection_config': config})
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .queues import get_unique_connection_configs SHOW_ADMIN_LINK = getattr(settings, 'RQ_SHOW_ADMIN_LINK', False) QUEUES = getattr(settings, 'RQ_QUEUES', None) if QUEUES is None: raise ImproperlyConfigured("You have to define RQ_QUEUES in settings.py") NAME = getattr(settings, 'RQ_NAME', 'default') BURST = getattr(settings, 'RQ_BURST', False) # All queues in list format so we can get them by index, includes failed queues QUEUES_LIST = [] for key, value in sorted(QUEUES.items()): QUEUES_LIST.append({'name': key, 'connection_config': value}) for config in get_unique_connection_configs(): QUEUES_LIST.append({'name': 'failed', 'connection_config': config})
Sort the queues by name, so that they are deterministic across instances of `django_rq`.
Sort the queues by name, so that they are deterministic across instances of `django_rq`.
Python
mit
sbussetti/django-rq,lechup/django-rq,mjec/django-rq,lechup/django-rq,mjec/django-rq,1024inc/django-rq,ryanisnan/django-rq,ui/django-rq,sbussetti/django-rq,viaregio/django-rq,ui/django-rq,viaregio/django-rq,ryanisnan/django-rq,1024inc/django-rq
--- +++ @@ -13,7 +13,7 @@ # All queues in list format so we can get them by index, includes failed queues QUEUES_LIST = [] -for key, value in QUEUES.items(): +for key, value in sorted(QUEUES.items()): QUEUES_LIST.append({'name': key, 'connection_config': value}) for config in get_unique_connection_configs(): QUEUES_LIST.append({'name': 'failed', 'connection_config': config})
642f3109cb9fb6179d51de7a7d5781044ff6be3b
satori.core/satori/core/__init__.py
satori.core/satori/core/__init__.py
# vim:ts=4:sts=4:sw=4:expandtab """The core of the system. Manages the database and operational logic. Functionality is exposed over Thrift. """ import os def manage(): from django.core.management import execute_manager import satori.core.settings # HACK import django.core.management old_fmm = django.core.management.find_management_module def find_management_module(app_name): if app_name == 'satori.core': return os.path.join(os.path.dirname(__file__), 'management') else: return old_fmm(app_name) django.core.management.find_management_module = find_management_module # END OF HACK execute_manager(satori.core.settings)
# vim:ts=4:sts=4:sw=4:expandtab """The core of the system. Manages the database and operational logic. Functionality is exposed over Thrift. """ import sys import os def manage(): from django.core.management import execute_manager settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'satori.core.settings') __import__(settings_module_name) settings_module = sys.modules[settings_module_name] # HACK import django.core.management old_fmm = django.core.management.find_management_module def find_management_module(app_name): if app_name == 'satori.core': return os.path.join(os.path.dirname(__file__), 'management') else: return old_fmm(app_name) django.core.management.find_management_module = find_management_module # END OF HACK execute_manager(settings_module)
Allow specification of custom settings module using DJANGO_SETTINGS_MODULE environment variable.
Allow specification of custom settings module using DJANGO_SETTINGS_MODULE environment variable.
Python
mit
zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori
--- +++ @@ -3,12 +3,16 @@ exposed over Thrift. """ +import sys import os def manage(): from django.core.management import execute_manager - import satori.core.settings + + settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'satori.core.settings') + __import__(settings_module_name) + settings_module = sys.modules[settings_module_name] # HACK import django.core.management @@ -24,5 +28,5 @@ django.core.management.find_management_module = find_management_module # END OF HACK - execute_manager(satori.core.settings) + execute_manager(settings_module)
6054f2a103639dc1da51ddd4d63777a9d728a9ba
hr/admin.py
hr/admin.py
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): return len(obj.recommendation_set.all()) recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin)
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): return obj.recommendation_set.all().count() recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') search_fields = ('value') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin)
Add searchfield Blacklists, and use count() for recommendation count
Add searchfield Blacklists, and use count() for recommendation count
Python
bsd-3-clause
nikdoof/test-auth
--- +++ @@ -9,7 +9,7 @@ list_filter = ('status',) def recommendations(self, obj): - return len(obj.recommendation_set.all()) + return obj.recommendation_set.all().count() recommendations.short_description = '# of Recommendations' @@ -33,6 +33,7 @@ class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') + search_fields = ('value') admin.site.register(Blacklist, BlacklistAdmin)
79f1f198820f74a62501fc572b2f1162eafede2e
tests.py
tests.py
#!/usr/bin/env python """Test UW Menu Flask application.""" import unittest from uwmenu import app, attach_filters class UWMenuTestCase(unittest.TestCase): def setUp(self): attach_filters() app.config['TESTING'] = True self.app = app.test_client() def tearDown(self): pass def test_menu_pageload(self): """Ensure description on menu page is present.""" rv = self.app.get('/') assert 'Weekly menus for the University of Waterloo\'s on-campus eateries.' in rv.data def test_about_pageload(self): """Ensure attribution on about page is present.""" rv = self.app.get('/') assert 'This is an open source application available on GitHub' in rv.data if __name__ == "__main__": unittest.main()
#!/usr/bin/env python """Test UW Menu Flask application.""" import json import unittest from uwmenu import app, attach_filters class UWMenuTestCase(unittest.TestCase): def setUp(self): attach_filters() app.config['TESTING'] = True self.app = app.test_client() def tearDown(self): pass def test_menu_pageload(self): """Ensure description on menu page is present.""" rv = self.app.get('/') assert 'Weekly menus for the University of Waterloo\'s on-campus eateries.' in rv.data def test_about_pageload(self): """Ensure attribution on about page is present.""" rv = self.app.get('/') assert 'This is an open source application available on GitHub' in rv.data def test_api_endpoint(self): """Ensure API endpoint returns valid JSON.""" rv = self.app.get('/menu/') assert json.loads(rv.data) if __name__ == "__main__": unittest.main()
Add test for API endpoint
Add test for API endpoint
Python
mit
alykhank/FoodMenu,alykhank/FoodMenu,alykhank/FoodMenu
--- +++ @@ -2,6 +2,7 @@ """Test UW Menu Flask application.""" +import json import unittest from uwmenu import app, attach_filters @@ -27,6 +28,11 @@ rv = self.app.get('/') assert 'This is an open source application available on GitHub' in rv.data + def test_api_endpoint(self): + """Ensure API endpoint returns valid JSON.""" + rv = self.app.get('/menu/') + assert json.loads(rv.data) + if __name__ == "__main__": unittest.main()
e7f923488ebf589aa78f7dc37792ffba3fffd2a3
pyinfra_kubernetes/defaults.py
pyinfra_kubernetes/defaults.py
DEFAULTS = { # Install 'kubernetes_version': None, # must be provided 'kubernetes_download_base_url': 'https://dl.k8s.io', 'kubernetes_install_dir': '/usr/local/kubernetes', 'kubernetes_bin_dir': '/usr/local/bin', 'kubernetes_conf_dir': '/etc/kubernetes', # Config 'kubernetes_service_cidr': None, # must be provided 'kubernetes_master_url': 'http://127.0.0.1', }
DEFAULTS = { # Install 'kubernetes_version': None, # must be provided 'kubernetes_download_base_url': 'https://dl.k8s.io', 'kubernetes_install_dir': '/usr/local/kubernetes', 'kubernetes_bin_dir': '/usr/local/bin', 'kubernetes_conf_dir': '/etc/kubernetes', # Config 'kubernetes_service_cidr': None, # must be provided # API server URL for master components (controller-manager, scheduler) 'kubernetes_master_url': 'http://127.0.0.1', }
Update comment about default data.
Update comment about default data.
Python
mit
EDITD/pyinfra-kubernetes,EDITD/pyinfra-kubernetes
--- +++ @@ -8,5 +8,7 @@ # Config 'kubernetes_service_cidr': None, # must be provided + + # API server URL for master components (controller-manager, scheduler) 'kubernetes_master_url': 'http://127.0.0.1', }
3f7ccf17528b91b0b1145ad81c3f5aad68085aa5
varify/variants/translators.py
varify/variants/translators.py
from avocado.query.translators import Translator, registry from modeltree.tree import trees class AllowNullsTranslator(Translator): """For data sources that only apply to SNPs, this translator ensures only SNPs are filtered down and not other types of variants. """ def translate(self, field, roperator, rvalue, tree, **kwargs): output = super(AllowNullsTranslator, self).translate( field, roperator, rvalue, tree, **kwargs) # Create a null condition for this field null_condition = trees[tree].query_condition( field.field, 'isnull', True) # Allow the null condition output['query_modifiers']['condition'] |= null_condition return output registry.register(AllowNullsTranslator, 'Allow Nulls')
from avocado.query.translators import Translator, registry from modeltree.tree import trees class AllowNullsTranslator(Translator): """For data sources that only apply to SNPs, this translator ensures only SNPs are filtered down and not other types of variants. """ def translate(self, field, roperator, rvalue, tree, **kwargs): output = super(AllowNullsTranslator, self).translate( field, roperator, rvalue, tree, **kwargs) # We are excluding nulls in the case of range, gt, and gte operators. # If we did not do this, then null values would be included all the # time which would be confusing, especially then they are included # for both lt and gt queries as it appears nulls are simultaneously # 0 and infinity. if roperator not in ('range', 'gt', 'gte'): # Create a null condition for this field null_condition = trees[tree].query_condition( field.field, 'isnull', True) # Allow the null condition output['query_modifiers']['condition'] |= null_condition return output registry.register(AllowNullsTranslator, 'Allow Nulls')
Exclude nulls in translator when operator is range, gt, gte
Exclude nulls in translator when operator is range, gt, gte Previously, nulls were included in all cases making it appear that null was but 0 and infinity. Now, null is effectively treated as 0. Signed-off-by: Don Naegely <e690a32c1e2176a2bfface09e204830e1b5491e3@gmail.com>
Python
bsd-2-clause
chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify,chop-dbhi/varify
--- +++ @@ -9,11 +9,19 @@ def translate(self, field, roperator, rvalue, tree, **kwargs): output = super(AllowNullsTranslator, self).translate( field, roperator, rvalue, tree, **kwargs) - # Create a null condition for this field - null_condition = trees[tree].query_condition( - field.field, 'isnull', True) - # Allow the null condition - output['query_modifiers']['condition'] |= null_condition + + # We are excluding nulls in the case of range, gt, and gte operators. + # If we did not do this, then null values would be included all the + # time which would be confusing, especially then they are included + # for both lt and gt queries as it appears nulls are simultaneously + # 0 and infinity. + if roperator not in ('range', 'gt', 'gte'): + # Create a null condition for this field + null_condition = trees[tree].query_condition( + field.field, 'isnull', True) + # Allow the null condition + output['query_modifiers']['condition'] |= null_condition + return output
cd4534ee267bd06944dcce1fe40ee662351eb114
test/python-swig-test.py
test/python-swig-test.py
#!/usr/bin/env python3 import deepstream version = deepstream.version_to_string() if deepstream.version_to_string() != "0.1.0": raise Exception("Version mismatch; expected 0.0.1, got {}".format(version))
#!/usr/bin/env python3 import deepstream version = deepstream.version_to_string() if deepstream.version_to_string() != "0.1.0": raise ValueError("Version mismatch; expected 0.0.1, got {}".format(version))
Use ValueError for Swig Python test
Use ValueError for Swig Python test
Python
apache-2.0
deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp
--- +++ @@ -5,7 +5,7 @@ version = deepstream.version_to_string() if deepstream.version_to_string() != "0.1.0": - raise Exception("Version mismatch; expected 0.0.1, got {}".format(version)) + raise ValueError("Version mismatch; expected 0.0.1, got {}".format(version))
02548b44a3b5de203e4a82693288ebae4037d90e
jug/__init__.py
jug/__init__.py
# -*- coding: utf-8 -*- # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # Copyright (C) 2008-2010, Luis Pedro Coelho <lpc@cmu.edu> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division from .task import TaskGenerator, Task from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.0'
# -*- coding: utf-8 -*- # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # Copyright (C) 2008-2010, Luis Pedro Coelho <lpc@cmu.edu> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division from .task import TaskGenerator, Task, value from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.9-git'
Add value() to jug namespace
Add value() to jug namespace The jug namespace might need some attention.
Python
mit
unode/jug,luispedro/jug,luispedro/jug,unode/jug
--- +++ @@ -21,9 +21,9 @@ # THE SOFTWARE. from __future__ import division -from .task import TaskGenerator, Task +from .task import TaskGenerator, Task, value from .jug import init from .backends import file_store, dict_store, redis_store -__version__ = '0.5.0' +__version__ = '0.5.9-git'
e57793b654ac29becb358832d83d4dea78dc1a50
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
whats_fresh/whats_fresh_api/tests/views/entry/test_list_products.py
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()])
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()]))
Rebase off develop, add missing parenthesis
Rebase off develop, add missing parenthesis
Python
apache-2.0
iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api
--- +++ @@ -33,5 +33,4 @@ product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), - sort([prep.name for prep in product.preparations.all()]) - + sort([prep.name for prep in product.preparations.all()]))
ee4faf2e1a81fe400d818a5a7337cf562c968d2e
quantecon/common_messages.py
quantecon/common_messages.py
""" Warnings Module =============== Contains a collection of warning messages for consistent package wide notifications """ #-Numba-# numba_import_fail_message = "Numba import failed. Falling back to non-optimized routine."
""" Warnings Module =============== Contains a collection of warning messages for consistent package wide notifications """ #-Numba-# numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n" "This will reduce the overall performance of this package.\n" "To install please use the anaconda distribution.\n" "http://continuum.io/downloads")
Update warning message if numba import fails
Update warning message if numba import fails
Python
bsd-3-clause
gxxjjj/QuantEcon.py,agutieda/QuantEcon.py,andybrnr/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,andybrnr/QuantEcon.py,gxxjjj/QuantEcon.py,QuantEcon/QuantEcon.py,dingliumath/quant-econ,mgahsan/QuantEcon.py,jviada/QuantEcon.py,dingliumath/quant-econ,agutieda/QuantEcon.py,jviada/QuantEcon.py,mgahsan/QuantEcon.py,oyamad/QuantEcon.py
--- +++ @@ -7,4 +7,7 @@ """ #-Numba-# -numba_import_fail_message = "Numba import failed. Falling back to non-optimized routine." +numba_import_fail_message = ("Numba import failed. Falling back to non-optimized routines.\n" + "This will reduce the overall performance of this package.\n" + "To install please use the anaconda distribution.\n" + "http://continuum.io/downloads")
7f0684583de39552e4117df8cd12c3e030c98f3e
securesystemslib/__init__.py
securesystemslib/__init__.py
import logging # Configure a basic 'securesystemslib' top-level logger with a StreamHandler # (print to console) and the WARNING log level (print messages of type # warning, error or critical). This is similar to what 'logging.basicConfig' # would do with the root logger. All 'securesystemslib.*' loggers default to # this top-level logger and thus may be configured (e.g. formatted, silenced, # etc.) with it. It can be accessed via logging.getLogger('securesystemslib'). logger = logging.getLogger(__name__) logger.setLevel(logging.WARNING) logger.addHandler(logging.StreamHandler())
Configure basic securesystemslib top-level logger
Configure basic securesystemslib top-level logger As pointed out by @FlorianVeaux in #210, securesystemslib does not correctly initialize its loggers. As a consequence the logging module logs a one-off "No handler could be found ..." warning when used for the first time (only on Python 2). The logging module then calls basicConfig, which attaches a basic StreamHandler to the root logger, to which securesystemslib's log messages are propagated. This commit adds the configuration of a simple securesystemslib top-level logger, with an attached StreamHandler and log level WARNING, to which all other securesystemslib loggers default. This removes the one-off warning, while providing a similar logging behavior as before and clear instructions (see added comments) on how to customize (format, silence, etc...) securesystemslib's logging.
Python
mit
secure-systems-lab/securesystemslib,secure-systems-lab/securesystemslib
--- +++ @@ -0,0 +1,11 @@ +import logging + +# Configure a basic 'securesystemslib' top-level logger with a StreamHandler +# (print to console) and the WARNING log level (print messages of type +# warning, error or critical). This is similar to what 'logging.basicConfig' +# would do with the root logger. All 'securesystemslib.*' loggers default to +# this top-level logger and thus may be configured (e.g. formatted, silenced, +# etc.) with it. It can be accessed via logging.getLogger('securesystemslib'). +logger = logging.getLogger(__name__) +logger.setLevel(logging.WARNING) +logger.addHandler(logging.StreamHandler())
156d6f7dd56a5f2554a425fb5a001c99656e320b
semanticize/_semanticizer.py
semanticize/_semanticizer.py
import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(sentence + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(json.dumps(sentence) + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
Send json to semanticizer stdin
Send json to semanticizer stdin
Python
apache-2.0
semanticize/st,semanticize/st
--- +++ @@ -29,7 +29,7 @@ - linkcount - ngramcount ''' - self.proc.stdin.write(sentence + '\n\n') + self.proc.stdin.write(json.dumps(sentence) + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata)
b0237011251815e883b4fa60839dafd513907227
forum/templatetags/forum_extras.py
forum/templatetags/forum_extras.py
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def make_tree(posts): levels = [] depth = 0 html = '<ul>' for post in posts: try: while levels[-1] < post.left: html += '</ul></li>' levels.pop() depth -= 1 except IndexError: pass html += ' ' * depth + '<li>' + post.subject if post.right - post.left > 1: html += '<ul>' levels.append(post.right) depth = len(levels) else: html += '</li>' html += '</ul></li>' * depth html += '</ul>' return mark_safe(html)
from django import template from django.urls import reverse from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def make_tree(posts): levels = [] depth = 0 html = '<ul>' for post in posts: try: while levels[-1] < post.left: html += '</ul></li>' levels.pop() depth -= 1 except IndexError: pass html += '<li><a href="{url}">{title}</a> by {user} on {date}'.format( url=reverse('forum:post', kwargs={ 'board':post.topic.board.slug, 'pk':post.pk }), title=post.subject, user=post.user.username, date='[date]', ) if post.right - post.left > 1: html += '<ul>' levels.append(post.right) depth = len(levels) else: html += '</li>' html += '</ul></li>' * depth html += '</ul>' return mark_safe(html)
Add formatting to post tree
Add formatting to post tree
Python
mit
Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano
--- +++ @@ -1,4 +1,5 @@ from django import template +from django.urls import reverse from django.utils.safestring import mark_safe @@ -20,7 +21,15 @@ except IndexError: pass - html += ' ' * depth + '<li>' + post.subject + html += '<li><a href="{url}">{title}</a> by {user} on {date}'.format( + url=reverse('forum:post', kwargs={ + 'board':post.topic.board.slug, + 'pk':post.pk + }), + title=post.subject, + user=post.user.username, + date='[date]', + ) if post.right - post.left > 1: html += '<ul>'
cd91c7f1db5c2462127a76dd9957c36017ac06cd
tests/run_tests.py
tests/run_tests.py
""" Simple test runner to separate out the functional tests and the unit tests. """ import os import subprocess PLATFORMS = ['bsd', 'linux', 'nt'] # Detect what platform we are on try: platform = os.uname()[0].lower() except AttributeError: platform = os.name.lower() if platform == 'darwin': platform = 'bsd' DIRECTORIES = ['functional'] # Unit tests to be added here def run_test(file): print "Running test: %s" % file print proc = subprocess.Popen("python %s" % file, shell=True, stdout=subprocess.PIPE) output = proc.communicate()[0] print output # We don't do anything with this yet but I'll probably try and group all # these calls up and keep track of the data at the top level if output.find('OK'): return True return False for directory in DIRECTORIES: files = os.listdir(directory) for file in files: file_path = os.path.join(directory, file) if os.path.isfile('%s' % file_path) and file[-3:] == '.py': if file[:-3] in PLATFORMS: if platform == file[:3]: run_test(file_path) else: run_test(file_path)
""" Simple test runner to separate out the functional tests and the unit tests. """ import os import subprocess PLATFORMS = ['bsd', 'linux', 'nt'] # Detect what platform we are on try: platform = os.uname()[0].lower() except AttributeError: platform = os.name.lower() if platform == 'darwin': platform = 'bsd' DIRECTORIES = ['functional'] # Unit tests to be added here def run_test(file): print "Running test: %s" % file print proc = subprocess.Popen("python %s" % file, shell=True, stdout=subprocess.PIPE) output = proc.communicate()[0] print output # We don't do anything with this yet but I'll probably try and group all # these calls up and keep track of the data at the top level if output.find('OK'): return True return False for directory in DIRECTORIES: files = os.listdir(directory) for file in files: file_path = os.path.join(directory, file) if os.path.isfile('%s' % file_path) and file[-3:] == '.py': if file[:-3] in PLATFORMS: if platform == file[:-3]: run_test(file_path) else: run_test(file_path)
Fix a platform detection bug
Fix a platform detection bug
Python
bsd-3-clause
Zephor5/pika,jstnlef/pika,fkarb/pika-python3,vitaly-krugl/pika,pika/pika,Tarsbot/pika,skftn/pika,benjamin9999/pika,reddec/pika,vrtsystems/pika,zixiliuyue/pika,shinji-s/pika,hugoxia/pika,knowsis/pika,renshawbay/pika-python3
--- +++ @@ -40,7 +40,7 @@ file_path = os.path.join(directory, file) if os.path.isfile('%s' % file_path) and file[-3:] == '.py': if file[:-3] in PLATFORMS: - if platform == file[:3]: + if platform == file[:-3]: run_test(file_path) else: run_test(file_path)
375513808e3fa83ff23de942aeedbd0d9cc4d1c2
tests/test_h5py.py
tests/test_h5py.py
import h5py import bitshuffle.h5 import numpy import tempfile def test_is_h5py_correctly_installed(): """ If this test fails you probably need to install h5py from source manually: $ pip install --no-binary=h5py h5py """ f = h5py.File(tempfile.gettempdir() + '/h5testfile', "w") block_size = 0 dataset = f.create_dataset( "data", (100, 100, 100), compression=bitshuffle.h5.H5FILTER, compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4), dtype='float32', ) array = numpy.random.rand(100, 100, 100) array = array.astype('float32') dataset[:] = array f.close()
import h5py import hdf5plugin import numpy import tempfile def test_is_h5py_correctly_installed(): """ If this test fails you probably need to install h5py from source manually: $ pip install --no-binary=h5py h5py """ f = h5py.File(tempfile.gettempdir() + '/h5testfile', "w") block_size = 0 dataset = f.create_dataset( "data", (100, 100, 100), dtype='float32', **hdf5plugin.Bitshuffle(nelems=0, lz4=True) ) array = numpy.random.rand(100, 100, 100) array = array.astype('float32') dataset[:] = array f.close()
Change bitshuffle call to hdf5plugin
Change bitshuffle call to hdf5plugin
Python
bsd-3-clause
UCBerkeleySETI/blimpy,UCBerkeleySETI/blimpy
--- +++ @@ -1,5 +1,5 @@ import h5py -import bitshuffle.h5 +import hdf5plugin import numpy import tempfile @@ -15,9 +15,8 @@ dataset = f.create_dataset( "data", (100, 100, 100), - compression=bitshuffle.h5.H5FILTER, - compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4), dtype='float32', + **hdf5plugin.Bitshuffle(nelems=0, lz4=True) ) array = numpy.random.rand(100, 100, 100)
39e00164541535db2de8c8143d8728e5624f98f9
configuration/development.py
configuration/development.py
import os _basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db') SECRET_KEY = 'INSECURE' MAIL_SERVER = 'localhost' MAIL_PORT = '25' MAIL_DEFAULT_SENDER = 'no-reply@localhost.localdomain' del os
import pathlib _basedir = pathlib.Path(__file__).parents[1] SQLALCHEMY_DATABASE_URI = ( 'sqlite:///' + str(_basedir.joinpath(pathlib.PurePath('app.db')).resolve()) ) SECRET_KEY = 'INSECURE' MAIL_SERVER = 'localhost' MAIL_PORT = '25' MAIL_DEFAULT_SENDER = 'no-reply@localhost.localdomain' del pathlib
Move the db back to the correct location
Move the db back to the correct location
Python
agpl-3.0
interactomix/iis,interactomix/iis
--- +++ @@ -1,7 +1,10 @@ -import os -_basedir = os.path.abspath(os.path.dirname(__file__)) +import pathlib -SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db') +_basedir = pathlib.Path(__file__).parents[1] + +SQLALCHEMY_DATABASE_URI = ( + 'sqlite:///' + str(_basedir.joinpath(pathlib.PurePath('app.db')).resolve()) +) SECRET_KEY = 'INSECURE' @@ -9,4 +12,4 @@ MAIL_PORT = '25' MAIL_DEFAULT_SENDER = 'no-reply@localhost.localdomain' -del os +del pathlib
2726404284fbae6388dbf40e01b6ad5ccf1c56a2
knights/compiler.py
knights/compiler.py
import ast from .context import ContextScope from .parser import Parser from .utils import Helpers def kompile(src, raw=False, filename='<compiler>'): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function ''' parser = Parser(src) parser.load_library('knights.tags') parser.load_library('knights.helpers') parser.build_method('_root') if parser.parent: # Remove _root from the method list parser.methods = [ method for method in parser.methods if method.name != '_root' ] klass = parser.build_class() # Wrap it in a module inst = ast.Module(body=[klass]) ast.fix_missing_locations(inst) # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2) # Execute it and return the instance g = { '_': Helpers(parser.helpers), 'parent': parser.parent, 'ContextScope': ContextScope, } eval(code, g) klass = g['Template'] if raw: return klass return klass()
import ast from .context import ContextScope from .parser import Parser from .utils import Helpers def kompile(src, raw=False, filename='<compiler>', **kwargs): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function ''' parser = Parser(src) parser.load_library('knights.tags') parser.load_library('knights.helpers') parser.build_method('_root') if parser.parent: # Remove _root from the method list parser.methods = [ method for method in parser.methods if method.name != '_root' ] klass = parser.build_class() # Wrap it in a module inst = ast.Module(body=[klass]) ast.fix_missing_locations(inst) if kwargs.get('astor', False): import astor print(astor.to_source(inst)) # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2) # Execute it and return the instance g = { '_': Helpers(parser.helpers), 'parent': parser.parent, 'ContextScope': ContextScope, } eval(code, g) klass = g['Template'] if raw: return klass return klass()
Add option to print astor reconstructed source of template
Add option to print astor reconstructed source of template
Python
mit
funkybob/knights-templater,funkybob/knights-templater
--- +++ @@ -5,7 +5,7 @@ from .utils import Helpers -def kompile(src, raw=False, filename='<compiler>'): +def kompile(src, raw=False, filename='<compiler>', **kwargs): ''' Creates a new class based on the supplied template, and returnsit. @@ -45,6 +45,10 @@ ast.fix_missing_locations(inst) + if kwargs.get('astor', False): + import astor + print(astor.to_source(inst)) + # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2)
70e1e6cde0c31d34cbd2a0118b3215618b84a5d9
adhocracy4/projects/views.py
adhocracy4/projects/views.py
from django.shortcuts import redirect from django.views import generic from rules.contrib import views as rules_views from . import mixins, models class ProjectDetailView(rules_views.PermissionRequiredMixin, mixins.PhaseDispatchMixin, generic.DetailView): model = models.Project permission_required = 'a4projects.view_project' @property def raise_exception(self): return self.request.user.is_authenticated() def handle_no_permission(self): """ Check if user clould join """ user = self.request.user is_member = user.is_authenticated() and self.project.has_member(user) if not is_member: return self.handle_no_membership() else: return super().handle_no_permission() def handle_no_membership(self): """ Handle that an authenticated user is not member of project. Override this function to configure the behaviour if a user has no permissions to view the project and is not member of the project. """ return super().handle_no_permission() @property def project(self): """ Emulate ProjectMixin interface for template sharing. """ return self.get_object()
from django.shortcuts import redirect from django.views import generic from rules.contrib import views as rules_views from . import mixins, models class ProjectDetailView(rules_views.PermissionRequiredMixin, mixins.PhaseDispatchMixin, generic.DetailView): model = models.Project permission_required = 'a4projects.view_project' @property def raise_exception(self): return self.request.user.is_authenticated() @property def project(self): """ Emulate ProjectMixin interface for template sharing. """ return self.get_object()
Remove last memberships related hooks from project
Remove last memberships related hooks from project
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
--- +++ @@ -16,28 +16,6 @@ def raise_exception(self): return self.request.user.is_authenticated() - def handle_no_permission(self): - """ - Check if user clould join - """ - user = self.request.user - is_member = user.is_authenticated() and self.project.has_member(user) - - if not is_member: - return self.handle_no_membership() - else: - return super().handle_no_permission() - - def handle_no_membership(self): - """ - Handle that an authenticated user is not member of project. - - Override this function to configure the behaviour if a user has no - permissions to view the project and is not member of the project. - """ - return super().handle_no_permission() - - @property def project(self): """
1f2a30f5c9ac68c53ed042ab6b5b9c365a1d0d16
rate_limit.py
rate_limit.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2016 Eddie Antonio Santos <easantos@ualberta.ca> # # 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 logging import time from connection import github logger = logging.getLogger(__name__) def wait_for_rate_limit(): """ Checks the rate limit and waits if the rate limit is beyond a certain threshold. """ limit_info = github.rate_limit() core = limit_info['resources']['core'] remaining = core['remaining'] logger.debug('%d requests remaining', remaining) if remaining < 10: # Wait until reset reset = core['reset'] logger.info('Exceded rate limit; waiting until %r', reset) time.sleep(seconds_until(reset) + 1)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2016 Eddie Antonio Santos <easantos@ualberta.ca> # # 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 logging import time from connection import github logger = logging.getLogger(__name__) def wait_for_rate_limit(resource='core'): """ Checks the rate limit and waits if the rate limit is beyond a certain threshold. """ assert resource in ('core', 'search') response = github.rate_limit() limit_info = response['resources'][resource] remaining = limit_info['remaining'] logger.debug('%d requests remaining', remaining) if remaining < 10: # Wait until reset reset = limit_info['reset'] logger.info('Exceded rate limit; waiting until %r', reset) time.sleep(seconds_until(reset) + 1)
Allow for checking search rate limit.
Allow for checking search rate limit.
Python
apache-2.0
naturalness/sensibility,eddieantonio/ad-hoc-miner,naturalness/sensibility,naturalness/sensibility,eddieantonio/ad-hoc-miner,eddieantonio/ad-hoc-miner,naturalness/sensibility,eddieantonio/ad-hoc-miner
--- +++ @@ -25,17 +25,20 @@ logger = logging.getLogger(__name__) -def wait_for_rate_limit(): +def wait_for_rate_limit(resource='core'): """ Checks the rate limit and waits if the rate limit is beyond a certain threshold. """ - limit_info = github.rate_limit() - core = limit_info['resources']['core'] - remaining = core['remaining'] + assert resource in ('core', 'search') + response = github.rate_limit() + limit_info = response['resources'][resource] + + remaining = limit_info['remaining'] logger.debug('%d requests remaining', remaining) + if remaining < 10: # Wait until reset - reset = core['reset'] + reset = limit_info['reset'] logger.info('Exceded rate limit; waiting until %r', reset) time.sleep(seconds_until(reset) + 1)
f20dd39fd3ae739bf6460f452a5d67bc42785adf
src/ansible/urls.py
src/ansible/urls.py
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail'), ]
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), ]
Add playbook file detail view
Add playbook file detail view
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
--- +++ @@ -2,6 +2,7 @@ from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, + PlaybookFileView ) from . import views @@ -9,5 +10,10 @@ urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), - url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail'), + url(r'^(?P<pk>[-\w]+)/$', + PlaybookDetailView.as_view(), name='playbook-detail' + ), + url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', + PlaybookFileView.as_view(), name='playbook-file-detail' + ), ]
4ecd19f7a1a36a424021e42c64fb273d7591ef1f
haas/plugin_manager.py
haas/plugin_manager.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from .utils import find_module_by_name class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None: return None try: module, module_attributes = find_module_by_name(class_spec) except ImportError: return None if len(module_attributes) != 1: return None klass = getattr(module, module_attributes[0], None) if klass is None: return None return klass def load_plugin(self, class_spec): klass = self.load_plugin_class(class_spec) if klass is None: return None return klass()
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals import logging from .utils import get_module_by_name logger = logging.getLogger(__name__) class PluginError(Exception): pass class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None or '.' not in class_spec: msg = 'Malformed plugin factory specification {0!r}'.format( class_spec) logger.error(msg) raise PluginError(msg) module_name, factory_name = class_spec.rsplit('.', 1) try: module = get_module_by_name(module_name) except ImportError: msg = 'Unable to import {0!r}'.format(class_spec) logger.exception(msg) raise PluginError(msg) try: klass = getattr(module, factory_name) except AttributeError: msg = 'Module %r has no attribute {0!r}'.format( module.__name__, factory_name) logger.error(msg) raise PluginError(msg) return klass def load_plugin(self, class_spec): if class_spec is None: return None klass = self.load_plugin_class(class_spec) return klass()
Add logging and raise exceptions when loading plugin factories
Add logging and raise exceptions when loading plugin factories
Python
bsd-3-clause
sjagoe/haas,itziakos/haas,sjagoe/haas,scalative/haas,itziakos/haas,scalative/haas
--- +++ @@ -6,27 +6,44 @@ # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals -from .utils import find_module_by_name +import logging + +from .utils import get_module_by_name + +logger = logging.getLogger(__name__) + + +class PluginError(Exception): + + pass class PluginManager(object): def load_plugin_class(self, class_spec): - if class_spec is None: - return None + if class_spec is None or '.' not in class_spec: + msg = 'Malformed plugin factory specification {0!r}'.format( + class_spec) + logger.error(msg) + raise PluginError(msg) + module_name, factory_name = class_spec.rsplit('.', 1) try: - module, module_attributes = find_module_by_name(class_spec) + module = get_module_by_name(module_name) except ImportError: - return None - if len(module_attributes) != 1: - return None - klass = getattr(module, module_attributes[0], None) - if klass is None: - return None + msg = 'Unable to import {0!r}'.format(class_spec) + logger.exception(msg) + raise PluginError(msg) + try: + klass = getattr(module, factory_name) + except AttributeError: + msg = 'Module %r has no attribute {0!r}'.format( + module.__name__, factory_name) + logger.error(msg) + raise PluginError(msg) return klass def load_plugin(self, class_spec): + if class_spec is None: + return None klass = self.load_plugin_class(class_spec) - if klass is None: - return None return klass()
83c682264582a345d4c5ada0a8fd2fd540595d1e
trex/management/commands/zeiterfassung.py
trex/management/commands/zeiterfassung.py
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.core.management.base import BaseCommand, CommandError from trex.models.project import Project from trex.utils import Zeiterfassung class Command(BaseCommand): args = "<project> <name>" help = "Load entries from a zeiterfassung.txt to a project" def handle(self, *args, **options): if len(args) < 2: raise CommandError("You must specifiy a project name and a " "zeiterfassung.txt") name = args[0] zeiterfassung_txt = args[1] try: project = Project.objects.get(name=name) except Project.DoesNotExist: raise CommandError("Unknown project name %s" % name) with open(zeiterfassung_txt, "r") as f: zeiterfassung = Zeiterfassung(f) created = project.create_entries_from_zeiterfassung(zeiterfassung) self.stdout.write(u"Loaded %s entries" % created)
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from optparse import make_option from django.core.management.base import BaseCommand, CommandError from trex.models.project import Project from trex.utils import Zeiterfassung class Command(BaseCommand): args = "<project> <name>" help = "Load entries from a zeiterfassung.txt to a project" option_list = BaseCommand.option_list + ( make_option("-e", "--encoding", dest="encoding", default="utf-8", help="Encoding of the input file", type="string"), ) def handle(self, *args, **options): if len(args) < 2: raise CommandError("You must specifiy a project name and a " "zeiterfassung.txt") name = args[0] zeiterfassung_txt = args[1] encoding = options.get("encoding") try: project = Project.objects.get(name=name) except Project.DoesNotExist: raise CommandError("Unknown project name %s" % name) with open(zeiterfassung_txt, "r") as f: zeiterfassung = Zeiterfassung(f, encoding) created = project.create_entries_from_zeiterfassung(zeiterfassung) self.stdout.write(u"Loaded %s entries" % created)
Allow to pass the encoding via a command option
Allow to pass the encoding via a command option
Python
mit
bjoernricks/trex,bjoernricks/trex
--- +++ @@ -4,6 +4,8 @@ # # See LICENSE comming with the source of 'trex' for details. # + +from optparse import make_option from django.core.management.base import BaseCommand, CommandError @@ -16,6 +18,11 @@ args = "<project> <name>" help = "Load entries from a zeiterfassung.txt to a project" + option_list = BaseCommand.option_list + ( + make_option("-e", "--encoding", dest="encoding", default="utf-8", + help="Encoding of the input file", type="string"), + ) + def handle(self, *args, **options): if len(args) < 2: raise CommandError("You must specifiy a project name and a " @@ -24,12 +31,14 @@ name = args[0] zeiterfassung_txt = args[1] + encoding = options.get("encoding") + try: project = Project.objects.get(name=name) except Project.DoesNotExist: raise CommandError("Unknown project name %s" % name) with open(zeiterfassung_txt, "r") as f: - zeiterfassung = Zeiterfassung(f) + zeiterfassung = Zeiterfassung(f, encoding) created = project.create_entries_from_zeiterfassung(zeiterfassung) self.stdout.write(u"Loaded %s entries" % created)
da39921f94a90e330c796e0ad9ff861e9fc5a8af
examples/tutorial_pandas.py
examples/tutorial_pandas.py
import argparse import pandas as pd from influxdb import DataFrameClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(30)), index=pd.date_range(start='2014-11-16', periods=30, freq='H')) print("Create database: " + dbname) client.create_database(dbname) print("Write DataFrame") client.write_points(df, 'demo') print("Write DataFrame with Tags") client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'}) print("Read DataFrame") client.query("select * from demo") print("Delete database: " + dbname) client.delete_database(dbname) def parse_args(): parser = argparse.ArgumentParser( description='example code to play with InfluxDB') parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname of InfluxDB http API') parser.add_argument('--port', type=int, required=False, default=8086, help='port of InfluxDB http API') return parser.parse_args() if __name__ == '__main__': args = parse_args() main(host=args.host, port=args.port)
import argparse import pandas as pd from influxdb import DataFrameClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' protocol = 'json' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(30)), index=pd.date_range(start='2014-11-16', periods=30, freq='H')) print("Create database: " + dbname) client.create_database(dbname) print("Write DataFrame") client.write_points(df, 'demo') print("Write DataFrame with Tags") client.write_points(df, 'demo', {'k1': 'v1', 'k2': 'v2'}) print("Read DataFrame") client.query("select * from demo") print("Delete database: " + dbname) client.delete_database(dbname) def parse_args(): parser = argparse.ArgumentParser( description='example code to play with InfluxDB') parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname of InfluxDB http API') parser.add_argument('--port', type=int, required=False, default=8086, help='port of InfluxDB http API') return parser.parse_args() if __name__ == '__main__': args = parse_args() main(host=args.host, port=args.port)
Add correct protocol to the Pandas client
Add correct protocol to the Pandas client @nicolajkirchhof Is this what you were talking about?
Python
mit
BenHewins/influxdb-python,BenHewins/influxdb-python,influxdb/influxdb-python,tzonghao/influxdb-python,tzonghao/influxdb-python,influxdata/influxdb-python,omki2005/influxdb-python,influxdb/influxdb-python,influxdata/influxdb-python,omki2005/influxdb-python
--- +++ @@ -8,6 +8,7 @@ user = 'root' password = 'root' dbname = 'example' + protocol = 'json' client = DataFrameClient(host, port, user, password, dbname)
aaaa857642fa4ce2631fb47f3c929d3197037231
falcom/generate_pageview.py
falcom/generate_pageview.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Pagetags: default_confidence = 100 def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Pagetags: def __init__ (self): self.default_confidence = 100 @property def default_confidence (self): return self.__default_confid @default_confidence.setter def default_confidence (self, value): self.__default_confid = value def generate_pageview (self): return "" def add_raw_tags (self, tag_data): pass
Make default_confidence into a @property
:muscle: Make default_confidence into a @property
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
--- +++ @@ -4,7 +4,16 @@ class Pagetags: - default_confidence = 100 + def __init__ (self): + self.default_confidence = 100 + + @property + def default_confidence (self): + return self.__default_confid + + @default_confidence.setter + def default_confidence (self, value): + self.__default_confid = value def generate_pageview (self): return ""
6f83e51dc505366187c911b90a017e0fe0531a17
stock_planning/models/stock_move.py
stock_planning/models/stock_move.py
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
Fix condition cond.append(('date', '>=', from_date))
[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))
Python
agpl-3.0
Daniel-CA/odoomrp-wip-public,sergiocorato/odoomrp-wip,agaldona/odoomrp-wip-1,jobiols/odoomrp-wip,odoomrp/odoomrp-wip,odoomrp/odoomrp-wip,jobiols/odoomrp-wip,agaldona/odoomrp-wip-1,Daniel-CA/odoomrp-wip-public,sergiocorato/odoomrp-wip
--- +++ @@ -16,7 +16,7 @@ ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: - cond.append(('date', '=>', from_date)) + cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id:
86678fce3817388641db3d0f4002b3f8d409377d
pdcupdater/tests/handler_tests/test_kerberos_auth.py
pdcupdater/tests/handler_tests/test_kerberos_auth.py
import pytest import requests_kerberos from mock import patch, Mock import pdcupdater.utils from test.test_support import EnvironmentVarGuard import os class TestKerberosAuthentication(object): @patch('os.path.exists', return_value=True) @patch('requests_kerberos.HTTPKerberosAuth') @patch('requests.get') def test_get_token(self, requests_get, kerb_auth, os_path): self.url = 'https://pdc.fedoraproject.org/rest_api/v1/' set_env=patch.dict(os.environ,{'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'}) requests_rv = Mock() requests_rv.json.return_value = {"token": "12345"} requests_get.return_value = requests_rv set_env.start() rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab') set_env.stop() assert rv == '12345'
import os from mock import patch, Mock import pdcupdater.utils class TestKerberosAuthentication(object): @patch('os.path.exists', return_value=True) @patch('requests_kerberos.HTTPKerberosAuth') @patch('requests.get') def test_get_token(self, requests_get, kerb_auth, os_path): self.url = 'https://pdc.fedoraproject.org/rest_api/v1/' set_env = patch.dict( os.environ, {'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'}) requests_rv = Mock() requests_rv.json.return_value = {"token": "12345"} requests_get.return_value = requests_rv set_env.start() rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab') set_env.stop() assert rv == '12345'
Remove invalid imports for TestKerberosAuthentication and fix its styling
Remove invalid imports for TestKerberosAuthentication and fix its styling
Python
lgpl-2.1
fedora-infra/pdc-updater
--- +++ @@ -1,23 +1,22 @@ -import pytest -import requests_kerberos -from mock import patch, Mock -import pdcupdater.utils -from test.test_support import EnvironmentVarGuard import os +from mock import patch, Mock + +import pdcupdater.utils + + class TestKerberosAuthentication(object): - - @patch('os.path.exists', return_value=True) - @patch('requests_kerberos.HTTPKerberosAuth') - @patch('requests.get') - def test_get_token(self, requests_get, kerb_auth, os_path): - self.url = 'https://pdc.fedoraproject.org/rest_api/v1/' - set_env=patch.dict(os.environ,{'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'}) - requests_rv = Mock() - requests_rv.json.return_value = {"token": "12345"} - requests_get.return_value = requests_rv - set_env.start() - rv = pdcupdater.utils.get_token(self.url, - '/etc/foo.keytab') - set_env.stop() - assert rv == '12345' + @patch('os.path.exists', return_value=True) + @patch('requests_kerberos.HTTPKerberosAuth') + @patch('requests.get') + def test_get_token(self, requests_get, kerb_auth, os_path): + self.url = 'https://pdc.fedoraproject.org/rest_api/v1/' + set_env = patch.dict( + os.environ, {'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'}) + requests_rv = Mock() + requests_rv.json.return_value = {"token": "12345"} + requests_get.return_value = requests_rv + set_env.start() + rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab') + set_env.stop() + assert rv == '12345'
3d29cad334446613180e0279cb1197fab1f77764
lib/python/setup.py
lib/python/setup.py
from sys import version from distutils.core import setup setup(name='mosquitto', version='1.0.1', description='MQTT version 3.1 client class', author='Roger Light', author_email='roger@atchoo.org', url='http://mosquitto.org/', download_url='http://mosquitto.org/files/', license='BSD License', py_modules=['mosquitto'] )
from sys import version from distutils.core import setup setup(name='mosquitto', version='1.0.1', description='MQTT version 3.1 client class', author='Roger Light', author_email='roger@atchoo.org', url='http://mosquitto.org/', download_url='http://mosquitto.org/files/', license='BSD License', py_modules=['mosquitto'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Communications', 'Topic :: Internet', ] )
Add Python classifiers for PyPi.
Add Python classifiers for PyPi.
Python
bsd-3-clause
zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto,zlargon/mosquitto
--- +++ @@ -9,5 +9,20 @@ url='http://mosquitto.org/', download_url='http://mosquitto.org/files/', license='BSD License', - py_modules=['mosquitto'] + py_modules=['mosquitto'], + + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Operating System :: MacOS :: MacOS X', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: POSIX', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Topic :: Communications', + 'Topic :: Internet', + ] )
1a06f983a3edf3ee2f887c2e2094eb76820b5a73
examples/arabic.py
examples/arabic.py
#!/usr/bin/env python """ Create wordcloud with Arabic =============== Generating a wordcloud from Arabic text Dependencies: - bidi.algorithm - arabic_reshaper Dependencies installation: pip install python-bidi arabic_reshape """ from os import path import codecs from wordcloud import WordCloud import arabic_reshaper from bidi.algorithm import get_display d = path.dirname(__file__) # Read the whole text. f = codecs.open(path.join(d, 'arabicwords.txt'), 'r', 'utf-8') # Make text readable for a non-Arabic library like wordcloud text = arabic_reshaper.reshape(f.read()) text = get_display(text) # Generate a word cloud image wordcloud = WordCloud(font_path='fonts/NotoNaskhArabic/NotoNaskhArabic-Regular.ttf').generate(text) # Export to an image wordcloud.to_file("arabic_example.png")
#!/usr/bin/env python """ Create wordcloud with Arabic =============== Generating a wordcloud from Arabic text Dependencies: - bidi.algorithm - arabic_reshaper Dependencies installation: pip install python-bidi arabic_reshape """ import os import codecs from wordcloud import WordCloud import arabic_reshaper from bidi.algorithm import get_display # get data directory (using getcwd() is needed to support running example in generated IPython notebook) d = os.path.dirname(__file__) if "__file__" in locals() else os.getcwd() # Read the whole text. f = codecs.open(os.path.join(d, 'arabicwords.txt'), 'r', 'utf-8') # Make text readable for a non-Arabic library like wordcloud text = arabic_reshaper.reshape(f.read()) text = get_display(text) # Generate a word cloud image wordcloud = WordCloud(font_path='fonts/NotoNaskhArabic/NotoNaskhArabic-Regular.ttf').generate(text) # Export to an image wordcloud.to_file("arabic_example.png")
Fix the __file__ is not defined bug
Fix the __file__ is not defined bug
Python
mit
amueller/word_cloud
--- +++ @@ -12,16 +12,17 @@ pip install python-bidi arabic_reshape """ -from os import path +import os import codecs from wordcloud import WordCloud import arabic_reshaper from bidi.algorithm import get_display -d = path.dirname(__file__) +# get data directory (using getcwd() is needed to support running example in generated IPython notebook) +d = os.path.dirname(__file__) if "__file__" in locals() else os.getcwd() # Read the whole text. -f = codecs.open(path.join(d, 'arabicwords.txt'), 'r', 'utf-8') +f = codecs.open(os.path.join(d, 'arabicwords.txt'), 'r', 'utf-8') # Make text readable for a non-Arabic library like wordcloud text = arabic_reshaper.reshape(f.read())
633ba35c87f62b70e0aae275519514632d33a777
googleanalytics/__init__.py
googleanalytics/__init__.py
# encoding: utf-8 from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments from .auth import authenticate, authorize, revoke from .blueprint import Blueprint
# encoding: utf-8 import pkg_resources from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments from .auth import authenticate, authorize, revoke from .blueprint import Blueprint __version__ = pkg_resources.get_distribution("googleanalytics").version
Add version number to package.
Add version number to package.
Python
isc
debrouwere/google-analytics
--- +++ @@ -1,5 +1,9 @@ # encoding: utf-8 + +import pkg_resources from . import auth, commands, tests, utils, account, auth, blueprint, columns, errors, query, segments from .auth import authenticate, authorize, revoke from .blueprint import Blueprint + +__version__ = pkg_resources.get_distribution("googleanalytics").version
4e6c901140a667612fd311a2f18e1b7c18bafcd0
tests/test_octadecane_benchmarks.py
tests/test_octadecane_benchmarks.py
""" This module runs the benchmark test suite. """ from .context import phaseflow def test_lid_driven_cavity_benchmark__ci__(): phaseflow.helpers.run_simulation_with_temporary_output( phaseflow.octadecane_benchmarks.LidDrivenCavityBenchmarkSimulation()) def test_lid_driven_cavity_benchmark_with_solid_subdomain__ci__(): phaseflow.helpers.run_simulation_with_temporary_output( phaseflow.octadecane_benchmarks.LDCBenchmarkSimulationWithSolidSubdomain()) def test_heat_driven_cavity_benchmark_with_restart__ci__(): sim = phaseflow.octadecane_benchmarks.HeatDrivenCavityBenchmarkSimulation() sim.prefix_output_dir_with_tempdir = True sim.end_time = 2.*sim.timestep_size sim.run(verify = False) sim2 = phaseflow.octadecane_benchmarks.HeatDrivenCavityBenchmarkSimulation() sim2.read_checkpoint(sim.latest_checkpoint_filepath) assert(sim.state.time == sim2.old_state.time) assert(all(sim.state.solution.leaf_node().vector() == sim2.old_state.solution.leaf_node().vector())) sim.prefix_output_dir_with_tempdir = True sim2.run(verify = True) def test_stefan_problem_benchmark__ci__(): phaseflow.helpers.run_simulation_with_temporary_output( phaseflow.octadecane_benchmarks.StefanProblemBenchmarkSimulation())
""" This module runs the benchmark test suite. """ from .context import phaseflow def test_lid_driven_cavity_benchmark_with_solid_subdomain__ci__(): phaseflow.helpers.run_simulation_with_temporary_output( phaseflow.octadecane_benchmarks.LDCBenchmarkSimulationWithSolidSubdomain()) def test_heat_driven_cavity_benchmark__ci__(): phaseflow.helpers.run_simulation_with_temporary_output( phaseflow.octadecane_benchmarks.HeatDrivenCavityBenchmarkSimulation()) def test_stefan_problem_benchmark_with_restart__ci__(): """ This tests that restarting does not affect time accuracy. """ sim = phaseflow.octadecane_benchmarks.StefanProblemBenchmarkSimulation() sim.end_time = 0.01 sim.run(verify = False) sim2 = phaseflow.octadecane_benchmarks.StefanProblemBenchmarkSimulation() sim2.read_checkpoint(sim.latest_checkpoint_filepath) assert(sim.state.time == sim2.old_state.time) assert(all(sim.state.solution.leaf_node().vector() == sim2.old_state.solution.leaf_node().vector())) sim2.prefix_output_dir_with_tempdir = True sim2.run(verify = True)
Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests
Test restarting with Stefan problem instead of heat driven cavity. Removed some redundant tests
Python
mit
geo-fluid-dynamics/phaseflow-fenics
--- +++ @@ -1,12 +1,6 @@ """ This module runs the benchmark test suite. """ from .context import phaseflow - -def test_lid_driven_cavity_benchmark__ci__(): - - phaseflow.helpers.run_simulation_with_temporary_output( - phaseflow.octadecane_benchmarks.LidDrivenCavityBenchmarkSimulation()) - def test_lid_driven_cavity_benchmark_with_solid_subdomain__ci__(): @@ -14,30 +8,29 @@ phaseflow.octadecane_benchmarks.LDCBenchmarkSimulationWithSolidSubdomain()) -def test_heat_driven_cavity_benchmark_with_restart__ci__(): +def test_heat_driven_cavity_benchmark__ci__(): - sim = phaseflow.octadecane_benchmarks.HeatDrivenCavityBenchmarkSimulation() + phaseflow.helpers.run_simulation_with_temporary_output( + phaseflow.octadecane_benchmarks.HeatDrivenCavityBenchmarkSimulation()) + - sim.prefix_output_dir_with_tempdir = True +def test_stefan_problem_benchmark_with_restart__ci__(): + """ This tests that restarting does not affect time accuracy. """ + sim = phaseflow.octadecane_benchmarks.StefanProblemBenchmarkSimulation() - sim.end_time = 2.*sim.timestep_size + sim.end_time = 0.01 sim.run(verify = False) - sim2 = phaseflow.octadecane_benchmarks.HeatDrivenCavityBenchmarkSimulation() + sim2 = phaseflow.octadecane_benchmarks.StefanProblemBenchmarkSimulation() sim2.read_checkpoint(sim.latest_checkpoint_filepath) - + assert(sim.state.time == sim2.old_state.time) assert(all(sim.state.solution.leaf_node().vector() == sim2.old_state.solution.leaf_node().vector())) - sim.prefix_output_dir_with_tempdir = True + sim2.prefix_output_dir_with_tempdir = True sim2.run(verify = True) - -def test_stefan_problem_benchmark__ci__(): - - phaseflow.helpers.run_simulation_with_temporary_output( - phaseflow.octadecane_benchmarks.StefanProblemBenchmarkSimulation())
c3526f51afc23a4c672e86a850c4f49d094a2482
libpb/port/__init__.py
libpb/port/__init__.py
"""FreeBSD Ports.""" from __future__ import absolute_import __all__ = ["get_port"] class PortCache(object): """Caches created ports.""" def __init__(self): """Initialise port cache.""" self._ports = {} self._waiters = {} def __len__(self): return len(self._ports) def get_port(self, origin): """Get a port and callback with it.""" if origin in self._ports: from ..event import post_event from ..signal import Signal signal = Signal() post_event(signal.emit, self._ports[origin]) return signal else: if origin in self._waiters: return self._waiters[origin] else: from .mk import attr from ..signal import Signal signal = Signal() self._waiters[origin] = signal attr(origin).connect(self._attr) return signal def _attr(self, origin, attr): """Use attr to create a port.""" from .port import Port signal = self._waiters.pop(origin) if attr is None: port = origin else: port = Port(origin, attr) self._ports[origin] = port signal.emit(port) _cache = PortCache() ports = _cache.__len__ get_port = _cache.get_port
"""FreeBSD Ports.""" from __future__ import absolute_import __all__ = ["get_port", "get_ports", "ports"] class PortCache(object): """Caches created ports.""" def __init__(self): """Initialise port cache.""" self._ports = {} self._waiters = {} def __len__(self): return len(self._ports) def get_port(self, origin): """Get a port and callback with it.""" if origin in self._ports: from ..event import post_event from ..signal import Signal signal = Signal() post_event(signal.emit, self._ports[origin]) return signal else: if origin in self._waiters: return self._waiters[origin] else: from .mk import attr from ..signal import Signal signal = Signal() self._waiters[origin] = signal attr(origin).connect(self._attr) return signal def __iter__(self): return self._ports.values() def _attr(self, origin, attr): """Use attr to create a port.""" from .port import Port signal = self._waiters.pop(origin) if attr is None: port = origin else: port = Port(origin, attr) self._ports[origin] = port signal.emit(port) _cache = PortCache() ports = _cache.__len__ get_port = _cache.get_port get_ports = _cache.__iter__
Add ability to iterate over all currently loaded ports.
Add ability to iterate over all currently loaded ports. This function provides a snapshot of ports and does not provide support to query ports that are still loading.
Python
bsd-2-clause
DragonSA/portbuilder,DragonSA/portbuilder
--- +++ @@ -2,7 +2,7 @@ from __future__ import absolute_import -__all__ = ["get_port"] +__all__ = ["get_port", "get_ports", "ports"] class PortCache(object): @@ -37,6 +37,9 @@ attr(origin).connect(self._attr) return signal + def __iter__(self): + return self._ports.values() + def _attr(self, origin, attr): """Use attr to create a port.""" from .port import Port @@ -54,3 +57,4 @@ ports = _cache.__len__ get_port = _cache.get_port +get_ports = _cache.__iter__
029d5c9f85dedbe8d1b4d41a8cb27d70652c9c1b
tools/clean_output_directory.py
tools/clean_output_directory.py
#!/usr/bin/env python # # Copyright (c) 2012, 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 shutil import sys import subprocess import utils def Main(): build_root = utils.GetBuildRoot(utils.GuessOS()) print 'Deleting %s' % build_root if sys.platform != 'win32': shutil.rmtree(build_root, ignore_errors=True) else: # Intentionally ignore return value since a directory might be in use. subprocess.call(['rmdir', '/Q', '/S', build_root], env=os.environ.copy(), shell=True) return 0 if __name__ == '__main__': sys.exit(Main())
#!/usr/bin/env python # # Copyright (c) 2012, 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 shutil import sys import subprocess import utils def Main(): build_root = utils.GetBuildRoot(utils.GuessOS()) print 'Deleting %s' % build_root if sys.platform != 'win32': shutil.rmtree(build_root, ignore_errors=True) else: # Intentionally ignore return value since a directory might be in use. subprocess.call(['rmdir', '/Q', '/S', build_root], env=os.environ.copy(), shell=True) return 0 if __name__ == '__main__': sys.exit(Main())
Add missing python import to utility script
Add missing python import to utility script BUG= R=lrn@google.com Review URL: https://codereview.chromium.org//1226963005.
Python
bsd-3-clause
dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk
--- +++ @@ -5,6 +5,7 @@ # BSD-style license that can be found in the LICENSE file. # +import os import shutil import sys import subprocess
335ce70414ffecbfc506ce2c22a5a7e4aeeca1a1
sda/__init__.py
sda/__init__.py
# -*- coding: utf-8 -*- """sda .. codeauthor:: John Lane <jlane@fanthreesixty.com> """ from sda import element from sda import locators from sda import mixins from sda import page from sda import site from sda import structures __author__ = 'jlane' __email__ = 'jlane@fanthreesixty.com' __license__ = "MIT" __version__ = '0.9.1' __all__ = ['element', 'locators', 'page', 'shortcuts', 'site', 'structures']
# -*- coding: utf-8 -*- """sda .. codeauthor:: John Lane <jlane@fanthreesixty.com> """ from sda import locators from sda import mixins from sda import structures from sda.element import Element from sda.page import Page from sda.site import Site __author__ = 'jlane' __email__ = 'jlane@fanthreesixty.com' __license__ = "MIT" __version__ = '0.9.1' __all__ = ['locators', 'shortcuts', 'structures', 'Element', 'Page', 'Site']
Streamline imports for Element, Page and Site
Streamline imports for Element, Page and Site
Python
mit
jlane9/selenium_data_attributes,jlane9/selenium_data_attributes
--- +++ @@ -5,16 +5,16 @@ """ -from sda import element from sda import locators from sda import mixins -from sda import page -from sda import site from sda import structures +from sda.element import Element +from sda.page import Page +from sda.site import Site __author__ = 'jlane' __email__ = 'jlane@fanthreesixty.com' __license__ = "MIT" __version__ = '0.9.1' -__all__ = ['element', 'locators', 'page', 'shortcuts', 'site', 'structures'] +__all__ = ['locators', 'shortcuts', 'structures', 'Element', 'Page', 'Site']
51b179a6d8d2bef2a0371c870dbc1b7b3ebc9a38
grammpy/Grammars/Grammar.py
grammpy/Grammars/Grammar.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 16.08.2017 19:25 :Licence GNUv3 Part of grammpy """ from .CopyableGrammar import CopyableGrammar as _G class Grammar(_G): def __copy__(self): return self.copy() def copy(self, terminals=False, nonterminals=False, rules=False): c = self._copy(terminals=terminals, nonterminals=nonterminals, rules=rules) return Grammar(terminals=list(c.new_terms), nonterminals=list(c.new_nonterms), rules=list(c.new_rules), start_symbol=c.start) def copy_rules(self): return self.copy(rules=True) def __deepcopy__(self, memodict={}): return self.copy(terminals=True, nonterminals=True, rules=True)
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 16.08.2017 19:25 :Licence GNUv3 Part of grammpy """ from .CopyableGrammar import CopyableGrammar as _G class Grammar(_G): def __copy__(self): return self.copy() def copy(self, terminals=False, nonterminals=False, rules=False): c = self._copy(terminals=terminals, nonterminals=nonterminals, rules=rules) return Grammar(terminals=list(c.new_terms), nonterminals=list(c.new_nonterms), rules=list(c.new_rules), start_symbol=c.start) def __deepcopy__(self, memodict={}): return self.copy(terminals=True, nonterminals=True, rules=True)
Remove method for copying rules only
Remove method for copying rules only
Python
mit
PatrikValkovic/grammpy
--- +++ @@ -22,8 +22,5 @@ rules=list(c.new_rules), start_symbol=c.start) - def copy_rules(self): - return self.copy(rules=True) - def __deepcopy__(self, memodict={}): return self.copy(terminals=True, nonterminals=True, rules=True)
56fde910c417a8d1943e5ff110327fee49cb4a6d
fineants/models.py
fineants/models.py
# -*- coding: utf-8 -*- from datetime import datetime from django.contrib.auth.models import User from django.db import models class Transaction(models.Model): title = models.CharField("Title", max_length=255, blank=False) creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor") debitors = models.ManyToManyField(User, verbose_name="Debitors", related_name="Debitors") amount = models.FloatField("Amount", blank=False) created = models.DateTimeField('Created', default=datetime.now)
# -*- coding: utf-8 -*- from datetime import datetime from django.contrib.auth.models import User from django.db import models class Transaction(models.Model): title = models.CharField("Title", max_length=255, blank=False) creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor") debitors = models.ManyToManyField(User, verbose_name="Debitors", related_name="Debitors") amount = models.FloatField("Amount", blank=False) description = models.TextField("Description", blank=True) created = models.DateTimeField('Created', default=datetime.now)
Add description field to transaction
Add description field to transaction
Python
mit
n2o/FineAnts,n2o/FineAnts
--- +++ @@ -9,4 +9,5 @@ creditor = models.ForeignKey(User, verbose_name="Creditor", related_name="Creditor") debitors = models.ManyToManyField(User, verbose_name="Debitors", related_name="Debitors") amount = models.FloatField("Amount", blank=False) + description = models.TextField("Description", blank=True) created = models.DateTimeField('Created', default=datetime.now)
bb319f73d16066ffae81cd1f0a7d644b7621dec7
shcol/config.py
shcol/config.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ from __future__ import unicode_literals import logging import os import sys ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' LOGGER = logging.getLogger('shol') MAKE_UNIQUE = False ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout if PY_VERSION >= (3, 0): ENCODING = sys.getdefaultencoding() UNICODE_TYPE = type('') else: ENCODING = TERMINAL_STREAM.encoding or sys.getdefaultencoding() UNICODE_TYPE = type(u'')
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import logging import os import sys ENCODING = 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' LOGGER = logging.getLogger('shol') MAKE_UNIQUE = False ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout UNICODE_TYPE = type(u'')
Use UTF-8 as default encoding.
Use UTF-8 as default encoding.
Python
bsd-2-clause
seblin/shcol
--- +++ @@ -9,13 +9,11 @@ needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ - -from __future__ import unicode_literals - import logging import os import sys +ENCODING = 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None @@ -28,10 +26,4 @@ SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout - -if PY_VERSION >= (3, 0): - ENCODING = sys.getdefaultencoding() - UNICODE_TYPE = type('') -else: - ENCODING = TERMINAL_STREAM.encoding or sys.getdefaultencoding() - UNICODE_TYPE = type(u'') +UNICODE_TYPE = type(u'')
edfa2547b9ad2f6e8a2f1ab547c08d5d0c702dee
pybossa_z3950/__init__.py
pybossa_z3950/__init__.py
# -*- coding: utf8 -*- """Main package for pybossa-z3950.""" from flask import current_app as app from flask.ext.plugins import Plugin from flask.ext.z3950 import Z3950Manager __plugin__ = "PyBossaZ3950" __version__ = "0.0.1" class PyBossaZ3950(Plugin): """A PyBossa plugin for Z39.50 integration.""" def setup(self): """Setup plugin.""" try: if app.config.get('Z3950_DATABASES'): Z3950Manager.init_app(app) self.setup_blueprint() except Exception as inst: # pragma: no cover print type(inst) print inst.args print inst print "Z39.50 plugin disabled" log_message = 'Z39.50 plugin disabled: %s' % str(inst) app.logger.info(log_message) def setup_blueprint(self): """Setup blueprint.""" from .view import blueprint app.register_blueprint(blueprint, url_prefix="/z3950")
# -*- coding: utf8 -*- """Main package for pybossa-z3950.""" from flask import current_app as app from flask.ext.plugins import Plugin from flask.ext.z3950 import Z3950Manager __plugin__ = "PyBossaZ3950" __version__ = "0.0.1" class PyBossaZ3950(Plugin): """A PyBossa plugin for Z39.50 integration.""" def setup(self): """Setup plugin.""" try: if app.config['Z3950_DATABASES']: Z3950Manager.init_app(app) self.setup_blueprint() except Exception as inst: # pragma: no cover print type(inst) print inst.args print inst print "Z39.50 plugin disabled" log_message = 'Z39.50 plugin disabled: %s' % str(inst) app.logger.info(log_message) def setup_blueprint(self): """Setup blueprint.""" from .view import blueprint app.register_blueprint(blueprint, url_prefix="/z3950")
Raise error when plugin not configured
Raise error when plugin not configured
Python
bsd-3-clause
alexandermendes/pybossa-z3950
--- +++ @@ -15,7 +15,7 @@ def setup(self): """Setup plugin.""" try: - if app.config.get('Z3950_DATABASES'): + if app.config['Z3950_DATABASES']: Z3950Manager.init_app(app) self.setup_blueprint() except Exception as inst: # pragma: no cover
fb63b49302560d4ab139c3749347edf5878a18c9
modules/pushover.py
modules/pushover.py
import http.client import urllib def send_message(settings, message): conn = http.client.HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urllib.parse.urlencode({ "token": settings.PUSHOVER_APP_TOKEN, "user": settings.PUSHOVER_USER_KEY, "message": message, }), {"Content-type": "application/x-www-form-urlencoded"}) conn.getresponse()
import http.client import urllib def send_message(settings, message, title="Argus"): conn = http.client.HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urllib.parse.urlencode({ "token": settings.PUSHOVER_APP_TOKEN, "user": settings.PUSHOVER_USER_KEY, "message": message, "title": title, }), {"Content-type": "application/x-www-form-urlencoded"}) conn.getresponse()
Support for title in the notification, defaulting to 'Argus'
Support for title in the notification, defaulting to 'Argus'
Python
apache-2.0
aquatix/argus,aquatix/argus
--- +++ @@ -2,12 +2,13 @@ import urllib -def send_message(settings, message): +def send_message(settings, message, title="Argus"): conn = http.client.HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urllib.parse.urlencode({ "token": settings.PUSHOVER_APP_TOKEN, "user": settings.PUSHOVER_USER_KEY, "message": message, + "title": title, }), {"Content-type": "application/x-www-form-urlencoded"}) conn.getresponse()
68673a0c3185b9575ec031c7b7590e5bc091ccb5
h2o-bindings/bin/gen_all.py
h2o-bindings/bin/gen_all.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import print_function import gen_csharp import gen_docs_json import gen_java import gen_python import gen_thrift import bindings import sys, os sys.path.insert(0, "../../scripts") import run # Create results/ folder, where H2OCloud stores its logs if not os.path.exists("results"): os.mkdir("results") # Start H2O cloud print("Starting H2O cloud...") cloud = run.H2OCloud( cloud_num=0, use_client=False, nodes_per_cloud=1, h2o_jar=os.path.abspath("../../build/h2o.jar"), base_port=48000, xmx="4g", cp="", output_dir="results" ) cloud.start() cloud.wait_for_cloud_to_be_up() # Manipulate the command line arguments, so that bindings module would know which cloud to use sys.argv.insert(1, "--usecloud") sys.argv.insert(2, "%s:%s" % (cloud.get_ip(), cloud.get_port())) # Actually generate all the bindings print() gen_java.main() gen_python.main() gen_docs_json.main() gen_thrift.main() gen_csharp.main() bindings.done() print() # The END cloud.stop()
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import print_function import gen_csharp import gen_docs_json import gen_java import gen_python import gen_thrift import bindings import sys, os sys.path.insert(0, "../../scripts") import run # Create results folder, where H2OCloud stores its logs, and ../build/test-results where Jenkins stores its stuff if not os.path.exists("results"): os.mkdir("results") os.mkdir("results/failed") if not os.path.exists("../build/test-results"): os.mkdir("../build/test-results") # Start H2O cloud print("Starting H2O cloud...") cloud = run.H2OCloud( cloud_num=0, use_client=False, nodes_per_cloud=1, h2o_jar=os.path.abspath("../../build/h2o.jar"), base_port=48000, xmx="4g", cp="", output_dir="results" ) cloud.start() cloud.wait_for_cloud_to_be_up() # Manipulate the command line arguments, so that bindings module would know which cloud to use sys.argv.insert(1, "--usecloud") sys.argv.insert(2, "%s:%s" % (cloud.get_ip(), cloud.get_port())) # Actually generate all the bindings print() gen_java.main() gen_python.main() gen_docs_json.main() gen_thrift.main() gen_csharp.main() bindings.done() print() # The END cloud.stop()
Create test-results folder, to make Jenkins happy
Create test-results folder, to make Jenkins happy
Python
apache-2.0
h2oai/h2o-dev,mathemage/h2o-3,mathemage/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,mathemage/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,spennihana/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,jangorecki/h2o-3,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,jangorecki/h2o-3,h2oai/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,spennihana/h2o-3,spennihana/h2o-3,spennihana/h2o-3
--- +++ @@ -12,9 +12,12 @@ sys.path.insert(0, "../../scripts") import run -# Create results/ folder, where H2OCloud stores its logs +# Create results folder, where H2OCloud stores its logs, and ../build/test-results where Jenkins stores its stuff if not os.path.exists("results"): os.mkdir("results") + os.mkdir("results/failed") +if not os.path.exists("../build/test-results"): + os.mkdir("../build/test-results") # Start H2O cloud print("Starting H2O cloud...")
8ee418b9a51d418901951b4f7d4cc975b203c0ed
blanc_basic_assets/listeners.py
blanc_basic_assets/listeners.py
from django.db.models.signals import pre_save, post_delete from django.core.files.storage import default_storage def asset_file_change(sender, instance, **kwargs): # Must be saved already if instance.pk is not None: try: old_obj = sender.objects.get(pk=instance.pk) # Delete the old file if the file names don't match if old_obj.file.path != instance.file.path: default_storage.delete(old_obj.file.path) except: pass def asset_file_delete(sender, instance, **kwargs): # Try and remove the file if possible try: instance.file.delete(save=False) except: pass pre_save.connect(asset_file_change, sender='assets.Image') pre_save.connect(asset_file_change, sender='assets.File') post_delete.connect(asset_file_delete, sender='assets.Image') post_delete.connect(asset_file_delete, sender='assets.File')
from django.db.models.signals import post_delete, pre_save def asset_file_change(sender, instance, **kwargs): # Must be saved already if instance.pk is not None: old_obj = sender.objects.get(pk=instance.pk) # Delete the old file if the file names don't match if old_obj.file.name != instance.file.name: storage = old_obj.file.storage storage.delete(name=old_obj.file.name) def asset_file_delete(instance, **kwargs): # Remove the file along with it instance.file.delete(save=False) pre_save.connect(asset_file_change, sender='assets.Image') pre_save.connect(asset_file_change, sender='assets.File') post_delete.connect(asset_file_delete, sender='assets.Image') post_delete.connect(asset_file_delete, sender='assets.File')
Fix file deletion if we're using remote storage
Fix file deletion if we're using remote storage
Python
bsd-3-clause
blancltd/blanc-basic-assets
--- +++ @@ -1,26 +1,20 @@ -from django.db.models.signals import pre_save, post_delete -from django.core.files.storage import default_storage +from django.db.models.signals import post_delete, pre_save def asset_file_change(sender, instance, **kwargs): # Must be saved already if instance.pk is not None: - try: - old_obj = sender.objects.get(pk=instance.pk) + old_obj = sender.objects.get(pk=instance.pk) - # Delete the old file if the file names don't match - if old_obj.file.path != instance.file.path: - default_storage.delete(old_obj.file.path) - except: - pass + # Delete the old file if the file names don't match + if old_obj.file.name != instance.file.name: + storage = old_obj.file.storage + storage.delete(name=old_obj.file.name) -def asset_file_delete(sender, instance, **kwargs): - # Try and remove the file if possible - try: - instance.file.delete(save=False) - except: - pass +def asset_file_delete(instance, **kwargs): + # Remove the file along with it + instance.file.delete(save=False) pre_save.connect(asset_file_change, sender='assets.Image')
b04afdc4a6808029443e8107c651a24ba5f9842a
gitman/__init__.py
gitman/__init__.py
"""Package for GitMan.""" from pkg_resources import get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update __version__ = get_distribution("gitman").version
"""Package for GitMan.""" from pkg_resources import DistributionNotFound, get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update try: __version__ = get_distribution("gitman").version except DistributionNotFound: __version__ = "???"
Handle missing distribution on ReadTheDocs
Handle missing distribution on ReadTheDocs
Python
mit
jacebrowning/gitman
--- +++ @@ -1,9 +1,12 @@ """Package for GitMan.""" -from pkg_resources import get_distribution +from pkg_resources import DistributionNotFound, get_distribution from .commands import delete as uninstall # pylint: disable=redefined-builtin from .commands import display as list from .commands import init, install, lock, update -__version__ = get_distribution("gitman").version +try: + __version__ = get_distribution("gitman").version +except DistributionNotFound: + __version__ = "???"
42f2f4453552c2c01c0a066ba800b4c92d9d06f6
src/txacme/challenges/_http.py
src/txacme/challenges/_http.py
""" ``http-01`` challenge implementation. """ from twisted.web.http import OK from twisted.web.resource import Resource from zope.interface import implementer from txacme.interfaces import IResponder @implementer(IResponder) class HTTP01Responder(object): """ An ``http-01`` challenge responder for txsni. """ challenge_type = u'http-01' def __init__(self): self.resource = Resource() def start_responding(self, server_name, challenge, response): """ Add the child resource. """ self.resource.putChild(challenge.path, _HTTP01Resource(response)) def stop_responding(self, server_name, challenge, response): """ Remove the child resource. """ if self.resource.getStaticEntity(challenge.path) is not None: self.resource.delEntity(challenge.path) class _HTTP01Resource(Resource): isLeaf = True def __init__(self, response): self.response = response def render_GET(self, request): request.setResponseCode(OK) return self.response.key_authorization.encode() __all__ = ['HTTP01Responder']
""" ``http-01`` challenge implementation. """ from twisted.web.resource import Resource from twisted.web.static import Data from zope.interface import implementer from txacme.interfaces import IResponder @implementer(IResponder) class HTTP01Responder(object): """ An ``http-01`` challenge responder for txsni. """ challenge_type = u'http-01' def __init__(self): self.resource = Resource() def start_responding(self, server_name, challenge, response): """ Add the child resource. """ self.resource.putChild( challenge.encode('token'), Data(self.response.key_authorization.encode(), 'text/plain')) def stop_responding(self, server_name, challenge, response): """ Remove the child resource. """ encoded_token = challenge.encode('token') if self.resource.getStaticEntity(encoded_token) is not None: self.resource.delEntity(encoded_token) __all__ = ['HTTP01Responder']
Make HTTP01Responder's resource be at the token's path
Make HTTP01Responder's resource be at the token's path * Not /.well-known/acme-challenge/<token>, just /<token> * Use twisted.web.static.Data as the child resource
Python
mit
mithrandi/txacme
--- +++ @@ -1,8 +1,8 @@ """ ``http-01`` challenge implementation. """ -from twisted.web.http import OK from twisted.web.resource import Resource +from twisted.web.static import Data from zope.interface import implementer @@ -23,25 +23,17 @@ """ Add the child resource. """ - self.resource.putChild(challenge.path, _HTTP01Resource(response)) + self.resource.putChild( + challenge.encode('token'), + Data(self.response.key_authorization.encode(), 'text/plain')) def stop_responding(self, server_name, challenge, response): """ Remove the child resource. """ - if self.resource.getStaticEntity(challenge.path) is not None: - self.resource.delEntity(challenge.path) - - -class _HTTP01Resource(Resource): - isLeaf = True - - def __init__(self, response): - self.response = response - - def render_GET(self, request): - request.setResponseCode(OK) - return self.response.key_authorization.encode() + encoded_token = challenge.encode('token') + if self.resource.getStaticEntity(encoded_token) is not None: + self.resource.delEntity(encoded_token) __all__ = ['HTTP01Responder']
4212b35221a69468b62f933e3dbe5ffeaa9d53dc
tests/test_domain_parser.py
tests/test_domain_parser.py
import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www')
# -*- coding: utf-8 -*- import unittest from domain_parser import domain_parser class DomainParserTestCase(unittest.TestCase): def test_google(self): """Is google.com properly parsed?""" assert domain_parser.parse_domain( 'http://www.google.com') == ('com', 'google', 'www') def test_guardian(self): """Is 'co.uk', which is wildcarded in the TLD list, parsed properly?""" assert domain_parser.parse_domain( 'http://www.guardian.co.uk') == ('co.uk', 'guardian', 'www') def test_no_scheme(self): """Is 'www.google.com', which doesn't include the scheme ('http'), parsed properly?""" assert domain_parser.parse_domain( 'www.google.com') == ('com', 'google', 'www') def test_secure_scheme(self): """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') def test_internationalized_domain_name(self): """Is 'маил.гоогле.рф', which is entirely composed of non-latin characters, parsed properly?""" # Should always pass when run with Python 3. assert domain_parser.parse_domain( 'http://маил.гоогле.рф') == ('рф', 'гоогле', 'маил')
Add test for internationalized domain names
Add test for internationalized domain names Test that a domain name composed entirely of non-latin characters is parsed properly. This should always pass with Python 3 but it will fail with Python 2 because 'parse_domain' returns 'str(second_level_domain)', which tries to encode second_level_domain in ASCII.
Python
apache-2.0
jeffknupp/domain-parser,jeffknupp/domain-parser
--- +++ @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- import unittest from domain_parser import domain_parser @@ -23,3 +24,9 @@ """Is 'https://www.google.com', which include 'https' instead of 'http', parsed properly?""" assert domain_parser.parse_domain( 'https://www.google.com') == ('com', 'google', 'www') + + def test_internationalized_domain_name(self): + """Is 'маил.гоогле.рф', which is entirely composed of non-latin characters, parsed properly?""" + # Should always pass when run with Python 3. + assert domain_parser.parse_domain( + 'http://маил.гоогле.рф') == ('рф', 'гоогле', 'маил')
b7175449096717dcce9d3f90dd55e341a350b47b
flask_nav/elements.py
flask_nav/elements.py
from flask import url_for, request, current_app from markupsafe import Markup from . import get_renderer class NavigationItem(object): def render(self, renderer=None, **kwargs): return Markup( get_renderer(current_app, renderer)(**kwargs).visit(self) ) class TagItem(NavigationItem): def __init__(self, title, **attribs): self.title = title self.attribs = attribs class View(NavigationItem): def __init__(self, title, endpoint, *args, **kwargs): self.title = title self.endpoint = endpoint self.url_for_args = args self.url_for_kwargs = kwargs def get_url(self): return url_for(self.endpoint, *self.url_for_args, **self.url_for_kwargs) @property def active(self): # this is a better check because it takes arguments into account return request.path == self.get_url() class Separator(NavigationItem): pass class Subgroup(NavigationItem): def __init__(self, title, *items): self.title = title self.items = items class Label(TagItem): pass class Link(TagItem): pass class Navbar(Subgroup): id = 'nav_no_id'
from flask import url_for, request, current_app from markupsafe import Markup from . import get_renderer class NavigationItem(object): active = False def render(self, renderer=None, **kwargs): return Markup( get_renderer(current_app, renderer)(**kwargs).visit(self) ) class TagItem(NavigationItem): def __init__(self, title, **attribs): self.title = title self.attribs = attribs class View(NavigationItem): def __init__(self, title, endpoint, *args, **kwargs): self.title = title self.endpoint = endpoint self.url_for_args = args self.url_for_kwargs = kwargs def get_url(self): return url_for(self.endpoint, *self.url_for_args, **self.url_for_kwargs) @property def active(self): # this is a better check because it takes arguments into account return request.path == self.get_url() class Separator(NavigationItem): pass class Subgroup(NavigationItem): def __init__(self, title, *items): self.title = title self.items = items class Label(TagItem): pass class Link(TagItem): pass class Navbar(Subgroup): id = 'nav_no_id'
Make all navigation items have an active attribute.
Make all navigation items have an active attribute.
Python
mit
mbr/flask-nav,mbr/flask-nav
--- +++ @@ -5,6 +5,8 @@ class NavigationItem(object): + active = False + def render(self, renderer=None, **kwargs): return Markup( get_renderer(current_app, renderer)(**kwargs).visit(self)
efcdeb17ec1e3afdfbdbb50a201f90c422d7cd8e
tovp/contacts/lookups.py
tovp/contacts/lookups.py
from ajax_select import LookupChannel from django.utils.html import escape from django.db.models import Q from .models import Person class PersonLookup(LookupChannel): model = Person def get_query(self, q, request): return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q)) # .order_by('name') def get_result(self, obj): u""" result is the simple text that is the completion of what the person typed """ return obj.mixed_name def format_match(self, obj): """ (HTML) formatted item for display in the dropdown """ return self.format_item_display(obj) def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return u"%s<div></div>" % (escape(obj.mixed_name))
from ajax_select import LookupChannel from django.core.exceptions import PermissionDenied from django.utils.html import escape from django.db.models import Q from .models import Person class PersonLookup(LookupChannel): model = Person def get_query(self, q, request): return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q)) # .order_by('name') def get_result(self, obj): u""" result is the simple text that is the completion of what the person typed """ return obj.mixed_name def format_match(self, obj): """ (HTML) formatted item for display in the dropdown """ return self.format_item_display(obj) def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return u"%s<div></div>" % (escape(obj.mixed_name)) def check_auth(self, request): """Return results only to logged users.""" if not request.user.is_authenticated(): raise PermissionDenied
Allow to add contact to logged in users.
Allow to add contact to logged in users.
Python
mit
phani00/tovp,mayapurmedia/tovp,phani00/tovp,mayapurmedia/tovp,mayapurmedia/tovp,phani00/tovp
--- +++ @@ -1,4 +1,5 @@ from ajax_select import LookupChannel +from django.core.exceptions import PermissionDenied from django.utils.html import escape from django.db.models import Q from .models import Person @@ -22,3 +23,8 @@ def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return u"%s<div></div>" % (escape(obj.mixed_name)) + + def check_auth(self, request): + """Return results only to logged users.""" + if not request.user.is_authenticated(): + raise PermissionDenied
e5e621e511493a147f8ed3a7bae401874b5e5ef1
__init__.py
__init__.py
#Shoopdawoop from . import CuraEngineBackend from UM.Preferences import Preferences def getMetaData(): return { "name": "CuraBackend", "type": "Backend" } def register(app): Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine") engine = CuraEngineBackend.CuraEngineBackend() app.setBackend(engine) #engine.addCommand(TransferMeshCommand())
#Shoopdawoop from . import CuraEngineBackend from UM.Preferences import Preferences def getMetaData(): return { "name": "CuraEngine Backend", "type": "Backend" } def register(app): Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine") engine = CuraEngineBackend.CuraEngineBackend() app.setBackend(engine) #engine.addCommand(TransferMeshCommand())
Update name and displayName for a bunch of plugins
Update name and displayName for a bunch of plugins
Python
agpl-3.0
markwal/Cura,hmflash/Cura,quillford/Cura,derekhe/Cura,bq/Ultimaker-Cura,DeskboxBrazil/Cura,derekhe/Cura,ad1217/Cura,lo0ol/Ultimaker-Cura,bq/Ultimaker-Cura,Curahelper/Cura,DeskboxBrazil/Cura,quillford/Cura,fieldOfView/Cura,ynotstartups/Wanhao,lo0ol/Ultimaker-Cura,ynotstartups/Wanhao,markwal/Cura,totalretribution/Cura,fieldOfView/Cura,fxtentacle/Cura,ad1217/Cura,Curahelper/Cura,totalretribution/Cura,senttech/Cura,fxtentacle/Cura,senttech/Cura,hmflash/Cura
--- +++ @@ -4,7 +4,7 @@ from UM.Preferences import Preferences def getMetaData(): - return { "name": "CuraBackend", "type": "Backend" } + return { "name": "CuraEngine Backend", "type": "Backend" } def register(app): Preferences.addPreference("BackendLocation","../PinkUnicornEngine/CuraEngine")
b9388a64b274277eff32fe53c856527716eee282
docs/examples/servo_sweep.py
docs/examples/servo_sweep.py
from gpiozero import Servo from gpiozero.tools import sin_values servo = Servo(17) servo.source = sin_values() servo.source_delay = 0.1
from gpiozero import Servo from gpiozero.tools import sin_values from signal import pause servo = Servo(17) servo.source = sin_values() servo.source_delay = 0.1 pause()
Fix servo sweep example in docs
Fix servo sweep example in docs
Python
bsd-3-clause
waveform80/gpio-zero
--- +++ @@ -1,7 +1,10 @@ from gpiozero import Servo from gpiozero.tools import sin_values +from signal import pause servo = Servo(17) servo.source = sin_values() servo.source_delay = 0.1 + +pause()
9698dc9da2ca2ac9ba632b14e5757f0f930efe9d
Mollie/API/Object/List.py
Mollie/API/Object/List.py
from .Base import Base class List(Base): def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def __iter__(self): for item in self['data']: yield self.object_type(item) def getTotalCount(self): if 'totalCount' not in self: return None return self['totalCount'] def getOffset(self): if 'offset' not in self: return None return self['offset'] def getCount(self): if 'count' not in self: return None return self['count']
from .Base import Base class List(Base): def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def getResourceName(self): return self.object_type.__name__.lower() + 's' def __iter__(self): for item in self['_embedded'][self.getResourceName()]: yield self.object_type(item) def getTotalCount(self): if 'totalCount' not in self: return None return self['totalCount'] def getOffset(self): if 'offset' not in self: return None return self['offset'] def getCount(self): if 'count' not in self: return None return self['count']
Make list objects return the embedded resource data again
Make list objects return the embedded resource data again
Python
bsd-2-clause
mollie/mollie-api-python
--- +++ @@ -6,8 +6,11 @@ Base.__init__(self, result) self.object_type = object_type + def getResourceName(self): + return self.object_type.__name__.lower() + 's' + def __iter__(self): - for item in self['data']: + for item in self['_embedded'][self.getResourceName()]: yield self.object_type(item) def getTotalCount(self):
7a4d9c88895449b54d016226a383bde40502060c
supersaver/product/managers.py
supersaver/product/managers.py
from django.apps import apps from django.db.models import manager from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank class ProductManager (manager.Manager): # Custom manager to facilitate product query # Refs: https://docs.djangoproject.com/en/2.0/topics/db/managers/ def search(self, keywords): search_vectors = SearchVector('title', weight='A') \ + SearchVector('description', weight='C') \ + SearchVector('landing_page', weight='D') # Avoid import cycle Product = apps.get_model('product', 'Product') # The search_vector has already added as a SearchVectorField and updated by the trigger, we can use it directly. products = Product.objects.annotate(rank=SearchRank(search_vectors, keywords)) \ .filter(search_vector=keywords).order_by('-rank') return products
from datetime import datetime from django.apps import apps from django.db.models import manager from django.db.models import expressions from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank class ProductManager (manager.Manager): """ Custom manager to facilitate product query Refs: https://docs.djangoproject.com/en/2.0/topics/db/managers/ """ def _get_product_model(self): return apps.get_model('product', 'Product') def _search_by_keywords_no_sort(self, keywords): now = datetime.now().timestamp() # Use expressions.Value to represent search_vector column. # This can avoid create the search vector for each request. # The search_vector has already added as a SearchVectorField and updated by the trigger, we can use it directly. products = self.annotate(rank=SearchRank(expressions.Value('search_vector'), keywords)) \ .filter(active=True, promotion_start_date__lte=now, promotion_end_date__gt=now, search_vector=keywords) return products def search_by_relevance(self, keywords): """ search product by keyword order by relevance (desc). :param keywords: search keyword. :return: product query set. """ query_set = self._search_by_keywords_no_sort(keywords) return query_set.order_by("-rank") def search_by_price(self, keywords): """ search product by keyword order by price (asc). :param keywords: search keyword. :return: product query set. """ query_set = self._search_by_keywords_no_sort(keywords) return query_set.order_by("price")
Add 2 methods to search product by keywords.
Add 2 methods to search product by keywords.
Python
bsd-2-clause
ftkghost/SuperSaver,ftkghost/SuperSaver
--- +++ @@ -1,18 +1,46 @@ +from datetime import datetime + from django.apps import apps from django.db.models import manager +from django.db.models import expressions from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank class ProductManager (manager.Manager): - # Custom manager to facilitate product query - # Refs: https://docs.djangoproject.com/en/2.0/topics/db/managers/ - def search(self, keywords): - search_vectors = SearchVector('title', weight='A') \ - + SearchVector('description', weight='C') \ - + SearchVector('landing_page', weight='D') - # Avoid import cycle - Product = apps.get_model('product', 'Product') + """ + Custom manager to facilitate product query + Refs: https://docs.djangoproject.com/en/2.0/topics/db/managers/ + """ + + def _get_product_model(self): + return apps.get_model('product', 'Product') + + def _search_by_keywords_no_sort(self, keywords): + now = datetime.now().timestamp() + # Use expressions.Value to represent search_vector column. + # This can avoid create the search vector for each request. # The search_vector has already added as a SearchVectorField and updated by the trigger, we can use it directly. - products = Product.objects.annotate(rank=SearchRank(search_vectors, keywords)) \ - .filter(search_vector=keywords).order_by('-rank') + products = self.annotate(rank=SearchRank(expressions.Value('search_vector'), keywords)) \ + .filter(active=True, + promotion_start_date__lte=now, + promotion_end_date__gt=now, + search_vector=keywords) return products + + def search_by_relevance(self, keywords): + """ + search product by keyword order by relevance (desc). + :param keywords: search keyword. + :return: product query set. + """ + query_set = self._search_by_keywords_no_sort(keywords) + return query_set.order_by("-rank") + + def search_by_price(self, keywords): + """ + search product by keyword order by price (asc). + :param keywords: search keyword. + :return: product query set. + """ + query_set = self._search_by_keywords_no_sort(keywords) + return query_set.order_by("price")
1f38afdff13c7ccee797fe6063c75630dd642f0a
matador/commands/command.py
matador/commands/command.py
#!/usr/bin/env python import logging import argparse from matador.session import Session class Command(object): def __init__(self, **kwargs): if kwargs: # If kwargs have been supplied, use these in same way argsparse # would. # Mainly used for testing. class Args(object): pass self.args = Args() for key, value in kwargs.items(): setattr(self.args, key, value) else: # If the command is created from the command line, we'll have # arguments to parse. parser = argparse.ArgumentParser( description="Taming the bull: Change management for Agresso systems") self._add_arguments(parser) self.args, unknown = parser.parse_known_args() self._logger = logging.getLogger(__name__) Session.initialise_session() self._execute() def _add_arguments(self, parser): pass def _execute(self): raise NotImplementedError
#!/usr/bin/env python import logging import argparse from matador.session import Session class Command(object): def __init__(self, **kwargs): if kwargs: # If kwargs have been supplied, use these in same way argsparse # would. # Mainly used for testing. class Args(object): pass self.args = Args() for key, value in kwargs.items(): setattr(self.args, key, value) else: # If the command is created from the command line, we'll have # arguments to parse. parser = argparse.ArgumentParser( description="Taming the bull: Change management for Agresso systems") self._add_arguments(parser) self.args, unknown = parser.parse_known_args() self._logger = logging.getLogger(__name__) Session.initialise() self._execute() def _add_arguments(self, parser): pass def _execute(self): raise NotImplementedError
Change name of session init method
Change name of session init method
Python
mit
Empiria/matador
--- +++ @@ -26,7 +26,7 @@ self.args, unknown = parser.parse_known_args() self._logger = logging.getLogger(__name__) - Session.initialise_session() + Session.initialise() self._execute() def _add_arguments(self, parser):
a7dce25964cd740b0d0db86b255ede60c913e73d
chdb.py
chdb.py
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE IF EXISTS categories ''') db.execute(''' DROP TABLE IF EXISTS articles ''') db.execute(''' DROP TABLE IF EXISTS snippets ''') db.execute(''' DROP TABLE IF EXISTS articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT) ''') db.execute(''' INSERT INTO categories VALUES ("unassigned", "unassigned") ''') db.execute(''' CREATE TABLE articles_categories (article_id TEXT, category_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE, FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE) ''') db.execute(''' CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT, title TEXT) ''') db.execute(''' CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT, section TEXT, article_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE) ''') return db def create_indices(): db = init_db() db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles ON snippets(article_id);''')
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE categories ''') db.execute(''' DROP TABLE articles ''') db.execute(''' DROP TABLE snippets ''') db.execute(''' DROP TABLE articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT) ''') db.execute(''' INSERT INTO categories VALUES ("unassigned", "unassigned") ''') db.execute(''' CREATE TABLE articles_categories (article_id TEXT, category_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE, FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE) ''') db.execute(''' CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT, title TEXT) ''') db.execute(''' CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT, section TEXT, article_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE) ''') return db def create_indices(): db = init_db() db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles ON snippets(article_id);''')
Remove IF EXISTS from DROP TABLE when resetting the db.
Remove IF EXISTS from DROP TABLE when resetting the db.
Python
mit
Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt
--- +++ @@ -10,16 +10,16 @@ with db: db.execute(''' - DROP TABLE IF EXISTS categories + DROP TABLE categories ''') db.execute(''' - DROP TABLE IF EXISTS articles + DROP TABLE articles ''') db.execute(''' - DROP TABLE IF EXISTS snippets + DROP TABLE snippets ''') db.execute(''' - DROP TABLE IF EXISTS articles_categories + DROP TABLE articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT)
280e7cf4f7e667ccba796294c58edd5a0f744b70
geopandas/__init__.py
geopandas/__init__.py
try: from geopandas.version import version as __version__ except ImportError: __version__ = '0.1.0' from geopandas.geoseries import GeoSeries from geopandas.geodataframe import GeoDataFrame from geopandas.io.file import read_file from geopandas.io.sql import read_postgis # make the interactive namespace easier to use # for `from geopandas import *` demos. import geopandas as gpd import pandas as pd import numpy as np
try: from geopandas.version import version as __version__ except ImportError: __version__ = '0.2.0.dev-unknown' from geopandas.geoseries import GeoSeries from geopandas.geodataframe import GeoDataFrame from geopandas.io.file import read_file from geopandas.io.sql import read_postgis # make the interactive namespace easier to use # for `from geopandas import *` demos. import geopandas as gpd import pandas as pd import numpy as np
Set default version to 0.2.0.dev-unknown
BLD: Set default version to 0.2.0.dev-unknown
Python
bsd-3-clause
IamJeffG/geopandas,geopandas/geopandas,perrygeo/geopandas,jorisvandenbossche/geopandas,ozak/geopandas,ozak/geopandas,micahcochran/geopandas,jorisvandenbossche/geopandas,geopandas/geopandas,scw/geopandas,urschrei/geopandas,koldunovn/geopandas,micahcochran/geopandas,jorisvandenbossche/geopandas,kwinkunks/geopandas,jdmcbr/geopandas,fonnesbeck/geopandas,jdmcbr/geopandas,geopandas/geopandas,maxalbert/geopandas,snario/geopandas
--- +++ @@ -1,7 +1,7 @@ try: from geopandas.version import version as __version__ except ImportError: - __version__ = '0.1.0' + __version__ = '0.2.0.dev-unknown' from geopandas.geoseries import GeoSeries from geopandas.geodataframe import GeoDataFrame
d173f5688d2ea466e52e58673d920723847f12a1
gittip/utils/timer.py
gittip/utils/timer.py
import time def start(): return {'start_time': time.time()} def end(start_time): print("count#requests=1") response_time = time.time() - start_time print("measure#response_time={}ms".format(response_time * 1000))
import time def start(): return {'start_time': time.time()} def end(start_time, website): if website.log_metrics: print("count#requests=1") response_time = time.time() - start_time print("measure#response_time={}ms".format(response_time * 1000))
Clean up merge of LOG_METRICS from master
Clean up merge of LOG_METRICS from master
Python
mit
mccolgst/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com
--- +++ @@ -3,7 +3,8 @@ def start(): return {'start_time': time.time()} -def end(start_time): - print("count#requests=1") - response_time = time.time() - start_time - print("measure#response_time={}ms".format(response_time * 1000)) +def end(start_time, website): + if website.log_metrics: + print("count#requests=1") + response_time = time.time() - start_time + print("measure#response_time={}ms".format(response_time * 1000))
b75570a5897383c6fa9834c1f5f1b2aaf8d236cd
wakatime/projects/projectmap.py
wakatime/projects/projectmap.py
# -*- coding: utf-8 -*- """ wakatime.projects.projectmap ~~~~~~~~~~~~~~~~~~~~~~~~~~ Information from ~/.waka-projectmap mapping folders (relative to home folder) to project names :author: 3onyc :license: BSD, see LICENSE for more details. """ import logging import os from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): if self.settings: return True return False def branch(self): return None def name(self): for path in self._path_generator(): if self.settings.has_option('projectmap', path): return self.settings.get('projectmap', path) return None def _path_generator(self): path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
# -*- coding: utf-8 -*- """ wakatime.projects.projectmap ~~~~~~~~~~~~~~~~~~~~~~~~~~ Information from ~/.waka-projectmap mapping folders (relative to home folder) to project names :author: 3onyc :license: BSD, see LICENSE for more details. """ import logging import os from functools import partial from ..packages import simplejson as json from .base import BaseProject log = logging.getLogger(__name__) class ProjectMap(BaseProject): def process(self): if not self.settings: return False self.project = self._find_project() return self.project != None def _find_project(self): has_option = partial(self.settings.has_option, 'projectmap') get_option = partial(self.settings.get, 'projectmap') paths = self._path_generator() projects = map(get_option, filter(has_option, paths)) return projects[0] if projects else None def branch(self): return None def name(self): return self.project def _path_generator(self): """ Generates paths from the current directory up to the user's home folder stripping anything in the path before the home path """ path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path path = os.path.dirname(path)
Fix ProjectMap always returning true if it has a config section
Fix ProjectMap always returning true if it has a config section
Python
bsd-3-clause
gandarez/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,queenp/wakatime,wakatime/wakatime,prashanthr/wakatime,wangjun/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,gandarez/wakatime,queenp/wakatime,wakatime/wakatime,Djabbz/wakatime,prashanthr/wakatime,wangjun/wakatime,Djabbz/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime,wakatime/wakatime,Djabbz/wakatime,wakatime/wakatime
--- +++ @@ -12,6 +12,7 @@ import logging import os +from functools import partial from ..packages import simplejson as json @@ -23,22 +24,32 @@ class ProjectMap(BaseProject): def process(self): - if self.settings: - return True + if not self.settings: + return False - return False + self.project = self._find_project() + return self.project != None + + def _find_project(self): + has_option = partial(self.settings.has_option, 'projectmap') + get_option = partial(self.settings.get, 'projectmap') + paths = self._path_generator() + + projects = map(get_option, filter(has_option, paths)) + return projects[0] if projects else None def branch(self): return None def name(self): - for path in self._path_generator(): - if self.settings.has_option('projectmap', path): - return self.settings.get('projectmap', path) - - return None + return self.project def _path_generator(self): + """ + Generates paths from the current directory up to the user's home folder + stripping anything in the path before the home path + """ + path = self.path.replace(os.environ['HOME'], '') while path != os.path.dirname(path): yield path
73ee4af73309c4d20cf7b28ac82a5e1037a5d65a
poetry_core/packages/project_package.py
poetry_core/packages/project_package.py
from poetry_core.semver import VersionRange from poetry_core.semver import parse_constraint from poetry_core.version.markers import parse_marker from .package import Package from .utils.utils import create_nested_marker class ProjectPackage(Package): def __init__(self, name, version, pretty_version=None): super(ProjectPackage, self).__init__(name, version, pretty_version) self.build = None self.packages = [] self.include = [] self.exclude = [] self.custom_urls = {} if self._python_versions == "*": self._python_constraint = parse_constraint("~2.7 || >=3.4") def is_root(self): return True @property def python_versions(self): return self._python_versions @python_versions.setter def python_versions(self, value): self._python_versions = value if value == "*" or value == VersionRange(): value = "~2.7 || >=3.4" self._python_constraint = parse_constraint(value) self._python_marker = parse_marker( create_nested_marker("python_version", self._python_constraint) ) @property def urls(self): urls = super(ProjectPackage, self).urls urls.update(self.custom_urls) return urls
from poetry_core.semver import VersionRange from poetry_core.semver import parse_constraint from poetry_core.version.markers import parse_marker from .package import Package from .utils.utils import create_nested_marker class ProjectPackage(Package): def __init__(self, name, version, pretty_version=None): super(ProjectPackage, self).__init__(name, version, pretty_version) self.build = None self.packages = [] self.include = [] self.exclude = [] self.custom_urls = {} if self._python_versions == "*": self._python_constraint = parse_constraint("~2.7 || >=3.4") def is_root(self): return True def to_dependency(self): dependency = super(ProjectPackage, self).to_dependency() dependency.is_root = True return dependency @property def python_versions(self): return self._python_versions @python_versions.setter def python_versions(self, value): self._python_versions = value if value == "*" or value == VersionRange(): value = "~2.7 || >=3.4" self._python_constraint = parse_constraint(value) self._python_marker = parse_marker( create_nested_marker("python_version", self._python_constraint) ) @property def urls(self): urls = super(ProjectPackage, self).urls urls.update(self.custom_urls) return urls
Add the to_dependency method to ProjectPackage
Add the to_dependency method to ProjectPackage
Python
mit
python-poetry/poetry-core,python-poetry/poetry-core,python-poetry/poetry-core
--- +++ @@ -22,6 +22,13 @@ def is_root(self): return True + def to_dependency(self): + dependency = super(ProjectPackage, self).to_dependency() + + dependency.is_root = True + + return dependency + @property def python_versions(self): return self._python_versions
3043a2400e46648f01921aad265816d2bcf18211
test/test_conjunctive_graph.py
test/test_conjunctive_graph.py
from rdflib.graph import ConjunctiveGraph from rdflib.term import Identifier, URIRef from rdflib.parser import StringInputSource from os import path DATA = u""" <http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> . """ PUBLIC_ID = u"http://example.org/record/1" def test_graph_ids(): def check(kws): cg = ConjunctiveGraph() cg.parse(**kws) for g in cg.contexts(): gid = g.identifier assert isinstance(gid, Identifier) yield check, dict(data=DATA, publicID=PUBLIC_ID, format="turtle") source = StringInputSource(DATA) source.setPublicId(PUBLIC_ID) yield check, dict(source=source, format='turtle') if __name__ == '__main__': import nose nose.main(defaultTest=__name__)
from rdflib.graph import ConjunctiveGraph from rdflib.term import Identifier, URIRef from rdflib.parser import StringInputSource from os import path DATA = u""" <http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> . """ PUBLIC_ID = u"http://example.org/record/1" def test_graph_ids(): def check(kws): cg = ConjunctiveGraph() cg.parse(**kws) for g in cg.contexts(): gid = g.identifier assert isinstance(gid, Identifier) yield check, dict(data=DATA, publicID=PUBLIC_ID, format="turtle") source = StringInputSource(DATA.encode('utf8')) source.setPublicId(PUBLIC_ID) yield check, dict(source=source, format='turtle') if __name__ == '__main__': import nose nose.main(defaultTest=__name__)
Fix py3-incompatible test code that causes PY3 test failure.
Fix py3-incompatible test code that causes PY3 test failure.
Python
bsd-3-clause
avorio/rdflib,yingerj/rdflib,avorio/rdflib,RDFLib/rdflib,ssssam/rdflib,marma/rdflib,marma/rdflib,avorio/rdflib,armandobs14/rdflib,RDFLib/rdflib,dbs/rdflib,armandobs14/rdflib,yingerj/rdflib,yingerj/rdflib,ssssam/rdflib,RDFLib/rdflib,dbs/rdflib,yingerj/rdflib,marma/rdflib,dbs/rdflib,armandobs14/rdflib,RDFLib/rdflib,avorio/rdflib,marma/rdflib,ssssam/rdflib,armandobs14/rdflib,ssssam/rdflib,dbs/rdflib
--- +++ @@ -22,7 +22,7 @@ yield check, dict(data=DATA, publicID=PUBLIC_ID, format="turtle") - source = StringInputSource(DATA) + source = StringInputSource(DATA.encode('utf8')) source.setPublicId(PUBLIC_ID) yield check, dict(source=source, format='turtle')
9be02e353335db2c5923be0959595aeb35e9311c
testing/test_direct_wrapper.py
testing/test_direct_wrapper.py
import os from cffitsio._cfitsio import ffi, lib def test_create_file(tmpdir): filename = str(tmpdir.join('test.fits')) f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_create_file(f, filename, status) assert status[0] == 0 assert os.path.isfile(filename) def test_open_file(test_file): f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_open_file(f, test_file, 0, status) assert status[0] == 0
import os from cffitsio._cfitsio import ffi, lib def test_create_file(tmpdir): filename = str(tmpdir.join('test.fits')) f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_create_file(f, filename, status) assert status[0] == 0 assert os.path.isfile(filename) def test_open_file(test_file): f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_open_file(f, test_file, 0, status) assert status[0] == 0 def test_close_file(test_file): f = ffi.new('fitsfile **') status = ffi.new('int *') lib.fits_open_file(f, test_file, 0, status) assert status[0] == 0 lib.fits_close_file(f[0], status) assert status[0] == 0
Add test for file closing
Add test for file closing
Python
mit
mindriot101/fitsio-cffi
--- +++ @@ -17,3 +17,12 @@ status = ffi.new('int *') lib.fits_open_file(f, test_file, 0, status) assert status[0] == 0 + + +def test_close_file(test_file): + f = ffi.new('fitsfile **') + status = ffi.new('int *') + lib.fits_open_file(f, test_file, 0, status) + assert status[0] == 0 + lib.fits_close_file(f[0], status) + assert status[0] == 0
f29360f7351e5c72769122ea215c45df7c069f20
tests/all-errors-documented.py
tests/all-errors-documented.py
#!/usr/bin/python # Check if all the errors have been added to # docs/reference/telepathy-glib-sections.txt import os import sys import xml.dom.minidom from libglibcodegen import NS_TP def check_all_errors_documented(abs_top_srcdir): error_path = os.path.join(abs_top_srcdir, 'spec', 'errors.xml') sections_path = os.path.join(abs_top_srcdir, 'docs', 'reference', 'telepathy-glib-sections.txt') sections = open(sections_path).readlines() dom = xml.dom.minidom.parse(error_path) errors = dom.getElementsByTagNameNS(NS_TP, 'errors')[0] for error in errors.getElementsByTagNameNS(NS_TP, 'error'): nick = error.getAttribute('name').replace(' ', '') name = ('TP_ERROR_STR_' + error.getAttribute('name').replace('.', '_').replace(' ', '_').upper() if '%s\n' % name not in sections: print "'%s' is missing in %s" % (name, sections_path) sys.exit(1) if __name__ == '__main__': check_all_errors_documented(os.environ['abs_top_srcdir'])
#!/usr/bin/python # Check if all the errors have been added to # docs/reference/telepathy-glib-sections.txt import os import sys import xml.dom.minidom from libglibcodegen import NS_TP def check_all_errors_documented(abs_top_srcdir): error_path = os.path.join(abs_top_srcdir, 'spec', 'errors.xml') sections_path = os.path.join(abs_top_srcdir, 'docs', 'reference', 'telepathy-glib-sections.txt') sections = open(sections_path).readlines() dom = xml.dom.minidom.parse(error_path) errors = dom.getElementsByTagNameNS(NS_TP, 'errors')[0] for error in errors.getElementsByTagNameNS(NS_TP, 'error'): nick = error.getAttribute('name').replace(' ', '') name = ('TP_ERROR_STR_' + error.getAttribute('name').replace('.', '_').replace(' ', '_').upper()) if '%s\n' % name not in sections: print "'%s' is missing in %s" % (name, sections_path) sys.exit(1) if __name__ == '__main__': check_all_errors_documented(os.environ['abs_top_srcdir'])
Add missing parenthesis to fix syntax of test
Add missing parenthesis to fix syntax of test
Python
lgpl-2.1
Distrotech/telepathy-glib,Distrotech/telepathy-glib,Distrotech/telepathy-glib,Distrotech/telepathy-glib,Distrotech/telepathy-glib
--- +++ @@ -21,7 +21,7 @@ for error in errors.getElementsByTagNameNS(NS_TP, 'error'): nick = error.getAttribute('name').replace(' ', '') name = ('TP_ERROR_STR_' + - error.getAttribute('name').replace('.', '_').replace(' ', '_').upper() + error.getAttribute('name').replace('.', '_').replace(' ', '_').upper()) if '%s\n' % name not in sections: print "'%s' is missing in %s" % (name, sections_path)
a77b62ccadf578b8e352e4fdae8e4efe5060f938
workshopvenues/venues/models.py
workshopvenues/venues/models.py
from django.db import models class Venues(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10)
from django.db import models class Venues(models.Model): name = models.CharField(max_length=30) website = models.CharField(max_length=50) address = models.CharField(max_length=200) town = models.CharField(max_length=30) postcode = models.CharField(max_length=10) def __unicode__(self): return self.name
Add descriptive name to Venues model
Add descriptive name to Venues model
Python
bsd-3-clause
andreagrandi/workshopvenues
--- +++ @@ -1,8 +1,11 @@ from django.db import models class Venues(models.Model): - name = models.CharField(max_length=30) - website = models.CharField(max_length=50) - address = models.CharField(max_length=200) - town = models.CharField(max_length=30) - postcode = models.CharField(max_length=10) + name = models.CharField(max_length=30) + website = models.CharField(max_length=50) + address = models.CharField(max_length=200) + town = models.CharField(max_length=30) + postcode = models.CharField(max_length=10) + + def __unicode__(self): + return self.name
bdecfc7f31b13718957e598947eb52b2e7988fd6
numba/postpasses.py
numba/postpasses.py
# -*- coding: utf-8 -*- """ Postpasses over the LLVM IR. The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc """ from __future__ import print_function, division, absolute_import from numba.support.math_support import math_support default_postpasses = {} def register_default(name): def dec(f): default_postpasses[name] = f return f return dec # ______________________________________________________________________ # Postpasses @register_default('math') def postpass_link_math(env, ee, lmod, lfunc): "numba.math.* -> mathcode.*" env.llvm_context.execution_engine math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library) return lfunc
# -*- coding: utf-8 -*- """ Postpasses over the LLVM IR. The signature of each postpass is postpass(env, ee, lmod, lfunc) -> lfunc """ from __future__ import print_function, division, absolute_import from numba.support.math_support import math_support default_postpasses = {} def register_default(name): def dec(f): default_postpasses[name] = f return f return dec # ______________________________________________________________________ # Postpasses @register_default('math') def postpass_link_math(env, ee, lmod, lfunc): "numba.math.* -> mathcode.*" math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library) return lfunc
Add pointer from math library to external numba.math.* functions
Add pointer from math library to external numba.math.* functions
Python
bsd-2-clause
pombredanne/numba,GaZ3ll3/numba,ssarangi/numba,numba/numba,ssarangi/numba,ssarangi/numba,stefanseefeld/numba,cpcloud/numba,pitrou/numba,cpcloud/numba,pitrou/numba,pitrou/numba,stuartarchibald/numba,jriehl/numba,gdementen/numba,stefanseefeld/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,IntelLabs/numba,GaZ3ll3/numba,gmarkall/numba,gmarkall/numba,seibert/numba,seibert/numba,IntelLabs/numba,gmarkall/numba,pombredanne/numba,sklam/numba,jriehl/numba,stefanseefeld/numba,gdementen/numba,numba/numba,jriehl/numba,pombredanne/numba,numba/numba,cpcloud/numba,ssarangi/numba,seibert/numba,stuartarchibald/numba,pombredanne/numba,gdementen/numba,GaZ3ll3/numba,cpcloud/numba,stonebig/numba,seibert/numba,sklam/numba,pitrou/numba,GaZ3ll3/numba,gmarkall/numba,stonebig/numba,gdementen/numba,gmarkall/numba,jriehl/numba,sklam/numba,stefanseefeld/numba,seibert/numba,stuartarchibald/numba,numba/numba,IntelLabs/numba,gdementen/numba,pitrou/numba,stonebig/numba,stonebig/numba,stonebig/numba,sklam/numba,ssarangi/numba,sklam/numba,stuartarchibald/numba,cpcloud/numba,GaZ3ll3/numba,pombredanne/numba,stefanseefeld/numba,jriehl/numba,IntelLabs/numba
--- +++ @@ -23,6 +23,5 @@ @register_default('math') def postpass_link_math(env, ee, lmod, lfunc): "numba.math.* -> mathcode.*" - env.llvm_context.execution_engine math_support.link_llvm_math_intrinsics(ee, lmod, math_support.llvm_library) return lfunc
25d36ba71aed866de468363ea6004eabbd8f22da
publish/tools/crontool.py
publish/tools/crontool.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This tool iterates through all of the scrapers in the datasets module and creates a cron-task for each one. ''' import os import pkgutil import random import sys from publish.lib.manifest import get_scraper_names def get_launch_binary(): this_location = sys.argv[0] return os.path.join(os.path.dirname(this_location), "run_scraper") def get_dmswitch_binary(): this_location = sys.argv[0] return os.path.join(os.path.dirname(this_location), "dmswitch") def get_random_hours_and_minutes(): random.seed() return random.choice(xrange(0, 23)), random.choice(xrange(0, 60, 5)) def main(): binary = get_launch_binary() dmswitch = get_dmswitch_binary() for scraper in get_scraper_names(): cli = "{cmd} {scraper} && {dms} --switch {scraper}"\ .format(cmd=binary, scraper=scraper, dms=dmswitch) hour, minute = get_random_hours_and_minutes() crontime = "{} {} * * * {}".format(minute, hour, cli) print crontime
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This tool iterates through all of the scrapers in the datasets module and creates a cron-task for each one. ''' import os import pkgutil import random import sys from publish.lib.manifest import get_scraper_names def get_launch_binary(): this_location = sys.argv[0] path = os.path.join(os.path.dirname(this_location), "run_scraper") return os.path.abspath(path) def get_dmswitch_binary(): this_location = sys.argv[0] path = os.path.join(os.path.dirname(this_location), "dmswitch") return os.path.abspath(path) def get_random_hours_and_minutes(): random.seed() return random.choice(xrange(0, 23)), random.choice(xrange(0, 60, 5)) def main(): binary = get_launch_binary() dmswitch = get_dmswitch_binary() for scraper in get_scraper_names(): cli = "{cmd} {scraper} && {dms} --switch {scraper}"\ .format(cmd=binary, scraper=scraper, dms=dmswitch) hour, minute = get_random_hours_and_minutes() crontime = "{} {} * * * {}".format(minute, hour, cli) print crontime
Make sure we use the absolute path in generating cron lines
Make sure we use the absolute path in generating cron lines
Python
mit
nhsengland/publish-o-matic
--- +++ @@ -14,11 +14,13 @@ def get_launch_binary(): this_location = sys.argv[0] - return os.path.join(os.path.dirname(this_location), "run_scraper") + path = os.path.join(os.path.dirname(this_location), "run_scraper") + return os.path.abspath(path) def get_dmswitch_binary(): this_location = sys.argv[0] - return os.path.join(os.path.dirname(this_location), "dmswitch") + path = os.path.join(os.path.dirname(this_location), "dmswitch") + return os.path.abspath(path) def get_random_hours_and_minutes(): random.seed()
ad17e166cac2863692af96bccf0317d97e102e24
tests/integration/test_juju.py
tests/integration/test_juju.py
import pytest from juju.controller import Controller from juju.juju import Juju from .. import base @base.bootstrapped @pytest.mark.asyncio async def test_get_controllers(event_loop): async with base.CleanController() as controller: j = Juju() controllers = j.get_controllers() assert isinstance(controllers, dict) assert len(controllers) >= 1 assert controller.controller_name in controllers cc = await j.get_controller(controller.controller_name) assert isinstance(cc, Controller) assert controller.connection().endpoint == cc.connection().endpoint
import pytest from juju.controller import Controller from juju.juju import Juju from .. import base @base.bootstrapped @pytest.mark.asyncio async def test_get_controllers(event_loop): async with base.CleanController() as controller: j = Juju() controllers = j.get_controllers() assert isinstance(controllers, dict) assert len(controllers) >= 1 assert controller.controller_name in controllers cc = await j.get_controller(controller.controller_name) assert isinstance(cc, Controller) assert controller.connection().endpoint == cc.connection().endpoint await cc.disconnect()
Make sure to disconnect the extra connection before finishing the test
Make sure to disconnect the extra connection before finishing the test
Python
apache-2.0
juju/python-libjuju,juju/python-libjuju
--- +++ @@ -19,3 +19,4 @@ cc = await j.get_controller(controller.controller_name) assert isinstance(cc, Controller) assert controller.connection().endpoint == cc.connection().endpoint + await cc.disconnect()
ab1fca145208dfcc0581fce8076b8f52fe237b94
src/settings.py
src/settings.py
# -*- coding: utf-8 -*- import os HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000') class ProdConfig(Config): ENV = 'prod' DEBUG = False class DevConfig(Config): ENV = 'dev' DEBUG = True LOAD_FAKE_DATA = True class TestConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'postgresql://localhost/') TESTING = True DEBUG = True # For: `nose.proxy.AssertionError: Popped wrong request context.` # http://stackoverflow.com/a/28139033/399726 # https://github.com/jarus/flask-testing/issues/21 PRESERVE_CONTEXT_ON_EXCEPTION = False
# -*- coding: utf-8 -*- import os HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000') class ProdConfig(Config): ENV = 'prod' DEBUG = False class DevConfig(Config): ENV = 'dev' DEBUG = True LOAD_FAKE_DATA = True class TestConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'postgresql://localhost/') TESTING = True DEBUG = True # For: `nose.proxy.AssertionError: Popped wrong request context.` # http://stackoverflow.com/a/28139033/399726 # https://github.com/jarus/flask-testing/issues/21 PRESERVE_CONTEXT_ON_EXCEPTION = False
Set production databse to test database
Set production databse to test database
Python
mit
codeforamerica/pdfhook,codeforamerica/pdfhook,codeforamerica/pdfhook,gauravmk/pdfhook,gauravmk/pdfhook,gauravmk/pdfhook
--- +++ @@ -8,7 +8,7 @@ class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False - SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') + SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000')
497116839db95bf734ed66e5cf87e986141ad50d
txircd/modules/rfc/cmd_info.py
txircd/modules/rfc/cmd_info.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") user.sendMessage(irc.RPL_INFO, ": ekimekim") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()
Add self to contributors list
Add self to contributors list
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
--- +++ @@ -26,6 +26,7 @@ user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") + user.sendMessage(irc.RPL_INFO, ": ekimekim") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True
6292cd114d8d982162fa8076605cce569acd8fc5
panphon/xsampa.py
panphon/xsampa.py
from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) xs_regex = re.compile('|'.join(map(re.escape, xs))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) ipasegs = map(seg2ipa, xsampa.split(self.delimiter)) return ''.join(ipasegs)
from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) xs_regex = re.compile('|'.join(list(map(re.escape, xs)))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter))) return ''.join(ipasegs)
Convert map objects to lists
Convert map objects to lists
Python
mit
dmort27/panphon,dmort27/panphon
--- +++ @@ -17,7 +17,7 @@ with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) - xs_regex = re.compile('|'.join(map(re.escape, xs))) + xs_regex = re.compile('|'.join(list(map(re.escape, xs)))) return xs_regex, xs2ipa def convert(self, xsampa): @@ -31,5 +31,5 @@ else: seg = seg[1:] return ''.join(ipa) - ipasegs = map(seg2ipa, xsampa.split(self.delimiter)) + ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter))) return ''.join(ipasegs)
2809f97696791f34e659dc9fc3c9e29c802082d2
django_evolution/tests/test_evolution_models.py
django_evolution/tests/test_evolution_models.py
from datetime import datetime from django.test.testcases import TestCase from django_evolution.models import Version class VersionManagerTests(TestCase): """Unit tests for django_evolution.models.VersionManager.""" def test_current_version_with_dup_timestamps(self): """Testing Version.current_version() with two entries with same timestamps""" timestamp = datetime(year=2015, month=12, day=10, hour=12, minute=13, second=14) Version.objects.create(signature='abc123', when=timestamp) version = Version.objects.create(signature='abc123-def456', when=timestamp) latest_version = Version.objects.current_version() self.assertEqual(latest_version, version)
from datetime import datetime from django.test.testcases import TestCase from django_evolution.models import Version class VersionManagerTests(TestCase): """Unit tests for django_evolution.models.VersionManager.""" def test_current_version_with_dup_timestamps(self): """Testing Version.current_version() with two entries with same timestamps""" # Remove anything that may already exist. Version.objects.all().delete() timestamp = datetime(year=2015, month=12, day=10, hour=12, minute=13, second=14) Version.objects.create(signature='abc123', when=timestamp) version = Version.objects.create(signature='abc123-def456', when=timestamp) latest_version = Version.objects.current_version() self.assertEqual(latest_version, version)
Fix unit tests for Version.objects.get_current().
Fix unit tests for Version.objects.get_current(). The unit tests assumed that no Version objects were present, but this wasn't always the case. This clears them before the test runs.
Python
bsd-3-clause
beanbaginc/django-evolution
--- +++ @@ -10,6 +10,9 @@ def test_current_version_with_dup_timestamps(self): """Testing Version.current_version() with two entries with same timestamps""" + # Remove anything that may already exist. + Version.objects.all().delete() + timestamp = datetime(year=2015, month=12, day=10, hour=12, minute=13, second=14)
8ebaf59aa2f966bf0a807c1cbce5359ae0868863
tests/encode_decode_tests.py
tests/encode_decode_tests.py
# -*- encoding: utf-8 -*- from datetime import datetime from decimal import Decimal try: import unittest2 as unittest except ImportError: import unittest from pamqp import encode, decode from pamqp import PYTHON3 if PYTHON3: long = int def to_bytes(value): if isinstance(value, bytes): return bytes if PYTHON3: return bytes(value, 'utf-8') return bytes(value) class EncodeDecodeTests(unittest.TestCase): def test_encode_decode_field_table_long_keys(self): """Encoding and decoding a field_table with too long keys.""" # second key is 126 A's + \N{PILE OF POO} data = {'A' * 256: 1, ((b'A' * 128) + b'\xf0\x9f\x92\xa9').decode('utf-8'): 2} encoded = encode.field_table(data) decoded = decode.field_table(encoded)[1] self.assertIn(b'A' * 128, decoded)
# -*- encoding: utf-8 -*- from datetime import datetime from decimal import Decimal try: import unittest2 as unittest except ImportError: import unittest from pamqp import encode, decode from pamqp import PYTHON3 if PYTHON3: long = int def to_bytes(value): if isinstance(value, bytes): return bytes if PYTHON3: return bytes(value, 'utf-8') return bytes(value) class EncodeDecodeTests(unittest.TestCase): def test_encode_decode_field_table_long_keys(self): """Encoding and decoding a field_table with too long keys.""" # second key is 126 A's + \N{PILE OF POO} data = {'A' * 256: 1, ((b'A' * 128) + b'\xf0\x9f\x92\xa9').decode('utf-8'): 2} encoded = encode.field_table(data) decoded = decode.field_table(encoded)[1] self.assertIn('A' * 128, decoded)
Update to reflect str key change
Update to reflect str key change
Python
bsd-3-clause
gmr/pamqp
--- +++ @@ -30,4 +30,4 @@ ((b'A' * 128) + b'\xf0\x9f\x92\xa9').decode('utf-8'): 2} encoded = encode.field_table(data) decoded = decode.field_table(encoded)[1] - self.assertIn(b'A' * 128, decoded) + self.assertIn('A' * 128, decoded)
e3959d1dcf33dff0d69ba36abf2ff37f2dcf8d60
spiff/membership/tests.py
spiff/membership/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from django.contrib.auth.models import User, Group import models class MemberTest(TestCase): def testUserCreation(self): u = User.objects.create_user('test', 'test@example.com', 'test') self.assertIsNotNone(u.member) self.assertEqual(u.member.user, u) u.delete() class RankTest(TestCase): def testGroupCreation(self): g = Group.objects.create(name="Test Group") self.assertIsNotNone(g.rank) self.assertEqual(g.rank.group, g) g.delete() class PaymentTest(TestCase): def setUp(self): self.user = User.objects.create_user('test', 'test@example.com', 'test') def tearDown(self): self.user.delete() def testCreation(self): p = models.DuePayment.objects.create(member=self.user.member, value=1) self.assertEqual(p.value, 1) self.assertEqual(len(self.user.member.payments.all()), 1)
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from django.contrib.auth.models import User, Group import models from spiff.payment.models import Payment class MemberTest(TestCase): def testUserCreation(self): u = User.objects.create_user('test', 'test@example.com', 'test') self.assertIsNotNone(u.member) self.assertEqual(u.member.user, u) u.delete() class RankTest(TestCase): def testGroupCreation(self): g = Group.objects.create(name="Test Group") self.assertIsNotNone(g.rank) self.assertEqual(g.rank.group, g) g.delete()
Remove broken and old test
Remove broken and old test
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
--- +++ @@ -8,6 +8,7 @@ from django.test import TestCase from django.contrib.auth.models import User, Group import models +from spiff.payment.models import Payment class MemberTest(TestCase): def testUserCreation(self): @@ -22,15 +23,3 @@ self.assertIsNotNone(g.rank) self.assertEqual(g.rank.group, g) g.delete() - -class PaymentTest(TestCase): - def setUp(self): - self.user = User.objects.create_user('test', 'test@example.com', 'test') - - def tearDown(self): - self.user.delete() - - def testCreation(self): - p = models.DuePayment.objects.create(member=self.user.member, value=1) - self.assertEqual(p.value, 1) - self.assertEqual(len(self.user.member.payments.all()), 1)
2430e87f2c44c46863ed47c8b3a55c4010820260
frontend/modloop/__init__.py
frontend/modloop/__init__.py
from flask import render_template, request, send_from_directory import saliweb.frontend from saliweb.frontend import get_completed_job from . import submit app = saliweb.frontend.make_application(__name__, "##CONFIG##") @app.route('/') def index(): return render_template('index.html') @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/help') def help(): return render_template('help.html') @app.route('/download') def download(): return render_template('download.html') @app.route('/job', methods=['GET', 'POST']) def job(): if request.method == 'GET': return saliweb.frontend.render_queue_page() else: return submit.handle_new_job() @app.route('/job/<name>') def results(name): job = get_completed_job(name, request.args.get('passwd')) return render_template('results.html', job=job) @app.route('/job/<name>/<path:fp>') def results_file(name, fp): job = get_completed_job(name, request.args.get('passwd')) return send_from_directory(job.directory, fp)
from flask import render_template, request, send_from_directory import saliweb.frontend from saliweb.frontend import get_completed_job, Parameter, FileParameter from . import submit parameters=[Parameter("name", "Job name", optional=True), FileParameter("pdb", "PDB file to be refined"), Parameter("modkey", "MODELLER license key"), Parameter("loops", "Loops to be refined")] app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters) @app.route('/') def index(): return render_template('index.html') @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/help') def help(): return render_template('help.html') @app.route('/download') def download(): return render_template('download.html') @app.route('/job', methods=['GET', 'POST']) def job(): if request.method == 'GET': return saliweb.frontend.render_queue_page() else: return submit.handle_new_job() @app.route('/job/<name>') def results(name): job = get_completed_job(name, request.args.get('passwd')) return saliweb.frontend.render_results_template('results.html', job=job) @app.route('/job/<name>/<path:fp>') def results_file(name, fp): job = get_completed_job(name, request.args.get('passwd')) return send_from_directory(job.directory, fp)
Add basic REST API support
Add basic REST API support
Python
lgpl-2.1
salilab/modloop,salilab/modloop
--- +++ @@ -1,10 +1,14 @@ from flask import render_template, request, send_from_directory import saliweb.frontend -from saliweb.frontend import get_completed_job +from saliweb.frontend import get_completed_job, Parameter, FileParameter from . import submit -app = saliweb.frontend.make_application(__name__, "##CONFIG##") +parameters=[Parameter("name", "Job name", optional=True), + FileParameter("pdb", "PDB file to be refined"), + Parameter("modkey", "MODELLER license key"), + Parameter("loops", "Loops to be refined")] +app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters) @app.route('/') @@ -38,7 +42,7 @@ @app.route('/job/<name>') def results(name): job = get_completed_job(name, request.args.get('passwd')) - return render_template('results.html', job=job) + return saliweb.frontend.render_results_template('results.html', job=job) @app.route('/job/<name>/<path:fp>')
3e6aa4b740b6b22b7ea381db71f76c0c692afa53
pydispatch/__init__.py
pydispatch/__init__.py
import sys import warnings import pkg_resources try: __version__ = pkg_resources.require('python-dispatch')[0].version except: # pragma: no cover __version__ = 'unknown' if sys.version_info < (3, 6): # pragma: no cover warnings.warn('You are using `python-dispatch` with a deprecated Python version. ' 'After version 0.1.x, `python-dispatch` will only support Python 3.6 or greater.', UserWarning) from pydispatch.dispatch import Dispatcher from pydispatch.properties import *
import sys import warnings import pkg_resources try: __version__ = pkg_resources.require('python-dispatch')[0].version except: # pragma: no cover __version__ = 'unknown' if sys.version_info < (3, 6): # pragma: no cover warnings.warn('You are using `python-dispatch` with a deprecated Python version. ' 'After version 0.1.x, `python-dispatch` will only support Python 3.6 or greater.', UserWarning) from pydispatch.dispatch import Dispatcher, Event from pydispatch.properties import *
Add back missing import from merge commit c40da341b
Add back missing import from merge commit c40da341b
Python
mit
nocarryr/python-dispatch
--- +++ @@ -12,5 +12,5 @@ 'After version 0.1.x, `python-dispatch` will only support Python 3.6 or greater.', UserWarning) -from pydispatch.dispatch import Dispatcher +from pydispatch.dispatch import Dispatcher, Event from pydispatch.properties import *
27e7f47f2506be8607f29961dd629a8038c7e67f
ecmd-core/pyecmd/test_api.py
ecmd-core/pyecmd/test_api.py
from pyecmd import * with Ecmd(fapi2="ver1"): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
from pyecmd import * extensions = {} if hasattr(ecmd, "fapi2InitExtension"): extensions["fapi2"] = "ver1" with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) # These interfaces may not be defined for some plugins # Pull them to prevent compile issues #core_id, thread_id = t.targetToSequenceId() #unit_id_string = unitIdToString(2) #clock_state = t.queryClockState("SOMECLOCK") t.relatedTargets("pu.c") retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version if "fapi2" in extensions: try: t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") assert(""=="That was supposed to throw!") except KeyError: pass t.fapi2SetAttr("ATTR_CHIP_ID", 42) assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
Make fapi2 test conditional on fapi2 being built into ecmd
pyecmd: Make fapi2 test conditional on fapi2 being built into ecmd
Python
apache-2.0
open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD
--- +++ @@ -1,6 +1,10 @@ from pyecmd import * -with Ecmd(fapi2="ver1"): +extensions = {} +if hasattr(ecmd, "fapi2InitExtension"): + extensions["fapi2"] = "ver1" + +with Ecmd(**extensions): t = loopTargets("pu", ECMD_SELECTED_TARGETS_LOOP)[0] data = t.getScom(0x1234) t.putScom(0x1234, 0x10100000) @@ -13,11 +17,13 @@ retval = t.queryFileLocation(ECMD_FILE_SCANDEF, "") for loc in retval.fileLocations: testval = loc.textFile + loc.hashFile + retval.version - try: - t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") - assert(""=="That was supposed to throw!") - except KeyError: - pass - t.fapi2SetAttr("ATTR_CHIP_ID", 42) - assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID")) + if "fapi2" in extensions: + try: + t.fapi2GetAttr("ATTR_DOES_NOT_EXIST") + assert(""=="That was supposed to throw!") + except KeyError: + pass + + t.fapi2SetAttr("ATTR_CHIP_ID", 42) + assert(42 == t.fapi2GetAttr("ATTR_CHIP_ID"))
aca410866dfdd9ced23df14fb3e51fb02f910e85
IPython/html/widgets/__init__.py
IPython/html/widgets/__init__.py
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual from .widget_link import Link, link, DirectionalLink, dlink # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from warnings import warn warn("""The widget API is still considered experimental and may change in the future.""", FutureWarning, stacklevel=2)
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual from .widget_link import Link, link, DirectionalLink, dlink # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from warnings import warn warn("IPython widgets are experimental and may change in the future.", FutureWarning, stacklevel=2)
Make the widget error message shorter and more understandable.
Make the widget error message shorter and more understandable.
Python
bsd-3-clause
jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets
--- +++ @@ -26,4 +26,4 @@ # Warn on import from warnings import warn -warn("""The widget API is still considered experimental and may change in the future.""", FutureWarning, stacklevel=2) +warn("IPython widgets are experimental and may change in the future.", FutureWarning, stacklevel=2)
69d18539fb4f394ca45d1116a521084c83ea21b5
icekit_events/migrations/0012_auto_20160706_1606.py
icekit_events/migrations/0012_auto_20160706_1606.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_events', '0011_event_show_in_calendar'), ] operations = [ migrations.AlterModelTable( name='event', table=None, ), migrations.AlterModelTable( name='recurrencerule', table=None, ), migrations.RunSQL( "UPDATE django_content_type SET app_label='icekit_events' WHERE app_label='eventkit'", # No-op: I haven't yet found a way to make this reversible in the # way you would expect without unique constraint DB errors, whereas # it works (according to unit tests at least) with a no-op. "", ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_events', '0011_event_show_in_calendar'), ] operations = [ migrations.AlterModelTable( name='event', table=None, ), migrations.AlterModelTable( name='recurrencerule', table=None, ), migrations.RunSQL( "UPDATE django_content_type SET app_label='icekit_events' WHERE app_label='eventkit'", # No-op: I haven't yet found a way to make this reversible in the # way you would expect without unique constraint DB errors, whereas # it works (according to unit tests at least) with a no-op. "UPDATE django_content_type SET app_label=app_label WHERE app_label='NONE!'", ), ]
Make migration reverse no-op a valid SQL query
Make migration reverse no-op a valid SQL query When using a PostgreSQL database with Django 1.7 empty reverse query statements in DB migrations cause an error, so we replace the empty no-op statement with a valid query that still does nothing so the reverse migration will work in this case. This problem doesn't seem to affect Django 1.8, which must be smarter about accepted but not actually running empty statements in DB migrations.
Python
mit
ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
--- +++ @@ -24,6 +24,6 @@ # No-op: I haven't yet found a way to make this reversible in the # way you would expect without unique constraint DB errors, whereas # it works (according to unit tests at least) with a no-op. - "", + "UPDATE django_content_type SET app_label=app_label WHERE app_label='NONE!'", ), ]
8c20bb711486a95cc861ffeb4bd61e67b3d8f99b
ledger-core-samples/nodejs/glob.py
ledger-core-samples/nodejs/glob.py
#!/usr/bin/env python # a helper for gyp to do file globbing cross platform # Usage: python glob.py root_dir pattern [pattern...] import fnmatch import os import sys root_dir = sys.argv[1] patterns = sys.argv[2:] for (dirpath, dirnames, files) in os.walk(root_dir): for f in files: match = False for pattern in patterns: match = match or fnmatch.fnmatch(f, pattern) if match: print dirpath + '/' + f
#!/usr/bin/env python # a helper for gyp to do file globbing cross platform # Usage: python glob.py root_dir pattern [pattern...] import fnmatch import os import sys root_dir = sys.argv[1] patterns = sys.argv[2:] for (dirpath, dirnames, files) in os.walk(root_dir): for f in files: match = False for pattern in patterns: match = match or fnmatch.fnmatch(f, pattern) if match: print(dirpath + '/' + f)
Fix Python invokation (2.7 -> 3.7) in ledger-samples.
Fix Python invokation (2.7 -> 3.7) in ledger-samples.
Python
mit
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
--- +++ @@ -15,4 +15,4 @@ for pattern in patterns: match = match or fnmatch.fnmatch(f, pattern) if match: - print dirpath + '/' + f + print(dirpath + '/' + f)
033c16034074d4fd6eab054a9c97888d23668316
tests/test_empty_polygons.py
tests/test_empty_polygons.py
from shapely.geometry import MultiPolygon, Polygon def test_empty_polygon(): """No constructor arg makes an empty polygon geometry.""" assert Polygon().is_empty def test_empty_multipolygon(): """No constructor arg makes an empty multipolygon geometry.""" assert MultiPolygon().is_empty def test_multipolygon_empty_polygon(): """An empty polygon passed to MultiPolygon() makes an empty multipolygon geometry.""" assert MultiPolygon([Polygon()]).is_empty
from shapely.geometry import MultiPolygon, Point, Polygon def test_empty_polygon(): """No constructor arg makes an empty polygon geometry.""" assert Polygon().is_empty def test_empty_multipolygon(): """No constructor arg makes an empty multipolygon geometry.""" assert MultiPolygon().is_empty def test_multipolygon_empty_polygon(): """An empty polygon passed to MultiPolygon() makes an empty multipolygon geometry.""" assert MultiPolygon([Polygon()]).is_empty def test_multipolygon_empty_among_polygon(): """An empty polygon passed to MultiPolygon() is ignored.""" assert len(MultiPolygon([Point(0,0).buffer(1.0), Polygon()])) == 1
Add test of an empty and non empty polygon
Add test of an empty and non empty polygon
Python
bsd-3-clause
jdmcbr/Shapely,jdmcbr/Shapely
--- +++ @@ -1,4 +1,4 @@ -from shapely.geometry import MultiPolygon, Polygon +from shapely.geometry import MultiPolygon, Point, Polygon def test_empty_polygon(): @@ -15,3 +15,8 @@ """An empty polygon passed to MultiPolygon() makes an empty multipolygon geometry.""" assert MultiPolygon([Polygon()]).is_empty + + +def test_multipolygon_empty_among_polygon(): + """An empty polygon passed to MultiPolygon() is ignored.""" + assert len(MultiPolygon([Point(0,0).buffer(1.0), Polygon()])) == 1
c28b0f5ea02652f7899e34d9a8779e2ff47d8020
tests/test_internal_links.py
tests/test_internal_links.py
# -*- encoding: utf-8 from http_crawler import crawl def test_no_links_are_broken(baseurl): """ Check that all internal links point to working pages. """ responses = [] for rsp in crawl(baseurl, follow_external_links=False): responses.append(rsp) failed_responses = [rsp for rsp in responses if rsp.status_code != 200] failures = [ '%s (%d)' % (rsp.url, rsp.status_code) for rsp in failed_responses ] print('\n'.join(failures)) assert len(failures) == 0
# -*- encoding: utf-8 from http_crawler import crawl import pytest _responses = [] @pytest.fixture def responses(baseurl): if not _responses: for rsp in crawl(baseurl, follow_external_links=False): _responses.append(rsp) return _responses def test_no_links_are_broken(responses): """ Check that all internal links point to working pages. """ failed_responses = [rsp for rsp in responses if rsp.status_code != 200] failures = [ '%s (%d)' % (rsp.url, rsp.status_code) for rsp in failed_responses ] print('\n'.join(failures)) assert len(failures) == 0
Move the responses to a cacheable fixture
Move the responses to a cacheable fixture
Python
mit
alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net
--- +++ @@ -1,16 +1,23 @@ # -*- encoding: utf-8 from http_crawler import crawl +import pytest + +_responses = [] -def test_no_links_are_broken(baseurl): +@pytest.fixture +def responses(baseurl): + if not _responses: + for rsp in crawl(baseurl, follow_external_links=False): + _responses.append(rsp) + return _responses + + +def test_no_links_are_broken(responses): """ Check that all internal links point to working pages. """ - responses = [] - for rsp in crawl(baseurl, follow_external_links=False): - responses.append(rsp) - failed_responses = [rsp for rsp in responses if rsp.status_code != 200] failures = [ '%s (%d)' % (rsp.url, rsp.status_code)
3bb2258e75658f8e9c01217fc9b0ae7f53df861a
extensions/ExtGameController.py
extensions/ExtGameController.py
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, game=None): super(ExtGameController, self).__init__(game=game) # self.add_mode(self.additional_modes)
from python_cowbull_game.GameController import GameController from python_cowbull_game.GameMode import GameMode class ExtGameController(GameController): additional_modes = [ GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0), GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1) ] def __init__(self, game=None): super(ExtGameController, self).__init__(game=game) self.add_mode(self.additional_modes)
Update Dockerfile to include extensions
Update Dockerfile to include extensions
Python
apache-2.0
dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server
--- +++ @@ -10,4 +10,4 @@ def __init__(self, game=None): super(ExtGameController, self).__init__(game=game) -# self.add_mode(self.additional_modes) + self.add_mode(self.additional_modes)
178006e4a299ca67e758184be50ae94333f09821
test_settings.py
test_settings.py
from malaria24.settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'malaria24', } } ONAPIE_ACCESS_TOKEN = 'foo' VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY' VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN' VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
from malaria24.settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'malaria24', } } ONAPIE_ACCESS_TOKEN = 'foo' ONA_API_URL = 'https://odk.ona.io' VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY' VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN' VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
Add url setting to test settings
Add url setting to test settings
Python
bsd-2-clause
praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django
--- +++ @@ -8,6 +8,7 @@ } ONAPIE_ACCESS_TOKEN = 'foo' +ONA_API_URL = 'https://odk.ona.io' VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY' VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN' VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
0d81ecbe4126585d8af089e76fc3bb98b5dc2098
eforge/__init__.py
eforge/__init__.py
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from eforge.menu import ItemOrder EFORGE_PLUGIN = { 'name': 'EForge Core', 'credit': 'Copyright &copy; 2010 Element43 and contributors', 'provides': { 'mnu': [('project-page', ItemOrder(000, 'Summary'))], }, } VERSION = (0, 5, 0) def get_version(): return '%d.%d.%d' % VERSION
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from eforge.menu import ItemOrder EFORGE_PLUGIN = { 'name': 'EForge Core', 'credit': 'Copyright &copy; 2010 Element43 and contributors', 'provides': { 'mnu': [('project-page', ItemOrder(000, 'Summary'))], }, } VERSION = (0, 5, 0, 'beta 1') def get_version(): return '%d.%d.%d %s' % VERSION
Add beta version tagging for 0.5 beta 1
Add beta version tagging for 0.5 beta 1
Python
isc
oshepherd/eforge,oshepherd/eforge,oshepherd/eforge
--- +++ @@ -25,7 +25,7 @@ }, } -VERSION = (0, 5, 0) +VERSION = (0, 5, 0, 'beta 1') def get_version(): - return '%d.%d.%d' % VERSION + return '%d.%d.%d %s' % VERSION
3ff7704d9c9998f023fb2d93e279b0f1e4410ad8
arim/models.py
arim/models.py
from django.db import models class Autoreg(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField()
from django.db import models class Lease(models.Model): class Meta: db_table = 'autoreg' mac = models.CharField(max_length=17, db_index=True) ip = models.IntegerField(primary_key=True) date = models.IntegerField()
Change model name (but not table name)
Change model name (but not table name)
Python
bsd-3-clause
drkitty/arim,OSU-Net/arim,drkitty/arim,OSU-Net/arim,OSU-Net/arim,drkitty/arim
--- +++ @@ -1,7 +1,7 @@ from django.db import models -class Autoreg(models.Model): +class Lease(models.Model): class Meta: db_table = 'autoreg'
690dbc1ce63a6dc107a34d5b0315d316ef334e49
vdi/context_preprocessors.py
vdi/context_preprocessors.py
from django.conf import settings def context_preprocessor(request): d = { 'vdi_media_dir': settings.VDI_MEDIA_PREFIX, } if request.user.is_authenticated(): d['institution'] = request.user.username.split('++')[0] return d
from django.conf import settings def context_preprocessor(request): d = { 'vdi_media_dir': settings.VDI_MEDIA_PREFIX, } if request.user.is_authenticated(): institution = request.user.username.split('++') if len(institution) == 1: institution = 'local' else: institution = institution[0] d['institution'] = institution return d
Edit to populate the local themeing.
Edit to populate the local themeing.
Python
apache-2.0
bmbouter/Opus,ehelms/Opus,ehelms/Opus,bmbouter/Opus,ehelms/Opus,bmbouter/Opus
--- +++ @@ -5,5 +5,10 @@ 'vdi_media_dir': settings.VDI_MEDIA_PREFIX, } if request.user.is_authenticated(): - d['institution'] = request.user.username.split('++')[0] + institution = request.user.username.split('++') + if len(institution) == 1: + institution = 'local' + else: + institution = institution[0] + d['institution'] = institution return d
3ed33d83b1ade56b41166b50713b1087d6559b70
hello-world/hello_world_test.py
hello-world/hello_world_test.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest import hello_world class BobTests(unittest.TestCase): def test_hello_without_name(self): self.assertEqual( 'Hello, World!', hello_world.hello() ) def test_hello_with_name(self): self.assertEqual( 'Hello, Jane!', hello_world.hello('Jane') ) def test_hello_with_umlaut_name(self): self.assertEqual( 'Hello, Jürgen!', hello_world.hello('Jürgen') ) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest import hello_world class HelloWorldTests(unittest.TestCase): def test_hello_without_name(self): self.assertEqual( 'Hello, World!', hello_world.hello() ) def test_hello_with_sample_name(self): self.assertEqual( 'Hello, Alice!', hello_world.hello('Alice') ) def test_hello_with_other_sample_name(self): self.assertEqual( 'Hello, Bob!', hello_world.hello('Bob') ) def test_hello_with_umlaut_name(self): self.assertEqual( 'Hello, Jürgen!', hello_world.hello('Jürgen') ) if __name__ == '__main__': unittest.main()
Fix Hello World test class name & update test
Fix Hello World test class name & update test Fix test class name to reflect exercise name. Update tests to reflect Hello World metadata in x-common.
Python
mit
pheanex/xpython,de2Zotjes/xpython,jmluy/xpython,rootulp/xpython,rootulp/xpython,oalbe/xpython,exercism/xpython,mweb/python,outkaj/xpython,exercism/xpython,mweb/python,jmluy/xpython,behrtam/xpython,N-Parsons/exercism-python,pheanex/xpython,smalley/python,orozcoadrian/xpython,N-Parsons/exercism-python,orozcoadrian/xpython,smalley/python,oalbe/xpython,exercism/python,outkaj/xpython,behrtam/xpython,exercism/python,de2Zotjes/xpython
--- +++ @@ -6,7 +6,7 @@ import hello_world -class BobTests(unittest.TestCase): +class HelloWorldTests(unittest.TestCase): def test_hello_without_name(self): self.assertEqual( @@ -14,10 +14,16 @@ hello_world.hello() ) - def test_hello_with_name(self): + def test_hello_with_sample_name(self): self.assertEqual( - 'Hello, Jane!', - hello_world.hello('Jane') + 'Hello, Alice!', + hello_world.hello('Alice') + ) + + def test_hello_with_other_sample_name(self): + self.assertEqual( + 'Hello, Bob!', + hello_world.hello('Bob') ) def test_hello_with_umlaut_name(self):
c2726978a1272b13af2ffdfb10b4238985768317
tests/test_db.py
tests/test_db.py
import pytest from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val def pytestmark(func): pytest.mark.django_db(func) pytest.mark.usefixtures('test_table')(func) @pytest.fixture(scope='module') def test_table(): do_sql(''' begin; create table test ( id int primary key, tag int not null ); insert into test values (1, 10), (2, 20); commit; ''') def test_fetch_val(): assert fetch_val('select min(id) from test') == 1 def test_fetch_col(): assert fetch_col('select tag from test order by tag') == [10, 20] def test_fetch_row(): assert fetch_row('select * from test where id = 2') == (2, 20) def test_fetch_all(): assert fetch_all('select * from test order by id') == [(1, 10), (2, 20)]
import pytest from handy.db import do_sql, fetch_all, fetch_row, fetch_col, fetch_val def pytestmark(func): pytest.mark.django_db(func) pytest.mark.usefixtures('test_table')(func) @pytest.fixture(scope='module') def test_table(): # NOTE: We wrap that into transaction because in other case django will gobble it up # into single transaction with first test and then rollback everything happily on # that tests end. do_sql(''' begin; create table test ( id int primary key, tag int not null ); insert into test values (1, 10), (2, 20); commit; ''') def test_fetch_val(): assert fetch_val('select min(id) from test') == 1 def test_fetch_col(): assert fetch_col('select tag from test order by tag') == [10, 20] def test_fetch_row(): assert fetch_row('select * from test where id = 2') == (2, 20) def test_fetch_all(): assert fetch_all('select * from test order by id') == [(1, 10), (2, 20)]
Add NOTE regarding transaction to db tests setup
Add NOTE regarding transaction to db tests setup
Python
bsd-3-clause
leliel12/handy,leliel12/handy
--- +++ @@ -10,14 +10,18 @@ @pytest.fixture(scope='module') def test_table(): + # NOTE: We wrap that into transaction because in other case django will gobble it up + # into single transaction with first test and then rollback everything happily on + # that tests end. do_sql(''' begin; + create table test ( id int primary key, tag int not null ); + insert into test values (1, 10), (2, 20); - insert into test values (1, 10), (2, 20); commit; ''')
221a94c38ac0ad0c6d08f02b587c259423b96311
wagtailaltgenerator/utils.py
wagtailaltgenerator/utils.py
import os import requests from django.utils.translation import get_language from wagtailaltgenerator.translation_providers import get_current_provider from wagtailaltgenerator.providers import DescriptionResult def get_image_data(image_url): ''' Load external image and return byte data ''' image_data = requests.get(image_url) if image_data.status_code > 200 and image_data.status_code < 300: return None return image_data.content def get_local_image_data(image_file): ''' Retrive byte data from a local file ''' abs_path = os.path.abspath(image_file.path) image_data = open(abs_path, 'rb').read() return image_data def translate_description_result(result): provider = get_current_provider()() to_lang = get_language() strings = [] if result.description: strings = [result.description] if result.tags: strings = [*strings, result.tags] translated_strings = provider.translate( strings, target_language=to_lang ) translated_description = ( translated_strings[0] if result.description else result.description ) translated_tags = ( translated_strings[1:] if result.description else translated_strings ) return DescriptionResult( description=translated_description, tags=translated_tags, )
import os import requests from django.utils.translation import get_language from wagtailaltgenerator.translation_providers import get_current_provider from wagtailaltgenerator.providers import DescriptionResult def get_image_data(image_url): ''' Load external image and return byte data ''' image_data = requests.get(image_url) if image_data.status_code > 200 and image_data.status_code < 300: return None return image_data.content def get_local_image_data(image_file): ''' Retrive byte data from a local file ''' abs_path = os.path.abspath(image_file.path) image_data = open(abs_path, 'rb').read() return image_data def translate_description_result(result): provider = get_current_provider()() lang_and_country_code = get_language() lang_code = lang_and_country_code.split("-")[0] strings = [] if result.description: strings = [result.description] if result.tags: strings = [*strings, *result.tags] translated_strings = provider.translate( strings, target_language=lang_code ) translated_description = ( translated_strings[0] if result.description else result.description ) translated_tags = ( translated_strings[1:] if result.description else translated_strings ) return DescriptionResult( description=translated_description, tags=translated_tags, )
Fix issue where lang was not parsed properly
Fix issue where lang was not parsed properly
Python
mit
marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator,marteinn/wagtail-alt-generator
--- +++ @@ -30,17 +30,19 @@ def translate_description_result(result): provider = get_current_provider()() - to_lang = get_language() + + lang_and_country_code = get_language() + lang_code = lang_and_country_code.split("-")[0] strings = [] if result.description: strings = [result.description] if result.tags: - strings = [*strings, result.tags] + strings = [*strings, *result.tags] translated_strings = provider.translate( - strings, target_language=to_lang + strings, target_language=lang_code ) translated_description = (
b2c527e912260253be459c9ad3dd6139be21a75d
faucet/valve_manager_base.py
faucet/valve_manager_base.py
"""Valve Manager base class""" # pylint: disable=R0201 # pylint: disable=W0613 class ValveManagerBase: # pylint: disable=too-few-public-methods """Base class for ValveManager objects. Expected to control the installation of flows into datapath tables. Ideally each datapath table should be controlled by 1 manager only.""" _MISS_PRIORITY = 0 _LOW_PRIORITY = 0x1000 _MATCH_PRIORITY = 0x2000 _LPM_PRIORITY = 0x3000 _HIGH_PRIORITY = 0x4000 _FILTER_PRIORITY = 0x5000 def initialise_tables(self): '''initialise tables controlled by this manager''' return [] def add_vlan(self, vlan): """install flows in response to a new vlan""" return [] def add_port(self, port): """install flows in response to a new port""" return [] def del_vlan(self, vlan): """delete flows in response to a vlan removal""" return [] def del_port(self, port): """delete flows in response to a port removal""" return []
"""Valve Manager base class""" # pylint: disable=R0201 # pylint: disable=W0613 class ValveManagerBase: # pylint: disable=too-few-public-methods """Base class for ValveManager objects. Expected to control the installation of flows into datapath tables. Ideally each datapath table should be controlled by 1 manager only.""" _MISS_PRIORITY = 0 _LOW_PRIORITY = 0x1000 _MATCH_PRIORITY = 0x2000 _LPM_PRIORITY = 0x3000 _HIGH_PRIORITY = 0x4000 _FILTER_PRIORITY = 0x5000 def initialise_tables(self): """initialise tables controlled by this manager.""" return [] def add_vlan(self, vlan): """install flows in response to a new VLAN""" return [] def update_vlan(self, vlan): """flows in response to updating an existing VLAN.""" return [] def add_port(self, port): """install flows in response to a new port""" return [] def del_vlan(self, vlan): """delete flows in response to a VLAN removal""" return [] def del_port(self, port): """delete flows in response to a port removal""" return []
Update manager API for update.
Update manager API for update.
Python
apache-2.0
REANNZ/faucet,faucetsdn/faucet,mwutzke/faucet,anarkiwi/faucet,shivarammysore/faucet,trungdtbk/faucet,REANNZ/faucet,gizmoguy/faucet,anarkiwi/faucet,mwutzke/faucet,trungdtbk/faucet,shivarammysore/faucet,faucetsdn/faucet,gizmoguy/faucet
--- +++ @@ -17,11 +17,15 @@ _FILTER_PRIORITY = 0x5000 def initialise_tables(self): - '''initialise tables controlled by this manager''' + """initialise tables controlled by this manager.""" return [] def add_vlan(self, vlan): - """install flows in response to a new vlan""" + """install flows in response to a new VLAN""" + return [] + + def update_vlan(self, vlan): + """flows in response to updating an existing VLAN.""" return [] def add_port(self, port): @@ -29,7 +33,7 @@ return [] def del_vlan(self, vlan): - """delete flows in response to a vlan removal""" + """delete flows in response to a VLAN removal""" return [] def del_port(self, port):
26f48bc7a5e39f50b035f20a517664dade87b981
binder/json.py
binder/json.py
import json import datetime from uuid import UUID from django.http import HttpResponse from .exceptions import BinderRequestError class BinderJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): # FIXME: was .isoformat(), but that omits the microseconds if they # are 0, which upsets our front-end devs. This is ugly. # I hear .isoformat() might learn a timespec parameter in 3.6... tz = obj.strftime("%z") tz = tz if tz else '+0000' return obj.strftime("%Y-%m-%dT%H:%M:%S.%f") + tz elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, UUID): return str(obj) # Standard string notation elif isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj) def jsondumps(o, indent=None): return json.dumps(o, cls=BinderJSONEncoder, indent=indent) def jsonloads(data): try: return json.loads(data.decode()) except ValueError as e: raise BinderRequestError('JSON parse error: {}.'.format(str(e))) def JsonResponse(data): return HttpResponse(jsondumps(data), content_type='application/json')
import json import datetime from uuid import UUID from django.http import HttpResponse from .exceptions import BinderRequestError try: from dateutil.relativedelta import relativedelta from relativedeltafield import format_relativedelta except ImportError: class relativedelta: pass class BinderJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): # FIXME: was .isoformat(), but that omits the microseconds if they # are 0, which upsets our front-end devs. This is ugly. # I hear .isoformat() might learn a timespec parameter in 3.6... tz = obj.strftime("%z") tz = tz if tz else '+0000' return obj.strftime("%Y-%m-%dT%H:%M:%S.%f") + tz elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, UUID): return str(obj) # Standard string notation elif isinstance(obj, set): return list(obj) elif isinstance(obj, relativedelta): return format_relativedelta(obj) return json.JSONEncoder.default(self, obj) def jsondumps(o, indent=None): return json.dumps(o, cls=BinderJSONEncoder, indent=indent) def jsonloads(data): try: return json.loads(data.decode()) except ValueError as e: raise BinderRequestError('JSON parse error: {}.'.format(str(e))) def JsonResponse(data): return HttpResponse(jsondumps(data), content_type='application/json')
Add support for relativedelta timespecs
Add support for relativedelta timespecs This uses the django-relativedeltafield formatter. We could copy the formatter into here but that's not great either. This can be improved once we have a pluggable JSON serializer.
Python
mit
CodeYellowBV/django-binder
--- +++ @@ -6,7 +6,12 @@ from .exceptions import BinderRequestError - +try: + from dateutil.relativedelta import relativedelta + from relativedeltafield import format_relativedelta +except ImportError: + class relativedelta: + pass class BinderJSONEncoder(json.JSONEncoder): def default(self, obj): @@ -23,6 +28,8 @@ return str(obj) # Standard string notation elif isinstance(obj, set): return list(obj) + elif isinstance(obj, relativedelta): + return format_relativedelta(obj) return json.JSONEncoder.default(self, obj)
82ba42bf269e7897129976c07d28b4bc0f23df69
shopify/mixins.py
shopify/mixins.py
import shopify.resources class Countable(object): @classmethod def count(cls, _options=None, **kwargs): if _options is None: _options = kwargs return int(cls.get("count", **_options)) class Metafields(object): def metafields(self): return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return shopify.resources.Event.find(resource=self.__class__.plural, resource_id=self.id)
import shopify.resources class Countable(object): @classmethod def count(cls, _options=None, **kwargs): if _options is None: _options = kwargs return int(cls.get("count", **_options)) class Metafields(object): def metafields(self, _options=None, **kwargs): if _options is None: _options = kwargs return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id, **_options) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return shopify.resources.Event.find(resource=self.__class__.plural, resource_id=self.id)
Enable keyword arguments when requesting metafields
Enable keyword arguments when requesting metafields
Python
mit
Shopify/shopify_python_api
--- +++ @@ -11,8 +11,10 @@ class Metafields(object): - def metafields(self): - return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id) + def metafields(self, _options=None, **kwargs): + if _options is None: + _options = kwargs + return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id, **_options) def add_metafield(self, metafield): if self.is_new():
3395943d4c202709c2f1f110e19a2aa0dc741e63
UM/Qt/Bindings/DirectoryListModel.py
UM/Qt/Bindings/DirectoryListModel.py
from UM.Qt.ListModel import ListModel from UM.Application import Application from PyQt5.QtCore import Qt, pyqtProperty, pyqtSignal, QUrl import os import os.path class DirectoryListModel(ListModel): NameRole = Qt.UserRole + 1 UrlRole = Qt.UserRole + 2 def __init__(self): super().__init__() self.addRoleName(self.NameRole, 'name') self.addRoleName(self.UrlRole, 'url') self._directory = None directoryChanged = pyqtSignal() def getDirectory(self): return self._directory def setDirectory(self, path): if path != self._directory: if path.startswith('file://'): path = path[7:] self._directory = os.path.dirname(path) self.clear() extensions = Application.getInstance().getMeshFileHandler().getSupportedFileTypesRead() for entry in os.listdir(self._directory): if os.path.splitext(entry)[1] in extensions: self.appendItem({ 'name': os.path.basename(entry), 'url': QUrl.fromLocalFile(os.path.join(self._directory, entry)) }) self.sort(lambda e: e['name']) directory = pyqtProperty(str, fget = getDirectory, fset = setDirectory, notify = directoryChanged)
from UM.Qt.ListModel import ListModel from UM.Application import Application from PyQt5.QtCore import Qt, pyqtProperty, pyqtSignal, QUrl import os import os.path import platform class DirectoryListModel(ListModel): NameRole = Qt.UserRole + 1 UrlRole = Qt.UserRole + 2 def __init__(self): super().__init__() self.addRoleName(self.NameRole, 'name') self.addRoleName(self.UrlRole, 'url') self._directory = None directoryChanged = pyqtSignal() def getDirectory(self): return self._directory def setDirectory(self, path): if path != self._directory: if path.startswith('file://'): if platform.system() == "Windows" and path.startswith('file:///'): path = path[8:] else: path = path[7:] self._directory = os.path.dirname(path) self.clear() extensions = Application.getInstance().getMeshFileHandler().getSupportedFileTypesRead() for entry in os.listdir(self._directory): if os.path.splitext(entry)[1] in extensions: self.appendItem({ 'name': os.path.basename(entry), 'url': QUrl.fromLocalFile(os.path.join(self._directory, entry)) }) self.sort(lambda e: e['name']) directory = pyqtProperty(str, fget = getDirectory, fset = setDirectory, notify = directoryChanged)
Fix directory listing on windows.
Fix directory listing on windows.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
--- +++ @@ -5,6 +5,7 @@ import os import os.path +import platform class DirectoryListModel(ListModel): NameRole = Qt.UserRole + 1 @@ -26,7 +27,10 @@ def setDirectory(self, path): if path != self._directory: if path.startswith('file://'): - path = path[7:] + if platform.system() == "Windows" and path.startswith('file:///'): + path = path[8:] + else: + path = path[7:] self._directory = os.path.dirname(path) self.clear()
5429534fc79237fb175aa8f7888565dd14092d9d
yetibridge/bridge/console.py
yetibridge/bridge/console.py
import threading from . import BaseBridge from .. import BaseEvent class ConsoleBridge(BaseBridge): def __init__(self, config): BaseBridge.__init__(self, config) self._thread = threading.Thread(target=self.run, daemon=True) self.users = {} def on_register(self): self._thread.start() def run(self): while True: command = input() self.send_event('bridge_command', command, 'console') def ev_user_join(self, event, user_id, name): self.users[user_id] = name bridge_name = self._manager._bridge_name(event.bridge_id) print("{}: user '{}' joined".format(bridge_name, name)) def ev_user_leave(self, event, user_id): bridge_name = self._manager._bridge_name(event.bridge_id) print("{}: user '{}' joined".format(bridge_name, self.users[user_id])) del self.users[user_id]
import threading from . import BaseBridge from .. import BaseEvent class ConsoleBridge(BaseBridge): def __init__(self, config): BaseBridge.__init__(self, config) self._thread = threading.Thread(target=self.run, daemon=True) self.users = {} def on_register(self): self._thread.start() def run(self): while True: command = input() self.send_event('bridge_command', command, 'console') def name(self, item_id): try: return self.users[item_id] except KeyError: pass try: return self._manager._bridge_name(item_id) except ValueError: pass if item_id == id(self._manager): return 'manager' return str(item_id) def ev_user_join(self, event, user_id, name): self.users[user_id] = name print("{}: user '{}' joined".format(self.name(event.bridge_id), name)) def ev_user_leave(self, event, user_id): print("{}: user '{}' left".format(self.name(event.bridge_id), self.users[user_id])) del self.users[user_id]
Add name method to ConsoleBridge
Add name method to ConsoleBridge Add method to name an id, be it a user, bridge, or the manager itself.
Python
mit
Hornwitser/YetiBridge
--- +++ @@ -17,12 +17,27 @@ command = input() self.send_event('bridge_command', command, 'console') + def name(self, item_id): + try: + return self.users[item_id] + except KeyError: + pass + + try: + return self._manager._bridge_name(item_id) + except ValueError: + pass + + if item_id == id(self._manager): + return 'manager' + + return str(item_id) + def ev_user_join(self, event, user_id, name): self.users[user_id] = name - bridge_name = self._manager._bridge_name(event.bridge_id) - print("{}: user '{}' joined".format(bridge_name, name)) + print("{}: user '{}' joined".format(self.name(event.bridge_id), name)) def ev_user_leave(self, event, user_id): - bridge_name = self._manager._bridge_name(event.bridge_id) - print("{}: user '{}' joined".format(bridge_name, self.users[user_id])) + print("{}: user '{}' left".format(self.name(event.bridge_id), + self.users[user_id])) del self.users[user_id]