commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
62cee7d5a625bb3515eddaddbe940239a41ba31c
rest_framework_msgpack/parsers.py
rest_framework_msgpack/parsers.py
import decimal import msgpack from dateutil.parser import parse from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % unicode(exc))
import decimal import msgpack from dateutil.parser import parse from django.utils.six import text_type from rest_framework.parsers import BaseParser from rest_framework.exceptions import ParseError class MessagePackDecoder(object): def decode(self, obj): if '__class__' in obj: decode_func = getattr(self, 'decode_%s' % obj['__class__']) return decode_func(obj) return obj def decode_datetime(self, obj): return parse(obj['as_str']) def decode_date(self, obj): return parse(obj['as_str']).date() def decode_time(self, obj): return parse(obj['as_str']).time() def decode_decimal(self, obj): return decimal.Decimal(obj['as_str']) class MessagePackParser(BaseParser): """ Parses MessagePack-serialized data. """ media_type = 'application/msgpack' def parse(self, stream, media_type=None, parser_context=None): try: return msgpack.load(stream, use_list=True, encoding="utf-8", object_hook=MessagePackDecoder().decode) except Exception as exc: raise ParseError('MessagePack parse error - %s' % text_type(exc))
Use six.text_type for python3 compat
Use six.text_type for python3 compat
Python
bsd-3-clause
juanriaza/django-rest-framework-msgpack
ecf8b600868534e82056a83f9b86f27db8812e0f
setup.py
setup.py
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name="portinus", version="1.0.10", author="Justin Dray", author_email="[email protected]", url="https://github.com/justin8/portinus", description="This utility creates a systemd service file for a docker-compose file", packages=find_packages(), package_data={'portinus': ['templates/*']}, license="MIT", install_requires=[ "click", "docker", "jinja2", "systemd_unit" ], tests_require=[ "nose", "coverage", "mock>=2.0.0", ], test_suite="nose.collector", entry_points={ "console_scripts": [ "portinus=portinus.cli:task", "portinus-monitor=portinus.monitor.cli:task", ] }, classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", "Environment :: Console", "License :: OSI Approved :: MIT License", "Development Status :: 5 - Production/Stable", "Programming Language :: Python", ], )
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name="portinus", version="1.0.10", author="Justin Dray", author_email="[email protected]", url="https://github.com/justin8/portinus", description="This utility creates a systemd service file for a docker-compose file", packages=find_packages(), package_data={'portinus': ['templates/*']}, license="MIT", install_requires=[ "click", "docker", "docker-compose", "jinja2", "systemd_unit" ], tests_require=[ "nose", "coverage", "mock>=2.0.0", ], test_suite="nose.collector", entry_points={ "console_scripts": [ "portinus=portinus.cli:task", "portinus-monitor=portinus.monitor.cli:task", ] }, classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", "Environment :: Console", "License :: OSI Approved :: MIT License", "Development Status :: 5 - Production/Stable", "Programming Language :: Python", ], )
Add a dependency on docker-compose
Add a dependency on docker-compose
Python
mit
justin8/portinus,justin8/portinus
9d58310b2106e3ed5fc140a8479e003a4a647e82
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages README = 'README.md' def long_desc(): try: import pypandoc except ImportError: with open(README) as f: return f.read() else: return pypandoc.convert(README, 'rst') setup( name='ecmcli', version='2.3.0', description='Command Line Interface for Cradlepoint ECM', author='Justin Mayfield', author_email='[email protected]', url='https://github.com/mayfield/ecmcli/', license='MIT', long_description=long_desc(), packages=find_packages(), install_requires=[ 'syndicate==1.2.0', 'shellish>=0.5.9', 'humanize' ], entry_points = { 'console_scripts': ['ecm=ecmcli.main:main'], }, include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', ] )
#!/usr/bin/env python from setuptools import setup, find_packages README = 'README.md' def long_desc(): try: import pypandoc except ImportError: with open(README) as f: return f.read() else: return pypandoc.convert(README, 'rst') setup( name='ecmcli', version='2.3.1', description='Command Line Interface for Cradlepoint ECM', author='Justin Mayfield', author_email='[email protected]', url='https://github.com/mayfield/ecmcli/', license='MIT', long_description=long_desc(), packages=find_packages(), install_requires=[ 'syndicate==1.2.0', 'shellish>=0.6.0', 'humanize' ], entry_points = { 'console_scripts': ['ecm=ecmcli.main:main'], }, include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', ] )
Fix shellish requirement bump rev to 2.3.1
Fix shellish requirement bump rev to 2.3.1
Python
mit
mayfield/ecmcli
3db4d85164a2a2c41503b568505077cf2af86e90
setup.py
setup.py
from setuptools import setup setup( name='django-simpleimages', version='1.0.0', author='Saul Shanabrook', author_email='[email protected]', packages=['simpleimages', ], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.6", "six" ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries', ], )
from setuptools import setup setup( name='django-simpleimages', version='1.0.0', author='Saul Shanabrook', author_email='[email protected]', packages=['simpleimages', 'simpleimages.management.commands'], url='https://www.github.com/saulshanabrook/django-simpleimages', license=open('LICENSE.txt').read(), description='Opinionated Django image transforms on models', long_description=open('README.rst').read(), install_requires=[ "Django>=1.5,<=1.6", "six" ], zip_safe=False, # so that django finds management commands, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries', ], )
Add management file to packages so django can find it
Add management file to packages so django can find it
Python
mit
saulshanabrook/django-simpleimages
57e4d45d24b39287de12407350ce6c359332ac34
setup.py
setup.py
#!/usr/bin/env python # Copyright 2014 OpenMarket Ltd # # 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 os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="syweb", version="0.0.1", packages=find_packages(exclude=["tests", "tests.*"]), description="Matrix Angular Sdk", include_package_data=True, long_description=read("README.rst"), entry_points="""""" )
#!/usr/bin/env python # Copyright 2014 OpenMarket Ltd # # 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 os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="syweb", version="0.0.1", packages=find_packages(exclude=["tests", "tests.*"]), description="Matrix Angular Sdk", include_package_data=True, zip_safe=False, long_description=read("README.rst"), entry_points="""""" )
Mark syweb as not being zip safe so that bundled files are accessible from the filesystem
Mark syweb as not being zip safe so that bundled files are accessible from the filesystem
Python
apache-2.0
williamboman/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,matrix-org/matrix-angular-sdk,matrix-org/matrix-angular-sdk,williamboman/matrix-angular-sdk
4580bf5e1c4ada62f09bc4a33fae2b971c6fb3c1
setup.py
setup.py
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'invokust', version = '0.7', author = 'Max Williams', author_email = '[email protected]', description = 'A small wrapper for locust to allow running load tests from within Python or on AWS Lambda', long_description=long_description, long_description_content_type="text/markdown", url = 'https://github.com/FutureSharks/invokust', download_url = 'https://github.com/FutureSharks/invokust/archive/0.7.tar.gz', license = 'MIT', scripts = ['invokr.py'], packages = [ 'invokust', 'invokust.aws_lambda', ], install_requires = [ 'locustio==0.13.5', 'boto3', 'pyzmq', 'numpy' ], keywords = ['testing', 'loadtest', 'lamba', 'locust'], classifiers = [ 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Testing :: Traffic Generation', 'Programming Language :: Python :: 3.6' ], )
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'invokust', version = '0.71', author = 'Max Williams', author_email = '[email protected]', description = 'A small wrapper for locust to allow running load tests from within Python or on AWS Lambda', long_description=long_description, long_description_content_type="text/markdown", url = 'https://github.com/FutureSharks/invokust', download_url = 'https://github.com/FutureSharks/invokust/archive/0.71.tar.gz', license = 'MIT', scripts = ['invokr.py'], packages = [ 'invokust', 'invokust.aws_lambda', ], install_requires = [ 'locustio==0.13.5', 'boto3', 'pyzmq', 'numpy' ], keywords = ['testing', 'loadtest', 'lamba', 'locust'], classifiers = [ 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Testing :: Traffic Generation', 'Programming Language :: Python :: 3.6' ], )
Fix version number to be higher
Fix version number to be higher
Python
mit
FutureSharks/invokust,FutureSharks/invokust
eeb85c110bc9a723eeac4deb10d36e5b912035af
corehq/apps/accounting/management/commands/make_domain_enterprise_level.py
corehq/apps/accounting/management/commands/make_domain_enterprise_level.py
from django.core.management import BaseCommand from corehq.apps.domain.forms import DimagiOnlyEnterpriseForm from corehq.apps.domain.models import Domain from corehq.util.decorators import require_debug_true class Command(BaseCommand): help = ('Create a billing account and an enterprise level subscription ' 'for the given domain') args = ['domain'] @require_debug_true() def handle(self, domain, **kwargs): assert Domain.get_by_name(domain) is not None DimagiOnlyEnterpriseForm(domain, '[email protected]').process_subscription_management()
from django.core.management import BaseCommand from corehq.apps.domain.forms import DimagiOnlyEnterpriseForm from corehq.apps.domain.models import Domain from corehq.util.decorators import require_debug_true class Command(BaseCommand): help = ('Create a billing account and an enterprise level subscription ' 'for the given domain') def add_arguments(self, parser): parser.add_argument('domain') @require_debug_true() def handle(self, domain, **kwargs): assert Domain.get_by_name(domain) is not None DimagiOnlyEnterpriseForm(domain, '[email protected]').process_subscription_management()
Use parser to add command line arg
Use parser to add command line arg
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
c86efe7d1598cc9f7afc82c3118ec4cc20483312
src/hamcrest/__init__.py
src/hamcrest/__init__.py
from __future__ import absolute_import from hamcrest.core import * from hamcrest.library import * __version__ = "2.0.0a1" __author__ = "Chris Rose" __copyright__ = "Copyright 2014 hamcrest.org" __license__ = "BSD, see License.txt"
from __future__ import absolute_import from hamcrest.core import * from hamcrest.library import * __version__ = "1.8.0" __author__ = "Chris Rose" __copyright__ = "Copyright 2013 hamcrest.org" __license__ = "BSD, see License.txt"
Revert "Version move to 2.0.0a1"
Revert "Version move to 2.0.0a1" This reverts commit 4cd7d3062037dab13c99f0dd9b44f08fbd894ffa.
Python
bsd-3-clause
nitishr/PyHamcrest,msabramo/PyHamcrest,msabramo/PyHamcrest,nitishr/PyHamcrest
19bae697bc6e017a97eef77d1425d1ccfbe27ff6
vprof/__main__.py
vprof/__main__.py
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source print('Collecting profile stats...') program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
"""Visual profiler for Python.""" import argparse import functools import json import profile import stats_server import subprocess import sys _MODULE_DESC = 'Python visual profiler.' _HOST = 'localhost' _PORT = 8000 _PROFILE_MAP = { 'c': profile.CProfile } def main(): parser = argparse.ArgumentParser(description=_MODULE_DESC) parser.add_argument('profilers', metavar='opts', help='Profilers configuration') parser.add_argument('source', metavar='src', nargs=1, help='Python program to profile.') args = parser.parse_args() sys.argv[:] = args.source program_name = args.source[0] if len(args.profilers) > len(set(args.profilers)): print('Profiler configuration is ambiguous. Remove duplicates.') sys.exit(1) for prof_option in args.profilers: if prof_option not in _PROFILE_MAP: print('Unrecognized option: %s' % prof_option) sys.exit(2) print('Collecting profile stats...') prof_option = args.profilers[0] profiler = _PROFILE_MAP[prof_option] program_info = profile.CProfile(args.source[0]).run() partial_handler = functools.partial( stats_server.StatsHandler, profile_json=json.dumps(program_info)) subprocess.call(['open', 'http://%s:%s' % (_HOST, _PORT)]) stats_server.start(_HOST, _PORT, partial_handler) if __name__ == "__main__": main()
Add profilers selection as CLI option.
Add profilers selection as CLI option.
Python
bsd-2-clause
nvdv/vprof,nvdv/vprof,nvdv/vprof
e7fec5ccb9e70bf17b7878e63052a874afa06856
recipe_modules/runtime/api.py
recipe_modules/runtime/api.py
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from recipe_engine import recipe_api class RuntimeApi(recipe_api.RecipeApi): """This module assists in experimenting with production recipes. For example, when migrating builders from Buildbot to pure LUCI stack. """ def __init__(self, properties, **kwargs): super(RuntimeApi, self).__init__(**kwargs) self._properties = properties @property def is_luci(self): """True if this recipe is currently running on LUCI stack. Should be used only during migration from Buildbot to LUCI stack. """ return bool(self._properties.get('is_luci', False)) @property def is_experimental(self): """True if this recipe is currently running in experimental mode. Typical usage is to modify steps which produce external side-effects so that non-production runs of the recipe do not affect production data. Examples: * Uploading to an alternate google storage file name when in non-prod mode * Appending a 'non-production' tag to external RPCs """ return bool(self._properties.get('is_experimental', False))
# Copyright 2017 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from recipe_engine import recipe_api class RuntimeApi(recipe_api.RecipeApi): """This module assists in experimenting with production recipes. For example, when migrating builders from Buildbot to pure LUCI stack. """ def __init__(self, properties, **kwargs): super(RuntimeApi, self).__init__(**kwargs) self._properties = properties @property def is_luci(self): """True if this recipe is currently running on LUCI stack. Should be used only during migration from Buildbot to LUCI stack. """ return bool(self._properties.get('is_luci', True)) @property def is_experimental(self): """True if this recipe is currently running in experimental mode. Typical usage is to modify steps which produce external side-effects so that non-production runs of the recipe do not affect production data. Examples: * Uploading to an alternate google storage file name when in non-prod mode * Appending a 'non-production' tag to external RPCs """ return bool(self._properties.get('is_experimental', False))
Change is_luci default to True.
Change is_luci default to True. Most things should be on LUCI now, so this better reflects reality, and might help shakeout any obsolete non-LUCI handling. Bug: 993137 Recipe-Nontrivial-Roll: build Recipe-Nontrivial-Roll: build_limited_scripts_slave Recipe-Nontrivial-Roll: chromiumos Recipe-Nontrivial-Roll: depot_tools Recipe-Nontrivial-Roll: infra Recipe-Nontrivial-Roll: release_scripts Recipe-Nontrivial-Roll: skia Change-Id: I5d43654d1f8ef2d980a3c8892e718b102e6cbbe1 Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/recipes-py/+/1750109 Auto-Submit: Michael Moss <[email protected]> Reviewed-by: Robbie Iannucci <[email protected]> Commit-Queue: Michael Moss <[email protected]>
Python
apache-2.0
luci/recipes-py,luci/recipes-py
5e7cce09a6e6a847dad1714973fddb53d60c4c3f
yawf_sample/simple/models.py
yawf_sample/simple/models.py
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) @reversion.register class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False)
from django.db import models import reversion from yawf.revision import RevisionModelMixin class WINDOW_OPEN_STATUS: MINIMIZED = 'minimized' MAXIMIZED = 'maximized' NORMAL = 'normal' types = (MINIMIZED, MAXIMIZED, NORMAL) choices = zip(types, types) class Window(RevisionModelMixin, models.Model): title = models.CharField(max_length=255) width = models.IntegerField() height = models.IntegerField() workflow_type = 'simple' open_status = models.CharField( max_length=32, choices=WINDOW_OPEN_STATUS.choices, default='init', editable=False) reversion.register(Window)
Fix reversion register in sample app
Fix reversion register in sample app
Python
mit
freevoid/yawf
d970f2e4dc1d040bd352a68f6ebe4d3df93d19f7
web/celSearch/api/scripts/query_wikipedia.py
web/celSearch/api/scripts/query_wikipedia.py
''' Script used to query Wikipedia for summary of object ''' import sys import wikipedia def main(): # Check that we have the right number of arguments if (len(sys.argv) != 2): print 'Incorrect number of arguments; please pass in only one string that contains the subject' return 'Banana' print wikipedia.summary(sys.argv[1]).encode('utf-8') #return wikipedia.summary(sys.argv[1]) if __name__ == '__main__': main()
''' Script used to query Wikipedia for summary of object ''' import sys import wikipedia import nltk def main(): # Check that we have the right number of arguments if (len(sys.argv) != 2): print 'Incorrect number of arguments; please pass in only one string that contains the query' return 'Banana' # Get the noun from the query (uses the first noun it finds for now) print sys.argv[0] tokens = nltk.word_tokenize(sys.argv[1]) tagged = nltk.pos_tag(tokens) # Find first noun in query and provide Wikipedia summary for it for tag in tagged: if tag[1][0] == 'N': print wikipedia.summary(tag[0]).encode('utf-8') return if __name__ == '__main__': main()
Send query from android device to server
Send query from android device to server
Python
apache-2.0
christopher18/Celsearch,christopher18/Celsearch,christopher18/Celsearch
d15f6df74b8fe188a7a80c3491aeec62c35ce415
policy.py
policy.py
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version.replace('.', '_') return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
from __future__ import unicode_literals class PolicyError(RuntimeError): def __init__(self, message, url): self.message = message self.url = url def __str__(self): return "{}: {}".format(self.message, self.url) class RedirectLimitPolicy(object): def __init__(self, max_redirects): self.max_redirects = max_redirects self.redirects = 0 def __call__(self, url): if self.redirects >= self.max_redirects: raise PolicyError('too many redirects', url) self.redirects += 1 class VersionCheckPolicy(object): def __init__(self, os_family, version_string): self.version_string = version_string self.os_family = os_family self.url_version_string = self._version_transform(version_string) def _version_transform(self, version): if self.os_family == 'centos': return version[:version.rindex('.')] return version def __call__(self, url): if self.os_family == 'centos': ver = self.url_version_string if ver not in url: message = 'version "{}" not found in url'.format(ver) raise PolicyError(message, url)
Check for the first part of the version string
Check for the first part of the version string Older CentOS Linux images only used the xxxx part of the full xxxx.yy version string from Atlas.
Python
mit
lpancescu/atlas-lint
ebfb9290f5afdc07489be117f9ccb6df34e4023a
src/sentry/web/frontend/generic.py
src/sentry/web/frontend/generic.py
""" sentry.web.frontend.generic ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.views.generic import TemplateView as BaseTemplateView from sentry.web.helpers import render_to_response def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith(('.eot', '.ttf', '.woff')): response['Access-Control-Allow-Origin'] = '*' return response class TemplateView(BaseTemplateView): def render_to_response(self, context, **response_kwargs): return render_to_response( request=self.request, template=self.get_template_names(), context=context, **response_kwargs )
""" sentry.web.frontend.generic ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.views.generic import TemplateView as BaseTemplateView from sentry.web.helpers import render_to_response def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith(('.eot', '.ttf', '.woff', '.js')): response['Access-Control-Allow-Origin'] = '*' return response class TemplateView(BaseTemplateView): def render_to_response(self, context, **response_kwargs): return render_to_response( request=self.request, template=self.get_template_names(), context=context, **response_kwargs )
Add CORS headers to js files for local dev
Add CORS headers to js files for local dev
Python
bsd-3-clause
alexm92/sentry,daevaorn/sentry,ifduyue/sentry,daevaorn/sentry,mvaled/sentry,gencer/sentry,looker/sentry,beeftornado/sentry,ifduyue/sentry,zenefits/sentry,zenefits/sentry,gencer/sentry,looker/sentry,daevaorn/sentry,JackDanger/sentry,looker/sentry,mitsuhiko/sentry,looker/sentry,ifduyue/sentry,zenefits/sentry,jean/sentry,beeftornado/sentry,fotinakis/sentry,nicholasserra/sentry,mvaled/sentry,BuildingLink/sentry,fotinakis/sentry,nicholasserra/sentry,BuildingLink/sentry,jean/sentry,JamesMura/sentry,fotinakis/sentry,JamesMura/sentry,mvaled/sentry,gencer/sentry,gencer/sentry,JamesMura/sentry,alexm92/sentry,mvaled/sentry,beeftornado/sentry,daevaorn/sentry,gencer/sentry,zenefits/sentry,jean/sentry,looker/sentry,JackDanger/sentry,JackDanger/sentry,mvaled/sentry,ifduyue/sentry,JamesMura/sentry,nicholasserra/sentry,zenefits/sentry,mvaled/sentry,jean/sentry,BuildingLink/sentry,mitsuhiko/sentry,ifduyue/sentry,BuildingLink/sentry,alexm92/sentry,JamesMura/sentry,fotinakis/sentry,BuildingLink/sentry,jean/sentry
1cae75108cc3ec12911fc66b18875bf521baf00f
server/ntb/macros/npk_metadata.py
server/ntb/macros/npk_metadata.py
""" NPKSisteNytt Metadata Macro will perform the following changes to current content item: - change the byline to "(NPK-NTB)" - change the signoff to "[email protected]" - change the body footer to "(©NPK)" - NB: copyrightsign, not @ - change the service to "NPKSisteNytt" """ def npk_metadata_macro(item, **kwargs): item['byline'] = 'NPK ' + item.get('byline', '') item['sign_off'] = '[email protected]' item['body_footer'] = '(©NPK)' item['language'] = 'nn-NO' item['anpa_category'] = [ { 'qcode': 's', 'single_value': True, 'name': 'NPKSisteNytt', 'language': 'nn-NO', 'scheme': None } ] return item name = 'NPKSisteNytt Metadata Macro' label = 'NPKSisteNytt Metadata Macro' callback = npk_metadata_macro access_type = 'frontend' action_type = 'direct'
""" NPKSisteNytt Metadata Macro will perform the following changes to current content item: - change the byline to "(NPK-NTB)" - change the signoff to "[email protected]" - change the body footer to "(©NPK)" - NB: copyrightsign, not @ - change the service to "NPKSisteNytt" """ def npk_metadata_macro(item, **kwargs): item['byline'] = 'NPK-' + item.get('byline', '') item['sign_off'] = '[email protected]' item['body_footer'] = '(©NPK)' item['language'] = 'nn-NO' item['anpa_category'] = [ { 'qcode': 's', 'single_value': True, 'name': 'NPKSisteNytt', 'language': 'nn-NO', 'scheme': None } ] return item name = 'NPKSisteNytt Metadata Macro' label = 'NPKSisteNytt Metadata Macro' callback = npk_metadata_macro access_type = 'frontend' action_type = 'direct'
Change the byline format for NPK MAcro
fix(macro): Change the byline format for NPK MAcro
Python
agpl-3.0
petrjasek/superdesk-ntb,superdesk/superdesk-ntb,petrjasek/superdesk-ntb,petrjasek/superdesk-ntb,petrjasek/superdesk-ntb,ioanpocol/superdesk-ntb,superdesk/superdesk-ntb,ioanpocol/superdesk-ntb,superdesk/superdesk-ntb,ioanpocol/superdesk-ntb,superdesk/superdesk-ntb
c7ba0ecbbe263fbf7378edbc45fcbbefb150a8fb
tests/test_probabilistic_interleave_speed.py
tests/test_probabilistic_interleave_speed.py
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il.Probabilistic([r1, r2]) ranking = method.interleave() print(list(ranking))
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(range(150, 250)) for i in range(1000): method = il.Probabilistic([r1, r2, r3, r4]) ranking = method.interleave() method.evaluate(ranking, [0, 1, 2])
Add tests for measuring the speed of probabilistic interleaving
Add tests for measuring the speed of probabilistic interleaving
Python
mit
mpkato/interleaving
5c3bd2ebdfd1abdacc0e2603fbba0f4e5b3eb5e3
tests/test_reshape_image.py
tests/test_reshape_image.py
import numpy as np import rasterio def test_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: im_data = rasterio.plot.reshape_as_image(src) assert im_data.shape == (718, 791, 3) def test_toundtrip_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: data = src.read() im_data = rasterio.plot.reshape_as_image(data) assert np.array_equal(data, rasterio.plot.reshape_as_raster(im_data))
import numpy as np import rasterio def test_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: im_data = rasterio.plot.reshape_as_image(src.read()) assert im_data.shape == (718, 791, 3) def test_toundtrip_reshape(): with rasterio.open('tests/data/RGB.byte.tif') as src: data = src.read() im_data = rasterio.plot.reshape_as_image(data) assert np.array_equal(data, rasterio.plot.reshape_as_raster(im_data))
Update reshape_image test for new decoupled io function
Update reshape_image test for new decoupled io function
Python
bsd-3-clause
kapadia/rasterio,brendan-ward/rasterio,kapadia/rasterio,kapadia/rasterio,brendan-ward/rasterio,brendan-ward/rasterio
2965891b46e89e0d7222ec16a2327f2bdef86f52
chemex/util.py
chemex/util.py
"""The util module contains a variety of utility functions.""" import configparser import sys def read_cfg_file(filename): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser(inline_comment_prefixes=("#", ";")) config.optionxform = str try: out = config.read(str(filename)) if not out and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
"""The util module contains a variety of utility functions.""" import configparser import sys def listfloat(text): return [float(val) for val in text.strip("[]").split(",")] def read_cfg_file(filename=None): """Read and parse the experiment configuration file with configparser.""" config = configparser.ConfigParser( comment_prefixes="#", inline_comment_prefixes="#", converters=listfloat ) config.optionxform = str try: result = config.read(str(filename)) if not result and filename is not None: exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n") except configparser.MissingSectionHeaderError: exit(f"\nERROR: You are missing a section heading in {filename:s}\n") except configparser.ParsingError: exit( "\nERROR: Having trouble reading your parameter file, did you" " forget '=' signs?\n{:s}".format(sys.exc_info()[1]) ) return config def normalize_path(working_dir, filename): """Normalize the path of a filename relative to a specific directory.""" path = filename if not path.is_absolute(): path = working_dir / path return path.resolve() def header1(string): """Print a formatted heading.""" print(("\n".join(["", "", string, "=" * len(string), ""]))) def header2(string): """Print a formatted subheading.""" print(("\n".join(["", string, "-" * len(string), ""])))
Update settings for reading config files
Update settings for reading config files Update the definition of comments, now only allowing the use of "#" for comments. Add a converter function to parse list of floats, such as: list_of_floats = [1.0, 2.0, 3.0]
Python
bsd-3-clause
gbouvignies/chemex
b6e9e37350a4b435df00a54b2ccd9da70a4db788
nogotofail/mitm/util/ip.py
nogotofail/mitm/util/ip.py
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet addr:([^ ]*)", output) v6 = re.findall("inet6 addr: ([^ ]*)", output) return v4, v6
r''' Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import subprocess import re def get_interface_addresses(): """Get all ip addresses assigned to interfaces. Returns a tuple of (v4 addresses, v6 addresses) """ try: output = subprocess.check_output("ifconfig") except subprocess.CalledProcessError: # Couldn't call ifconfig. Best guess it. return (["127.0.0.1"], []) # Parse out the results. v4 = re.findall("inet (addr:)?([^ ]*)", output) v6 = re.findall("inet6 (addr: )?([^ ]*)", output) v4 = [e[1] for e in v4] v6 = [e[1] for e in v6] return v4, v6
Fix local interface addr parsing
Fix local interface addr parsing On Fedora 21 the format of ifconfig is a little different. Fixes #17
Python
apache-2.0
google/nogotofail,leasual/nogotofail,mkenne11/nogotofail,joshcooper/nogotofail,digideskio/nogotofail,mkenne11/nogotofail-pii,joshcooper/nogotofail,google/nogotofail,mkenne11/nogotofail,digideskio/nogotofail,leasual/nogotofail,mkenne11/nogotofail-pii
79b5227deaf830a9ce51d18387372fe6cf88e51d
monasca_setup/detection/plugins/neutron.py
monasca_setup/detection/plugins/neutron.py
import monasca_setup.detection class Neutron(monasca_setup.detection.ServicePlugin): """Detect Neutron daemons and setup configuration to monitor them. """ def __init__(self, template_dir, overwrite=True, args=None): service_params = { 'args': args, 'template_dir': template_dir, 'overwrite': overwrite, 'service_name': 'networking', 'process_names': ['neutron-server', 'neutron-openvswitch-agent', 'neutron-rootwrap', 'neutron-dhcp-agent', 'neutron-vpn-agent', 'neutron-metadata-agent', 'neutron-metering-agent', 'neutron-l3-agent', 'neutron-ns-metadata-proxy', '/opt/stack/service/neutron/venv/bin/neutron-lbaas-agent', '/opt/stack/service/neutron/venv/bin/neutron-lbaasv2-agent', 'neutron-l2gateway-agent'], 'service_api_url': 'http://localhost:9696', 'search_pattern': '.*v2.0.*' } super(Neutron, self).__init__(service_params) def build_config(self): """Build the config as a Plugins object and return.""" # Skip the http check if neutron-server is not on this box if 'neutron-server' not in self.found_processes: self.service_api_url = None self.search_pattern = None return monasca_setup.detection.ServicePlugin.build_config(self)
import monasca_setup.detection class Neutron(monasca_setup.detection.ServicePlugin): """Detect Neutron daemons and setup configuration to monitor them. """ def __init__(self, template_dir, overwrite=True, args=None): service_params = { 'args': args, 'template_dir': template_dir, 'overwrite': overwrite, 'service_name': 'networking', 'process_names': ['neutron-server', 'neutron-openvswitch-agent', 'neutron-rootwrap', 'neutron-dhcp-agent', 'neutron-vpn-agent', 'neutron-metadata-agent', 'neutron-metering-agent', 'neutron-l3-agent', 'neutron-ns-metadata-proxy', 'bin/neutron-lbaas-agent', 'neutron-lbaasv2-agent', 'neutron-l2gateway-agent'], 'service_api_url': 'http://localhost:9696', 'search_pattern': '.*v2.0.*' } super(Neutron, self).__init__(service_params) def build_config(self): """Build the config as a Plugins object and return.""" # Skip the http check if neutron-server is not on this box if 'neutron-server' not in self.found_processes: self.service_api_url = None self.search_pattern = None return monasca_setup.detection.ServicePlugin.build_config(self)
Remove vendor-specific paths on LBaaS agent executables
Remove vendor-specific paths on LBaaS agent executables The monasca agent uses simple string matching in the process detection plugin. This can result in false positive matches in the case where a process name appears elsehwere in the "ps" output. In particular, "neutron-lbaas-agent" is used for both process and log file names. The initial attempt at solving this used full path names for the LBaaS agents, but these paths were only valid for specific vendor distributions. This patch reverts to using only "neutron-lbaasv2-agent" for the V2 LBaaS agent, and uses "bin/neutron-lbaas-agent" for the V1 agent. While it is possible that a vendor would deliver the neutron-lbaas-agent in a directory other than "bin", they would be diverging from the layout generally assumed by the overall neutron project. Change-Id: I6654d99ea060e26b7cdd5b0bdb1a1c0a2537ba3b
Python
bsd-3-clause
sapcc/monasca-agent,sapcc/monasca-agent,sapcc/monasca-agent
91f5db6ddf6e26cec27917109689c200498dc85f
statsmodels/formula/try_formula.py
statsmodels/formula/try_formula.py
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
import statsmodels.api as sm import numpy as np star98 = sm.datasets.star98.load_pandas().data formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHISP", "PCTCHRT", "PCTYRRND", "PERMINTE", "AVYRSEXP", "AVSALK", "PERSPENK", "PTRATIO", "PCTAF"]] endog = dta["NABOVE"]/(dta["NABOVE"] + dta.pop("NBELOW")) del dta["NABOVE"] dta["SUCCESS"] = endog endog = dta.pop("SUCCESS") exog = dta mod = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit() # try passing a formula object, using user-injected code def double_it(x): return 2*x # What is the correct entry point for this? Should users be able to inject # code into default_env or similar? I don't see a way to do this yet using # the approach I have been using, it should be an argument to Desc from charlton.builtins import builtins builtins['double_it'] = double_it formula = 'SUCCESS ~ double_it(LOWINC) + PERASIAN + PERBLACK + PERHISP + ' formula += 'PCTCHRT ' formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF' mod2 = sm.GLM(endog, exog, formula=formula, family=sm.families.Binomial()).fit()
Add example for injecting user transform
ENH: Add example for injecting user transform
Python
bsd-3-clause
bert9bert/statsmodels,YihaoLu/statsmodels,cbmoore/statsmodels,hlin117/statsmodels,bavardage/statsmodels,detrout/debian-statsmodels,hainm/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,statsmodels/statsmodels,astocko/statsmodels,DonBeo/statsmodels,bzero/statsmodels,Averroes/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,josef-pkt/statsmodels,kiyoto/statsmodels,kiyoto/statsmodels,saketkc/statsmodels,bavardage/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,YihaoLu/statsmodels,ChadFulton/statsmodels,wdurhamh/statsmodels,phobson/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,wkfwkf/statsmodels,jstoxrocky/statsmodels,bert9bert/statsmodels,gef756/statsmodels,astocko/statsmodels,wdurhamh/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,ChadFulton/statsmodels,phobson/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,yl565/statsmodels,rgommers/statsmodels,yl565/statsmodels,nvoron23/statsmodels,edhuckle/statsmodels,nguyentu1602/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,waynenilsen/statsmodels,wwf5067/statsmodels,wwf5067/statsmodels,edhuckle/statsmodels,josef-pkt/statsmodels,wzbozon/statsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,gef756/statsmodels,phobson/statsmodels,wwf5067/statsmodels,huongttlan/statsmodels,waynenilsen/statsmodels,adammenges/statsmodels,DonBeo/statsmodels,yl565/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,gef756/statsmodels,bashtage/statsmodels,musically-ut/statsmodels,bavardage/statsmodels,wzbozon/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bzero/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,YihaoLu/statsmodels,josef-pkt/statsmodels,saketkc/statsmodels,jseabold/statsmodels,josef-pkt/statsmodels,phobson/statsmodels,kiyoto/statsmodels,wzbozon/statsmodels,alekz112/statsmodels,nvoron23/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,musically-ut/statsmodels,wdurhamh/statsmodels,yl565/statsmodels,statsmodels/statsmodels,bsipocz/statsmodels,yarikoptic/pystatsmodels,DonBeo/statsmodels,jseabold/statsmodels,nguyentu1602/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,wdurhamh/statsmodels,rgommers/statsmodels,adammenges/statsmodels,alekz112/statsmodels,detrout/debian-statsmodels,YihaoLu/statsmodels,musically-ut/statsmodels,bert9bert/statsmodels,jseabold/statsmodels,detrout/debian-statsmodels,bavardage/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,Averroes/statsmodels,cbmoore/statsmodels,wwf5067/statsmodels,hainm/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,detrout/debian-statsmodels,hlin117/statsmodels,Averroes/statsmodels,phobson/statsmodels,bzero/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,edhuckle/statsmodels,hainm/statsmodels,astocko/statsmodels,jseabold/statsmodels,bashtage/statsmodels,waynenilsen/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,astocko/statsmodels,rgommers/statsmodels,hainm/statsmodels,kiyoto/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,nvoron23/statsmodels,jstoxrocky/statsmodels,huongttlan/statsmodels,yarikoptic/pystatsmodels,bashtage/statsmodels,jseabold/statsmodels,DonBeo/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels,adammenges/statsmodels,rgommers/statsmodels,bavardage/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,bzero/statsmodels,yarikoptic/pystatsmodels,YihaoLu/statsmodels,bzero/statsmodels,hlin117/statsmodels,nguyentu1602/statsmodels
5e7c99844a0687125e34104cf2c7ee87ca69c0de
mopidy_soundcloud/__init__.py
mopidy_soundcloud/__init__.py
import os from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), "ext.conf") return config.read(conf_file) def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
import pathlib from mopidy import config, ext from mopidy.exceptions import ExtensionError __version__ = "2.1.0" class Extension(ext.Extension): dist_name = "Mopidy-SoundCloud" ext_name = "soundcloud" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["explore_songs"] = config.Integer(optional=True) schema["auth_token"] = config.Secret() schema["explore"] = config.Deprecated() schema["explore_pages"] = config.Deprecated() return schema def validate_config(self, config): # no_coverage if not config.getboolean("soundcloud", "enabled"): return if not config.get("soundcloud", "auth_token"): raise ExtensionError( "In order to use SoundCloud extension you must provide an " "auth token. For more information refer to " "https://github.com/mopidy/mopidy-soundcloud/" ) def setup(self, registry): from .actor import SoundCloudBackend registry.add("backend", SoundCloudBackend)
Use pathlib to read ext.conf
Use pathlib to read ext.conf
Python
mit
mopidy/mopidy-soundcloud
d6551b93f5900eca3f44af6e45cf96ba9573fe0e
shub/fetch_eggs.py
shub/fetch_eggs.py
import click import requests from shub.utils import find_api_key from shub.click_utils import log @click.command(help="Download a project's eggs from the Scrapy Cloud") @click.argument("project_id", required=True) def cli(project_id): auth = (find_api_key(), '') url = "https://staging.scrapinghub.com/api/eggs/bundle.zip?project=%s" % project_id rsp = requests.get(url=url, auth=auth, stream=True, timeout=300) destfile = 'eggs-%s.zip' % project_id log("Downloading eggs to %s" % destfile) with open(destfile, 'wb') as f: for chunk in rsp.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush()
import click import requests from shub.utils import find_api_key from shub.click_utils import log @click.command(help="Download a project's eggs from the Scrapy Cloud") @click.argument("project_id", required=True) def cli(project_id): auth = (find_api_key(), '') url = "https://dash.scrapinghub.com/api/eggs/bundle.zip?project=%s" % project_id rsp = requests.get(url=url, auth=auth, stream=True, timeout=300) destfile = 'eggs-%s.zip' % project_id log("Downloading eggs to %s" % destfile) with open(destfile, 'wb') as f: for chunk in rsp.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush()
Use production dashboard API endpoint
Use production dashboard API endpoint
Python
bsd-3-clause
scrapinghub/shub
94ec7d4816d2a243b8a2b0a0f2dc8a55a7347122
tests/saltunittest.py
tests/saltunittest.py
""" This file provides a single interface to unittest objects for our tests while supporting python < 2.7 via unittest2. If you need something from the unittest namespace it should be imported here from the relevant module and then imported into your test from here """ # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: print("You need to install unittest2 to run the salt tests") sys.exit(1) else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
""" This file provides a single interface to unittest objects for our tests while supporting python < 2.7 via unittest2. If you need something from the unittest namespace it should be imported here from the relevant module and then imported into your test from here """ # Import python libs import os import sys # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: from unittest2 import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf except ImportError: raise SystemExit("You need to install unittest2 to run the salt tests") else: from unittest import TestLoader, TextTestRunner,\ TestCase, expectedFailure, \ TestSuite, skipIf # Set up paths TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__))) SALT_LIBS = os.path.dirname(TEST_DIR) for dir_ in [TEST_DIR, SALT_LIBS]: if not dir_ in sys.path: sys.path.insert(0, dir_)
Make an error go to stderr and remove net 1 LOC
Make an error go to stderr and remove net 1 LOC
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
b6737b91938d527872eff1d645a205cacf94e15d
tests/test_gobject.py
tests/test_gobject.py
# -*- Mode: Python -*- import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') self.assertEquals(obj.__grefcount__, 1) class TestFloating(unittest.TestCase): def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
# -*- Mode: Python -*- import unittest import gobject import testhelper class TestGObjectAPI(unittest.TestCase): def testGObjectModule(self): obj = gobject.GObject() self.assertEquals(obj.__module__, 'gobject._gobject') class TestReferenceCounting(unittest.TestCase): def testRegularObject(self): obj = gobject.GObject() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(gobject.GObject) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithSinkFunc(self): obj = testhelper.FloatingWithSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithSinkFunc) self.assertEquals(obj.__grefcount__, 1) def testFloatingWithoutSinkFunc(self): obj = testhelper.FloatingWithoutSinkFunc() self.assertEquals(obj.__grefcount__, 1) obj = gobject.new(testhelper.FloatingWithoutSinkFunc) self.assertEquals(obj.__grefcount__, 1)
Add a test to check for regular object reference count
Add a test to check for regular object reference count https://bugzilla.gnome.org/show_bug.cgi?id=639949
Python
lgpl-2.1
alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,davibe/pygobject,jdahlin/pygobject,choeger/pygobject-cmake,MathieuDuponchelle/pygobject,choeger/pygobject-cmake,davidmalcolm/pygobject,davibe/pygobject,pexip/pygobject,Distrotech/pygobject,alexef/pygobject,sfeltman/pygobject,jdahlin/pygobject,GNOME/pygobject,GNOME/pygobject,thiblahute/pygobject,sfeltman/pygobject,thiblahute/pygobject,GNOME/pygobject,Distrotech/pygobject,MathieuDuponchelle/pygobject,nzjrs/pygobject,Distrotech/pygobject,nzjrs/pygobject,jdahlin/pygobject,MathieuDuponchelle/pygobject,davibe/pygobject,pexip/pygobject,alexef/pygobject,pexip/pygobject,sfeltman/pygobject,choeger/pygobject-cmake,thiblahute/pygobject,davidmalcolm/pygobject,nzjrs/pygobject,davibe/pygobject
5cf0b19d67a667d4e0d48a12f0ee94f3387cfa37
tests/test_helpers.py
tests/test_helpers.py
# -*- encoding: utf-8 -*- # # Copyright 2013 Jay Pipes # # 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 testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout')
# -*- encoding: utf-8 -*- # # Copyright 2013 Jay Pipes # # 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 testtools from talons import helpers from tests import base class TestHelpers(base.TestCase): def test_bad_import(self): with testtools.ExpectedException(ImportError): helpers.import_function('not.exist.function') def test_no_function_in_module(self): with testtools.ExpectedException(ImportError): helpers.import_function('sys.noexisting') def test_not_callable(self): with testtools.ExpectedException(TypeError): helpers.import_function('sys.stdout') def test_return_function(self): fn = helpers.import_function('os.path.join') self.assertEqual(callable(fn), True)
Add test to ensure talons.helpers.import_function returns a callable
Add test to ensure talons.helpers.import_function returns a callable
Python
apache-2.0
talons/talons,jaypipes/talons
73dfb1fc4ff62705f37b1128e0684e88be416d8f
src/webmention/models.py
src/webmention/models.py
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return '<a href="{href}">{href}</a>'.format(href=self.source) source_for_admin.allow_tags = True source_for_admin.short_description = "source" def response_to_for_admin(self): return '<a href="{href}">{href}</a>'.format(href=self.response_to) response_to_for_admin.allow_tags = True response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
from django.db import models class WebMentionResponse(models.Model): response_body = models.TextField() response_to = models.URLField() source = models.URLField() reviewed = models.BooleanField(default=False) current = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Meta: verbose_name = "webmention" verbose_name_plural = "webmentions" def __str__(self): return self.source def source_for_admin(self): return format_html('<a href="{href}">{href}</a>'.format(href=self.source)) source_for_admin.short_description = "source" def response_to_for_admin(self): return format_html('<a href="{href}">{href}</a>'.format(href=self.response_to)) response_to_for_admin.short_description = "response to" def invalidate(self): if self.id: self.current = False self.save() def update(self, source, target, response_body): self.response_body = response_body self.source = source self.response_to = target self.current = True self.save()
Update deprecated allow_tags to format_html
Update deprecated allow_tags to format_html
Python
mit
easy-as-python/django-webmention
9c0d79d5d019c941806c09ccb79593b96f5e9fbe
discoverage/settings.py
discoverage/settings.py
from django.conf import settings # The name of the iterable ``django-discoverage`` looks for in the discovery # process TESTED_APPS_VAR_NAME = getattr(settings, 'TESTED_APPS_VAR_NAME', 'TESTS_APPS') # Modules not to trace COVERAGE_OMIT_MODULES = getattr(settings, 'COVERAGE_OMIT_MODULES', ['*test*']) COVERAGE_EXCLUDE_PATTERNS = getattr(settings, 'COVERAGE_EXCLUDE_PATTERNS', [ r'def __unicode__\(self\):', r'def __str__\(self\):', r'def get_absolute_url\(self\):', r'from .* import .*', 'import .*', ]) # Determines whether the apps to be included in the coverage report # should be inferred from the test's subpackage name PKG_NAME_APP_DISCOVERY = getattr(settings, 'PKG_NAME_APP_DISCOVERY', True) # Determines whether tested apps are guessed from module names MODULE_NAME_APP_DISCOVERY = getattr(settings, 'MODULE_NAME_APP_DISCOVERY', False) MODULE_NAME_DISCOVERY_PATTERN = getattr(settings, 'MODULE_NAME_DISCOVERY_PATTERN', r'test_?(\w+)')
from django.conf import settings # The name of the iterable ``django-discoverage`` looks for in the discovery # process TESTED_APPS_VAR_NAME = getattr(settings, 'TESTED_APPS_VAR_NAME', 'TESTS_APPS') # Modules not to trace COVERAGE_OMIT_MODULES = getattr(settings, 'COVERAGE_OMIT_MODULES', ['*test*']) COVERAGE_EXCLUDE_PATTERNS = getattr(settings, 'COVERAGE_EXCLUDE_PATTERNS', [ r'def __unicode__\(self\):', r'def __str__\(self\):', r'def get_absolute_url\(self\):', r'from .* import .*', r'import .*', ]) # Determines whether the apps to be included in the coverage report # should be inferred from the test's subpackage name PKG_NAME_APP_DISCOVERY = getattr(settings, 'PKG_NAME_APP_DISCOVERY', True) # Determines whether tested apps are guessed from module names MODULE_NAME_APP_DISCOVERY = getattr(settings, 'MODULE_NAME_APP_DISCOVERY', False) MODULE_NAME_DISCOVERY_PATTERN = getattr(settings, 'MODULE_NAME_DISCOVERY_PATTERN', r'test_?(\w+)')
Move exclude pattern to its own line.
Move exclude pattern to its own line.
Python
bsd-2-clause
ryankask/django-discoverage,ryankask/django-discoverage
e612a742caeedf5398522365c984a39c505e7872
warehouse/exceptions.py
warehouse/exceptions.py
class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals class FailedSynchronization(Exception): pass class SynchronizationTimeout(Exception): """ A synchronization for a particular project took longer than the timeout. """
Add the standard __future__ imports
Add the standard __future__ imports
Python
bsd-2-clause
davidfischer/warehouse
34c427200c6ab50fb64fa0d6116366a8fa9186a3
netman/core/objects/bond.py
netman/core/objects/bond.py
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or []
# Copyright 2015 Internap. # # 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 warnings from netman.core.objects.interface import BaseInterface class Bond(BaseInterface): def __init__(self, number=None, link_speed=None, members=None, **interface): super(Bond, self).__init__(**interface) self.number = number self.link_speed = link_speed self.members = members or [] @property def interface(self): warnings.warn('Deprecated: Use directly the members of Bond instead.', category=DeprecationWarning) return self
Support deprecated use of the interface property of Bond.
Support deprecated use of the interface property of Bond.
Python
apache-2.0
idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman
071004d9e70b769df2303ed9be1a4d494197667c
39_string_slice.py
39_string_slice.py
musketeersName = 'Tom Dick Harry' print 'Three musketeers are', musketeersName musketeer_1 = musketeersName[0:3] print 'First musketeer :', musketeer_1 musketeer_2 = musketeersName[4:8] print 'Second musketeer :', musketeer_2 musketeer_3 = musketeersName[9:14] print 'Third musketeer :', musketeer_3 print "\n----------------- Special case STARTS, in case if you are not sure about the final length of the string --------------------\n" musketeer_3 = musketeersName[9:20] print 'Third musketeer [9:20], it should be [9:14]:', musketeer_3 print "\n----------------- Special case ENDS, in case if you are not sure about the final length of the string --------------------\n" firstTwoChars = musketeersName[:2] print 'First Two characters of the string :', firstTwoChars lastTwoChars = musketeersName[12:] print 'First Two characters of the string :', lastTwoChars allChars = musketeersName[:] print 'All characters of the string :', allChars
musketeersName = 'Tom Dick Harry' print 'Three musketeers are', musketeersName musketeer_1 = musketeersName[0:3] print 'First musketeer :', musketeer_1 musketeer_2 = musketeersName[4:8] print 'Second musketeer :', musketeer_2 musketeer_3 = musketeersName[9:14] print 'Third musketeer :', musketeer_3 print "\n----------------- Special case STARTS, in case if you are not sure about the final length of the string --------------------\n" musketeer_3 = musketeersName[9:20] print 'Third musketeer [9:20], it should be [9:14]:', musketeer_3 print "\n----------------- Special case ENDS, in case if you are not sure about the final length of the string --------------------\n" firstTwoChars = musketeersName[:2] print 'First Two characters of the string :', firstTwoChars lastTwoChars = musketeersName[12:] print 'Last Two characters of the string :', lastTwoChars allChars = musketeersName[:] print 'All characters of the string :', allChars
Update the put put text
Update the put put text
Python
mit
rahulbohra/Python-Basic
962b1a7e0258db1bd6d8e5b37d32f8012684792a
spoppy/__init__.py
spoppy/__init__.py
import logging import click from lockfile import LockFile, LockTimeout logger = logging.getLogger('spoppy.main') def get_version(): return '1.1.0' @click.command() @click.argument('username', required=False) @click.argument('password', required=False) def main(username, password): # Ignore error, logging set up in logging utils from . import logging_utils from .navigation import Leifur from .config import get_config, set_config, get_config_from_user lock = LockFile('/tmp/spoppy.lock') try: # Try for 5s to acquire the lock lock.acquire(5) except LockTimeout: click.echo('Could not acquire lock, is spoppy running?') else: if username and password: set_config(username, password) else: username, password = get_config() if not (username and password): username, password = get_config_from_user() try: navigator = Leifur(username, password) navigator.start() finally: navigator.shutdown() logger.debug('Finally, bye!') finally: if lock.i_am_locking(): lock.release()
import logging try: import click from lockfile import LockFile, LockTimeout except ImportError: click = None logger = logging.getLogger('spoppy.main') def get_version(): return '1.1.0' if click: @click.command() @click.argument('username', required=False) @click.argument('password', required=False) def main(username, password): # Ignore error, logging set up in logging utils from . import logging_utils from .navigation import Leifur from .config import get_config, set_config, get_config_from_user lock = LockFile('/tmp/spoppy.lock') try: # Try for 5s to acquire the lock lock.acquire(5) except LockTimeout: click.echo('Could not acquire lock, is spoppy running?') else: if username and password: set_config(username, password) else: username, password = get_config() if not (username and password): username, password = get_config_from_user() try: navigator = Leifur(username, password) navigator.start() finally: navigator.shutdown() logger.debug('Finally, bye!') finally: if lock.i_am_locking(): lock.release() else: def main(*args, **kwargs): print('Something went horribly wrong, missing requirements...')
Handle importerrors when f.x. we are installing
Handle importerrors when f.x. we are installing
Python
mit
sindrig/spoppy,sindrig/spoppy
ab06e871a6c820845da2d4d60bb6b1874350cf16
circuits/web/__init__.py
circuits/web/__init__.py
# Module: __init__ # Date: 3rd October 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Library - Web circuits.web contains the circuits full stack web server that is HTTP and WSGI compliant. """ from loggers import Logger from core import Controller from sessions import Sessions from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
# Module: __init__ # Date: 3rd October 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Library - Web circuits.web contains the circuits full stack web server that is HTTP and WSGI compliant. """ from utils import url from loggers import Logger from sessions import Sessions from core import expose, Controller from events import Request, Response from servers import BaseServer, Server from errors import HTTPError, Forbidden, NotFound, Redirect from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC try: from dispatchers import JSONRPC except ImportError: pass
Add url and expose to this namesapce
circuits.web: Add url and expose to this namesapce
Python
mit
eriol/circuits,eriol/circuits,nizox/circuits,treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits
1e484c288bb95dc10b15c0c73d5c8146f1b92627
rynda/Rynda/settings/local.py
rynda/Rynda/settings/local.py
# coding: utf-8 from .base import * DEBUG = True TEMPLATE_DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'devrynda', 'USER': 'devrynda', 'PASSWORD': 'devrynda', 'HOST': 'localhost', 'PORT': '', } } INSTALLED_APPS += ( 'debug_toolbar', 'test', ) INTERNAL_IPS = ('127.0.0.1') MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
# coding: utf-8 import re import debug_toolbar from .base import * DEBUG = True TEMPLATE_DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'devrynda', 'USER': 'devrynda', 'PASSWORD': 'devrynda', 'HOST': 'localhost', 'PORT': '', } } def show_toolbar(request): uri = request.get_full_path() if re.match('/admin/', uri): return False return debug_toolbar.middleware.show_toolbar INSTALLED_APPS += ( 'debug_toolbar', 'test', ) INTERNAL_IPS = ('127.0.0.1') MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': "Rynda.settings.local.show_toolbar", }
Hide debug_toolbar in admin application
Hide debug_toolbar in admin application
Python
mit
sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa
04c92e1fe7efa38f7d99d501286d3b7e627e73ca
scripts/slave/chromium/dart_buildbot_run.py
scripts/slave/chromium/dart_buildbot_run.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') # Temporary until 1.6 ships on stable. if builder_name.endswith('-be') or builder_name.endswith("-dev"): script = 'src/dart/tools/dartium/buildbot_annotated_steps.py' else: script = 'src/dartium_tools/buildbot_annotated_steps.py' chromium_utils.RunCommand([sys.executable, script]) # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for the dartium buildbots. This script is called from buildbot and reports results using the buildbot annotation scheme. """ import os import sys from common import chromium_utils def main(): builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='') # Temporary until 1.6 ships on stable. if builder_name.endswith('-be') or builder_name.endswith("-dev"): script = 'src/dart/tools/dartium/buildbot_annotated_steps.py' else: script = 'src/dartium_tools/buildbot_annotated_steps.py' result = chromium_utils.RunCommand([sys.executable, script]) if result: print 'Running annotated steps % failed' % script return 1 # BIG HACK # Normal ninja clobbering does not work due to symlinks/python on windows # Full clobbering before building does not work since it will destroy # the ninja build files # So we basically clobber at the end here if chromium_utils.IsWindows() and 'full' in builder_name: chromium_utils.RemoveDirectory('src/out') return 0 if __name__ == '__main__': sys.exit(main())
Use exitcode of running the annotated steps script
Use exitcode of running the annotated steps script If there is an error in the annotated steps we will still have a green bot!!!! Example: http://chromegw.corp.google.com/i/client.dart/builders/dartium-lucid64-full-be/builds/3566/steps/annotated_steps/logs/stdio TBR=whesse Review URL: https://codereview.chromium.org/450923002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@288225 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
5dd07cdc94a479b5c274a2335a50815b957cffe6
zoe_web/web/__init__.py
zoe_web/web/__init__.py
# Copyright (c) 2015, Daniele Venzano # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from flask import Blueprint web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static') import zoe_web.web.start import zoe_web.web.status import zoe_web.web.applications from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION @web_bp.context_processor def inject_version(): return { 'zoe_lib_version': ZOE_VERSION, 'zoe_api_version': ZOE_API_VERSION, }
# Copyright (c) 2015, Daniele Venzano # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from flask import Blueprint web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static') import zoe_web.web.start import zoe_web.web.status import zoe_web.web.applications from zoe_lib.version import ZOE_API_VERSION, ZOE_VERSION @web_bp.context_processor def inject_version(): return { 'zoe_version': ZOE_VERSION, 'zoe_api_version': ZOE_API_VERSION, }
Fix version in web pages
Fix version in web pages
Python
apache-2.0
DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe
fa7aecae90026037c9f5ce2ffef37184ee83f679
nova/objects/__init__.py
nova/objects/__init__.py
# Copyright 2013 IBM Corp. # # 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.
# Copyright 2013 IBM Corp. # # 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. def register_all(): # NOTE(danms): You must make sure your object gets imported in this # function in order for it to be registered by services that may # need to receive it via RPC. __import__('nova.objects.instance')
Use Instance Objects for Start/Stop
Use Instance Objects for Start/Stop This patch makes the start and stop operations use the Instance object instead of passing SQLA-derived dicts over RPC. Until something more sophisticated is needed (and developed), it also adds a nova.object.register_all() function which just triggers imports of all the object models so that they are registered. When adding a new object type, that register function should be updated appropriately. Related to bp/unified-object-model Change-Id: I3c8d9cba07d34097a279502062906de802d19d1f
Python
apache-2.0
citrix-openstack-build/oslo.versionedobjects,openstack/oslo.versionedobjects
59371c5951f476e1684022744f4a37eb6fe62c98
DebianDevelChangesBot/utils/tidy_bug_title.py
DebianDevelChangesBot/utils/tidy_bug_title.py
# -*- coding: utf-8 -*- # # Debian Changes Bot # Copyright (C) 2008 Chris Lamb <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. def tidy_bug_title(title, package): """ Strips various package name prefixes from a bug title. For example: "emacs: Not as good as vim" => "Not as good as vim" "[emacs] Not as good as vim" => "Not as good as vim" """ for prefix in ('%s: ', '[%s]: ', '[%s] '): if title.lower().startswith(prefix % package.lower()): title = title[len(package) + len(prefix) - 2:] return title
# -*- coding: utf-8 -*- # # Debian Changes Bot # Copyright (C) 2008 Chris Lamb <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re WHITESPACE = re.compile(r'\s{2,}') def tidy_bug_title(title, package): """ Strips various package name prefixes from a bug title. For example: "emacs: Not as good as vim" => "Not as good as vim" "[emacs] Not as good as vim" => "Not as good as vim" """ title = title.strip() for prefix in ('%s: ', '[%s]: ', '[%s] '): if title.lower().startswith(prefix % package.lower()): title = title[len(package) + len(prefix) - 2:] title = WHITESPACE.sub(' ', title) return title
Remove extra whitespace from bug title
Remove extra whitespace from bug title Signed-off-by: Chris Lamb <[email protected]>
Python
agpl-3.0
lamby/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,lamby/debian-devel-changes-bot
186a2c3f235264c3c71396efcbb8a33924758db9
scrape.py
scrape.py
import discord import asyncio from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Discord channel scraper') requiredNamed = parser.add_argument_group('Required arguments:') requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True) requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True) args = parser.parse_args() client = discord.Client() @client.event async def on_ready(): print('Connection successful.') print('Your ID: ' + client.user.id) target = open(args.output, 'w') print(args.output, 'has been opened.') messageCount = 0 channel = discord.Object(id=args.channel) print("Scraping messages... Don't send any messages while scraping!") with tqdm(leave=True,unit=' messages') as scraped: async for msg in client.logs_from(channel, 10000000000): line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content) line = line.encode('utf-8') toWrite = "{}".format(line) target.write(toWrite) target.write("\n") messageCount += 1 scraped.update(1) print('-----') print('Scraping complete.') #---------------------------- client.run('email', 'password')
import discord import asyncio from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Discord channel scraper') requiredNamed = parser.add_argument_group('Required arguments:') requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True) requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True) args = parser.parse_args() client = discord.Client() @client.event async def on_ready(): print('Connection successful.') print('Your ID: ' + client.user.id) target = open(args.output, 'w') print(args.output, 'has been opened.') messageCount = 0 channel = discord.Object(id=args.channel) print("Scraping messages... Don't send any messages while scraping!") with tqdm(leave=True,unit=' messages') as scraped: async for msg in client.logs_from(channel, 10000000000): line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content) line = line.encode('utf-8') toWrite = "{}".format(line) target.write(toWrite) target.write("\n") messageCount += 1 scraped.update(1) print('-----') print('Scraping complete.') #---------------------------- client.run(usertoken,bot=False)
Update to use token instead of email+pass
Update to use token instead of email+pass
Python
mit
suclearnub/discordgrapher
3ddad0538430499182c583a0a7f877884038c0a5
Lib/test/test_symtable.py
Lib/test/test_symtable.py
from test.test_support import vereq, TestFailed import symtable symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time
from test import test_support import symtable import unittest ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time class SymtableTest(unittest.TestCase): def test_invalid_args(self): self.assertRaises(TypeError, symtable.symtable, "42") self.assertRaises(ValueError, symtable.symtable, "42", "?", "") def test_eval(self): symbols = symtable.symtable("42", "?", "eval") def test_single(self): symbols = symtable.symtable("42", "?", "single") def test_exec(self): symbols = symtable.symtable("def f(x): return x", "?", "exec") def test_main(): test_support.run_unittest(SymtableTest) if __name__ == '__main__': test_main()
Use unittest and make sure a few other cases don't crash
Use unittest and make sure a few other cases don't crash
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f
OMDB_api_scrape.py
OMDB_api_scrape.py
#!/usr/bin/python3 # OMDB_api_scrape.py - parses a movie and year from the command line, grabs the # JSON and saves a copy for later import json, requests, sys, os URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) theJSON = json.loads(response.text) # Save the JSON file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile: json.dump(theJSON, outfile)
#!/usr/bin/python3 # OMDB_api_scrape.py - parses a movie and year from the command line, grabs the # xml and saves a copy for later import requests, sys, os import lxml.etree URL_BASE = 'http://www.omdbapi.com/?' if len(sys.argv) > 1: # Get address from command line. mTitle = '+'.join(sys.argv[1:-1]) mYear = sys.argv[-1] print(mTitle) print(mYear) else: print("Usage: OMDB_api_scrape.py <Movie Title> <Year>") sys.exit(1) # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml' # Try to get the url try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: print(err) sys.exit(1) # Save the XML file with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile: outfile.write(response.text)
Convert OMDB scrapper to grab xml
Convert OMDB scrapper to grab xml
Python
mit
samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia
8ac20f5bec2d94e71b92e48568d18fd74be4e5d4
fabfile.py
fabfile.py
from fabric.api import task, local @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx")
from fabric.api import task, local, execute @task def up(): """ Deploy new release to pypi. Using twine util """ local("rm -rf dist") local("rm -rf pgup.egg-info") local("python ./setup.py sdist") local("twine upload dist/{}".format(local("ls dist", capture=True).strip())) execute(syncMezzo) @task def docs(): """ Deploy documentation to pythonhosted. Using sphinx """ local("rm -rf build/html") local("python ./setup.py build_sphinx") local("python ./setup.py upload_sphinx") @task def syncMezzo(): """ Copy current module version to mezzo project """ local("rm -rf /opt/mezzo/pgup") local("mkdir /opt/mezzo/pgup") local("cp -R etc pgup /opt/mezzo/pgup") local("cp LICENSE MANIFEST.in README.md setup.py /opt/mezzo/pgup")
Add fab task for syncing pgup with mezzo
Add fab task for syncing pgup with mezzo
Python
mit
stepan-perlov/pgup
c3c26c15895a192fba22482306182950c0ccd57c
python/simple-linked-list/simple_linked_list.py
python/simple-linked-list/simple_linked_list.py
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self.size = 0 for value in values: self.push(value) def __len__(self): return self.size def head(self): pass def push(self, value): node = Node(value) if self.head is None: self.head = node self.size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): pass
class Node(object): def __init__(self, value): pass def value(self): pass def next(self): pass class LinkedList(object): def __init__(self, values=[]): self._size = 0 self._head = None for value in values: self.push(value) def __len__(self): return self._size def head(self): if self._head is None: raise EmptyListException("Head is empty") def push(self, value): node = Node(value) if self._head is None: self._head = node self._size += 1 def pop(self): pass def reversed(self): pass class EmptyListException(Exception): def __init__(self, message): self.message = message
Mark instance variables private with leading _
Mark instance variables private with leading _
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
fa609681c2732e655cde9075182af918983ccc1f
photutils/utils/_misc.py
photutils/utils/_misc.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides tools to return the installed astropy and photutils versions. """ from datetime import datetime, timezone def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides tools to return the installed astropy and photutils versions. """ from datetime import datetime, timezone import sys def _get_version_info(): """ Return a dictionary of the installed version numbers for photutils and its dependencies. Returns ------- result : dict A dictionary containing the version numbers for photutils and its dependencies. """ versions = {'Python': sys.version.split()[0]} packages = ('photutils', 'astropy', 'numpy', 'scipy', 'skimage', 'sklearn', 'matplotlib', 'gwcs', 'bottleneck') for package in packages: try: pkg = __import__(package) version = pkg.__version__ except ImportError: version = None versions[package] = version return versions def _get_date(utc=False): """ Return a string of the current date/time. Parameters ---------- utz : bool, optional Whether to use the UTZ timezone instead of the local timezone. Returns ------- result : str The current date/time. """ if not utc: now = datetime.now().astimezone() else: now = datetime.now(timezone.utc) return now.strftime('%Y-%m-%d %H:%M:%S %Z') def _get_meta(utc=False): """ Return a metadata dictionary with the package versions and current date/time. """ return {'date': _get_date(utc=utc), 'version': _get_version_info()}
Add all optional dependencies to version info dict
Add all optional dependencies to version info dict
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
1a51b2e2043a3b3eb4fa9d356ebaa43461d7d464
tests/on_the_fly_selector_tests.py
tests/on_the_fly_selector_tests.py
""" This module contains tests of code from the file named `../forecastonishing/selection/on_the_fly_selector.py`. @author: Nikolay Lysenko """ import unittest import numpy as np import pandas as pd from forecastonishing.selection.on_the_fly_selector import OnTheFlySelector from forecastonishing.miscellaneous.simple_forecasters import ( MovingAverageForecaster, MovingMedianForecaster ) class TestOnTheFlySelector(unittest.TestCase): """ Tests of `OnTheFlySelector` class. """ def test_fit(self) -> type(None): """ Test `fit` method. :return: None """ candidates = { MovingAverageForecaster(): [{'rolling_kwargs': {'window': w, 'min_periods': 1}} for w in range(1, 3)], MovingMedianForecaster(): [{'rolling_kwargs': {'window': w, 'min_periods': 1}} for w in range(3, 4)] } selector = OnTheFlySelector(candidates) df = pd.DataFrame( [[1, 2], [1, 3], [1, 6], [1, 5], [2, 3], [2, 4], [2, 4.5], [2, 1]], columns=['key', 'target'] ) selector.fit(df, 'target', ['key']) print(selector.best_scores_) true_answer = None # TODO: Finish this test. def main(): test_loader = unittest.TestLoader() suites_list = [] testers = [ TestOnTheFlySelector() ] for tester in testers: suite = test_loader.loadTestsFromModule(tester) suites_list.append(suite) overall_suite = unittest.TestSuite(suites_list) unittest.TextTestRunner().run(overall_suite) if __name__ == '__main__': main()
Create stub of fit testing
test: Create stub of fit testing
Python
mit
osahp/forecastonishing
a346eb2b19f3a0b72dc6565e9d0c4fabf3c5784a
migrations/versions/0014_add_template_version.py
migrations/versions/0014_add_template_version.py
"""empty message Revision ID: 0014_add_template_version Revises: 0013_add_loadtest_client Create Date: 2016-05-11 16:00:51.478012 """ # revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
"""empty message Revision ID: 0014_add_template_version Revises: 0013_add_loadtest_client Create Date: 2016-05-11 16:00:51.478012 """ # revision identifiers, used by Alembic. revision = '0014_add_template_version' down_revision = '0013_add_loadtest_client' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True)) op.get_bind() op.execute('update jobs set template_version = (select version from templates where id = template_id)') op.add_column('notifications', sa.Column('template_version', sa.Integer(), nullable=True)) op.execute('update notifications set template_version = (select version from templates where id = template_id)') op.alter_column('jobs', 'template_version', nullable=False) op.alter_column('notifications', 'template_version', nullable=False) # fix template_history where created_by_id is not set. query = "update templates_history set created_by_id = " \ " (select created_by_id from templates " \ " where templates.id = templates_history.id " \ " and templates.version = templates_history.version) " \ "where templates_history.created_by_id is null" op.execute(query) def downgrade(): op.drop_column('notifications', 'template_version') op.drop_column('jobs', 'template_version')
Add a update query to fix templates_history where the created_by_id is missing.
Add a update query to fix templates_history where the created_by_id is missing.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
e7fad19d22d90a4fe04d7e9c064b386686600938
plugins/FileHandlers/STLWriter/__init__.py
plugins/FileHandlers/STLWriter/__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import STLWriter from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "mesh_writer", "plugin": { "name": "STL Writer", "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("STL Writer plugin description", "Provides support for writing STL files.") }, "mesh_reader": { "extension": "stl", "description": i18n_catalog.i18nc("STL Reader plugin file type", "STL File") } } def register(app): return { "mesh_writer": STLWriter.STLWriter() }
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import STLWriter from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "type": "mesh_writer", "plugin": { "name": "STL Writer", "author": "Ultimaker", "version": "1.0", "decription": i18n_catalog.i18nc("STL Writer plugin description", "Provides support for writing STL files.") }, "mesh_writer": { "extension": "stl", "description": i18n_catalog.i18nc("STL Reader plugin file type", "STL File") } } def register(app): return { "mesh_writer": STLWriter.STLWriter() }
Fix STL Writer to properly advertise itself as mesh writer
Fix STL Writer to properly advertise itself as mesh writer This makes the STL writer show up correctly
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
587e22c86f8f811f94e1172a1f6cd60f3b0899de
src/keybar/core/auth.py
src/keybar/core/auth.py
from rest_framework_httpsignature.authentication import SignatureAuthentication from keybar.models.user import User class KeybarApiSignatureAuthentication(SignatureAuthentication): API_KEY_HEADER = 'X-Api-Key' def fetch_user_data(self, api_key): try: user = User.objects.get(api_key=api_key) return (user, 'my secret string') except User.DoesNotExist: return None
from rest_framework_httpsignature.authentication import SignatureAuthentication from keybar.models.user import User class KeybarApiSignatureAuthentication(SignatureAuthentication): API_KEY_HEADER = 'X-Api-Key' def fetch_user_data(self, api_key): try: user = User.objects.get(api_key=api_key) return (user, 'my secret string') except User.DoesNotExist: return (None, None)
Fix return value in case user was not found
Fix return value in case user was not found
Python
bsd-3-clause
keybar/keybar
64010f5151c03cbc99ff702b825f0e2ad4b96692
product_configurator_mrp/models/product.py
product_configurator_mrp/models/product.py
# -*- coding: utf-8 -*- from odoo import models, api class ProductTemplate(models.Model): _inherit = 'product.template' @api.multi def create_variant(self, value_ids, custom_values=None): """Add bill of matrials to the configured variant.""" if custom_values is None: custom_values = {} variant = super(ProductTemplate, self).create_variant( value_ids, custom_values=custom_values ) attr_products = variant.attribute_value_ids.mapped('product_id') line_vals = [ (0, 0, {'product_id': product.id}) for product in attr_products ] values = { 'product_tmpl_id': self.id, 'product_id': variant.id, 'bom_line_ids': line_vals } self.env['mrp.bom'].create(values) return variant
# -*- coding: utf-8 -*- from odoo import models, api class ProductTemplate(models.Model): _inherit = 'product.template' @api.multi def create_get_variant(self, value_ids, custom_values=None): """Add bill of matrials to the configured variant.""" if custom_values is None: custom_values = {} variant = super(ProductTemplate, self).create_get_variant( value_ids, custom_values=custom_values ) attr_products = variant.attribute_value_ids.mapped('product_id') line_vals = [ (0, 0, {'product_id': product.id}) for product in attr_products ] values = { 'product_tmpl_id': self.id, 'product_id': variant.id, 'bom_line_ids': line_vals } self.env['mrp.bom'].create(values) return variant
Fix creation of BOM when create Variant
Fix creation of BOM when create Variant
Python
agpl-3.0
richard-willdooit/odoo-product-configurator,microcom/odoo-product-configurator,richard-willdooit/odoo-product-configurator,microcom/odoo-product-configurator,richard-willdooit/odoo-product-configurator,microcom/odoo-product-configurator
af17bc003e486f27d9801ae56bb2e91c4fe6abc0
config.py
config.py
from os import getenv class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL') STRIP_WWW_PREFIX = True API_KEY = getenv('API_KEY') class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' class TestingConfig(Config): TESTING = True
from os import getenv class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///app.db') STRIP_WWW_PREFIX = True API_KEY = getenv('API_KEY') class ProductionConfig(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True
Allow overriding the DATABASE_URL with an environment varible if in development mode
Allow overriding the DATABASE_URL with an environment varible if in development mode
Python
mit
taeram/idiocy,taeram/idiocy,taeram/idiocy
df000e724ce1f307a478fcf4790404183df13610
_setup_database.py
_setup_database.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- from setup.create_teams import migrate_teams from setup.create_divisions import create_divisions from setup.create_players import migrate_players if __name__ == '__main__': # migrating teams from json file to database migrate_teams(simulation=True) # creating divisions from division configuration file create_divisions(simulation=True) # migrating players from json file to database migrate_players(simulation=True)
Include player data migration in setup
Include player data migration in setup
Python
mit
leaffan/pynhldb
c0d9a94899af84e8a075cfc7cfb054a934470e3a
static_precompiler/tests/test_templatetags.py
static_precompiler/tests/test_templatetags.py
import django.template import django.template.loader import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.loader.get_template_from_string("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.loader.get_template_from_string( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
import django.template import pretend def test_compile_filter(monkeypatch): compile_static = pretend.call_recorder(lambda source_path: "compiled") monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static) template = django.template.Template("""{% load compile_static %}{{ "source"|compile }}""") assert template.render(django.template.Context({})) == "compiled" monkeypatch.setattr("static_precompiler.settings.PREPEND_STATIC_URL", True) assert template.render(django.template.Context({})) == "/static/compiled" assert compile_static.calls == [pretend.call("source"), pretend.call("source")] def test_inlinecompile_tag(monkeypatch): compiler = pretend.stub(compile_source=pretend.call_recorder(lambda *args: "compiled")) get_compiler_by_name = pretend.call_recorder(lambda *args: compiler) monkeypatch.setattr("static_precompiler.utils.get_compiler_by_name", get_compiler_by_name) template = django.template.Template( "{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}" ) assert template.render(django.template.Context({})) == "compiled" assert get_compiler_by_name.calls == [pretend.call("sass")] assert compiler.compile_source.calls == [pretend.call("source")]
Fix tests for Django 1.8
Fix tests for Django 1.8
Python
mit
liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler
eaa4de2ecbcf29c9e56ebf2fa69099055e469fbc
tests/test_conversion.py
tests/test_conversion.py
from asciisciit import conversions as conv import numpy as np def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
import itertools from asciisciit import conversions as conv import numpy as np import pytest @pytest.mark.parametrize("invert,equalize,lut,lookup_func", itertools.product((True, False), (True, False), ("simple", "binary"), (None, conv.apply_lut_pil))) def test_pil_to_ascii(invert, equalize, lut, lookup_func): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 img = conv.numpy_to_pil(img) text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func) assert(len(text) == expected_len) @pytest.mark.parametrize("invert,equalize,lut", itertools.product((True, False), (True, False), ("simple", "binary"))) def test_numpy_to_ascii(invert, equalize, lut): img = np.random.randint(0, 255, (480, 640), dtype=np.uint8) h, w = img.shape expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1 text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut) assert(len(text) == expected_len) def test_lookup_method_equivalency(): img = np.random.randint(0, 255, (300,300), dtype=np.uint8) pil_ascii = conv.apply_lut_pil(img) np_ascii = conv.apply_lut_numpy(img) assert(pil_ascii == np_ascii) pil_ascii = conv.apply_lut_pil(img, "binary") np_ascii = conv.apply_lut_numpy(img, "binary") assert(pil_ascii == np_ascii)
Add tests to minimally exercise basic conversion functionality
Add tests to minimally exercise basic conversion functionality
Python
mit
derricw/asciisciit
a0420b066e0a5064ebe0944a16348debf107a9a4
speech.py
speech.py
"""Export long monologues for Nao. Functions: introduction -- Make Nao introduce itself. """ import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
"""Export long monologues for Nao. Functions: introduction -- Make Nao introduce itself. """ import time from say import say def introduction(tts): """Make Nao introduce itself. Keyword arguments: tts - Nao proxy. """ say("Hello world!", tts) say("I'm Leyva and I will teach you how to program in a programming\ language called python", tts) say("Computer Science is one of the coolest subjects to study in the\ modern world.", tts) say("Programming is a tool used by Scientists and Engineers to create\ all kinds of interesting things.", tts) say("For example, you can program mobile phones, laptops, cars, the\ Internet and more. Every day more things are being enhanced by\ Artificial Intelligence, like me.", tts) say("Now I want to talk about what programming is like.", tts) say("Programming is about solving puzzles of the real world and helping\ people deal with important problems to make the world a better\ place.", tts) time.sleep(2) say("Now, what topic would you like to learn about? Show me a number to\ choose the activity.", tts) say("Number one to practice input and output.", tts)
Make Nao say its name and the programming language
Make Nao say its name and the programming language
Python
mit
AliGhahraei/nao-classroom
40122e169e6a887caa6371a0ff3029c35ce265d5
third_party/node/node.py
third_party/node/node.py
#!/usr/bin/env vpython # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
#!/usr/bin/env vpython # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from os import path as os_path import platform import subprocess import sys import os def GetBinaryPath(): return os_path.join( os_path.dirname(__file__), *{ 'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'), 'Linux': ('linux', 'node-linux-x64', 'bin', 'node'), 'Windows': ('win', 'node.exe'), }[platform.system()]) def RunNode(cmd_parts, output=subprocess.PIPE): cmd = [GetBinaryPath()] + cmd_parts process = subprocess.Popen(cmd, cwd=os.getcwd(), stdout=output, stderr=output, universal_newlines=True) stdout, stderr = process.communicate() if process.returncode != 0: print('%s failed:\n%s\n%s' % (cmd, stdout, stderr)) exit(process.returncode) return stdout if __name__ == '__main__': args = sys.argv[1:] # Accept --output as the first argument, and then remove # it from the args entirely if present. if len(args) > 0 and args[0] == '--output': output = None args = sys.argv[2:] else: output = subprocess.PIPE RunNode(args, output)
Fix line ending printing on Python 3
Fix line ending printing on Python 3 To reflect the changes in https://chromium-review.googlesource.com/c/chromium/src/+/2896248/8/third_party/node/node.py [email protected] Bug: none Change-Id: I25ba29042f537bfef57fba93115be2c194649864 Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2914883 Commit-Queue: Tim van der Lippe <[email protected]> Commit-Queue: Jack Franklin <[email protected]> Auto-Submit: Tim van der Lippe <[email protected]> Reviewed-by: Jack Franklin <[email protected]>
Python
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
91b0bcad27f12c29681235079960ee272275e0bd
src/main/python/dlfa/solvers/__init__.py
src/main/python/dlfa/solvers/__init__.py
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, }
from .nn_solver import NNSolver from .lstm_solver import LSTMSolver from .tree_lstm_solver import TreeLSTMSolver from .memory_network import MemoryNetworkSolver from .differentiable_search import DifferentiableSearchSolver from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver concrete_solvers = { # pylint: disable=invalid-name 'LSTMSolver': LSTMSolver, 'TreeLSTMSolver': TreeLSTMSolver, 'MemoryNetworkSolver': MemoryNetworkSolver, 'DifferentiableSearchSolver': DifferentiableSearchSolver, 'MultipleChoiceMemoryNetworkSolver': MultipleChoiceMemoryNetworkSolver, }
Add MCMemoryNetwork as a usable solver
Add MCMemoryNetwork as a usable solver
Python
apache-2.0
allenai/deep_qa,matt-gardner/deep_qa,DeNeutoy/deep_qa,allenai/deep_qa,DeNeutoy/deep_qa,matt-gardner/deep_qa
0fd6a6e3281bc49addd1131ae30b1985b9da30f9
tests/benchmark/plugins/clear_buffer_cache.py
tests/benchmark/plugins/clear_buffer_cache.py
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.util.cluster_controller import ClusterController from tests.benchmark.plugins import Plugin class ClearBufferCache(Plugin): """Plugin that clears the buffer cache before a query is run.""" __name__ = "ClearBufferCache" def __init__(self, *args, **kwargs): self.cluster_controller = ClusterController(*args, **kwargs) Plugin.__init__(self, *args, **kwargs) def run_pre_hook(self, context=None): cmd = "sysctl -w vm.drop_caches=3 vm.drop_caches=0" self.cluster_controller.run_cmd(cmd)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.util.cluster_controller import ClusterController from tests.benchmark.plugins import Plugin class ClearBufferCache(Plugin): """Plugin that clears the buffer cache before a query is run.""" __name__ = "ClearBufferCache" def __init__(self, *args, **kwargs): self.cluster_controller = ClusterController(*args, **kwargs) Plugin.__init__(self, *args, **kwargs) def run_pre_hook(self, context=None): # Drop the page cache (drop_caches=1). We'll leave the inodes and dentries # since that is not what we are testing and it causes excessive performance # variability. cmd = "sysctl -w vm.drop_caches=1 vm.drop_caches=0" self.cluster_controller.run_cmd(cmd)
Update clear buffer cache plugin to only flush page cache.
Update clear buffer cache plugin to only flush page cache. More detail: http://linux-mm.org/Drop_Caches Change-Id: I7fa675ccdc81f375d88e9cfab330fca3bc983ec8 Reviewed-on: http://gerrit.ent.cloudera.com:8080/1157 Reviewed-by: Alex Behm <[email protected]> Reviewed-by: Lenni Kuff <[email protected]> Tested-by: Nong Li <[email protected]>
Python
apache-2.0
brightchen/Impala,rampage644/impala-cut,brightchen/Impala,XiaominZhang/Impala,caseyching/Impala,cgvarela/Impala,ImpalaToGo/ImpalaToGo,caseyching/Impala,tempbottle/Impala,cchanning/Impala,scalingdata/Impala,tempbottle/Impala,AtScaleInc/Impala,scalingdata/Impala,gistic/PublicSpatialImpala,rampage644/impala-cut,bowlofstew/Impala,rampage644/impala-cut,lirui-intel/Impala,cchanning/Impala,rdblue/Impala,henryr/Impala,XiaominZhang/Impala,grundprinzip/Impala,kapilrastogi/Impala,scalingdata/Impala,tempbottle/Impala,cloudera/recordservice,ImpalaToGo/ImpalaToGo,mapr/impala,henryr/Impala,lirui-intel/Impala,cgvarela/Impala,kapilrastogi/Impala,lnliuxing/Impala,gistic/PublicSpatialImpala,cchanning/Impala,bowlofstew/Impala,tempbottle/Impala,brightchen/Impala,rdblue/Impala,lirui-intel/Impala,caseyching/Impala,mapr/impala,tempbottle/Impala,rdblue/Impala,brightchen/Impala,cloudera/recordservice,cchanning/Impala,rdblue/Impala,cgvarela/Impala,lnliuxing/Impala,AtScaleInc/Impala,mapr/impala,mapr/impala,bratatidas9/Impala-1,XiaominZhang/Impala,ImpalaToGo/ImpalaToGo,brightchen/Impala,tempbottle/Impala,ImpalaToGo/ImpalaToGo,andybab/Impala,gerashegalov/Impala,brightchen/Impala,ibmsoe/ImpalaPPC,cgvarela/Impala,cchanning/Impala,kapilrastogi/Impala,gerashegalov/Impala,scalingdata/Impala,XiaominZhang/Impala,bratatidas9/Impala-1,gerashegalov/Impala,bowlofstew/Impala,caseyching/Impala,placrosse/ImpalaToGo,lirui-intel/Impala,grundprinzip/Impala,cloudera/recordservice,bratatidas9/Impala-1,theyaa/Impala,lirui-intel/Impala,bratatidas9/Impala-1,henryr/Impala,lnliuxing/Impala,placrosse/ImpalaToGo,henryr/Impala,grundprinzip/Impala,kapilrastogi/Impala,rampage644/impala-cut,kapilrastogi/Impala,placrosse/ImpalaToGo,grundprinzip/Impala,ibmsoe/ImpalaPPC,caseyching/Impala,bowlofstew/Impala,placrosse/ImpalaToGo,gerashegalov/Impala,cchanning/Impala,XiaominZhang/Impala,bratatidas9/Impala-1,kapilrastogi/Impala,kapilrastogi/Impala,lirui-intel/Impala,cloudera/recordservice,lnliuxing/Impala,caseyching/Impala,rdblue/Impala,grundprinzip/Impala,cloudera/recordservice,theyaa/Impala,rampage644/impala-cut,bratatidas9/Impala-1,ImpalaToGo/ImpalaToGo,gistic/PublicSpatialImpala,andybab/Impala,henryr/Impala,theyaa/Impala,theyaa/Impala,grundprinzip/Impala,bowlofstew/Impala,lirui-intel/Impala,lnliuxing/Impala,tempbottle/Impala,cgvarela/Impala,ibmsoe/ImpalaPPC,andybab/Impala,cloudera/recordservice,AtScaleInc/Impala,AtScaleInc/Impala,scalingdata/Impala,ibmsoe/ImpalaPPC,gerashegalov/Impala,ImpalaToGo/ImpalaToGo,theyaa/Impala,rampage644/impala-cut,ibmsoe/ImpalaPPC,scalingdata/Impala,gistic/PublicSpatialImpala,gerashegalov/Impala,rdblue/Impala,ibmsoe/ImpalaPPC,lnliuxing/Impala,mapr/impala,bowlofstew/Impala,AtScaleInc/Impala,andybab/Impala,cgvarela/Impala,gistic/PublicSpatialImpala,henryr/Impala,brightchen/Impala,placrosse/ImpalaToGo,XiaominZhang/Impala,andybab/Impala,cloudera/recordservice,rdblue/Impala,lnliuxing/Impala,bratatidas9/Impala-1,XiaominZhang/Impala,AtScaleInc/Impala,placrosse/ImpalaToGo,bowlofstew/Impala,theyaa/Impala,theyaa/Impala,cchanning/Impala,gerashegalov/Impala,caseyching/Impala,cgvarela/Impala,gistic/PublicSpatialImpala,ibmsoe/ImpalaPPC,andybab/Impala
385879b90d3aaa7452931108c999cbbc5e41a1b2
pyhmsa/gui/util/human.py
pyhmsa/gui/util/human.py
""" Convert code to human readable text """ # Standard library modules. import re # Third party modules. # Local modules. # Globals and constants variables. _CAMELCASE_TO_WORDS_PATTERN = re.compile('([A-Z][a-z0-9]*)') def camelcase_to_words(text): words = _CAMELCASE_TO_WORDS_PATTERN.split(text) return [word for word in words if word]
""" Convert code to human readable text """ # Standard library modules. import re # Third party modules. # Local modules. # Globals and constants variables. _CAMELCASE_TO_WORDS_PATTERN = re.compile('([A-Z][a-z0-9]*)') def camelcase_to_words(text): words = _CAMELCASE_TO_WORDS_PATTERN.split(text) return tuple(word for word in words if word)
Return tuple instead of list.
Return tuple instead of list.
Python
mit
pyhmsa/pyhmsa-gui
b94458b5dc184798580ade159ace700a46ab5877
enigma.py
enigma.py
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self, notch, wiring): assert isinstance(notch, str) assert isinstance(wiring, str) assert len(wiring) == len(string.ascii_uppercase) self.notch = notch self.wiring = wiring class Enigma: def __init__(self): pass def cipher(self, message): pass
Initialize rotors with notches and wiring data
Initialize rotors with notches and wiring data
Python
mit
ranisalt/enigma
e650c319b109ca554c2d66f2d9446ef62440cc0f
anna/model/utils.py
anna/model/utils.py
import tensorflow as tf def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None): dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0 cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse) if dropout > 0.0: keep_prop = (1.0 - dropout) cell = tf.nn.rnn_cell.DropoutWrapper( cell=cell, input_keep_prob=keep_prop, ) if residual: cell = tf.nn.rnn_cell.ResidualWrapper(cell) return cell
import tensorflow as tf def rnn_cell(num_units, dropout, mode, residual=False, name=None, reuse=None): dropout = dropout if mode == tf.estimator.ModeKeys.TRAIN else 0.0 cell = tf.nn.rnn_cell.GRUCell(num_units, name=name, reuse=reuse) if dropout > 0.0: keep_prop = (1.0 - dropout) cell = tf.nn.rnn_cell.DropoutWrapper( cell=cell, input_keep_prob=keep_prop, ) if residual: cell = tf.nn.rnn_cell.ResidualWrapper(cell) return cell
Fix bug in RNN dropout
Fix bug in RNN dropout
Python
mit
jpbottaro/anna
7add1c5a43c6bef29613167ca430ad7ff0e26670
src/ocspdash/web/blueprints/ui.py
src/ocspdash/web/blueprints/ui.py
# -*- coding: utf-8 -*- import base64 import json from nacl.encoding import URLSafeBase64Encoder import nacl.exceptions import nacl.signing from flask import Blueprint, abort, current_app, render_template, request from nacl.signing import VerifyKey __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) @ui.route('/submit', methods=['POST']) def submit(): """Show the submit view.""" location_id = int(request.headers['authorization']) location = current_app.manager.get_location_by_id(location_id) if not location.activated: return abort(403, f'Not activated: {location}') key = location.pubkey try: verify_key = VerifyKey(key=key, encoder=URLSafeBase64Encoder) payload = verify_key.verify(request.data, encoder=URLSafeBase64Encoder) except nacl.exceptions.BadSignatureError as e: return abort(403, f'Bad Signature: {e}') decoded_payload = json.loads(base64.urlsafe_b64decode(payload).decode('utf-8')) current_app.manager.insert_payload(decoded_payload) return '', 204
# -*- coding: utf-8 -*- # import nacl.exceptions # import nacl.signing from flask import Blueprint, current_app, render_template # from nacl.encoding import URLSafeBase64Encoder # from nacl.signing import VerifyKey __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = current_app.manager.make_payload() return render_template('index.html', payload=payload) # @ui.route('/submit', methods=['POST']) # def submit(): # """Show the submit view.""" # location_id = int(request.headers['authorization']) # # location = current_app.manager.get_location_by_id(location_id) # # if not location.activated: # return abort(403, f'Not activated: {location}') # # key = location.pubkey # # try: # verify_key = VerifyKey(key=key, encoder=URLSafeBase64Encoder) # payload = verify_key.verify(request.data, encoder=URLSafeBase64Encoder) # # except nacl.exceptions.BadSignatureError as e: # return abort(403, f'Bad Signature: {e}') # # decoded_payload = json.loads(base64.urlsafe_b64decode(payload).decode('utf-8')) # current_app.manager.insert_payload(decoded_payload) # # return '', 204
Remove /submit endpoint from UI blueprint for now
Remove /submit endpoint from UI blueprint for now
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
d4356b7aa879a345939c1885742efc3deceeb08f
lib/aquilon/__init__.py
lib/aquilon/__init__.py
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2013 Contributor # # 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.
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2013 Contributor # # 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. # This is a namespace package try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Make aquilon a namespace package
Make aquilon a namespace package In the future we may want to import the protocols as "from aquilon.protocols import blah", and that needs both the broker and the protocols to be marked as namespace packages. Change-Id: Ib3b712e727b0dd176c231a396bec4e7168a0039e Reviewed-by: Dave Reeve <[email protected]>
Python
apache-2.0
guillaume-philippon/aquilon,quattor/aquilon,quattor/aquilon,guillaume-philippon/aquilon,guillaume-philippon/aquilon,quattor/aquilon
68e51fd9772aaf4bd382ffe05721e27da6bddde6
argus/exceptions.py
argus/exceptions.py
# Copyright 2014 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass
# Copyright 2014 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Various exceptions that can be raised by the CI project.""" class ArgusError(Exception): pass class ArgusTimeoutError(ArgusError): pass class ArgusCLIError(ArgusError): pass class ArgusPermissionDenied(ArgusError): pass class ArgusHeatTeardown(ArgusError): pass class ArgusEnvironmentError(ArgusError): """Base class for errors related to the argus environment.""" pass class ErrorArgusInvalidDecorator(ArgusError): """The `skip_on_os` decorator was used improperly.""" pass
Add exception for Logic Errors
Add exception for Logic Errors
Python
apache-2.0
stefan-caraiman/cloudbase-init-ci,cloudbase/cloudbase-init-ci,micumatei/cloudbase-init-ci
2eb4fcb2d75e6f93f33b1ae41098919f6d4ebc92
neovim/__init__.py
neovim/__init__.py
from client import Client from uv_stream import UvStream __all__ = ['Client', 'UvStream', 'c']
from client import Client from uv_stream import UvStream __all__ = ['connect'] def connect(address, port=None): client = Client(UvStream(address, port)) client.discover_api() return client.vim
Add helper function for connecting with Neovim
Add helper function for connecting with Neovim
Python
apache-2.0
fwalch/python-client,Shougo/python-client,bfredl/python-client,brcolow/python-client,starcraftman/python-client,traverseda/python-client,justinmk/python-client,neovim/python-client,meitham/python-client,meitham/python-client,0x90sled/python-client,justinmk/python-client,zchee/python-client,traverseda/python-client,bfredl/python-client,neovim/python-client,starcraftman/python-client,0x90sled/python-client,fwalch/python-client,Shougo/python-client,zchee/python-client,timeyyy/python-client,brcolow/python-client,timeyyy/python-client
f71897270d9a040930bfb41801bf955ea3d0a36e
slave/skia_slave_scripts/android_run_gm.py
slave/skia_slave_scripts/android_run_gm.py
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM))
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run GM on an Android device. """ from android_build_step import AndroidBuildStep from build_step import BuildStep from run_gm import RunGM import sys class AndroidRunGM(AndroidBuildStep, RunGM): def __init__(self, timeout=9600, **kwargs): super(AndroidRunGM, self).__init__(timeout=timeout, **kwargs) def _Run(self): self._gm_args.append('--nopdf') RunGM._Run(self) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(AndroidRunGM))
Increase timeout for GM on Android
Increase timeout for GM on Android Unreviewed. (SkipBuildbotRuns) Review URL: https://codereview.chromium.org/18845002 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9906 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot
3e1033637d0bb5dd8856052ffd1667df0ccceb5d
entity.py
entity.py
"""This module contains base classes for defining game objects as well as their individual components and behaviours. """ from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ components = [] class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
"""This module contains base classes for defining game objects as well as their individual components and behaviours. """ from pygame.sprite import Sprite class Entity(Sprite): """An object within the game. It contains several Component objects that are used to define how it is handled graphically and physically, as well as its behaviour. Since it inherits from PyGame's Sprite class, it can be added to any Groups you have created. (Components will automatically add it to the appropriate Groups.) This also makes discarding it from the game simple, as it will automatically be removed from memory once it belongs to no Groups. Attributes: components (list): Contains all of the Component objects that are contained in this Entity. * Note that components will also be added as unique attributes automatically. This will make it possible to access each component directly, rather than having to add .components. in-between this Entity's name and the component's name. """ pass class Component(object): """Part of an Entity object. It will handle one facet of the Entity, which can be graphics, physics, or part of its behaviour. Subclasses should define their own attributes and methods in order to accomplish this. Ideally, a game would have many Component subclasses to define the many different parts that make up different game objects. Attributes: entity (Entity): This Component is bound to it and has access to all of its members. """ pass
Remove components as class attribute
Entity: Remove components as class attribute It is meant to be an instance attribute and should be defined in init() instead.
Python
unlicense
MarquisLP/gamehappy
a2182bf8360b6c13983fc0abb2b058ab0273d54c
tensorflow/python/ops/ragged/__init__.py
tensorflow/python/ops/ragged/__init__.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Ragged Tensors. This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`), which are tensors with non-uniform shapes. In particular, each `RaggedTensor` has one or more *ragged dimensions*, which are dimensions whose slices may have different lengths. For example, the inner (column) dimension of `rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices (`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed description of ragged tensors, see the `tf.RaggedTensor` class documentation and the [Ragged Tensor Guide](/guide/ragged_tensors). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Ragged Tensors. This package defines ops for manipulating ragged tensors (`tf.RaggedTensor`), which are tensors with non-uniform shapes. In particular, each `RaggedTensor` has one or more *ragged dimensions*, which are dimensions whose slices may have different lengths. For example, the inner (column) dimension of `rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` is ragged, since the column slices (`rt[0, :]`, ..., `rt[4, :]`) have different lengths. For a more detailed description of ragged tensors, see the `tf.RaggedTensor` class documentation and the [Ragged Tensor Guide](/guide/ragged_tensor). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
Fix broken link to ragged tensor guide
Fix broken link to ragged tensor guide PiperOrigin-RevId: 368443422 Change-Id: I69818413b7ed8cf2f372580878860a469b9735a8
Python
apache-2.0
paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,yongtang/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,gautam1858/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,paolodedios/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,gautam1858/tensorflow,Intel-tensorflow/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,karllessard/tensorflow
ec91f28dfe4e1f48f7ff92f1fe499944aa366763
tools/checkdependencies.py
tools/checkdependencies.py
#!/usr/bin/env python import sys, os # list of (packagename, filename) DEPENDENCIES = [ ('zlib1g-dev / zlib-devel', '/usr/include/zlib.h'), ('g++ / gcc-c++', '/usr/bin/g++'), ('wget', '/usr/bin/wget'), ('libsqlite3-dev / sqlite-devel', '/usr/include/sqlite3.h'), ] if os.environ.get('BOOST_INCLUDE', ''): DEPENDENCIES += [ ('boost headers to %s' % os.environ['BOOST_INCLUDE'], '%(BOOST_INCLUDE)s/boost/lexical_cast.hpp' % os.environ), ] else: DEPENDENCIES += [ ('libboost-dev / boost-devel', '/usr/include/boost/lexical_cast.hpp'), ] ALTERNATIVES = [ ('/usr/lib', '/usr/lib/x86_64-linux-gnu'), ('/usr/lib', '/usr/lib64'), ] missing = False def find_file(filename): if os.path.exists(filename): return True for pattern, replacement in ALTERNATIVES: if os.path.exists(filename.replace(pattern, replacement)): return True return False for package, filename in DEPENDENCIES: if not find_file(filename): print '*** Please install package %s' % package missing = True if missing: sys.exit(1) else: sys.exit(0)
#!/usr/bin/env python import sys, os # list of (packagename, filename) DEPENDENCIES = [ ('zlib1g-dev / zlib-devel', '/usr/include/zlib.h'), ('libbz2-dev / bzip2-devel', '/usr/include/bzlib.h'), ('g++ / gcc-c++', '/usr/bin/g++'), ('wget', '/usr/bin/wget'), ('libsqlite3-dev / sqlite-devel', '/usr/include/sqlite3.h'), ] if os.environ.get('BOOST_INCLUDE', ''): DEPENDENCIES += [ ('boost headers to %s' % os.environ['BOOST_INCLUDE'], '%(BOOST_INCLUDE)s/boost/lexical_cast.hpp' % os.environ), ] else: DEPENDENCIES += [ ('libboost-dev / boost-devel', '/usr/include/boost/lexical_cast.hpp'), ] ALTERNATIVES = [ ('/usr/lib', '/usr/lib/x86_64-linux-gnu'), ('/usr/lib', '/usr/lib64'), ] missing = False def find_file(filename): if os.path.exists(filename): return True for pattern, replacement in ALTERNATIVES: if os.path.exists(filename.replace(pattern, replacement)): return True return False for package, filename in DEPENDENCIES: if not find_file(filename): print '*** Please install package %s' % package missing = True if missing: sys.exit(1) else: sys.exit(0)
Add libbz2-dev dependency for PinPlay
[build] Add libbz2-dev dependency for PinPlay
Python
mit
abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper
368e2d6407cb021d80fe3679c65737581c3cc221
bliski_publikator/institutions/serializers.py
bliski_publikator/institutions/serializers.py
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'} }
from rest_framework import serializers from .models import Institution class InstitutionSerializer(serializers.HyperlinkedModelSerializer): on_site = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Institution fields = ('on_site', 'url', 'name', 'slug', 'user', 'email', 'region', 'regon', 'krs', 'monitorings') extra_kwargs = { 'region': {'view_name': 'jednostkaadministracyjna-detail'}, 'user': {'read_only': True} }
Make user field read-only in InstitutionSerializer
Make user field read-only in InstitutionSerializer
Python
mit
watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator
5cadfe1b0a8da0f46950ff63786bf79c42af9b90
tutorials/forms.py
tutorials/forms.py
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('title', 'html', 'markdown')
from django import forms from .models import Tutorial class TutorialForm(forms.ModelForm): # ToDO: Set required fields?? class Meta: model = Tutorial fields = ('category', 'title', 'markdown', 'level')
Add new model fields to form
Add new model fields to form
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
9b4333f25f22269f02f605579d4756da43701241
manage.py
manage.py
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_reloader = True, host = '0.0.0.0', port = 8080, )) @manager.command def db_create_tables(): """Create all the db tables.""" current_app.preprocess_request() db = g.sl('db') db.create_tables() @manager.command def db_drop_tables(): """Drop all the db tables.""" if prompt_bool('Are you sure you want to drop all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() if __name__ == '__main__': manager.run()
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_reloader = True, host = '0.0.0.0', port = 8080, )) @manager.command def db_create_tables(): """Create all the db tables.""" current_app.preprocess_request() db = g.sl('db') db.create_tables() @manager.command def db_drop_tables(): """Drop all the db tables.""" if prompt_bool('Are you sure you want to drop all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() @manager.command def db_reset_tables(): """Drop and (re)create all the db tables.""" if prompt_bool('Are you sure you want to reset all the db tables?'): current_app.preprocess_request() db = g.sl('db') db.drop_tables() db.create_tables() if __name__ == '__main__': manager.run()
Add a reset task to drop and recreate the db tables with one command.
Add a reset task to drop and recreate the db tables with one command.
Python
mit
jaapverloop/massa
2353c00e76d841b10e7c27750c4ce973d536f453
manage.py
manage.py
# Set the path import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask.ext.script import Manager, Server from maproulette import app manager = Manager(app) # Turn on debugger by default and reloader manager.add_command("runserver", Server( use_debugger = True, use_reloader = True, host = '0.0.0.0') ) if __name__ == "__main__": manager.run()
# Set the path import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask.ext.script import Manager, Server from maproulette import app manager = Manager(app) # Turn on debugger by default and reloader manager.add_command("runserver", Server( use_debugger = True, use_reloader = True, host = '0.0.0.0') ) @manager.command def clean_pyc(): """Removes all *.pyc files from the project folder""" clean_command = "find . -name *.pyc -delete".split() subprocess.call(clean_command) if __name__ == "__main__": manager.run()
Manage can now clean up pyc files
Manage can now clean up pyc files
Python
apache-2.0
mvexel/maproulette,mvexel/mr-tnav,Crashfreak/maproulette,mvexel/maproulette,osmlab/maproulette,osmlab/maproulette,osmlab/maproulette,mvexel/maproulette,osmlab/maproulette,Crashfreak/maproulette,mvexel/mr-tnav,mvexel/maproulette,Crashfreak/maproulette,Crashfreak/maproulette
1abb838a1fa56af25b9c6369dff93c65e17fbc3a
manage.py
manage.py
import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) COV.erase() if __name__ == '__main__': manager.run()
import os COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db from config import BASE_DIR app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def test(coverage=False): """Run the unit tests.""" if coverage and not os.environ.get('FLASK_COVERAGE'): import sys os.environ['FLASK_COVERAGE'] = '1' os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print('Coverage Summary:') COV.report() covdir = os.path.join(BASE_DIR, 'htmlcov') COV.html_report(directory=covdir) print('HTML version: file://%s/index.html' % covdir) if __name__ == '__main__': manager.run()
Remove erase of coverage file as it's needed by coveralls
Remove erase of coverage file as it's needed by coveralls
Python
apache-2.0
atindale/business-glossary,atindale/business-glossary
873b7d7e7de770b9407840f6ccd662929b5dd3b6
src/modularframework/login.py
src/modularframework/login.py
''' Created on 01.06.2014 @author: ionitadaniel19 ''' from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class LoginPage(): def __init__(self,driver,url="http://localhost/autframeworks/index.html"): self.driver=driver self.driver.get(url) def login(self,username,pwd): WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.CSS_SELECTOR,"div.login")),'Element not found login form') self.driver.find_element_by_name("login").clear() self.driver.find_element_by_name("login").send_keys(username) self.driver.find_element_by_name("password").clear() self.driver.find_element_by_name("password").send_keys(pwd) self.driver.find_element_by_name("commit").click() def remember_me(self): WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.ID,"remember_me")),'Element not found remember me option') self.driver.find_element_by_id("remember_me").click()
''' Created on 01.06.2014 @author: ionitadaniel19 ''' from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class LoginPage(): def __init__(self,driver,url="http://localhost:81/autframeworks/index.html"): self.driver=driver self.driver.get(url) def login(self,username,pwd): WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.CSS_SELECTOR,"div.login")),'Element not found login form') self.driver.find_element_by_name("login").clear() self.driver.find_element_by_name("login").send_keys(username) self.driver.find_element_by_name("password").clear() self.driver.find_element_by_name("password").send_keys(pwd) self.driver.find_element_by_name("commit").click() def remember_me(self): WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.ID,"remember_me")),'Element not found remember me option') self.driver.find_element_by_id("remember_me").click()
Update the default url port
Update the default url port
Python
mit
ionitadaniel19/testframeworksevolution
1be8c268f2da618e9e9e13d55d53599d637d3a6a
abel/tests/test_tools.py
abel/tests/test_tools.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np from numpy.testing import assert_allclose from abel.tools import calculate_speeds DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') def assert_equal(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) def test_centering_function(): pass
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import numpy as np from numpy.testing import assert_allclose, assert_equal from abel.tools import calculate_speeds, center_image DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data') def assert_allclose_msg(x, y, message, rtol=1e-5): assert np.allclose(x, y, rtol=1e-5), message def test_speeds(): # This very superficial test checks that calculate_speeds is able to # execute (no syntax errors) n = 101 IM = np.random.randn(n, n) calculate_speeds(IM, n) def test_centering_function_shape(): # ni -> original shape # n -> result of the centering function for (ni, n) in [(20, 10), # crop image (20, 11), (4, 10), # pad image (4, 11)]: data = np.zeros((ni, ni)) res = center_image(data, (ni//2, ni//2), n) yield assert_equal, res.shape, (n, n),\ 'Centering preserves shapes for ni={}, n={}'.format(ni, n)
Test to enforce that center_image preserves shape
Test to enforce that center_image preserves shape
Python
mit
rth/PyAbel,huletlab/PyAbel,DhrubajyotiDas/PyAbel,PyAbel/PyAbel,stggh/PyAbel
92d61a641cfade2ed323576719cfc0ff54d34cbd
test/repository_test.py
test/repository_test.py
import unittest from jip.repository import MavenFileSystemRepos from jip.maven import Artifact from contextlib import contextmanager import shutil import tempfile import errno import os @contextmanager def tmpdir(): dirname = tempfile.mkdtemp() try: yield dirname finally: shutil.rmtree(dirname) def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise class RespositoryTests(unittest.TestCase): def testLocalDownloadOfPomWithUtfChars(self): with tmpdir() as temp_repo_dir: artifact_dir = "%s/dummygroup/dummyartifact/1.0.0/" % temp_repo_dir mkdir_p(artifact_dir) with open("%sdummyartifact-1.0.0.pom" % artifact_dir, "wb") as f: f.write("\xe2") testee = MavenFileSystemRepos('dummy_name', temp_repo_dir) artifact = Artifact('dummygroup', 'dummyartifact', '1.0.0') pom = testee.download_pom(artifact) # should not raise an UnicodeDecodeError pom.encode("utf-8") if __name__ == '__main__': unittest.main()
import unittest from jip.repository import MavenFileSystemRepos from jip.maven import Artifact from contextlib import contextmanager import shutil import tempfile import errno import os @contextmanager def tmpdir(): dirname = tempfile.mkdtemp() try: yield dirname finally: shutil.rmtree(dirname) def mkdir_p(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise class RespositoryTests(unittest.TestCase): def testLocalDownloadOfPomWithUtfChars(self): with tmpdir() as temp_repo_dir: artifact_dir = "%s/dummygroup/dummyartifact/1.0.0/" % temp_repo_dir mkdir_p(artifact_dir) with open("%sdummyartifact-1.0.0.pom" % artifact_dir, "w") as f: f.write("\xe2") testee = MavenFileSystemRepos('dummy_name', temp_repo_dir) artifact = Artifact('dummygroup', 'dummyartifact', '1.0.0') pom = testee.download_pom(artifact) # should not raise an UnicodeDecodeError pom.encode("utf-8") if __name__ == '__main__': unittest.main()
Fix test for Python 3
Fix test for Python 3
Python
mit
sunng87/jip,sunng87/jip
3e77090b2142e7802203b5e37f81b5d4cbb6f40d
rest_framework/urlpatterns.py
rest_framework/urlpatterns.py
from django.conf.urls.defaults import url from rest_framework.settings import api_settings def format_suffix_patterns(urlpatterns, suffix_required=False, suffix_kwarg=None): """ Supplement existing urlpatterns with corrosponding patterns that also include a '.format' suffix. Retains urlpattern ordering. """ suffix_kwarg = suffix_kwarg or api_settings.FORMAT_SUFFIX_KWARG suffix_pattern = '\.(?P<%s>[a-z]+)$' % suffix_kwarg ret = [] for urlpattern in urlpatterns: # Form our complementing '.format' urlpattern regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern view = urlpattern._callback or urlpattern._callback_str kwargs = urlpattern.default_args name = urlpattern.name # Add in both the existing and the new urlpattern if not suffix_required: ret.append(urlpattern) ret.append(url(regex, view, kwargs, name)) return ret
from django.conf.urls.defaults import url from rest_framework.settings import api_settings def format_suffix_patterns(urlpatterns, suffix_required=False, suffix_kwarg=None): """ Supplement existing urlpatterns with corrosponding patterns that also include a '.format' suffix. Retains urlpattern ordering. """ suffix_kwarg = suffix_kwarg or api_settings.FORMAT_SUFFIX_KWARG suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg ret = [] for urlpattern in urlpatterns: # Form our complementing '.format' urlpattern regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern view = urlpattern._callback or urlpattern._callback_str kwargs = urlpattern.default_args name = urlpattern.name # Add in both the existing and the new urlpattern if not suffix_required: ret.append(urlpattern) ret.append(url(regex, view, kwargs, name)) return ret
Fix bug in format suffix patterns
Fix bug in format suffix patterns
Python
bsd-2-clause
delinhabit/django-rest-framework,abdulhaq-e/django-rest-framework,pombredanne/django-rest-framework,werthen/django-rest-framework,sbellem/django-rest-framework,hunter007/django-rest-framework,waytai/django-rest-framework,arpheno/django-rest-framework,kgeorgy/django-rest-framework,arpheno/django-rest-framework,adambain-vokal/django-rest-framework,antonyc/django-rest-framework,paolopaolopaolo/django-rest-framework,rafaelang/django-rest-framework,damycra/django-rest-framework,vstoykov/django-rest-framework,antonyc/django-rest-framework,jpadilla/django-rest-framework,dmwyatt/django-rest-framework,antonyc/django-rest-framework,kennydude/django-rest-framework,ebsaral/django-rest-framework,krinart/django-rest-framework,James1345/django-rest-framework,raphaelmerx/django-rest-framework,gregmuellegger/django-rest-framework,vstoykov/django-rest-framework,ezheidtmann/django-rest-framework,d0ugal/django-rest-framework,thedrow/django-rest-framework-1,kylefox/django-rest-framework,damycra/django-rest-framework,cyberj/django-rest-framework,hnarayanan/django-rest-framework,sehmaschine/django-rest-framework,adambain-vokal/django-rest-framework,HireAnEsquire/django-rest-framework,rubendura/django-rest-framework,fishky/django-rest-framework,tcroiset/django-rest-framework,johnraz/django-rest-framework,ashishfinoit/django-rest-framework,uploadcare/django-rest-framework,wedaly/django-rest-framework,maryokhin/django-rest-framework,sehmaschine/django-rest-framework,wedaly/django-rest-framework,akalipetis/django-rest-framework,aericson/django-rest-framework,cyberj/django-rest-framework,agconti/django-rest-framework,jerryhebert/django-rest-framework,buptlsl/django-rest-framework,kylefox/django-rest-framework,bluedazzle/django-rest-framework,jpulec/django-rest-framework,jerryhebert/django-rest-framework,tigeraniya/django-rest-framework,VishvajitP/django-rest-framework,tomchristie/django-rest-framework,sheppard/django-rest-framework,pombredanne/django-rest-framework,rhblind/django-rest-framework,thedrow/django-rest-framework-1,tomchristie/django-rest-framework,ticosax/django-rest-framework,qsorix/django-rest-framework,jerryhebert/django-rest-framework,ezheidtmann/django-rest-framework,wangpanjun/django-rest-framework,abdulhaq-e/django-rest-framework,kezabelle/django-rest-framework,johnraz/django-rest-framework,linovia/django-rest-framework,YBJAY00000/django-rest-framework,iheitlager/django-rest-framework,gregmuellegger/django-rest-framework,iheitlager/django-rest-framework,ebsaral/django-rest-framework,ambivalentno/django-rest-framework,sbellem/django-rest-framework,zeldalink0515/django-rest-framework,tigeraniya/django-rest-framework,andriy-s/django-rest-framework,uploadcare/django-rest-framework,justanr/django-rest-framework,elim/django-rest-framework,douwevandermeij/django-rest-framework,uruz/django-rest-framework,ajaali/django-rest-framework,callorico/django-rest-framework,davesque/django-rest-framework,gregmuellegger/django-rest-framework,nryoung/django-rest-framework,jtiai/django-rest-framework,damycra/django-rest-framework,cyberj/django-rest-framework,YBJAY00000/django-rest-framework,potpath/django-rest-framework,ajaali/django-rest-framework,jtiai/django-rest-framework,yiyocx/django-rest-framework,HireAnEsquire/django-rest-framework,rhblind/django-rest-framework,maryokhin/django-rest-framework,hunter007/django-rest-framework,dmwyatt/django-rest-framework,ambivalentno/django-rest-framework,abdulhaq-e/django-rest-framework,canassa/django-rest-framework,ashishfinoit/django-rest-framework,kezabelle/django-rest-framework,ashishfinoit/django-rest-framework,potpath/django-rest-framework,alacritythief/django-rest-framework,werthen/django-rest-framework,johnraz/django-rest-framework,ticosax/django-rest-framework,jpulec/django-rest-framework,James1345/django-rest-framework,justanr/django-rest-framework,hnarayanan/django-rest-framework,waytai/django-rest-framework,AlexandreProenca/django-rest-framework,hnakamur/django-rest-framework,ambivalentno/django-rest-framework,leeahoward/django-rest-framework,buptlsl/django-rest-framework,rubendura/django-rest-framework,vstoykov/django-rest-framework,linovia/django-rest-framework,akalipetis/django-rest-framework,andriy-s/django-rest-framework,arpheno/django-rest-framework,ajaali/django-rest-framework,uruz/django-rest-framework,mgaitan/django-rest-framework,jtiai/django-rest-framework,uploadcare/django-rest-framework,edx/django-rest-framework,qsorix/django-rest-framework,bluedazzle/django-rest-framework,brandoncazander/django-rest-framework,brandoncazander/django-rest-framework,sehmaschine/django-rest-framework,agconti/django-rest-framework,davesque/django-rest-framework,adambain-vokal/django-rest-framework,aericson/django-rest-framework,sheppard/django-rest-framework,elim/django-rest-framework,dmwyatt/django-rest-framework,kylefox/django-rest-framework,mgaitan/django-rest-framework,MJafarMashhadi/django-rest-framework,edx/django-rest-framework,wwj718/django-rest-framework,VishvajitP/django-rest-framework,paolopaolopaolo/django-rest-framework,ossanna16/django-rest-framework,werthen/django-rest-framework,rubendura/django-rest-framework,hnarayanan/django-rest-framework,simudream/django-rest-framework,jness/django-rest-framework,YBJAY00000/django-rest-framework,rafaelcaricio/django-rest-framework,AlexandreProenca/django-rest-framework,xiaotangyuan/django-rest-framework,cheif/django-rest-framework,leeahoward/django-rest-framework,nhorelik/django-rest-framework,wangpanjun/django-rest-framework,callorico/django-rest-framework,andriy-s/django-rest-framework,jpadilla/django-rest-framework,jness/django-rest-framework,wedaly/django-rest-framework,ezheidtmann/django-rest-framework,nhorelik/django-rest-framework,canassa/django-rest-framework,d0ugal/django-rest-framework,lubomir/django-rest-framework,uruz/django-rest-framework,VishvajitP/django-rest-framework,delinhabit/django-rest-framework,brandoncazander/django-rest-framework,atombrella/django-rest-framework,jpadilla/django-rest-framework,alacritythief/django-rest-framework,thedrow/django-rest-framework-1,simudream/django-rest-framework,buptlsl/django-rest-framework,aericson/django-rest-framework,James1345/django-rest-framework,ebsaral/django-rest-framework,kezabelle/django-rest-framework,fishky/django-rest-framework,simudream/django-rest-framework,xiaotangyuan/django-rest-framework,qsorix/django-rest-framework,rhblind/django-rest-framework,rafaelang/django-rest-framework,douwevandermeij/django-rest-framework,AlexandreProenca/django-rest-framework,delinhabit/django-rest-framework,iheitlager/django-rest-framework,raphaelmerx/django-rest-framework,kgeorgy/django-rest-framework,hnakamur/django-rest-framework,krinart/django-rest-framework,sheppard/django-rest-framework,linovia/django-rest-framework,bluedazzle/django-rest-framework,tigeraniya/django-rest-framework,davesque/django-rest-framework,wwj718/django-rest-framework,tcroiset/django-rest-framework,ossanna16/django-rest-framework,leeahoward/django-rest-framework,potpath/django-rest-framework,justanr/django-rest-framework,waytai/django-rest-framework,d0ugal/django-rest-framework,nryoung/django-rest-framework,lubomir/django-rest-framework,krinart/django-rest-framework,rafaelcaricio/django-rest-framework,tcroiset/django-rest-framework,douwevandermeij/django-rest-framework,agconti/django-rest-framework,xiaotangyuan/django-rest-framework,fishky/django-rest-framework,MJafarMashhadi/django-rest-framework,rafaelcaricio/django-rest-framework,nhorelik/django-rest-framework,raphaelmerx/django-rest-framework,elim/django-rest-framework,hunter007/django-rest-framework,wwj718/django-rest-framework,zeldalink0515/django-rest-framework,kennydude/django-rest-framework,wzbozon/django-rest-framework,cheif/django-rest-framework,wangpanjun/django-rest-framework,yiyocx/django-rest-framework,atombrella/django-rest-framework,alacritythief/django-rest-framework,lubomir/django-rest-framework,HireAnEsquire/django-rest-framework,kgeorgy/django-rest-framework,pombredanne/django-rest-framework,yiyocx/django-rest-framework,cheif/django-rest-framework,kennydude/django-rest-framework,wzbozon/django-rest-framework,jness/django-rest-framework,nryoung/django-rest-framework,akalipetis/django-rest-framework,edx/django-rest-framework,zeldalink0515/django-rest-framework,atombrella/django-rest-framework,wzbozon/django-rest-framework,tomchristie/django-rest-framework,callorico/django-rest-framework,mgaitan/django-rest-framework,paolopaolopaolo/django-rest-framework,ossanna16/django-rest-framework,rafaelang/django-rest-framework,hnakamur/django-rest-framework,sbellem/django-rest-framework,maryokhin/django-rest-framework,jpulec/django-rest-framework,ticosax/django-rest-framework,canassa/django-rest-framework,MJafarMashhadi/django-rest-framework
85a873c79e3c3c7289a23da6fe3673259fac9cbd
sympy/sets/conditionset.py
sympy/sets/conditionset.py
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self): return len(self.lamda.variables) > 1 def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
Remove redundant _is_multivariate in ConditionSet
Remove redundant _is_multivariate in ConditionSet Signed-off-by: Harsh Gupta <[email protected]>
Python
bsd-3-clause
sampadsaha5/sympy,VaibhavAgarwalVA/sympy,mcdaniel67/sympy,MechCoder/sympy,farhaanbukhsh/sympy,abhiii5459/sympy,MechCoder/sympy,madan96/sympy,kaushik94/sympy,jaimahajan1997/sympy,skidzo/sympy,ahhda/sympy,abhiii5459/sympy,mafiya69/sympy,Curious72/sympy,shikil/sympy,aktech/sympy,hargup/sympy,Vishluck/sympy,oliverlee/sympy,debugger22/sympy,kaichogami/sympy,Shaswat27/sympy,postvakje/sympy,ga7g08/sympy,skidzo/sympy,kumarkrishna/sympy,emon10005/sympy,AkademieOlympia/sympy,oliverlee/sympy,atreyv/sympy,ahhda/sympy,Shaswat27/sympy,souravsingh/sympy,moble/sympy,yukoba/sympy,farhaanbukhsh/sympy,ahhda/sympy,debugger22/sympy,drufat/sympy,ChristinaZografou/sympy,chaffra/sympy,Davidjohnwilson/sympy,jbbskinny/sympy,moble/sympy,kumarkrishna/sympy,jbbskinny/sympy,Curious72/sympy,hargup/sympy,moble/sympy,mafiya69/sympy,souravsingh/sympy,rahuldan/sympy,chaffra/sympy,farhaanbukhsh/sympy,aktech/sympy,wanglongqi/sympy,Arafatk/sympy,iamutkarshtiwari/sympy,drufat/sympy,Titan-C/sympy,kaichogami/sympy,kaichogami/sympy,AkademieOlympia/sympy,jerli/sympy,rahuldan/sympy,mcdaniel67/sympy,VaibhavAgarwalVA/sympy,Shaswat27/sympy,cswiercz/sympy,iamutkarshtiwari/sympy,aktech/sympy,VaibhavAgarwalVA/sympy,madan96/sympy,kaushik94/sympy,Vishluck/sympy,drufat/sympy,jerli/sympy,pandeyadarsh/sympy,saurabhjn76/sympy,abhiii5459/sympy,Vishluck/sympy,sahmed95/sympy,wanglongqi/sympy,saurabhjn76/sympy,chaffra/sympy,Designist/sympy,ChristinaZografou/sympy,madan96/sympy,Titan-C/sympy,skidzo/sympy,sahmed95/sympy,lindsayad/sympy,Arafatk/sympy,oliverlee/sympy,kevalds51/sympy,lindsayad/sympy,shikil/sympy,pandeyadarsh/sympy,yukoba/sympy,grevutiu-gabriel/sympy,debugger22/sympy,Davidjohnwilson/sympy,cswiercz/sympy,jbbskinny/sympy,kumarkrishna/sympy,maniteja123/sympy,jaimahajan1997/sympy,mafiya69/sympy,maniteja123/sympy,rahuldan/sympy,yashsharan/sympy,hargup/sympy,yukoba/sympy,postvakje/sympy,grevutiu-gabriel/sympy,Designist/sympy,wanglongqi/sympy,iamutkarshtiwari/sympy,souravsingh/sympy,ChristinaZografou/sympy,jerli/sympy,kevalds51/sympy,yashsharan/sympy,Titan-C/sympy,atreyv/sympy,cswiercz/sympy,kevalds51/sympy,postvakje/sympy,jaimahajan1997/sympy,Davidjohnwilson/sympy,maniteja123/sympy,sampadsaha5/sympy,kaushik94/sympy,yashsharan/sympy,mcdaniel67/sympy,lindsayad/sympy,ga7g08/sympy,sahmed95/sympy,Designist/sympy,sampadsaha5/sympy,saurabhjn76/sympy,shikil/sympy,AkademieOlympia/sympy,pandeyadarsh/sympy,ga7g08/sympy,atreyv/sympy,emon10005/sympy,MechCoder/sympy,grevutiu-gabriel/sympy,Arafatk/sympy,Curious72/sympy,emon10005/sympy
647562550e2932a1eb5f89ff3bc4be84fa894dea
tba_config.py
tba_config.py
import json import os DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') # For choosing what the main landing page displays KICKOFF = 1 BUILDSEASON = 2 COMPETITIONSEASON = 3 OFFSEASON = 4 # The CONFIG variables should have exactly the same structure between environments # Eventually a test environment should be added. -gregmarra 17 Jul 2012 if DEBUG: CONFIG = { "env": "dev", "memcache": False, } else: CONFIG = { "env": "prod", "memcache": True, } CONFIG['landing_handler'] = COMPETITIONSEASON CONFIG["static_resource_version"] = 2
import json import os DEBUG = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev') # For choosing what the main landing page displays KICKOFF = 1 BUILDSEASON = 2 COMPETITIONSEASON = 3 OFFSEASON = 4 # The CONFIG variables should have exactly the same structure between environments # Eventually a test environment should be added. -gregmarra 17 Jul 2012 if DEBUG: CONFIG = { "env": "dev", "memcache": False, } else: CONFIG = { "env": "prod", "memcache": True, } CONFIG['landing_handler'] = COMPETITIONSEASON CONFIG["static_resource_version"] = 3
Increment static resource to account for CDN JS
Increment static resource to account for CDN JS
Python
mit
josephbisch/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,1fish2/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,1fish2/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,bvisness/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance
14c86e3c93bd5114b74c125fdb8213b22342c95c
tests/manual_cleanup.py
tests/manual_cleanup.py
from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) @patch("globus_cli.config.get_config_obj", new=default_test_config) def main(): tc = get_tc() cleanup_bookmarks(tc) if __name__ == '__main__': main()
#!/usr/bin/env python import click from globus_cli.services.transfer import get_client as get_tc from tests.framework.cli_testcase import default_test_config try: from mock import patch except ImportError: from unittest.mock import patch def cleanup_bookmarks(tc): for bm in tc.bookmark_list(): tc.delete_bookmark(bm['id']) def cleanup_tasks(tc): tasks = tc.task_list(num_results=None, filter="status:ACTIVE,INACTIVE") for t in tasks: tc.cancel_task(t['task_id']) @click.command("cleanup") @click.option("--cancel-jobs", is_flag=True) def main(cancel_jobs): with patch("globus_cli.config.get_config_obj", new=default_test_config): tc = get_tc() cleanup_bookmarks(tc) if cancel_jobs: cleanup_tasks(tc) if __name__ == '__main__': main()
Add `--cancel-jobs` to manual cleanup script
Add `--cancel-jobs` to manual cleanup script Add an option to this script to cancel all ACTIVE,INACTIVE tasks (i.e. not SUCCEDED,FAILED). While this can disrupt a run of the tests pretty badly if you run it while the tets are running, it's pretty much the only way to "fix it" if the tests go off the rails because of a partial or failed job, etc.
Python
apache-2.0
globus/globus-cli,globus/globus-cli
a3d087b2d7ec42eb5afe9f0064785d25500af11b
bitforge/errors.py
bitforge/errors.py
class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) self.message = self.__doc__.format(**self.__dict__) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value
class BitforgeError(Exception): def __init__(self, *args, **kwargs): self.cause = kwargs.pop('cause', None) self.prepare(*args, **kwargs) message = self.__doc__.format(**self.__dict__) super(BitforgeError, self).__init__(message) def prepare(self): pass def __str__(self): return self.message class ObjectError(BitforgeError): def prepare(self, object): self.object = object class StringError(BitforgeError): def prepare(self, string): self.string = repr(string) self.length = len(string) class NumberError(BitforgeError): def prepare(self, number): self.number = number class KeyValueError(BitforgeError): def prepare(self, key, value): self.key = key self.value = value
Call super constructor for BitforgeError
Call super constructor for BitforgeError
Python
mit
muun/bitforge,coinforge/bitforge
c19a64ecdbde5a387a84dec880c2ebea1013c3d6
canopus/auth/token_factory.py
canopus/auth/token_factory.py
from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user if user.last_signed_in is None: user.welcome() user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) return dict(token=token, user={})
from datetime import datetime, timedelta from ..schema import UserSchema class TokenFactory(object): def __init__(self, request, user): self.user = user self.request = request def create_access_token(self): user = self.user user.last_signed_in = datetime.now() token = self.request.create_jwt_token(user.id, expiration=timedelta(days=7)) user_schema = UserSchema(exclude=('enabled',)) return dict(token=token, user=user_schema.dump(user).data)
Include user in create_access_token return value
Include user in create_access_token return value
Python
mit
josuemontano/api-starter,josuemontano/API-platform,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/API-platform,josuemontano/api-starter,josuemontano/api-starter,josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform
b3f5aed7097241adffd54d9b1ff705cd44455165
examples/python/setup.py
examples/python/setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'Python Connector for Mongrel2', 'author': 'Zed A. Shaw', 'url': 'http://pypi.python.org/pypi/mongrel2-python', 'download_url': 'http://pypi.python.org/pypi/mongrel2-python', 'author_email': '[email protected]', 'version': '0.2', 'scripts': ['bin/m2sh'], 'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'], 'packages': ['mongrel2', 'mongrel2.config'], 'package_data': {'mongrel2': ['sql/config.sql']}, 'name': 'm2py' } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'Python Connector for Mongrel2', 'author': 'Zed A. Shaw', 'url': 'http://pypi.python.org/pypi/mongrel2-python', 'download_url': 'http://pypi.python.org/pypi/mongrel2-python', 'author_email': '[email protected]', 'version': '1.0beta5', 'scripts': ['bin/m2sh'], 'install_requires': ['nose', 'simplejson', 'pyrepl', 'storm'], 'packages': ['mongrel2', 'mongrel2.config'], 'package_data': {'mongrel2': ['sql/config.sql']}, 'name': 'm2py' } setup(**config)
Make m2sh have the same version number as mongrel2.
Make m2sh have the same version number as mongrel2.
Python
bsd-3-clause
ged/mongrel2,ged/mongrel2,ged/mongrel2,ged/mongrel2
72f03f05adc39a3d920ee8372f4108b5c8c8671c
modules/pwnchecker.py
modules/pwnchecker.py
#!/usr/bin/python3 import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module'} API = 'https://haveibeenpwned.com/api/v2/breachedaccount/{0}'.format(args.email_account) request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
#!/usr/bin/python3 import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) parser.add_argument('-k', '--api-key', help='Your HIBP API key', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module', f'hibp-api-key': {args.api_key}} API = f'https://haveibeenpwned.com/api/v3/breachedaccount/{args.email_account}' request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
Update to the v3 api
Update to the v3 api
Python
bsd-3-clause
L1ghtn1ng/usaf,L1ghtn1ng/usaf
5cd459485fee2611eb96229b0a600b3a21f4fc13
stagecraft/apps/datasets/admin/backdrop_user.py
stagecraft/apps/datasets/admin/backdrop_user.py
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email'] list_display = ('email', 'numer_of_datasets_user_has_access_to',) list_per_page = 30 filter_horizontal = ('data_sets',) def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def numer_of_datasets_user_has_access_to(self, obj): return obj.dataset_count numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin)
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email'] list_display = ('email', 'number_of_datasets_user_has_access_to',) list_per_page = 30 filter_horizontal = ('data_sets',) def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def number_of_datasets_user_has_access_to(self, obj): return obj.dataset_count number_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin)
Fix typo in BackdropUser admin model
Fix typo in BackdropUser admin model
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
31a9b285a0445c895aeff02b2abbeda12bf7f3d7
wagtail/admin/tests/pages/test_content_type_use_view.py
wagtail/admin/tests/pages/test_content_type_use_view.py
from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() def test_content_type_use(self): # Get use of event page response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas")
from django.test import TestCase from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") # Links to 'delete' etc should include a 'next' URL parameter pointing back here delete_url = ( reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + '?' + urlencode({'next': request_url}) ) self.assertContains(response, delete_url)
Add test for button URLs including a 'next' parameter
Add test for button URLs including a 'next' parameter
Python
bsd-3-clause
torchbox/wagtail,FlipperPA/wagtail,gasman/wagtail,gasman/wagtail,mixxorz/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,torchbox/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,mixxorz/wagtail,wagtail/wagtail,takeflight/wagtail,FlipperPA/wagtail,torchbox/wagtail,zerolab/wagtail,thenewguy/wagtail,takeflight/wagtail,zerolab/wagtail,kaedroho/wagtail,wagtail/wagtail,zerolab/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,kaedroho/wagtail,kaedroho/wagtail,thenewguy/wagtail,mixxorz/wagtail,zerolab/wagtail,jnns/wagtail,takeflight/wagtail,rsalmaso/wagtail,gasman/wagtail,FlipperPA/wagtail,wagtail/wagtail,wagtail/wagtail,zerolab/wagtail,rsalmaso/wagtail,kaedroho/wagtail,FlipperPA/wagtail,jnns/wagtail,jnns/wagtail,takeflight/wagtail,kaedroho/wagtail,mixxorz/wagtail,wagtail/wagtail,rsalmaso/wagtail,jnns/wagtail
f001bf192e1f0c40eee8c744f83aa55e1846d765
main/models.py
main/models.py
from django.contrib.postgres.fields import ArrayField from django.db import models class Track(models.Model): """ This model help us to store midi files. It will be easier for everyone to have one place to listen to the midi without having to install codecs, timidity or whatever """ title = models.CharField(max_length=255) midi_file = models.FileField() def __str__(self): return self.title class QuestionPage(models.Model): """ To avoid to write again and again stupid view for urls: est-ce-que-cest-bientot-xxxxxx with some response """ slug = models.SlugField(max_length=255) start_date = models.DateField() end_date = models.DateField() answers = ArrayField(models.CharField(max_length=1024, blank=True)) answers_before = ArrayField(models.CharField(max_length=1024, blank=True)) answers_expired = ArrayField(models.CharField(max_length=1024, blank=True)) def __str__(self): return self.slug def get_answers(self, date): if date < self.start_date: return self.answers_before elif date < self.end_date: return self.answers else: return self.answers_expired
from django.contrib.postgres.fields import ArrayField from django.db import models class Track(models.Model): """ This model help us to store midi files. It will be easier for everyone to have one place to listen to the midi without having to install codecs, timidity or whatever """ title = models.CharField(max_length=255) midi_file = models.FileField() def __str__(self): return self.title class QuestionPage(models.Model): """ To avoid to write again and again stupid view for urls: est-ce-que-cest-bientot-xxxxxx with some response """ slug = models.SlugField(max_length=255) start_date = models.DateField() end_date = models.DateField() answers = ArrayField(models.CharField(max_length=1024, blank=True)) answers_before = ArrayField(models.CharField(max_length=1024, blank=True)) answers_expired = ArrayField(models.CharField(max_length=1024, blank=True)) def __str__(self): return self.slug def get_answers(self, date): if date < self.start_date: return self.answers_before elif date <= self.end_date: return self.answers else: return self.answers_expired
Fix end_date management with Question Page
Fix end_date management with Question Page
Python
mit
adrienbrunet/fanfare_cuc,adrienbrunet/fanfare_cuc,adrienbrunet/fanfare_cuc
11fd3e5c8a2c7f591dff1ba1949508d178d1e5d5
byceps/util/irc.py
byceps/util/irc.py
""" byceps.util.irc ~~~~~~~~~~~~~~~ Send IRC messages to a bot via HTTP. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. sleep(DELAY_IN_SECONDS) requests.post(url, json=data) # Ignore response code for now.
""" byceps.util.irc ~~~~~~~~~~~~~~~ Send IRC messages to a bot via HTTP. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DEFAULT_DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. delay = int( current_app.config.get('ANNOUNCE_IRC_DELAY', DEFAULT_DELAY_IN_SECONDS) ) sleep(delay) requests.post(url, json=data) # Ignore response code for now.
Make IRC message delay configurable
Make IRC message delay configurable
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
6942497dc04683e2d627042b168476fd756dcbda
tasks/check_rd2_enablement.py
tasks/check_rd2_enablement.py
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT npsp__IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False self.logger.info("Identified Enhanced Recurring Donations status: {}".format(self.return_values)) return if settings.get("records"): if settings["records"][0]["npsp__IsRecurringDonations2Enabled__c"]: self.return_values = True self.logger.info("Identified Enhanced Recurring Donations status: {}".format(self.return_values)) return self.return_values = False self.logger.info("Identified Enhanced Recurring Donations status: {}".format(self.return_values))
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False self.logger.info("Identified Enhanced Recurring Donations status: {}".format(self.return_values)) return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True self.logger.info("Identified Enhanced Recurring Donations status: {}".format(self.return_values)) return self.return_values = False self.logger.info("Identified Enhanced Recurring Donations status: {}".format(self.return_values))
Remove namespace from RD2 enablement check
Remove namespace from RD2 enablement check
Python
bsd-3-clause
SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus
0c42909e5649b78260d9efa4e6ff7b77c82b1934
runtests.py
runtests.py
#!/usr/bin/env python # coding: utf-8 import sys from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings from django.test.simple import DjangoTestSuiteRunner def runtests(): parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) test_runner = DjangoTestSuiteRunner( verbosity=1, interactive=False, failfast=False) failures = test_runner.run_tests(['djoauth2']) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python # coding: utf-8 import sys from argparse import ArgumentParser from os.path import abspath from os.path import dirname # Load Django-related settings; necessary for tests to run and for Django # imports to work. import local_settings # Now, imports from Django will work properly without raising errors related to # missing or badly-configured settings. from django.test.simple import DjangoTestSuiteRunner def runtests(verbosity, failfast, interactive, test_labels): # Modify the path so that our djoauth2 app is in it. parent_dir = dirname(abspath(__file__)) sys.path.insert(0, parent_dir) test_runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=failfast) sys.exit(test_runner.run_tests(test_labels)) if __name__ == '__main__': # Parse any command line arguments. parser = ArgumentParser() parser.add_argument('--failfast', action='store_true', default=False, dest='failfast') parser.add_argument('--interactive', action='store_true', default=False, dest='interactive') parser.add_argument('--verbosity', default=1, type=int) parser.add_argument('test_labels', nargs='*', default=('djoauth2',)) args = parser.parse_args() # Run the tests. runtests(args.verbosity, args.failfast, args.interactive, args.test_labels)
Allow testing of specific apps.
Allow testing of specific apps.
Python
mit
seler/djoauth2,seler/djoauth2,vden/djoauth2-ng,Locu/djoauth2,vden/djoauth2-ng,Locu/djoauth2
d9844f5bcf6d48bde1a60d32998ccdaa87e99676
cloud_browser/__init__.py
cloud_browser/__init__.py
"""Cloud browser application. Provides a simple filesystem-like browser interface for cloud blob datastores. """ VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__ + "".join(str(v) for v in VERSION)
"""Cloud browser application. Provides a simple filesystem-like browser interface for cloud blob datastores. """ VERSION = (0, 2, 1) __version__ = ".".join(str(v) for v in VERSION) __version_full__ = __version__
Fix __version_full__ for new scheme.
Version: Fix __version_full__ for new scheme.
Python
mit
ryan-roemer/django-cloud-browser,UrbanDaddy/django-cloud-browser,UrbanDaddy/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser
e9b3865e37c1f4a275c323dcbf778696a27d69bd
testapp/testapp/management.py
testapp/testapp/management.py
from bitcategory import models from django.dispatch import receiver from django.db.models.signals import post_syncdb @receiver(post_syncdb, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2)
from bitcategory import models from django.dispatch import receiver from django.db.models.signals import post_migrate @receiver(post_migrate, sender=models) def load_test_categories(sender, **kwargs): r1, c = models.Category.objects.get_or_create(name="root1") r2, c = models.Category.objects.get_or_create(name="root2") c11, c = models.Category.objects.get_or_create(name="cat11", parent=r1) c12, c = models.Category.objects.get_or_create(name="cat12", parent=r1) c111, c = models.Category.objects.get_or_create(name="cat111", parent=c11) c112, c = models.Category.objects.get_or_create(name="cat112", parent=c11) c113, c = models.Category.objects.get_or_create(name="cat113", parent=c11) c21, c = models.Category.objects.get_or_create(name="cat21", parent=r2) c22, c = models.Category.objects.get_or_create(name="cat22", parent=r2)
Update tests to work under django 1.8+
Update tests to work under django 1.8+
Python
bsd-3-clause
atheiste/django-bit-category,atheiste/django-bit-category,atheiste/django-bit-category
67b50cde0fa1885dce936b95d58d82fc64316c85
src/satosa/micro_services/processors/scope_extractor_processor.py
src/satosa/micro_services/processors/scope_extractor_processor.py
from ..attribute_processor import AttributeProcessorError from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes for value in attributes.get(attribute, [None]): if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope]
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, [None]) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
Allow processor to handle the fact that the attribute might have no values, or that they are not scoped
Allow processor to handle the fact that the attribute might have no values, or that they are not scoped
Python
apache-2.0
SUNET/SATOSA,its-dirg/SATOSA,irtnog/SATOSA,SUNET/SATOSA,irtnog/SATOSA
a934303f40d835626cdd42096c869acb536d788d
examples/prompts/autocompletion.py
examples/prompts/autocompletion.py
#!/usr/bin/env python """ Autocompletion example. Press [Tab] to complete the current word. - The first Tab press fills in the common part of all completions and shows all the completions. (In the menu) - Any following tab press cycles through all the possible completions. """ from __future__ import unicode_literals from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit import prompt animal_completer = WordCompleter([ 'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison', 'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphine', 'dove', 'duck', 'eagle', 'elephant', 'fish', 'goat', 'gorilla', 'kangaroo', 'leopard', 'lion', 'mouse', 'rabbit', 'rat', 'snake', 'spider', 'turkey', 'turtle', ], ignore_case=True) def main(): text = prompt('Give some animals: ', completer=animal_completer, complete_while_typing=False) print('You said: %s' % text) if __name__ == '__main__': main()
#!/usr/bin/env python """ Autocompletion example. Press [Tab] to complete the current word. - The first Tab press fills in the common part of all completions and shows all the completions. (In the menu) - Any following tab press cycles through all the possible completions. """ from __future__ import unicode_literals from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit import prompt animal_completer = WordCompleter([ 'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison', 'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphin', 'dove', 'duck', 'eagle', 'elephant', 'fish', 'goat', 'gorilla', 'kangaroo', 'leopard', 'lion', 'mouse', 'rabbit', 'rat', 'snake', 'spider', 'turkey', 'turtle', ], ignore_case=True) def main(): text = prompt('Give some animals: ', completer=animal_completer, complete_while_typing=False) print('You said: %s' % text) if __name__ == '__main__': main()
Fix typo: `dolphine` -> `dolphin`
Fix typo: `dolphine` -> `dolphin`
Python
bsd-3-clause
jonathanslenders/python-prompt-toolkit
5749d976dee7d8a51e25842b528448a077a8f800
report_compassion/models/ir_actions_report.py
report_compassion/models/ir_actions_report.py
# Copyright (c) 2018 Emanuel Cino <[email protected]> from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values user = self.env.user if user.printing_action: default_action = user.printing_action for key, val in result.iteritems(): result[key]["action"] = default_action if user.printing_printer_id: default_printer = user.printing_printer_id for key, val in result.iteritems(): result[key]["printer"] = default_printer return result
# Copyright (c) 2018 Emanuel Cino <[email protected]> from odoo import models, api class IrActionsReport(models.Model): _inherit = "ir.actions.report" @api.multi def behaviour(self): """ Change behaviour to return user preference in priority. :return: report action for printing. """ result = super().behaviour() # Retrieve user default values result.update(self._get_user_default_print_behaviour()) return result
FIX default behaviour of printing
FIX default behaviour of printing
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland
a1a8ef302ac24d56a36d0671eb692943d14c4ddf
whats_open/website/urls.py
whats_open/website/urls.py
# Future Imports from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ]
# Future Imports from __future__ import (absolute_import, division, print_function, unicode_literals) # Django Imports from django.conf.urls import include, url from django.views.generic.base import RedirectView # App Imports from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet # Other Imports from rest_framework.routers import DefaultRouter # Instiantiate our DefaultRouter ROUTER = DefaultRouter() # Register views to the API router ROUTER.register(r'categories', CategoryViewSet) ROUTER.register(r'facilities', FacilityViewSet) ROUTER.register(r'schedules', ScheduleViewSet) urlpatterns = [ # / - Default route # We redirect to /api since this is in reality the default page for the API url(r'^$', RedirectView.as_view(url='/api')), # /api - Root API URL url(r'^api/', include(ROUTER.urls)), ]
Add a redirect for / -> /api
refactor: Add a redirect for / -> /api - This got really annoying in development to remember to go to /api all the time - Potentially in the future we will build a test landing page on / to test that the API works instead of having to rely on third party tools or just manual clicks - Until then, this will make life easier (imo)
Python
apache-2.0
srct/whats-open,srct/whats-open,srct/whats-open
d3f4d43b36b8d21a3102389d53bf3f1af4e00d79
st2common/st2common/runners/base_action.py
st2common/st2common/runners/base_action.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 abc import six from st2common.runners.utils import get_logger_for_python_runner_action @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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 abc import six from st2common.runners.utils import get_logger_for_python_runner_action __all__ = [ 'Action' ] @six.add_metaclass(abc.ABCMeta) class Action(object): """ Base action class other Python actions should inherit from. """ description = None def __init__(self, config=None, action_service=None): """ :param config: Action config. :type config: ``dict`` :param action_service: ActionService object. :type action_service: :class:`ActionService~ """ self.config = config or {} self.action_service = action_service self.logger = get_logger_for_python_runner_action(action_name=self.__class__.__name__) @abc.abstractmethod def run(self, **kwargs): pass
Add _all__ to the module.
Add _all__ to the module.
Python
apache-2.0
StackStorm/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2
d5a54a7fe207c0fde76774cdc8a11e12fcc3218a
core/data_loader.py
core/data_loader.py
import json import os import sys import dateparser __DATA_DIR = '../data/' def harmonize_data( data ): ## make dates as date objects data2 = [] for d in data: if 'created_time' in d: d['date'] = dateparser.parse( d['created_time'] ) ## should take care of the various formats d['creator'] = d['from']['name'] data2.append( d ) return data2 def load_facebook( terms = ['data_'] ): ## todo: better filtering data = [] for f in os.listdir( __DATA_DIR ): if any( term in f for term in terms ): print json.load( open( __DATA_DIR + f ) ).keys() data += json.load( open( __DATA_DIR + f ) )['feed'] return harmonize_data( data )
import json import os import sys #import dateparser from datetime import datetime __DATA_DIR = '../data/' def harmonize_data( data ): ## make dates as date objects data2 = [] for d in data: if 'created_time' in d: #d['date'] = dateparser.parse( d['created_time'] ) ## should take care of the various formats d['date'] = datetime.strptime( d['created_time'].replace( 'T', ' ' ).replace( '+0000', '' ), '%Y-%m-%d %H:%M:%S' ) d['creator'] = d['from']['name'] data2.append( d ) return data2 def load_facebook( terms = ['data_'] ): ## todo: better filtering data = [] for f in os.listdir( __DATA_DIR ): if any( term in f for term in terms ): print json.load( open( __DATA_DIR + f ) ).keys() data += json.load( open( __DATA_DIR + f ) )['feed'] return harmonize_data( data )
Change dateparser to datetime to use with Jupyter
Change dateparser to datetime to use with Jupyter
Python
mit
HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core
715733fce547aa010ae94239bf856453b9b62869
containers/default/pythia.py
containers/default/pythia.py
import json import sys import shutil import os #Copy /ro/task (which is read-only) in /task. Everything will be executed there shutil.copytree("/ro/task","/task") #Change directory to /task os.chdir("/task") #Parse input to return stupid output input = json.loads(sys.stdin.readline()) problems = {} for boxId in input: taskId = boxId.split("/")[0] problems[taskId] = str(input[boxId]) print json.dumps({"result":"failed","text":"In fact, it's working, but it's a test :D","problems":problems}) #TODO: launch task/control #Ressource: http://stackoverflow.com/questions/1689505/python-ulimit-and-nice-for-subprocess-call-subprocess-popen
import json import sys import shutil import os import resource import subprocess #Copy /ro/task (which is read-only) in /task. Everything will be executed there shutil.copytree("/ro/task","/task") #Change directory to /task os.chdir("/task") #Parse input to return stupid output input = json.loads(sys.stdin.readline()) problems = {} for boxId in input: taskId = boxId.split("/")[0] problems[taskId] = str(input[boxId]) def setlimits(): resource.setrlimit(resource.RLIMIT_CPU, (1, 1)) p = subprocess.Popen(["/task/run"], preexec_fn=setlimits, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() text = "It's a test. Here is what /task/run returned: "+str(p.stdout.read()) print json.dumps({"result":"failed","text":text,"problems":problems})
Insert a valid test task
Insert a valid test task
Python
agpl-3.0
GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious
873833d777536de5aa716a509e590ad1b076198a
scripts/examples/OpenMV/99-Tests/unittests.py
scripts/examples/OpenMV/99-Tests/unittests.py
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, result): s = "Unittest (%s)"%(test) padding = "."*(60-len(s)) print(s + padding + result) for test in sorted(os.listdir(SCRIPT_DIR)): if test.endswith(".py"): test_result = "PASSED" test_path = "/".join((SCRIPT_DIR, test)) try: exec(open(test_path).read()) gc.collect() if unittest(DATA_DIR, TEMP_DIR) == False: raise Exception() except Exception as e: test_failed = True test_result = "DISABLED" if "unavailable" in str(e) else "FAILED" print_result(test, test_result) if test_failed: print("\nSome tests have FAILED!!!\n\n") else: print("\nAll tests PASSED.\n\n")
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, result): s = "Unittest (%s)"%(test) padding = "."*(60-len(s)) print(s + padding + result) for test in sorted(os.listdir(SCRIPT_DIR)): if test.endswith(".py"): test_result = "PASSED" test_path = "/".join((SCRIPT_DIR, test)) try: exec(open(test_path).read()) gc.collect() if unittest(DATA_DIR, TEMP_DIR) == False: raise Exception() except Exception as e: if "unavailable" in str(e): test_result = "DISABLED" else: test_failed = True test_result = "FAILED" print_result(test, test_result) if test_failed: print("\nSome tests have FAILED!!!\n\n") else: print("\nAll tests PASSED.\n\n")
Fix unit-test failing on disabled functions.
Fix unit-test failing on disabled functions.
Python
mit
kwagyeman/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv,openmv/openmv,iabdalkader/openmv,iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,kwagyeman/openmv,kwagyeman/openmv,iabdalkader/openmv