commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
07ea75c5e5f0294a9ca184bc44619a83e5cda38b
tools/debug_launcher.py
tools/debug_launcher.py
#!/usr/bin/python # Debug stub for launching Python debug session inside LLDB import sys import subprocess args = ['*'] + sys.argv[3:] script = [ "import sys, runpy, __main__", "sys.orig_main = __main__", "sys.argv=['%s']" % "','".join(args), "runpy.run_module('ptvsd', alter_sys=True, run_name='__main__')" ] command = ['lldb-6.0', '-b', '-O', 'script ' + '; '.join(script)] subprocess.call(command)
#!/usr/bin/python # Debug stub for launching Python debug session inside LLDB import sys import subprocess args = sys.argv[1:] script = [ "import sys,runpy,__main__", "sys.orig_main = __main__", "sys.argv=['%s']" % "','".join(args), "runpy.run_path('%s', run_name='__main__')" % sys.argv[1] ] command = ['lldb-6.0', '-b', '-O', 'script ' + '; '.join(script)] subprocess.call(command)
Make python debugging work with latest Python extension.
Make python debugging work with latest Python extension.
Python
mit
vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb
--- +++ @@ -3,12 +3,12 @@ import sys import subprocess -args = ['*'] + sys.argv[3:] +args = sys.argv[1:] script = [ - "import sys, runpy, __main__", + "import sys,runpy,__main__", "sys.orig_main = __main__", "sys.argv=['%s']" % "','".join(args), - "runpy.run_module('ptvsd', alter_sys=True, run_name='__main__')" + "runpy.run_path('%s', run_name='__main__')" % sys.argv[1] ] command = ['lldb-6.0', '-b', '-O', 'script ' + '; '.join(script)] subprocess.call(command)
a18a19345298c43400dbfb984f97e97b3d0b624a
pyelasticsearch/__init__.py
pyelasticsearch/__init__.py
from __future__ import absolute_import from pyelasticsearch.client import ElasticSearch from pyelasticsearch.exceptions import (Timeout, ConnectionError, ElasticHttpError, InvalidJsonResponseError, ElasticHttpNotFoundError, IndexAlreadyExistsError) __author__ = 'Robert Eanes' __all__ = ['ElasticSearch', 'ElasticHttpError', 'InvalidJsonResponseError', 'Timeout', 'ConnectionError', 'ElasticHttpNotFoundError', 'IndexAlreadyExistsError'] __version__ = '0.6.1' __version_info__ = tuple(__version__.split('.')) get_version = lambda: __version_info__
from __future__ import absolute_import from pyelasticsearch.client import ElasticSearch from pyelasticsearch.exceptions import (Timeout, ConnectionError, ElasticHttpError, InvalidJsonResponseError, ElasticHttpNotFoundError, IndexAlreadyExistsError) __author__ = 'Erik Rose' __all__ = ['ElasticSearch', 'ElasticHttpError', 'InvalidJsonResponseError', 'Timeout', 'ConnectionError', 'ElasticHttpNotFoundError', 'IndexAlreadyExistsError'] __version__ = '0.7' __version_info__ = tuple(__version__.split('.')) get_version = lambda: __version_info__
Change author and bump version.
Change author and bump version.
Python
bsd-3-clause
erikrose/pyelasticsearch
--- +++ @@ -7,11 +7,11 @@ ElasticHttpNotFoundError, IndexAlreadyExistsError) -__author__ = 'Robert Eanes' +__author__ = 'Erik Rose' __all__ = ['ElasticSearch', 'ElasticHttpError', 'InvalidJsonResponseError', 'Timeout', 'ConnectionError', 'ElasticHttpNotFoundError', 'IndexAlreadyExistsError'] -__version__ = '0.6.1' +__version__ = '0.7' __version_info__ = tuple(__version__.split('.')) get_version = lambda: __version_info__
4022e09632602e65328f4561fe1b87a490ab587b
nau_timetable/wsgi.py
nau_timetable/wsgi.py
""" WSGI config for nau_timetable project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nau_timetable.settings") application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application)
""" WSGI config for nau_timetable project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nau_timetable.settings") application = DjangoWhiteNoise(get_wsgi_application())
Fix flake8: E402 module level import not at top of file
Fix flake8: E402 module level import not at top of file
Python
mit
bluebirrd/nau-timetable,bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrd/nau-timetable,bluebirrd/nau-timetable,bluebirrrrd/nau-timetable,bluebirrrrd/nau-timetable
--- +++ @@ -11,9 +11,8 @@ from django.core.wsgi import get_wsgi_application +from whitenoise.django import DjangoWhiteNoise + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nau_timetable.settings") -application = get_wsgi_application() - -from whitenoise.django import DjangoWhiteNoise -application = DjangoWhiteNoise(application) +application = DjangoWhiteNoise(get_wsgi_application())
7aa140778cd689a8efa86f0890c4ccb8fc7f0d43
infrastructure/tests/test_api_views.py
infrastructure/tests/test_api_views.py
from django.test import Client, TestCase from infrastructure import utils from infrastructure import models import json from infrastructure.models import FinancialYear, QuarterlySpendFile, Expenditure, Project from scorecard.models import Geography from scorecard.profiles import MunicipalityProfile from scorecard.admin import MunicipalityProfilesCompilationAdmin class TestProject(TestCase): def setUp(self): fixtures = ["test_infrastructure.json"] TestProject.geography = Geography.objects.create( geo_level="municipality", geo_code="BUF", province_name="Eastern Cape", province_code="EC", category="A", ) def test_infrastructure_project_search(self): response = self.client.get( "/api/v1/infrastructure/search/?province=Eastern+Cape&municipality=Buffalo+City&q=&budget_phase=Budget+year&financial_year=2019%2F2020&ordering=-total_forecast_budget") self.assertEqual(response.status_code, 200) js = response.json() self.assertEquals(len(js["results"]), 3)
from django.test import TestCase class TestProject(TestCase): fixtures = ["test_infrastructure.json"] def test_infrastructure_project_filters(self): response = self.client.get( "/api/v1/infrastructure/search/?q=&province=Western+Cape&municipality=City+of+Cape+Town&project_type=New&function=Administrative+and+Corporate+Support&budget_phase=Budget+year&quarterly_phase=Original+Budget&financial_year=2019%2F2020&ordering=-total_forecast_budget") self.assertEqual(response.status_code, 200) js = response.json() self.assertEquals(js["count"], 2) self.assertEquals(len(js["results"]["projects"]), 2) def test_infrastructure_project_search(self): response = self.client.get( "/api/v1/infrastructure/search/?q=PC001002004002_00473&budget_phase=Budget+year&quarterly_phase=Original+Budget&financial_year=2019%2F2020&ordering=-total_forecast_budget") self.assertEqual(response.status_code, 200) js = response.json() self.assertEquals(js["count"], 1) self.assertEquals(len(js["results"]["projects"]), 1) response = self.client.get( "/api/v1/infrastructure/search/?q=Acquisition&budget_phase=Budget+year&quarterly_phase=Original+Budget&financial_year=2019%2F2020&ordering=-total_forecast_budget") self.assertEqual(response.status_code, 200) js = response.json() self.assertEquals(js["count"], 1) self.assertEquals(len(js["results"]["projects"]), 1)
Add test for infra search API and some refactoring
Add test for infra search API and some refactoring
Python
mit
Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data
--- +++ @@ -1,30 +1,28 @@ -from django.test import Client, TestCase -from infrastructure import utils -from infrastructure import models -import json - -from infrastructure.models import FinancialYear, QuarterlySpendFile, Expenditure, Project - -from scorecard.models import Geography -from scorecard.profiles import MunicipalityProfile -from scorecard.admin import MunicipalityProfilesCompilationAdmin +from django.test import TestCase class TestProject(TestCase): - def setUp(self): - fixtures = ["test_infrastructure.json"] - TestProject.geography = Geography.objects.create( - geo_level="municipality", - geo_code="BUF", - province_name="Eastern Cape", - province_code="EC", - category="A", - ) + fixtures = ["test_infrastructure.json"] + def test_infrastructure_project_filters(self): + response = self.client.get( + "/api/v1/infrastructure/search/?q=&province=Western+Cape&municipality=City+of+Cape+Town&project_type=New&function=Administrative+and+Corporate+Support&budget_phase=Budget+year&quarterly_phase=Original+Budget&financial_year=2019%2F2020&ordering=-total_forecast_budget") + self.assertEqual(response.status_code, 200) + js = response.json() + self.assertEquals(js["count"], 2) + self.assertEquals(len(js["results"]["projects"]), 2) def test_infrastructure_project_search(self): - response = self.client.get( - "/api/v1/infrastructure/search/?province=Eastern+Cape&municipality=Buffalo+City&q=&budget_phase=Budget+year&financial_year=2019%2F2020&ordering=-total_forecast_budget") - self.assertEqual(response.status_code, 200) - js = response.json() - self.assertEquals(len(js["results"]), 3) + response = self.client.get( + "/api/v1/infrastructure/search/?q=PC001002004002_00473&budget_phase=Budget+year&quarterly_phase=Original+Budget&financial_year=2019%2F2020&ordering=-total_forecast_budget") + self.assertEqual(response.status_code, 200) + js = response.json() + self.assertEquals(js["count"], 1) + self.assertEquals(len(js["results"]["projects"]), 1) + + response = self.client.get( + "/api/v1/infrastructure/search/?q=Acquisition&budget_phase=Budget+year&quarterly_phase=Original+Budget&financial_year=2019%2F2020&ordering=-total_forecast_budget") + self.assertEqual(response.status_code, 200) + js = response.json() + self.assertEquals(js["count"], 1) + self.assertEquals(len(js["results"]["projects"]), 1)
fa0d478aeb167422a56d6e9e8c3e0a35947765e9
pipeline_notifier_test/routes_test.py
pipeline_notifier_test/routes_test.py
import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): def test_route_setup_works(self): setup_routes(Mock(), [])
import unittest from unittest.mock import Mock from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): def setUp(self): self.pipeline = Mock() self.app = AppMock() setup_routes(self.app, [self.pipeline]) def test_root_route_returns_something(self): result = self.app['/']() self.assertNotEqual(result, None) class AppMock: """ Acts as a mock flask app, but only recording the routes, so they can be then easily accessed for testing later. """ def __init__(self): self.routes = {} def route(self, route): return self.decoratorFor(route) def decoratorFor(self, route): def decorator(routeTarget): self.routes[route] = routeTarget return routeTarget return decorator def __getitem__(self, item): return self.routes[item]
Add framework for unit testing flask routes
Add framework for unit testing flask routes
Python
mit
pimterry/pipeline-notifier
--- +++ @@ -3,5 +3,32 @@ from pipeline_notifier.routes import setup_routes class RoutesTests(unittest.TestCase): - def test_route_setup_works(self): - setup_routes(Mock(), []) + def setUp(self): + self.pipeline = Mock() + self.app = AppMock() + setup_routes(self.app, [self.pipeline]) + + def test_root_route_returns_something(self): + result = self.app['/']() + self.assertNotEqual(result, None) + +class AppMock: + """ + Acts as a mock flask app, but only recording the routes, + so they can be then easily accessed for testing later. + """ + + def __init__(self): + self.routes = {} + + def route(self, route): + return self.decoratorFor(route) + + def decoratorFor(self, route): + def decorator(routeTarget): + self.routes[route] = routeTarget + return routeTarget + return decorator + + def __getitem__(self, item): + return self.routes[item]
06b9982ea716daa627a0beb700721c7ca53601fd
run.py
run.py
#!/usr/bin/env python if __name__ == '__main__': import os import sys if sys.version_info[0:2] < (3, 4): raise SystemExit('python 3.4+ is required') root_path = os.path.abspath(os.path.dirname(__file__)) try: import mtp_common # NB: this version does not need to be updated unless mtp_common changes significantly if mtp_common.VERSION < (10,): raise ImportError except ImportError: try: import pkg_resources except ImportError: raise SystemExit('setuptools and pip are required') try: pip = pkg_resources.load_entry_point('pip', 'console_scripts', 'pip') except pkg_resources.ResolutionError: raise SystemExit('setuptools and pip are required') print('Pre-installing MTP-common and base requirements') pip(['install', '--requirement', f'{root_path}/requirements/base.txt']) from mtp_common.build_tasks.executor import Executor import mtp_transaction_uploader.build_tasks # noqa exit(Executor(root_path=root_path).run())
#!/usr/bin/env python if __name__ == '__main__': import os import sys if sys.version_info[0:2] < (3, 6): raise SystemExit('Python 3.6+ is required') root_path = os.path.abspath(os.path.dirname(__file__)) try: import mtp_common # NB: this version does not need to be updated unless mtp_common changes significantly if mtp_common.VERSION < (10,): raise ImportError except ImportError: try: import pkg_resources except ImportError: raise SystemExit('setuptools and pip are required') try: pip = pkg_resources.load_entry_point('pip', 'console_scripts', 'pip') except pkg_resources.ResolutionError: raise SystemExit('setuptools and pip are required') print('Pre-installing MTP-common and base requirements') pip(['install', '--requirement', f'{root_path}/requirements/base.txt']) from mtp_common.build_tasks.executor import Executor import mtp_transaction_uploader.build_tasks # noqa exit(Executor(root_path=root_path).run())
Support only python versions 3.6+ explicitly …which has been the assumption for a while as 3.6 features are already in use and base docker images use 3.6.
Support only python versions 3.6+ explicitly …which has been the assumption for a while as 3.6 features are already in use and base docker images use 3.6.
Python
mit
ministryofjustice/money-to-prisoners-transaction-uploader
--- +++ @@ -3,8 +3,8 @@ import os import sys - if sys.version_info[0:2] < (3, 4): - raise SystemExit('python 3.4+ is required') + if sys.version_info[0:2] < (3, 6): + raise SystemExit('Python 3.6+ is required') root_path = os.path.abspath(os.path.dirname(__file__))
b996e2642cf46da5e99857060c5d2bd0107d8e62
troposphere/__init__.py
troposphere/__init__.py
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def application(path): return render_template('application.html') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/login') def login(): return "LOGIN!" @app.route('/logout') def logout(): return "LOGOUT!" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def application(path): return render_template('application.html') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
Add login and logout stubs
Add login and logout stubs
Python
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
--- +++ @@ -2,6 +2,14 @@ from flask import render_template app = Flask(__name__) + +@app.route('/login') +def login(): + return "LOGIN!" + +@app.route('/logout') +def logout(): + return "LOGOUT!" @app.route('/', defaults={'path': ''}) @app.route('/<path:path>')
a44eecac4306504e7d3e6b8253deeb35e6b1fb43
numpy/typing/setup.py
numpy/typing/setup.py
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('typing', parent_package, top_path) config.add_subpackage('tests') config.add_data_dir('tests/data') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('typing', parent_package, top_path) config.add_subpackage('tests') config.add_data_dir('tests/data') config.add_data_files('*.pyi') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
Add `.pyi` data files to the `numpy.typing` sub-package
BLD: Add `.pyi` data files to the `numpy.typing` sub-package
Python
bsd-3-clause
mattip/numpy,jakirkham/numpy,seberg/numpy,rgommers/numpy,anntzer/numpy,numpy/numpy,numpy/numpy,charris/numpy,jakirkham/numpy,anntzer/numpy,charris/numpy,pdebuyl/numpy,rgommers/numpy,charris/numpy,mattip/numpy,rgommers/numpy,simongibbons/numpy,mattip/numpy,jakirkham/numpy,pdebuyl/numpy,endolith/numpy,anntzer/numpy,seberg/numpy,endolith/numpy,pdebuyl/numpy,simongibbons/numpy,seberg/numpy,pdebuyl/numpy,anntzer/numpy,simongibbons/numpy,numpy/numpy,simongibbons/numpy,endolith/numpy,mhvk/numpy,jakirkham/numpy,mattip/numpy,jakirkham/numpy,seberg/numpy,mhvk/numpy,simongibbons/numpy,rgommers/numpy,mhvk/numpy,endolith/numpy,numpy/numpy,mhvk/numpy,mhvk/numpy,charris/numpy
--- +++ @@ -3,6 +3,7 @@ config = Configuration('typing', parent_package, top_path) config.add_subpackage('tests') config.add_data_dir('tests/data') + config.add_data_files('*.pyi') return config
95e2ee8c1969dc335237dd27221049fe6fc51111
django_emarsys/api.py
django_emarsys/api.py
# -*- coding: utf-8 -*- import emarsys from django.conf import settings client = emarsys.Emarsys(settings.EMARSYS_ACCOUNT, settings.EMARSYS_PASSWORD, settings.EMARSYS_BASE_URI) def get_events(): response = client.call('/api/v2/event', 'GET') return {event['name']: event['id'] for event in response} def trigger_event(event_id, email, context): client.call( '/api/v2/event/{}/trigger'.format(event_id), 'POST', { "key_id": 3, "external_id": email, "data": context } ) def create_contact(email): client.call('/api/v2/contact', 'POST', {"3": email})
# -*- coding: utf-8 -*- import emarsys from django.conf import settings client = emarsys.Emarsys(settings.EMARSYS_ACCOUNT, settings.EMARSYS_PASSWORD, settings.EMARSYS_BASE_URI) def get_events(): response = client.call('/api/v2/event', 'GET') return {event['name']: int(event['id']) for event in response} def trigger_event(event_id, email, context): client.call( '/api/v2/event/{}/trigger'.format(event_id), 'POST', { "key_id": 3, "external_id": email, "data": context } ) def create_contact(email): client.call('/api/v2/contact', 'POST', {"3": email})
Return event ids as int
Return event ids as int
Python
mit
machtfit/django-emarsys,machtfit/django-emarsys
--- +++ @@ -12,7 +12,7 @@ def get_events(): response = client.call('/api/v2/event', 'GET') - return {event['name']: event['id'] for event in response} + return {event['name']: int(event['id']) for event in response} def trigger_event(event_id, email, context):
4580913b9f8ef692e3417a9b04e88a34ff69716d
download_summaries.py
download_summaries.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils.summary_downloader import SummaryDownloader if __name__ == '__main__': # setting target dir and time interval of interest tgt_dir = r"D:\nhl\official_and_json\2016-17" tgt_dir = r"d:\tmp\test" date = "2017/04/03" to_date = "2017/04/03" downloader = SummaryDownloader(tgt_dir, date, to_date, workers=1) downloader.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils.summary_downloader import SummaryDownloader if __name__ == '__main__': # setting target dir and time interval of interest tgt_dir = r"D:\nhl\official_and_json\2016-17" tgt_dir = r"d:\tmp\test" date = "2017/05/01" to_date = "2017/05/01" downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8) downloader.run()
Adjust number of download workers
Adjust number of download workers
Python
mit
leaffan/pynhldb
--- +++ @@ -9,8 +9,8 @@ tgt_dir = r"D:\nhl\official_and_json\2016-17" tgt_dir = r"d:\tmp\test" - date = "2017/04/03" - to_date = "2017/04/03" + date = "2017/05/01" + to_date = "2017/05/01" - downloader = SummaryDownloader(tgt_dir, date, to_date, workers=1) + downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8) downloader.run()
70cfff61c8b3841e71674da0b13c6fc8eee3e924
api/institutions/serializers.py
api/institutions/serializers.py
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField class InstitutionSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'id', 'name' ]) name = ser.CharField(read_only=True) id = ser.CharField(read_only=True, source='_id') logo_path = ser.CharField(read_only=True) auth_url = ser.CharField(read_only=True) links = LinksField({'self': 'get_api_url', }) nodes = RelationshipField( related_view='institutions:institution-nodes', related_view_kwargs={'institution_id': '<pk>'}, ) registrations = RelationshipField( related_view='institutions:institution-registrations', related_view_kwargs={'institution_id': '<pk>'} ) users = RelationshipField( related_view='institutions:institution-users', related_view_kwargs={'institution_id': '<pk>'} ) def get_api_url(self, obj): return obj.absolute_api_v2_url class Meta: type_ = 'institutions'
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer, RelationshipField, LinksField class InstitutionSerializer(JSONAPISerializer): filterable_fields = frozenset([ 'id', 'name' ]) name = ser.CharField(read_only=True) id = ser.CharField(read_only=True, source='_id') logo_path = ser.CharField(read_only=True) auth_url = ser.CharField(read_only=True) links = LinksField({'self': 'get_api_url', }) nodes = RelationshipField( related_view='institutions:institution-nodes', related_view_kwargs={'institution_id': '<pk>'}, ) registrations = RelationshipField( related_view='institutions:institution-registrations', related_view_kwargs={'institution_id': '<pk>'} ) users = RelationshipField( related_view='institutions:institution-users', related_view_kwargs={'institution_id': '<pk>'} ) def get_api_url(self, obj): return obj.absolute_api_v2_url def get_absolute_url(self, obj): return obj.absolute_api_v2_url class Meta: type_ = 'institutions'
Add get_absolute_url method to institutions
Add get_absolute_url method to institutions
Python
apache-2.0
zamattiac/osf.io,doublebits/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,chennan47/osf.io,mluo613/osf.io,jnayak1/osf.io,Nesiehr/osf.io,leb2dg/osf.io,caneruguz/osf.io,SSJohns/osf.io,mluke93/osf.io,sloria/osf.io,hmoco/osf.io,binoculars/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,binoculars/osf.io,chrisseto/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,acshi/osf.io,brandonPurvis/osf.io,icereval/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,chrisseto/osf.io,doublebits/osf.io,TomBaxter/osf.io,mluke93/osf.io,pattisdr/osf.io,kwierman/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,doublebits/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,acshi/osf.io,asanfilippo7/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,rdhyee/osf.io,leb2dg/osf.io,cslzchen/osf.io,sloria/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,adlius/osf.io,TomBaxter/osf.io,felliott/osf.io,SSJohns/osf.io,icereval/osf.io,RomanZWang/osf.io,amyshi188/osf.io,billyhunt/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,emetsger/osf.io,zamattiac/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,TomHeatwole/osf.io,abought/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,wearpants/osf.io,zachjanicki/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,doublebits/osf.io,felliott/osf.io,GageGaskins/osf.io,Johnetordoff/osf.io,mluke93/osf.io,asanfilippo7/osf.io,brianjgeiger/osf.io,KAsante95/osf.io,adlius/osf.io,zachjanicki/osf.io,wearpants/osf.io,wearpants/osf.io,laurenrevere/osf.io,billyhunt/osf.io,amyshi188/osf.io,hmoco/osf.io,cwisecarver/osf.io,SSJohns/osf.io,jnayak1/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,GageGaskins/osf.io,adlius/osf.io,brianjgeiger/osf.io,wearpants/osf.io,billyhunt/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,erinspace/osf.io,mluo613/osf.io,alexschiller/osf.io,pattisdr/osf.io,chennan47/osf.io,asanfilippo7/osf.io,crcresearch/osf.io,jnayak1/osf.io,abought/osf.io,mfraezz/osf.io,mfraezz/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,icereval/osf.io,mattclark/osf.io,alexschiller/osf.io,acshi/osf.io,billyhunt/osf.io,emetsger/osf.io,Nesiehr/osf.io,abought/osf.io,erinspace/osf.io,caseyrollins/osf.io,erinspace/osf.io,cslzchen/osf.io,felliott/osf.io,laurenrevere/osf.io,felliott/osf.io,hmoco/osf.io,zachjanicki/osf.io,kwierman/osf.io,caneruguz/osf.io,GageGaskins/osf.io,TomBaxter/osf.io,aaxelb/osf.io,alexschiller/osf.io,emetsger/osf.io,mluo613/osf.io,Nesiehr/osf.io,kch8qx/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,acshi/osf.io,mluo613/osf.io,kch8qx/osf.io,cwisecarver/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,KAsante95/osf.io,RomanZWang/osf.io,kwierman/osf.io,GageGaskins/osf.io,alexschiller/osf.io,kch8qx/osf.io,cwisecarver/osf.io,zachjanicki/osf.io,kch8qx/osf.io,CenterForOpenScience/osf.io,kch8qx/osf.io,emetsger/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,caneruguz/osf.io,caseyrollins/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,adlius/osf.io,crcresearch/osf.io,mluo613/osf.io,pattisdr/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,baylee-d/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,binoculars/osf.io,mattclark/osf.io,mattclark/osf.io,kwierman/osf.io,amyshi188/osf.io,chennan47/osf.io,mfraezz/osf.io,sloria/osf.io,KAsante95/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,brandonPurvis/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,caneruguz/osf.io,acshi/osf.io,mluke93/osf.io,abought/osf.io,leb2dg/osf.io,zamattiac/osf.io,samchrisinger/osf.io,doublebits/osf.io,chrisseto/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,saradbowman/osf.io,baylee-d/osf.io,chrisseto/osf.io
--- +++ @@ -33,5 +33,8 @@ def get_api_url(self, obj): return obj.absolute_api_v2_url + def get_absolute_url(self, obj): + return obj.absolute_api_v2_url + class Meta: type_ = 'institutions'
e2d74754ad42f412b8344257cb3c1c9943931b17
test/integration/ggrc/models/test_control.py
test/integration/ggrc/models/test_control.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models import Control from integration.ggrc import TestCase from .factories import ControlCategoryFactory, ControlFactory from nose.plugins.skip import SkipTest from nose.tools import assert_in, eq_ class TestControl(TestCase): def test_simple_categorization(self): category = ControlCategoryFactory(scope_id=100) control = ControlFactory() control.categories.append(category) db.session.commit() self.assertIn(category, control.categories) # be really really sure control = db.session.query(Control).get(control.id) self.assertIn(category, control.categories) def test_has_test_plan(self): control = ControlFactory(test_plan="This is a test text") db.session.commit() control = db.session.query(Control).get(control.id) eq_(control.test_plan, "This is a test text")
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Tests for control model.""" from ggrc import db from ggrc.models import Control from integration.ggrc import TestCase from integration.ggrc.models import factories class TestControl(TestCase): def test_simple_categorization(self): category = factories.ControlCategoryFactory(scope_id=100) control = factories.ControlFactory() control.categories.append(category) db.session.commit() self.assertIn(category, control.categories) # be really really sure control = db.session.query(Control).get(control.id) self.assertIn(category, control.categories) def test_has_test_plan(self): control = factories.ControlFactory(test_plan="This is a test text") control = db.session.query(Control).get(control.id) self.assertEqual(control.test_plan, "This is a test text")
Clean up control model tests
Clean up control model tests
Python
apache-2.0
plamut/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core
--- +++ @@ -1,18 +1,17 @@ - # Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> + +"""Tests for control model.""" from ggrc import db from ggrc.models import Control from integration.ggrc import TestCase -from .factories import ControlCategoryFactory, ControlFactory -from nose.plugins.skip import SkipTest -from nose.tools import assert_in, eq_ +from integration.ggrc.models import factories class TestControl(TestCase): def test_simple_categorization(self): - category = ControlCategoryFactory(scope_id=100) - control = ControlFactory() + category = factories.ControlCategoryFactory(scope_id=100) + control = factories.ControlFactory() control.categories.append(category) db.session.commit() self.assertIn(category, control.categories) @@ -21,8 +20,6 @@ self.assertIn(category, control.categories) def test_has_test_plan(self): - control = ControlFactory(test_plan="This is a test text") - db.session.commit() - + control = factories.ControlFactory(test_plan="This is a test text") control = db.session.query(Control).get(control.id) - eq_(control.test_plan, "This is a test text") + self.assertEqual(control.test_plan, "This is a test text")
fbb3c38417e85f327e6a347338a005162779314b
run_tests.py
run_tests.py
from __future__ import print_function import os import imp import fnmatch # Test directory DIR_TEST = 'tests' def find_tests(pathname): """Recursively finds the test modules. :param str pathname: Path name where the tests are stored. :returns: List of paths to each test modules. :rtype: :class:`list` """ founds = [] for base, _, files in os.walk(pathname): founds.extend(( (matched_file, base) for matched_file in fnmatch.filter(files, '*.py') if matched_file != "__init__.py")) return founds def run_tests(pathnames): """Loads each test module and run their `run` function. :param list pathnames: List of (module_name, path_to_the_module). """ for module, path in pathnames: current_mod = imp.load_source( os.path.splitext(module)[0], os.path.join(path, module)) print("Testing:", current_mod.__testname__) current_mod.run() if __name__ == '__main__': run_tests(find_tests(os.path.join(os.getcwd(), DIR_TEST)))
from __future__ import print_function import os import sys import imp import fnmatch # Test directory DIR_TEST = 'tests' def find_tests(pathname): """Recursively finds the test modules. :param str pathname: Path name where the tests are stored. :returns: List of paths to each test modules. :rtype: :class:`list` """ founds = [] for base, _, files in os.walk(pathname): founds.extend(( (matched_file, base) for matched_file in fnmatch.filter(files, '*.py') if matched_file != "__init__.py")) return founds def run_tests(pathnames, test_name=None): """Loads each test module and run their `run` function. :param list pathnames: List of (module_name, path_to_the_module). """ for module, path in pathnames: current_mod = imp.load_source( os.path.splitext(module)[0], os.path.join(path, module)) if test_name and test_name != current_mod.__testname__: continue print("Testing:", current_mod.__testname__) current_mod.run() if __name__ == '__main__': test_name = None if len(sys.argv) == 2: test_name = sys.argv[1] run_tests(find_tests(os.path.join(os.getcwd(), DIR_TEST)), test_name)
Allow to chose a specific case test.
[tests] Allow to chose a specific case test.
Python
bsd-3-clause
owtf/ptp,DoomTaper/ptp
--- +++ @@ -1,6 +1,7 @@ from __future__ import print_function import os +import sys import imp import fnmatch @@ -26,7 +27,7 @@ return founds -def run_tests(pathnames): +def run_tests(pathnames, test_name=None): """Loads each test module and run their `run` function. :param list pathnames: List of (module_name, path_to_the_module). @@ -36,9 +37,14 @@ current_mod = imp.load_source( os.path.splitext(module)[0], os.path.join(path, module)) + if test_name and test_name != current_mod.__testname__: + continue print("Testing:", current_mod.__testname__) current_mod.run() if __name__ == '__main__': - run_tests(find_tests(os.path.join(os.getcwd(), DIR_TEST))) + test_name = None + if len(sys.argv) == 2: + test_name = sys.argv[1] + run_tests(find_tests(os.path.join(os.getcwd(), DIR_TEST)), test_name)
5ee6e2ce3854d8ca60b5aedfb21cd61172511a8f
hrmpy/tests/test_parser.py
hrmpy/tests/test_parser.py
import pytest from hrmpy import parser def test_parse_program_empty(): with pytest.raises(RuntimeError): parser.parse_program("") def test_parse_program_no_header(): with pytest.raises(RuntimeError): parser.parse_program("\n".join([ "INBOX", "OUTBOX", ])) def test_parse_program_header_only(): ops = parser.parse_program("-- HUMAN RESOURCE MACHINE PROGRAM --") assert ops == []
import pytest from hrmpy import parser class TestParseProgram(object): def test_empty_program(self): """ An empty string is not a program. """ with pytest.raises(RuntimeError): parser.parse_program("") def test_no_header(self): """ A program without a header is not a program. """ with pytest.raises(RuntimeError): parser.parse_program("\n".join([ "INBOX", "OUTBOX", ])) def test_header_only(self): """ A header on its own is an empty program. """ ops = parser.parse_program("-- HUMAN RESOURCE MACHINE PROGRAM --") assert ops == [] def test_header_after_nonsense(self): """ Anything before the header is ignored. """ ops = parser.parse_program("\n".join([ "This is an empty program.", "", "It is my empty program, but you can have it if you want.", "-- HUMAN RESOURCE MACHINE PROGRAM --", ])) assert ops == [] def test_small_program(self): """ A header followed by instructions is a valid program. """ ops = parser.parse_program("\n".join([ "-- HUMAN RESOURCE MACHINE PROGRAM --", "INBOX", "OUTBOX", ])) assert map(str, ops) == ['INBOX', 'OUTBOX'] def test_small_program_after_nonsense(self): """ A program can include documentation or whatever before the header. """ ops = parser.parse_program("\n".join([ "This is a small program that copies a single value from input", "to output.", "", "-- HUMAN RESOURCE MACHINE PROGRAM --", "INBOX", "OUTBOX", ])) assert map(str, ops) == ['INBOX', 'OUTBOX']
Test a (very) few more things.
Test a (very) few more things.
Python
mit
jerith/hrmpy
--- +++ @@ -3,19 +3,65 @@ from hrmpy import parser -def test_parse_program_empty(): - with pytest.raises(RuntimeError): - parser.parse_program("") +class TestParseProgram(object): + def test_empty_program(self): + """ + An empty string is not a program. + """ + with pytest.raises(RuntimeError): + parser.parse_program("") -def test_parse_program_no_header(): - with pytest.raises(RuntimeError): - parser.parse_program("\n".join([ + def test_no_header(self): + """ + A program without a header is not a program. + """ + with pytest.raises(RuntimeError): + parser.parse_program("\n".join([ + "INBOX", + "OUTBOX", + ])) + + def test_header_only(self): + """ + A header on its own is an empty program. + """ + ops = parser.parse_program("-- HUMAN RESOURCE MACHINE PROGRAM --") + assert ops == [] + + def test_header_after_nonsense(self): + """ + Anything before the header is ignored. + """ + ops = parser.parse_program("\n".join([ + "This is an empty program.", + "", + "It is my empty program, but you can have it if you want.", + "-- HUMAN RESOURCE MACHINE PROGRAM --", + ])) + assert ops == [] + + def test_small_program(self): + """ + A header followed by instructions is a valid program. + """ + ops = parser.parse_program("\n".join([ + "-- HUMAN RESOURCE MACHINE PROGRAM --", "INBOX", "OUTBOX", ])) + assert map(str, ops) == ['INBOX', 'OUTBOX'] - -def test_parse_program_header_only(): - ops = parser.parse_program("-- HUMAN RESOURCE MACHINE PROGRAM --") - assert ops == [] + def test_small_program_after_nonsense(self): + """ + A program can include documentation or whatever before the header. + """ + ops = parser.parse_program("\n".join([ + "This is a small program that copies a single value from input", + "to output.", + "", + "-- HUMAN RESOURCE MACHINE PROGRAM --", + "INBOX", + "OUTBOX", + ])) + assert map(str, ops) == ['INBOX', 'OUTBOX']
e0510d5161ad42ce265d5fc0d5e22147f4f0033c
dsub/_dsub_version.py
dsub/_dsub_version.py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.11.dev0'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.0'
Update dsub version to 0.4.0
Update dsub version to 0.4.0 PiperOrigin-RevId: 328430334
Python
apache-2.0
DataBiosphere/dsub,DataBiosphere/dsub
--- +++ @@ -26,4 +26,4 @@ 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ -DSUB_VERSION = '0.3.11.dev0' +DSUB_VERSION = '0.4.0'
c88478f399417e2099e90d9b445c2a7bfb57af70
aspc/senate/views.py
aspc/senate/views.py
from django.views.generic import ListView from aspc.senate.models import Document, Appointment import datetime class DocumentList(ListView): model = Document context_object_name = 'documents' paginate_by = 20 class AppointmentList(ListView): model = Appointment context_object_name = 'appointments' def get_queryset(self, *args, **kwargs): qs = super(AppointmentList, self).get_queryset(*args, **kwargs) qs.filter(end__isnull=True) qs |= qs.filter(end__gte=datetime.datetime.now()) qs = qs.order_by('position__sort_order') return qs
from django.views.generic import ListView from aspc.senate.models import Document, Appointment import datetime class DocumentList(ListView): model = Document context_object_name = 'documents' paginate_by = 20 class AppointmentList(ListView): model = Appointment context_object_name = 'appointments' def get_queryset(self, *args, **kwargs): qs = super(AppointmentList, self).get_queryset(*args, **kwargs) qs = qs.filter(end__isnull=True) qs |= qs.filter(end__gte=datetime.datetime.now()) qs = qs.order_by('position__sort_order') return qs
Correct typo in Appointments view
Correct typo in Appointments view
Python
mit
theworldbright/mainsite,aspc/mainsite,theworldbright/mainsite,aspc/mainsite,aspc/mainsite,theworldbright/mainsite,aspc/mainsite,theworldbright/mainsite
--- +++ @@ -13,7 +13,7 @@ def get_queryset(self, *args, **kwargs): qs = super(AppointmentList, self).get_queryset(*args, **kwargs) - qs.filter(end__isnull=True) + qs = qs.filter(end__isnull=True) qs |= qs.filter(end__gte=datetime.datetime.now()) qs = qs.order_by('position__sort_order') return qs
a44665230d2b589a1550b1293cb690d9116d0dca
acme/__init__.py
acme/__init__.py
# python3 # Copyright 2018 DeepMind Technologies Limited. 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. """Acme is a framework for reinforcement learning.""" # Internal import. # Expose specs and types modules. from acme import specs from acme import types # Make __version__ accessible. from acme._metadata import __version__ # Expose core interfaces. from acme.core import Actor from acme.core import Learner from acme.core import Saveable from acme.core import VariableSource from acme.core import Worker # Expose the environment loop. from acme.environment_loop import EnvironmentLoop from acme.specs import make_environment_spec # Acme loves you.
# Copyright 2018 DeepMind Technologies Limited. 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. """Acme is a framework for reinforcement learning.""" # Internal import. # Expose specs and types modules. from acme import specs from acme import types # Make __version__ accessible. from acme._metadata import __version__ # Expose core interfaces. from acme.core import Actor from acme.core import Learner from acme.core import Saveable from acme.core import VariableSource from acme.core import Worker # Expose the environment loop. from acme.environment_loop import EnvironmentLoop from acme.specs import make_environment_spec # Acme loves you.
Remove unused comments related to Python 2 compatibility.
Remove unused comments related to Python 2 compatibility. PiperOrigin-RevId: 440310765 Change-Id: I7afdea122cd2565b06f387509de2476106d46d8c
Python
apache-2.0
deepmind/acme,deepmind/acme
--- +++ @@ -1,4 +1,3 @@ -# python3 # Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License");
ea315b018fb3fab6925f1194fcd3e341166ab6fb
opt/resource/common.py
opt/resource/common.py
import json from urllib.parse import urljoin import sys def get_payload(): return json.load(sys.stdin) def get_index_url(payload): source = payload['source'] uri = source['uri'] index = source['index'] if not uri.endswith('/'): uri += '/' if not index.endswith('/'): index += '/' return urljoin(uri, index) def get_package_url(payload): package = payload['source']['package'] return get_index_url(payload) + package def get_auth(payload): source = payload['source'] return source['username'], source['password'] def get_version(payload): if 'version' in payload: version = payload['version']['version'] else: version = None return version
import json from urllib.parse import urljoin import sys def get_payload(): return json.load(sys.stdin) def get_index_url(payload): source = payload['source'] uri = source['uri'] index = source['index'] if not uri.endswith('/'): uri += '/' if not index.endswith('/'): index += '/' return urljoin(uri, index) def get_package_url(payload): package = payload['source']['package'] return get_index_url(payload) + package def get_auth(payload): source = payload['source'] return source['username'], source['password'] def get_version(payload): try: version = payload['version']['version'] except TypeError: version = None return version
Handle missing version in payload.
Handle missing version in payload.
Python
mit
mdomke/concourse-devpi-resource
--- +++ @@ -29,8 +29,8 @@ def get_version(payload): - if 'version' in payload: + try: version = payload['version']['version'] - else: + except TypeError: version = None return version
37178102a9518d73b4e2040ac8cbb622663f9afd
{{cookiecutter.project_slug}}/config/urls.py
{{cookiecutter.project_slug}}/config/urls.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), # Django Admin, use {% raw %}{% url 'admin:index' %}{% endraw %} url(settings.ADMIN_URL, include(admin.site.urls)), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: # This allows the error pages to be debugged during development, just visit # these url in browser to see how these error pages look like. urlpatterns += [ url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), url(r'^500/$', default_views.server_error), ] if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), # Django Admin, use {% raw %}{% url 'admin:index' %}{% endraw %} url(settings.ADMIN_URL, include(admin.site.urls)), # Your stuff: custom urls includes go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: # This allows the error pages to be debugged during development, just visit # these url in browser to see how these error pages look like. urlpatterns += [ url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), url(r'^500/$', default_views.server_error), ] if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
Include Debug Toolbar URLs only in debug mode
Include Debug Toolbar URLs only in debug mode
Python
bsd-3-clause
valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp
--- +++ @@ -27,10 +27,9 @@ url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), url(r'^500/$', default_views.server_error), ] + if 'debug_toolbar' in settings.INSTALLED_APPS: + import debug_toolbar -if 'debug_toolbar' in settings.INSTALLED_APPS: - import debug_toolbar - - urlpatterns += [ - url(r'^__debug__/', include(debug_toolbar.urls)), - ] + urlpatterns += [ + url(r'^__debug__/', include(debug_toolbar.urls)), + ]
cf0fa32efc6d89aad5d569ad59aefb66e9f7df12
wsgiservice/__init__.py
wsgiservice/__init__.py
"""This root level directives are importend from the submodules. They are made available here as well to keep the number of imports to a minimum for most applications. """ import wsgiservice.routing from wsgiservice.decorators import mount, validate, expires from wsgiservice.objects import Response from wsgiservice.application import get_app from wsgiservice.resource import Resource from wsgiservice.status import * class duration(object): def __getattr__(self, key): print "duration: {0}".format(key) return key duration = duration()
"""This root level directives are importend from the submodules. They are made available here as well to keep the number of imports to a minimum for most applications. """ import wsgiservice.routing from wsgiservice.decorators import mount, validate, expires from wsgiservice.objects import Response from wsgiservice.application import get_app from wsgiservice.resource import Resource from wsgiservice.status import *
Remove the unused duration access.
Remove the unused duration access.
Python
bsd-2-clause
pneff/wsgiservice,beekpr/wsgiservice
--- +++ @@ -8,9 +8,3 @@ from wsgiservice.application import get_app from wsgiservice.resource import Resource from wsgiservice.status import * - -class duration(object): - def __getattr__(self, key): - print "duration: {0}".format(key) - return key -duration = duration()
f1ef0652acdd9211f8e39eb57845251e7ccc496e
commands.py
commands.py
import generate as gen commands = {} def cmd_func(name): def _cmd_func(f): commands.setdefault(name, f) return f return _cmd_func @cmd_func('get-latest-rev') def get_latest_rev(args): return "%s %s" % (gen.success('( )', gen.string('test')), gen.success('12')) def handle_command(msg): command = msg[0] args = msg [1] if command not in commands: return gen.failure(gen.list('12', gen.string('unknown command: %s' % command), gen.string('commands.py'), '0')) return commands[command](args)
import generate as gen commands = {} def cmd_func(name): def _cmd_func(f): commands.setdefault(name, f) return f return _cmd_func @cmd_func('get-latest-rev') def get_latest_rev(args): return "%s %s" % (gen.success('( )', gen.string('test')), gen.success('12')) def handle_command(msg): command = msg[0] args = msg [1] if command not in commands: return gen.failure(gen.list('210001', gen.string("Unknown command '%s'" % command), gen.string('commands.py'), '0')) return commands[command](args)
Use the real unknown command err-code
Use the real unknown command err-code Using the real unknown command error code means that the client actually understands the error and behaves appropriately.
Python
bsd-3-clause
slonopotamus/git_svn_server
--- +++ @@ -19,8 +19,8 @@ args = msg [1] if command not in commands: - return gen.failure(gen.list('12', - gen.string('unknown command: %s' % command), + return gen.failure(gen.list('210001', + gen.string("Unknown command '%s'" % command), gen.string('commands.py'), '0')) return commands[command](args)
9d4908d28efd31a16a47bdfaf09895913dc2977f
sympy/utilities/tests/test_timeutils.py
sympy/utilities/tests/test_timeutils.py
"""Tests for simple tools for timing functions' execution. """ from sympy.utilities.timeutils import timed def test_timed(): result = timed(lambda: 1 + 1, limit=100000) assert result[0] == 100000 and result[3] == "ns" result = timed("1 + 1", limit=100000) assert result[0] == 100000 and result[3] == "ns"
"""Tests for simple tools for timing functions' execution. """ import sys if sys.version_info[:2] <= (2, 5): disabled = True from sympy.utilities.timeutils import timed def test_timed(): result = timed(lambda: 1 + 1, limit=100000) assert result[0] == 100000 and result[3] == "ns" result = timed("1 + 1", limit=100000) assert result[0] == 100000 and result[3] == "ns"
Disable timed() tests on Python 2.5
utilities: Disable timed() tests on Python 2.5
Python
bsd-3-clause
jbbskinny/sympy,kumarkrishna/sympy,oliverlee/sympy,shipci/sympy,yashsharan/sympy,meghana1995/sympy,vipulroxx/sympy,Vishluck/sympy,drufat/sympy,cswiercz/sympy,MechCoder/sympy,mcdaniel67/sympy,saurabhjn76/sympy,jaimahajan1997/sympy,dqnykamp/sympy,rahuldan/sympy,AunShiLord/sympy,Sumith1896/sympy,pandeyadarsh/sympy,shikil/sympy,jamesblunt/sympy,ChristinaZografou/sympy,jerli/sympy,wyom/sympy,jaimahajan1997/sympy,hargup/sympy,oliverlee/sympy,mafiya69/sympy,souravsingh/sympy,liangjiaxing/sympy,rahuldan/sympy,beni55/sympy,hargup/sympy,oliverlee/sympy,drufat/sympy,wanglongqi/sympy,yukoba/sympy,sahilshekhawat/sympy,aktech/sympy,chaffra/sympy,wanglongqi/sympy,sahmed95/sympy,kaushik94/sympy,Titan-C/sympy,liangjiaxing/sympy,chaffra/sympy,shipci/sympy,AkademieOlympia/sympy,skidzo/sympy,kaichogami/sympy,skidzo/sympy,Arafatk/sympy,ChristinaZografou/sympy,jaimahajan1997/sympy,hrashk/sympy,sampadsaha5/sympy,bukzor/sympy,beni55/sympy,madan96/sympy,cccfran/sympy,Curious72/sympy,mafiya69/sympy,sunny94/temp,maniteja123/sympy,garvitr/sympy,Curious72/sympy,kumarkrishna/sympy,pandeyadarsh/sympy,yukoba/sympy,lidavidm/sympy,amitjamadagni/sympy,lindsayad/sympy,wanglongqi/sympy,Shaswat27/sympy,shikil/sympy,diofant/diofant,postvakje/sympy,atreyv/sympy,pbrady/sympy,debugger22/sympy,atsao72/sympy,yashsharan/sympy,Gadal/sympy,hrashk/sympy,atsao72/sympy,Mitchkoens/sympy,MechCoder/sympy,garvitr/sympy,Designist/sympy,beni55/sympy,Arafatk/sympy,cswiercz/sympy,sahilshekhawat/sympy,souravsingh/sympy,rahuldan/sympy,jamesblunt/sympy,ChristinaZografou/sympy,meghana1995/sympy,meghana1995/sympy,grevutiu-gabriel/sympy,Curious72/sympy,moble/sympy,cswiercz/sympy,jbbskinny/sympy,sunny94/temp,VaibhavAgarwalVA/sympy,toolforger/sympy,AkademieOlympia/sympy,farhaanbukhsh/sympy,kevalds51/sympy,kaushik94/sympy,kevalds51/sympy,MridulS/sympy,Shaswat27/sympy,maniteja123/sympy,ga7g08/sympy,ahhda/sympy,emon10005/sympy,Sumith1896/sympy,garvitr/sympy,yashsharan/sympy,VaibhavAgarwalVA/sympy,skidzo/sympy,Titan-C/sympy,iamutkarshtiwari/sympy,toolforger/sympy,Davidjohnwilson/sympy,jerli/sympy,moble/sympy,grevutiu-gabriel/sympy,pbrady/sympy,Arafatk/sympy,madan96/sympy,aktech/sympy,kaichogami/sympy,Vishluck/sympy,sunny94/temp,mafiya69/sympy,kumarkrishna/sympy,abloomston/sympy,toolforger/sympy,Sumith1896/sympy,lindsayad/sympy,ahhda/sympy,jbbskinny/sympy,liangjiaxing/sympy,drufat/sympy,sampadsaha5/sympy,pandeyadarsh/sympy,asm666/sympy,moble/sympy,farhaanbukhsh/sympy,postvakje/sympy,yukoba/sympy,shipci/sympy,VaibhavAgarwalVA/sympy,jerli/sympy,AkademieOlympia/sympy,saurabhjn76/sympy,lidavidm/sympy,jamesblunt/sympy,dqnykamp/sympy,kmacinnis/sympy,skirpichev/omg,mcdaniel67/sympy,abhiii5459/sympy,AunShiLord/sympy,hargup/sympy,sahmed95/sympy,shikil/sympy,atsao72/sympy,grevutiu-gabriel/sympy,iamutkarshtiwari/sympy,dqnykamp/sympy,Designist/sympy,pbrady/sympy,Mitchkoens/sympy,Shaswat27/sympy,kmacinnis/sympy,debugger22/sympy,abhiii5459/sympy,kaichogami/sympy,bukzor/sympy,lidavidm/sympy,ga7g08/sympy,amitjamadagni/sympy,asm666/sympy,vipulroxx/sympy,lindsayad/sympy,Gadal/sympy,Davidjohnwilson/sympy,bukzor/sympy,aktech/sympy,Davidjohnwilson/sympy,Designist/sympy,mcdaniel67/sympy,vipulroxx/sympy,ahhda/sympy,kaushik94/sympy,atreyv/sympy,kevalds51/sympy,asm666/sympy,MridulS/sympy,chaffra/sympy,wyom/sympy,ga7g08/sympy,abloomston/sympy,kmacinnis/sympy,Vishluck/sympy,hrashk/sympy,wyom/sympy,cccfran/sympy,emon10005/sympy,abloomston/sympy,Titan-C/sympy,Mitchkoens/sympy,madan96/sympy,iamutkarshtiwari/sympy,MridulS/sympy,maniteja123/sympy,atreyv/sympy,saurabhjn76/sympy,abhiii5459/sympy,cccfran/sympy,sahmed95/sympy,AunShiLord/sympy,Gadal/sympy,sahilshekhawat/sympy,sampadsaha5/sympy,MechCoder/sympy,farhaanbukhsh/sympy,emon10005/sympy,souravsingh/sympy,postvakje/sympy,debugger22/sympy
--- +++ @@ -1,4 +1,9 @@ """Tests for simple tools for timing functions' execution. """ + +import sys + +if sys.version_info[:2] <= (2, 5): + disabled = True from sympy.utilities.timeutils import timed
4c7f36e6a5f277b1c84d665edb279476a9e15063
src/pyop/exceptions.py
src/pyop/exceptions.py
from oic.oauth2.message import ErrorResponse from .util import should_fragment_encode class BearerTokenError(ValueError): pass class InvalidAuthorizationCode(ValueError): pass class InvalidAccessToken(ValueError): pass class InvalidRefreshToken(ValueError): pass class InvalidSubjectIdentifier(ValueError): pass class InvalidScope(ValueError): pass class InvalidClientAuthentication(ValueError): pass class InvalidAuthenticationRequest(ValueError): def __init__(self, message, parsed_request, oauth_error=None): super().__init__(message) self.request = parsed_request self.oauth_error = oauth_error def to_error_url(self): redirect_uri = self.request.get('redirect_uri') if redirect_uri and self.oauth_error: error_resp = ErrorResponse(error=self.oauth_error, error_message=str(self)) return error_resp.request(redirect_uri, should_fragment_encode(self.request)) return None class AuthorizationError(Exception): pass class InvalidTokenRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error class InvalidUserinfoRequest(ValueError): pass class InvalidClientRegistrationRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error
import json from oic.oauth2.message import ErrorResponse from .util import should_fragment_encode class BearerTokenError(ValueError): pass class InvalidAuthorizationCode(ValueError): pass class InvalidAccessToken(ValueError): pass class InvalidRefreshToken(ValueError): pass class InvalidSubjectIdentifier(ValueError): pass class InvalidScope(ValueError): pass class InvalidClientAuthentication(ValueError): pass class InvalidAuthenticationRequest(ValueError): def __init__(self, message, parsed_request, oauth_error=None): super().__init__(message) self.request = parsed_request self.oauth_error = oauth_error def to_error_url(self): redirect_uri = self.request.get('redirect_uri') if redirect_uri and self.oauth_error: error_resp = ErrorResponse(error=self.oauth_error, error_message=str(self)) return error_resp.request(redirect_uri, should_fragment_encode(self.request)) return None class AuthorizationError(Exception): pass class InvalidTokenRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error class InvalidUserinfoRequest(ValueError): pass class InvalidClientRegistrationRequest(ValueError): def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error def to_json(self): error = {'error': self.oauth_error, 'error_description': str(self)} return json.dumps(error)
Add JSON convenience to InvalidRegistrationRequest.
Add JSON convenience to InvalidRegistrationRequest.
Python
apache-2.0
its-dirg/pyop
--- +++ @@ -1,3 +1,5 @@ +import json + from oic.oauth2.message import ErrorResponse from .util import should_fragment_encode @@ -64,3 +66,7 @@ def __init__(self, message, oauth_error='invalid_request'): super().__init__(message) self.oauth_error = oauth_error + + def to_json(self): + error = {'error': self.oauth_error, 'error_description': str(self)} + return json.dumps(error)
48ec1d9494ae8215f6b4bc4b79bcefe318d8a5b4
create_csv.py
create_csv.py
import csv from datetime import date from scraper.draft_scraper import scrape CSV_FILE = 'datasets/%s_nbadraft.csv' for year in range(1947, date.today().year): draft = scrape(year) header = [key for key in draft[1].keys()] with open(CSV_FILE % year, 'w', newline='') as outfile: dw = csv.DictWriter(outfile, header) dw.writeheader() dw.writerows([row for index, row in draft.items()])
import csv from datetime import date from scraper.draft_scraper import scrape CSV_FILE = 'datasets/%s_nbadraft.csv' for year in range(1947, date.today().year): draft = scrape(year) header = [key for key in draft[1].keys()] with open(CSV_FILE % year, 'w', newline='') as outfile: dw = csv.DictWriter(outfile, header) dw.writeheader() dw.writerows([row for index, row in draft.items()]) print('Data processed for %s.' % year)
Print line after creating each csv
Print line after creating each csv
Python
mit
kshvmdn/nbadrafts
--- +++ @@ -12,3 +12,4 @@ dw = csv.DictWriter(outfile, header) dw.writeheader() dw.writerows([row for index, row in draft.items()]) + print('Data processed for %s.' % year)
bf7571dfbf2f3081e539d5f3a5558d80fcd3fbee
app/utils/fields.py
app/utils/fields.py
from wtforms import Field from wtforms.widgets import TextInput class TagListField(Field): """ Field for comma-separated list of tags. From http://wtforms.readthedocs.org/en/latest/fields.html#custom-fields """ widget = TextInput() def _value(self): if self.data: try: # The data is a list of strings return u', '.join(self.data) except TypeError: # The data is a list of Tag objects return u', '.join([tag.name for tag in self.data]) else: return u'' def process_formdata(self, valuelist): if valuelist: try: # The data is a string self.data = [x.strip() for x in valuelist[0].split(',') if x] except AttributeError: # The data is a list of Tag objects self.data = [tag.name for tag in valuelist[0]] else: self.data = []
from wtforms import Field from wtforms.widgets import TextInput class TagListField(Field): """ Field for comma-separated list of tags. """ widget = TextInput() def _value(self): if self.data: try: # The data is a list of strings return ', '.join(self.data) except TypeError: # The data is a list of Tag objects return ', '.join([tag.name for tag in self.data]) else: return '' def process_formdata(self, valuelist): if valuelist: try: # The data is a string self.data = [x.strip() for x in valuelist[0].split(',') if x] except AttributeError: # The data is a list of Tag objects self.data = [tag.name for tag in valuelist[0]] else: self.data = []
Remove explicit unicode encoding on strings
Remove explicit unicode encoding on strings
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
--- +++ @@ -3,12 +3,7 @@ class TagListField(Field): - """ - Field for comma-separated list of tags. - - From http://wtforms.readthedocs.org/en/latest/fields.html#custom-fields - - """ + """ Field for comma-separated list of tags. """ widget = TextInput() @@ -16,12 +11,12 @@ if self.data: try: # The data is a list of strings - return u', '.join(self.data) + return ', '.join(self.data) except TypeError: # The data is a list of Tag objects - return u', '.join([tag.name for tag in self.data]) + return ', '.join([tag.name for tag in self.data]) else: - return u'' + return '' def process_formdata(self, valuelist): if valuelist:
52ef3152fb92c5f0363578fe1e7d51f57c18295b
core/fns.py
core/fns.py
from functools import partial from itertools import accumulate as accumulate_, chain, tee MYPY = False if MYPY: from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar T = TypeVar('T') filter_ = partial(filter, None) # type: Callable[[Iterator[Optional[T]]], Iterator[T]] flatten = chain.from_iterable def accumulate(iterable, initial): # type: (Iterable[int], int) -> Iterable[int] if initial is None: return accumulate_(iterable) else: return accumulate_(chain([initial], iterable)) def pairwise(iterable): # type: (Iterable[T]) -> Iterable[Tuple[T, T]] "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b)
from functools import partial from itertools import accumulate as accumulate_, chain, tee MYPY = False if MYPY: from typing import Callable, Iterable, Iterator, Optional, Tuple, TypeVar T = TypeVar('T') filter_ = partial(filter, None) # type: Callable[[Iterator[Optional[T]]], Iterator[T]] flatten = chain.from_iterable def accumulate(iterable, initial=None): # type: (Iterable[int], int) -> Iterable[int] if initial is None: return accumulate_(iterable) else: return accumulate_(chain([initial], iterable)) def pairwise(iterable): # type: (Iterable[T]) -> Iterable[Tuple[T, T]] "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b)
Make `initial` argument to `accumulate` optional
Make `initial` argument to `accumulate` optional
Python
mit
divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy
--- +++ @@ -11,7 +11,7 @@ flatten = chain.from_iterable -def accumulate(iterable, initial): +def accumulate(iterable, initial=None): # type: (Iterable[int], int) -> Iterable[int] if initial is None: return accumulate_(iterable)
eb0579d7bcd585e8ae0ca82060540743f8ec90ae
py/tables.py
py/tables.py
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relations" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) class User(Base): __tablename__ = "users" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) username = sqlalchemy.Column(sqlalchemy.String) password = sqlalchemy.Column(sqlalchemy.String) can_change_settings = sqlalchemy.column(sqlalchemy.Boolean) can_write_posts = sqlalchemy.column(sqlalchemy.Boolean) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relations" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) class User(Base): __tablename__ = "users" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) username = sqlalchemy.Column(sqlalchemy.String) password = sqlalchemy.Column(sqlalchemy.String) can_change_settings = sqlalchemy.Column(sqlalchemy.Boolean) can_write_posts = sqlalchemy.Column(sqlalchemy.Boolean) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
Fix bug where column the function was being called, rather than class
Fix bug where column the function was being called, rather than class
Python
mit
ollien/Timpani,ollien/Timpani,ollien/Timpani
--- +++ @@ -32,8 +32,8 @@ id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) username = sqlalchemy.Column(sqlalchemy.String) password = sqlalchemy.Column(sqlalchemy.String) - can_change_settings = sqlalchemy.column(sqlalchemy.Boolean) - can_write_posts = sqlalchemy.column(sqlalchemy.Boolean) + can_change_settings = sqlalchemy.Column(sqlalchemy.Boolean) + can_write_posts = sqlalchemy.Column(sqlalchemy.Boolean) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
007cd14cd3fd215cd91403ebe09cd5c0bb555f23
armstrong/apps/related_content/admin.py
armstrong/apps/related_content/admin.py
from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from .models import RelatedContent from .models import RelatedType class RelatedContentInline(GenericTabularInline): ct_field = "source_type" ct_fk_field = "source_id" model = RelatedContent admin.site.register(RelatedType)
from django import forms from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from armstrong.hatband import widgets from .models import RelatedContent from .models import RelatedType class RelatedContentInlineForm(forms.ModelForm): class Meta: widgets = { "destination_type": forms.HiddenInput(), "destination_id": widgets.GenericKeyWidget( object_id_name="destination_id", content_type_name="destination_type", ), "order": forms.HiddenInput(), } class RelatedContentInline(GenericTabularInline): ct_field = "source_type" ct_fk_field = "source_id" model = RelatedContent template = "admin/edit_inline/generickey.html" form = RelatedContentInlineForm admin.site.register(RelatedType)
Add in visualsearch for GFK
Add in visualsearch for GFK
Python
apache-2.0
texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,texastribune/armstrong.apps.related_content
--- +++ @@ -1,8 +1,22 @@ +from django import forms from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline +from armstrong.hatband import widgets + from .models import RelatedContent from .models import RelatedType + +class RelatedContentInlineForm(forms.ModelForm): + class Meta: + widgets = { + "destination_type": forms.HiddenInput(), + "destination_id": widgets.GenericKeyWidget( + object_id_name="destination_id", + content_type_name="destination_type", + ), + "order": forms.HiddenInput(), + } class RelatedContentInline(GenericTabularInline): @@ -10,6 +24,9 @@ ct_fk_field = "source_id" model = RelatedContent + template = "admin/edit_inline/generickey.html" + + form = RelatedContentInlineForm admin.site.register(RelatedType)
f9e5ee2bcb088aec6f0d1c012caaaca05fe69560
lims/celery.py
lims/celery.py
import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings') app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend='redis') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'process-deadlines': { 'task': 'lims.projects.tasks.process_deadlines', 'schedule': crontab(minute=0, hour='*/3'), } }
import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings') app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379')) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'process-deadlines': { 'task': 'lims.projects.tasks.process_deadlines', 'schedule': crontab(minute=0, hour='*/3'), } }
Fix issue with backend not being recognised
Fix issue with backend not being recognised
Python
mit
GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend
--- +++ @@ -4,7 +4,8 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lims.settings') -app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), backend='redis') +app = Celery('lims', broker=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379'), + backend=os.environ.get('REDIS_URL', 'redis://127.0.0.1:6379')) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()
027178a21083ceaa4151806e877a58ec7792f625
pysswords/__main__.py
pysswords/__main__.py
import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() parser.add_argument('path') parser.add_argument('--create', action='store_true') parser.add_argument('--password', default=None) parser.add_argument('--salt', default=None) parser.add_argument('--iterations', default=100000) return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main()
import argparse from getpass import getpass from pysswords.db import Database from pysswords.crypt import CryptOptions def get_args(): parser = argparse.ArgumentParser() main_group = parser.add_argument_group('Main options') main_group.add_argument('path', help='Path to database file') main_group.add_argument('--create', action='store_true', help='Create a new encrypted password database') crypt_group = parser.add_argument_group('Encryption options') crypt_group.add_argument('--password', default=None, help='Password to open database') crypt_group.add_argument('--salt', default=None, help='Salt for encryption') crypt_group.add_argument('--iterations', default=100000, help='Number of iterations for encryption') return parser.parse_args() def main(args=None): if not args: args = get_args() if not args.password: args.password = getpass() crypt_options = CryptOptions( password=args.password, salt=args.salt, iterations=args.iterations ) if args.create: Database.create(args.path, crypt_options) elif args.add: database = Database(args.path, crypt_options) database.add_credential(args.path, crypt_options) if __name__ == "__main__": main()
Refactor get args function from console interface
Refactor get args function from console interface
Python
mit
eiginn/passpie,scorphus/passpie,marcwebbie/passpie,scorphus/passpie,marcwebbie/pysswords,eiginn/passpie,marcwebbie/passpie
--- +++ @@ -6,11 +6,18 @@ def get_args(): parser = argparse.ArgumentParser() - parser.add_argument('path') - parser.add_argument('--create', action='store_true') - parser.add_argument('--password', default=None) - parser.add_argument('--salt', default=None) - parser.add_argument('--iterations', default=100000) + main_group = parser.add_argument_group('Main options') + main_group.add_argument('path', help='Path to database file') + main_group.add_argument('--create', action='store_true', + help='Create a new encrypted password database') + + crypt_group = parser.add_argument_group('Encryption options') + crypt_group.add_argument('--password', default=None, + help='Password to open database') + crypt_group.add_argument('--salt', default=None, + help='Salt for encryption') + crypt_group.add_argument('--iterations', default=100000, + help='Number of iterations for encryption') return parser.parse_args()
1b3c6c7dd8116ce0e523de4acd02aa19cedcfd70
appengine_config.py
appengine_config.py
# appengine_config.py from google.appengine.ext import vendor # Add any libraries install in the "lib" folder. vendor.add('lib')
# appengine_config.py from google.appengine.ext import vendor import os # Add any libraries install in the "lib" folder. vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
Use new-style method of setting module path
Use new-style method of setting module path
Python
agpl-3.0
sleinen/zrcal,sleinen/zrcal
--- +++ @@ -1,5 +1,7 @@ # appengine_config.py from google.appengine.ext import vendor +import os + # Add any libraries install in the "lib" folder. -vendor.add('lib') +vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
d28fa7874d7b0602eb5064d9f43b8b01674de69f
presentation/models.py
presentation/models.py
from django.db import models from model_utils.models import TimeStampedModel from warp.users.models import User class Presentation(TimeStampedModel): subject = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) def __str__(self): return self.subject class Slide(TimeStampedModel): presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) slide_order = models.PositiveSmallIntegerField() markdown = models.TextField() def __str__(self): return self.markdown
from django.db import models from django.db.models import Manager from django.db.models import QuerySet from model_utils.models import TimeStampedModel from warp.users.models import User class PresentationQuerySet(QuerySet): def public(self): return self.filter(is_public=True) def authored_by(self, author): return self.filter(author__username=author) class PresentationManager(Manager): def get_queryset(self): return PresentationQuerySet(self.model, using=self._db) def public(self): return self.get_queryset().public() def authored_by(self, author): return self.get_queryset().authored_by(author) class Presentation(TimeStampedModel): subject = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) objects = PresentationManager() def __str__(self): return self.subject class Slide(TimeStampedModel): presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) slide_order = models.PositiveSmallIntegerField() markdown = models.TextField() def __str__(self): return self.markdown
Add presentation queryset and model manager
Add presentation queryset and model manager
Python
mit
SaturDJang/warp,SaturDJang/warp,SaturDJang/warp,SaturDJang/warp
--- +++ @@ -1,7 +1,28 @@ from django.db import models +from django.db.models import Manager +from django.db.models import QuerySet from model_utils.models import TimeStampedModel from warp.users.models import User + + +class PresentationQuerySet(QuerySet): + def public(self): + return self.filter(is_public=True) + + def authored_by(self, author): + return self.filter(author__username=author) + + +class PresentationManager(Manager): + def get_queryset(self): + return PresentationQuerySet(self.model, using=self._db) + + def public(self): + return self.get_queryset().public() + + def authored_by(self, author): + return self.get_queryset().authored_by(author) class Presentation(TimeStampedModel): @@ -9,6 +30,8 @@ author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) + + objects = PresentationManager() def __str__(self): return self.subject
8d55268fb3239dd429cb488a6c13e09d7839aa1a
registration/forms.py
registration/forms.py
from django import forms from registration import constants class CompanyForm(forms.Form): company_number = forms.CharField( label='Company number', help_text=('This is the 8-digit number on the company certificate of ' 'incorporation.'), max_length=8, min_length=8, ) class CompanyBasicInfoForm(forms.Form): company_name = forms.CharField() website = forms.URLField() description = forms.CharField() class AimsForm(forms.Form): aim_one = forms.ChoiceField(choices=constants.AIMS) aim_two = forms.ChoiceField(choices=constants.AIMS) class UserForm(forms.Form): name = forms.CharField(label='Full name') email = forms.EmailField(label='Email address') password = forms.CharField(widget=forms.PasswordInput()) terms_agreed = forms.BooleanField() referrer = forms.CharField(required=False, widget=forms.HiddenInput())
from django import forms from registration import constants class CompanyForm(forms.Form): company_number = forms.CharField( label='Company number', help_text=('This is the 8-digit number on the company certificate of ' 'incorporation.'), max_length=8, min_length=8, ) class CompanyBasicInfoForm(forms.Form): company_name = forms.CharField() website = forms.URLField() description = forms.CharField(widget=forms.Textarea) class AimsForm(forms.Form): aim_one = forms.ChoiceField(choices=constants.AIMS) aim_two = forms.ChoiceField(choices=constants.AIMS) class UserForm(forms.Form): name = forms.CharField(label='Full name') email = forms.EmailField(label='Email address') password = forms.CharField(widget=forms.PasswordInput()) terms_agreed = forms.BooleanField() referrer = forms.CharField(required=False, widget=forms.HiddenInput())
Make description field a textarea in company form
Make description field a textarea in company form
Python
mit
uktrade/directory-ui-supplier,uktrade/directory-ui-supplier,uktrade/directory-ui-supplier
--- +++ @@ -16,7 +16,7 @@ class CompanyBasicInfoForm(forms.Form): company_name = forms.CharField() website = forms.URLField() - description = forms.CharField() + description = forms.CharField(widget=forms.Textarea) class AimsForm(forms.Form):
925f112863f128907862b230ed1767e10d91deed
run_tests.py
run_tests.py
import sys import os import subprocess def main(): executableName = './CuraEngine' if len(sys.argv) > 1: executableName = sys.argv[1] exitValue = 0 for subPath in os.listdir('testcase_models'): print 'Running test on %s' % (subPath) ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode']) if ret != 0: exitValue = 1 sys.exit(exitValue) if __name__ == '__main__': main()
import sys import os import subprocess def main(): executableName = './CuraEngine' if len(sys.argv) > 1: executableName = sys.argv[1] exitValue = 0 for subPath in os.listdir('testcase_models'): print 'Running test on %s' % (subPath) ret = subprocess.call([executableName, '-o', 'temp.gcode', os.path.join('testcase_models', subPath)]) if ret != 0: exitValue = 1 sys.exit(exitValue) if __name__ == '__main__': main()
Fix the python script that runs the tests.
Fix the python script that runs the tests.
Python
agpl-3.0
patrick3coffee/CuraTinyG,Ultimaker/CuraEngine,be3d/CuraEngine,uus169/CuraEngine,totalretribution/CuraEngine,be3d/CuraEngine,jacobdai/CuraEngine-1,electrocbd/CuraEngine,Intrinsically-Sublime/CuraEngine,robotustra/curax,derekhe/CuraEngine,uus169/CuraEngine,totalretribution/CuraEngine,phonyphonecall/CuraEngine,markwal/CuraEngine,alex1818/CuraEngine,alex1818/CuraEngine,electrocbd/CuraEngine,alephobjects/CuraEngine,foosel/CuraEngine,Skeen/CuraJS-Engine,jacobdai/CuraEngine-1,ROBO3D/CuraEngine,Skeen/CuraJS-Engine,patrick3coffee/CuraTinyG,Jwis921/PersonalCuraEngine,Intrinsically-Sublime/CuraEngine,fxtentacle/CuraEngine,ROBO3D/CuraEngine,Intrinsically-Sublime/CuraEngine,markwal/CuraEngine,Jwis921/PersonalCuraEngine,robotustra/curax,Jwis921/PersonalCuraEngine,phonyphonecall/CuraEngine,be3d/CuraEngine,robotustra/curax,mspark93/CuraEngine,daid/CuraCutEngine,Skeen/CuraJS-Engine,foosel/CuraEngine,ROBO3D/CuraEngine,mspark93/CuraEngine,alephobjects/CuraEngine,electrocbd/CuraEngine,alex1818/CuraEngine,pratikshashroff/pcura,Ultimaker/CuraEngine,uus169/CuraEngine,pratikshashroff/pcura,derekhe/CuraEngine,alephobjects/CuraEngine,fxtentacle/CuraEngine,mspark93/CuraEngine,markwal/CuraEngine,phonyphonecall/CuraEngine,pratikshashroff/pcura,jacobdai/CuraEngine-1,fxtentacle/CuraEngine,totalretribution/CuraEngine,derekhe/CuraEngine,foosel/CuraEngine,daid/CuraCutEngine,patrick3coffee/CuraTinyG
--- +++ @@ -10,7 +10,7 @@ exitValue = 0 for subPath in os.listdir('testcase_models'): print 'Running test on %s' % (subPath) - ret = subprocess.call([executableName, os.path.join('testcase_models', subPath), '-o', 'temp.gcode']) + ret = subprocess.call([executableName, '-o', 'temp.gcode', os.path.join('testcase_models', subPath)]) if ret != 0: exitValue = 1
a72c494c5c0f010192f39d84c13c90c0f0f8941e
sympycore/calculus/__init__.py
sympycore/calculus/__init__.py
from .algebra import Calculus, I, integrate, oo, undefined from .functions import exp, log, sqrt, sin, cos, tan, cot, pi, E Symbol = Calculus.Symbol Number = Calculus.Number Add = lambda *args: Calculus.Add(*map(Calculus.convert, args)) Mul = lambda *args: Calculus.Mul(*map(Calculus.convert, args)) Pow = lambda *args: Calculus.Pow(*map(Calculus.convert, args))
from .algebra import Calculus, I, integrate, oo, undefined from .functions import exp, log, sqrt, sin, cos, tan, cot, pi, E Symbol = Calculus.Symbol def Number(num, denom=None): n = Calculus.Number(Calculus.convert_coefficient(num)) if denom is None: return n return n / denom Add = lambda *args: Calculus.Add(*map(Calculus.convert, args)) Mul = lambda *args: Calculus.Mul(*map(Calculus.convert, args)) Pow = lambda *args: Calculus.Pow(*map(Calculus.convert, args))
Fix calculus.Number to handle floats.
Fix calculus.Number to handle floats.
Python
bsd-3-clause
pearu/sympycore,pearu/sympycore
--- +++ @@ -3,7 +3,12 @@ from .functions import exp, log, sqrt, sin, cos, tan, cot, pi, E Symbol = Calculus.Symbol -Number = Calculus.Number + +def Number(num, denom=None): + n = Calculus.Number(Calculus.convert_coefficient(num)) + if denom is None: + return n + return n / denom Add = lambda *args: Calculus.Add(*map(Calculus.convert, args)) Mul = lambda *args: Calculus.Mul(*map(Calculus.convert, args))
006a37819372ae9d161bece9c44a83bc26b7d43e
test/probe/__init__.py
test/probe/__init__.py
from test import get_config from swift.common.utils import config_true_value config = get_config('probe_test') CHECK_SERVER_TIMEOUT = int(config.get('check_server_timeout', 30)) VALIDATE_RSYNC = config_true_value(config.get('validate_rsync', False))
# Copyright (c) 2010-2017 OpenStack Foundation # # 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 test import get_config from swift.common.utils import config_true_value config = get_config('probe_test') CHECK_SERVER_TIMEOUT = int(config.get('check_server_timeout', 30)) VALIDATE_RSYNC = config_true_value(config.get('validate_rsync', False))
Add license in swift code file
Add license in swift code file Source code should be licensed under the Apache 2.0 license. Add Apache License in swift/probe/__init__.py file. Change-Id: I3b6bc2ec5fe5caac87ee23f637dbcc7a5d8fc331
Python
apache-2.0
tipabu/swift,tipabu/swift,psachin/swift,smerritt/swift,smerritt/swift,smerritt/swift,matthewoliver/swift,clayg/swift,notmyname/swift,nadeemsyed/swift,swiftstack/swift,openstack/swift,matthewoliver/swift,matthewoliver/swift,nadeemsyed/swift,tipabu/swift,openstack/swift,psachin/swift,openstack/swift,swiftstack/swift,psachin/swift,nadeemsyed/swift,smerritt/swift,openstack/swift,swiftstack/swift,clayg/swift,psachin/swift,notmyname/swift,notmyname/swift,notmyname/swift,nadeemsyed/swift,clayg/swift,matthewoliver/swift,tipabu/swift,clayg/swift
--- +++ @@ -1,5 +1,23 @@ +# Copyright (c) 2010-2017 OpenStack Foundation +# +# 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 test import get_config from swift.common.utils import config_true_value + + config = get_config('probe_test') CHECK_SERVER_TIMEOUT = int(config.get('check_server_timeout', 30)) VALIDATE_RSYNC = config_true_value(config.get('validate_rsync', False))
aec355326b0f6116d6ffb1b0aeb7e35c2074c9ed
ebcf_alexa.py
ebcf_alexa.py
""" Entry point for lambda """ from _ebcf_alexa import interaction_model import logging LOG = logging.getLogger() LOG.setLevel(logging.DEBUG) def lambda_handler(event, context) -> dict: """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ LOG.info("Start Lambda Event for event.session.application.applicationId=%s", event['session']['application']['applicationId']) # This is the official application id if (event['session']['application']['applicationId'] != 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'): raise ValueError("Invalid Application ID") request_type = event['request']['type'] try: handler = interaction_model.REQUEST_HANDLERS[request_type] except KeyError: LOG.error('Unknown request type: %s', request_type) raise ValueError('Unknown Request Type') speechlet = handler(event['request'], event['session']) return speechlet.dict()
""" Entry point for lambda """ from _ebcf_alexa import interaction_model, incoming_types, speechlet import logging LOG = logging.getLogger() LOG.setLevel(logging.DEBUG) ALEXA_SKILL_ID = 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969' def lambda_handler(event_dict: dict, context) -> dict: """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ LOG.debug(repr(event_dict)) event = incoming_types.LambdaEvent(event_dict) LOG.info("Start Lambda Event for event.session.application.applicationId=%s", event.session.application.application_id) # This is the official application id if event.session.application.application_id != ALEXA_SKILL_ID: raise ValueError("Invalid Application ID: %s" % event.session.application.application_id) return interaction_model.handle_event(event).dict()
Update lambda handler function to dispatch to interaction model
Update lambda handler function to dispatch to interaction model
Python
mit
dmotles/ebcf-alexa
--- +++ @@ -1,29 +1,26 @@ """ Entry point for lambda """ -from _ebcf_alexa import interaction_model +from _ebcf_alexa import interaction_model, incoming_types, speechlet import logging LOG = logging.getLogger() LOG.setLevel(logging.DEBUG) +ALEXA_SKILL_ID = 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969' -def lambda_handler(event, context) -> dict: + +def lambda_handler(event_dict: dict, context) -> dict: """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ + LOG.debug(repr(event_dict)) + event = incoming_types.LambdaEvent(event_dict) LOG.info("Start Lambda Event for event.session.application.applicationId=%s", - event['session']['application']['applicationId']) + event.session.application.application_id) # This is the official application id - if (event['session']['application']['applicationId'] != - 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'): - raise ValueError("Invalid Application ID") + if event.session.application.application_id != ALEXA_SKILL_ID: + raise ValueError("Invalid Application ID: %s" % event.session.application.application_id) - request_type = event['request']['type'] - try: - handler = interaction_model.REQUEST_HANDLERS[request_type] - except KeyError: - LOG.error('Unknown request type: %s', request_type) - raise ValueError('Unknown Request Type') - speechlet = handler(event['request'], event['session']) - return speechlet.dict() + return interaction_model.handle_event(event).dict() +
7df2e3bc6f651b9caa45d57a1cd21eac374148a3
compile/00-shortcuts.dg.py
compile/00-shortcuts.dg.py
builtins = import operator = import functools = import importlib = import # Choose a function based on the number of arguments. varary = (*fs) -> (*xs) -> (fs !! (len: xs - 1)): (*): xs builtins . $ = (f, *xs) -> f: (*): xs builtins . : = (f, *xs) -> f: (*): xs builtins . , = (*xs) -> xs builtins . < = operator.lt builtins . <= = operator.le builtins . == = operator.eq builtins . != = operator.ne builtins . > = operator.gt builtins . >= = operator.ge builtins . is = operator.is_ builtins . in = (a, b) -> operator.contains: b a builtins . not = operator.not_ builtins . ~ = operator.invert builtins . + = varary: operator.pos operator.add builtins . - = varary: operator.neg operator.sub builtins . * = operator.mul builtins . ** = operator.pow builtins . / = operator.truediv builtins . // = operator.floordiv builtins . % = operator.mod builtins . !! = operator.getitem builtins . & = operator.and_ builtins . ^ = operator.xor builtins . | = operator.or_ builtins . << = operator.lshift builtins . >> = operator.rshift builtins.import = importlib.import_module builtins.foldl = functools.reduce builtins . ~: = functools.partial builtins . ... = Ellipsis
builtins = import operator = import functools = import importlib = import # Choose a function based on the number of arguments. varary = (*fs) -> (*xs) -> (fs !! (len: xs)): (*): xs builtins . $ = (f, *xs) -> f: (*): xs builtins . : = (f, *xs) -> f: (*): xs builtins . , = (*xs) -> xs builtins . < = operator.lt builtins . <= = operator.le builtins . == = operator.eq builtins . != = operator.ne builtins . > = operator.gt builtins . >= = operator.ge builtins . is = operator.is_ builtins . in = (a, b) -> operator.contains: b a builtins . not = operator.not_ builtins . ~ = operator.invert builtins . + = varary: None operator.pos operator.add builtins . - = varary: None operator.neg operator.sub builtins . * = operator.mul builtins . ** = operator.pow builtins . / = operator.truediv builtins . // = operator.floordiv builtins . % = operator.mod builtins . !! = operator.getitem builtins . & = operator.and_ builtins . ^ = operator.xor builtins . | = operator.or_ builtins . << = operator.lshift builtins . >> = operator.rshift builtins.import = importlib.import_module builtins.foldl = functools.reduce builtins . ~: = functools.partial builtins . ... = Ellipsis
Fix the infinite recursion when calling runtime +/-.
Fix the infinite recursion when calling runtime +/-.
Python
mit
pyos/dg
--- +++ @@ -4,7 +4,7 @@ importlib = import # Choose a function based on the number of arguments. -varary = (*fs) -> (*xs) -> (fs !! (len: xs - 1)): (*): xs +varary = (*fs) -> (*xs) -> (fs !! (len: xs)): (*): xs builtins . $ = (f, *xs) -> f: (*): xs builtins . : = (f, *xs) -> f: (*): xs @@ -21,8 +21,8 @@ builtins . not = operator.not_ builtins . ~ = operator.invert -builtins . + = varary: operator.pos operator.add -builtins . - = varary: operator.neg operator.sub +builtins . + = varary: None operator.pos operator.add +builtins . - = varary: None operator.neg operator.sub builtins . * = operator.mul builtins . ** = operator.pow builtins . / = operator.truediv
678bd63609d80239668d596ce6fffe2ddd70f7d2
conf_site/settings/travis-ci.py
conf_site/settings/travis-ci.py
from base import * # noqa: F401,F403 DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "travis", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", } } SECRET_KEY = "foobar" STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.StaticFilesStorage")
from base import * # noqa: F401,F403 DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "travis", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", } } GOOGLE_ANALYTICS_PROPERTY_ID = "UA-000000-0" SECRET_KEY = "foobar" STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.StaticFilesStorage")
Add fake Google Analytics ID for Travis-CI.
Add fake Google Analytics ID for Travis-CI. Add GOOGLE_ANALYTICS_PROPERTY_ID setting to Travis CI settings so that we can load webpages without django-analytical causing errors. Note that an empty string does not work.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
--- +++ @@ -13,6 +13,7 @@ "PORT": "", } } +GOOGLE_ANALYTICS_PROPERTY_ID = "UA-000000-0" SECRET_KEY = "foobar" STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.StaticFilesStorage")
702fabfc96b3b07efb4d5c30a6807031b803a551
kolibri/deployment/default/wsgi.py
kolibri/deployment/default/wsgi.py
""" WSGI config for kolibri project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import logging import os import time from django.core.wsgi import get_wsgi_application from django.db.utils import OperationalError os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "kolibri.deployment.default.settings.base" ) logger = logging.getLogger(__name__) application = None tries_remaining = 6 interval = 10 while not application and tries_remaining: try: logger.info("Starting Kolibri") application = get_wsgi_application() except OperationalError: # an OperationalError happens when sqlite vacuum is being executed. the db is locked logger.info("DB busy. Trying again in {}s".format(interval)) tries_remaining -= 1 time.sleep(interval) application = get_wsgi_application() # try again one last time if not application: logger.error("Could not start Kolibri")
""" WSGI config for kolibri project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import logging import os import time from django.core.wsgi import get_wsgi_application from django.db.utils import OperationalError import kolibri os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "kolibri.deployment.default.settings.base" ) logger = logging.getLogger(__name__) application = None tries_remaining = 6 interval = 10 while not application and tries_remaining: try: logger.info("Starting Kolibri {version}".format(version=kolibri.__version__)) application = get_wsgi_application() except OperationalError: # an OperationalError happens when sqlite vacuum is being executed. the db is locked logger.info("DB busy. Trying again in {}s".format(interval)) tries_remaining -= 1 time.sleep(interval) application = get_wsgi_application() # try again one last time if not application: logger.error("Could not start Kolibri")
Add kolibri version to server start logging.
Add kolibri version to server start logging.
Python
mit
indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,mrpau/kolibri,mrpau/kolibri
--- +++ @@ -13,6 +13,8 @@ from django.core.wsgi import get_wsgi_application from django.db.utils import OperationalError +import kolibri + os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "kolibri.deployment.default.settings.base" ) @@ -23,7 +25,7 @@ interval = 10 while not application and tries_remaining: try: - logger.info("Starting Kolibri") + logger.info("Starting Kolibri {version}".format(version=kolibri.__version__)) application = get_wsgi_application() except OperationalError: # an OperationalError happens when sqlite vacuum is being executed. the db is locked
87d13bddb5f98438e959c3aafcf1d3a936dd264b
turbustat/statistics/statistics_list.py
turbustat/statistics/statistics_list.py
# Licensed under an MIT open source license - see LICENSE ''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Density", "VCS_Velocity", "PDF_Hellinger", "PDF_KS", "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"]
# Licensed under an MIT open source license - see LICENSE ''' Returns a list of all available distance metrics ''' statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Density", "VCS_Velocity", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"]
Remove PDF_AD from stats list
Remove PDF_AD from stats list
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
--- +++ @@ -7,11 +7,11 @@ statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer", "Skewness", "Kurtosis", "VCS_Density", "VCS_Velocity", - "PDF_Hellinger", "PDF_KS", "PDF_AD", + "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"] twoD_statistics_list = \ ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance", "Genus", "Tsallis", "Skewness", "Kurtosis", - "PDF_Hellinger", "PDF_KS", "PDF_AD", + "PDF_Hellinger", "PDF_KS", # "PDF_AD", "Dendrogram_Hist", "Dendrogram_Num"]
202027ac9a2680ba8825d488c146d152beaa4b5d
tests/test_coursera.py
tests/test_coursera.py
import unittest from mooc_aggregator_restful_api import coursera class CourseraTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.coursera_test_object = coursera.CourseraAPI() def test_coursera_api_courses_response(self): self.assertEqual(self.coursera_test_object.response_courses.status_code, 200) def test_coursera_api_universities_response(self): self.assertEqual(self.coursera_test_object.response_universities.status_code, 200) def test_coursera_api_categories_response(self): self.assertEqual(self.coursera_test_object.response_categories.status_code, 200) def test_coursera_api_instructors_response(self): self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200) def test_coursera_api_sessions_response(self): self.assertEqual(self.coursera_test_object.response_sessions.status_code, 200) def test_coursera_api_mongofy_courses(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main()
import unittest from mooc_aggregator_restful_api import coursera class CourseraTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.coursera_test_object = coursera.CourseraAPI() def test_coursera_api_courses_response(self): self.assertEqual(self.coursera_test_object.response_courses.status_code, 200) def test_coursera_api_universities_response(self): self.assertEqual(self.coursera_test_object.response_universities.status_code, 200) def test_coursera_api_categories_response(self): self.assertEqual(self.coursera_test_object.response_categories.status_code, 200) def test_coursera_api_instructors_response(self): self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200) def test_coursera_api_mongofy_courses(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main()
Remove test for sessions for Coursera API
Remove test for sessions for Coursera API
Python
mit
ueg1990/mooc_aggregator_restful_api
--- +++ @@ -24,9 +24,6 @@ def test_coursera_api_instructors_response(self): self.assertEqual(self.coursera_test_object.response_instructors.status_code, 200) - def test_coursera_api_sessions_response(self): - self.assertEqual(self.coursera_test_object.response_sessions.status_code, 200) - def test_coursera_api_mongofy_courses(self): pass
8db7072cef4c5ddbf408cdf1740e926f4d78747b
Functions/echo-python/lambda_function.py
Functions/echo-python/lambda_function.py
"""Created By: Andrew Ryan DeFilippis""" print('Lambda cold-start...') from json import dumps, loads # Disable 'testing_locally' when deploying to AWS Lambda testing_locally = False verbose = False class CWLogs(object): def __init__(self, context): self.context = context def event(self, message, event_prefix='LOG'): print('{} RequestId: {}\t{}'.format( event_prefix, self.context.aws_request_id, message )) def lambda_handler(event, context): log = CWLogs(context) if verbose is True: log.event('Event: {}'.format(dumps(event))) return event def local_test(): import context with open('event.json', 'r') as f: event = loads(f.read()) print('\nFunction Log:\n') lambda_handler(event, context) if testing_locally is True: local_test()
"""Created By: Andrew Ryan DeFilippis""" print('Lambda cold-start...') from json import dumps, loads # Disable 'testing_locally' when deploying to AWS Lambda testing_locally = True verbose = True class CWLogs(object): """Define the structure of log events to match all other CloudWatch Log Events logged by AWS Lambda. """ def __init__(self, context): """Define the instance of the context object. :param context: Lambda context object """ self.context = context def event(self, message, event_prefix='LOG'): # type: (any, str) -> None """Print an event into the CloudWatch Logs stream for the Function's invocation. :param message: The information to be logged (required) :param event_prefix: The prefix that appears before the 'RequestId' (default 'LOG') :return: """ print('{} RequestId: {}\t{}'.format( event_prefix, self.context.aws_request_id, message )) return None def lambda_handler(event, context): """AWS Lambda executes the 'lambda_handler' function on invocation. :param event: Ingested JSON event object provided at invocation :param context: Lambda context object, containing information specific to the invocation and Function :return: Final response to AWS Lambda, and passed to the invoker if the invocation type is RequestResponse """ # Instantiate our CloudWatch logging class log = CWLogs(context) if verbose is True: log.event('Event: {}'.format(dumps(event))) return event def local_test(): """Testing on a local development machine (outside of AWS Lambda) is made possible by... """ import context with open('event.json', 'r') as f: event = loads(f.read()) print('\nFunction Log:\n') lambda_handler(event, context) if testing_locally is True: local_test()
Add documentation, and modify default values
Add documentation, and modify default values
Python
apache-2.0
andrewdefilippis/aws-lambda
--- +++ @@ -4,25 +4,50 @@ from json import dumps, loads - # Disable 'testing_locally' when deploying to AWS Lambda -testing_locally = False -verbose = False +testing_locally = True +verbose = True class CWLogs(object): + """Define the structure of log events to match all other CloudWatch Log Events logged by AWS Lambda. + """ + def __init__(self, context): + """Define the instance of the context object. + + :param context: Lambda context object + """ + self.context = context def event(self, message, event_prefix='LOG'): + # type: (any, str) -> None + """Print an event into the CloudWatch Logs stream for the Function's invocation. + + :param message: The information to be logged (required) + :param event_prefix: The prefix that appears before the 'RequestId' (default 'LOG') + :return: + """ + print('{} RequestId: {}\t{}'.format( event_prefix, self.context.aws_request_id, message )) + return None + def lambda_handler(event, context): + """AWS Lambda executes the 'lambda_handler' function on invocation. + + :param event: Ingested JSON event object provided at invocation + :param context: Lambda context object, containing information specific to the invocation and Function + :return: Final response to AWS Lambda, and passed to the invoker if the invocation type is RequestResponse + """ + + # Instantiate our CloudWatch logging class log = CWLogs(context) if verbose is True: @@ -32,6 +57,9 @@ def local_test(): + """Testing on a local development machine (outside of AWS Lambda) is made possible by... + """ + import context with open('event.json', 'r') as f:
5de08e3b7be029a3a10dab9e4a259b046488d4af
examples/django_app/tests/test_integration.py
examples/django_app/tests/test_integration.py
from django.test import TestCase from django.core.urlresolvers import reverse import unittest class ApiIntegrationTestCase(TestCase): def setUp(self): super(ApiIntegrationTestCase, self).setUp() self.api_url = reverse('chatterbot:chatterbot') def _get_json(self, response): import json return json.loads(response.content) def test_get_recent_statements_empty(self): response = self.client.get(self.api_url) data = self._get_json(response) unittest.SkipTest('This test needs to be created.') def test_get_recent_statements(self): response = self.client.post( self.api_url, {'text': 'How are you?'}, format='json' ) response = self.client.get(self.api_url) data = self._get_json(response) self.assertIn('recent_statements', data) self.assertEqual(len(data['recent_statements']), 1) self.assertEqual(len(data['recent_statements'][0]), 2) self.assertIn('text', data['recent_statements'][0][0]) self.assertIn('text', data['recent_statements'][0][1])
from django.test import TestCase from django.core.urlresolvers import reverse import unittest class ApiIntegrationTestCase(TestCase): def setUp(self): super(ApiIntegrationTestCase, self).setUp() self.api_url = reverse('chatterbot:chatterbot') def tearDown(self): super(ApiIntegrationTestCase, self).tearDown() from chatterbot.ext.django_chatterbot.views import ChatterBotView # Clear the response queue between tests ChatterBotView.chatterbot.recent_statements.queue = [] def _get_json(self, response): import json return json.loads(response.content) def test_get_recent_statements_empty(self): response = self.client.get(self.api_url) data = self._get_json(response) self.assertIn('recent_statements', data) self.assertEqual(len(data['recent_statements']), 0) def test_get_recent_statements(self): response = self.client.post( self.api_url, {'text': 'How are you?'}, format='json' ) response = self.client.get(self.api_url) data = self._get_json(response) self.assertIn('recent_statements', data) self.assertEqual(len(data['recent_statements']), 1) self.assertEqual(len(data['recent_statements'][0]), 2) self.assertIn('text', data['recent_statements'][0][0]) self.assertIn('text', data['recent_statements'][0][1])
Add test method to clear response queue.
Add test method to clear response queue.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,Gustavo6046/ChatterBot,maclogan/VirtualPenPal,davizucon/ChatterBot,gunthercox/ChatterBot,Reinaesaya/OUIRL-ChatBot,vkosuri/ChatterBot
--- +++ @@ -9,6 +9,13 @@ super(ApiIntegrationTestCase, self).setUp() self.api_url = reverse('chatterbot:chatterbot') + def tearDown(self): + super(ApiIntegrationTestCase, self).tearDown() + from chatterbot.ext.django_chatterbot.views import ChatterBotView + + # Clear the response queue between tests + ChatterBotView.chatterbot.recent_statements.queue = [] + def _get_json(self, response): import json return json.loads(response.content) @@ -17,7 +24,8 @@ response = self.client.get(self.api_url) data = self._get_json(response) - unittest.SkipTest('This test needs to be created.') + self.assertIn('recent_statements', data) + self.assertEqual(len(data['recent_statements']), 0) def test_get_recent_statements(self): response = self.client.post( @@ -33,4 +41,4 @@ self.assertEqual(len(data['recent_statements']), 1) self.assertEqual(len(data['recent_statements'][0]), 2) self.assertIn('text', data['recent_statements'][0][0]) - self.assertIn('text', data['recent_statements'][0][1]) + self.assertIn('text', data['recent_statements'][0][1])
3ea9a14cdc4e19595ae8b14667d86ae42ba3d58c
astropy/wcs/tests/extension/test_extension.py
astropy/wcs/tests/extension/test_extension.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) env = os.environ.copy() env['PYTHONPATH'] = str(tmpdir) + ':' + env.get('PYTHONPATH', '') # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import os import subprocess import sys def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) astropy_path = os.path.abspath( os.path.join(setup_path, '..', '..', '..', '..')) env = os.environ.copy() paths = [str(tmpdir), astropy_path] if env.get('PYTHONPATH'): paths.append(env.get('PYTHONPATH')) env['PYTHONPATH'] = ':'.join(paths) # Build the extension subprocess.check_call( [sys.executable, 'setup.py', 'install', '--install-lib={0}'.format(tmpdir)], cwd=setup_path, env=env ) code = """ import sys import wcsapi_test sys.exit(wcsapi_test.test()) """ code = code.strip().replace('\n', '; ') # Import and run the extension subprocess.check_call( [sys.executable, '-c', code], env=env)
Make work when astropy isn't installed.
Make work when astropy isn't installed.
Python
bsd-3-clause
dhomeier/astropy,dhomeier/astropy,StuartLittlefair/astropy,joergdietrich/astropy,astropy/astropy,kelle/astropy,mhvk/astropy,stargaser/astropy,larrybradley/astropy,kelle/astropy,kelle/astropy,dhomeier/astropy,mhvk/astropy,joergdietrich/astropy,kelle/astropy,mhvk/astropy,astropy/astropy,saimn/astropy,MSeifert04/astropy,DougBurke/astropy,dhomeier/astropy,tbabej/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,AustereCuriosity/astropy,stargaser/astropy,funbaker/astropy,bsipocz/astropy,astropy/astropy,saimn/astropy,stargaser/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,DougBurke/astropy,lpsinger/astropy,larrybradley/astropy,funbaker/astropy,pllim/astropy,mhvk/astropy,joergdietrich/astropy,larrybradley/astropy,tbabej/astropy,bsipocz/astropy,mhvk/astropy,lpsinger/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,funbaker/astropy,astropy/astropy,joergdietrich/astropy,pllim/astropy,saimn/astropy,lpsinger/astropy,joergdietrich/astropy,kelle/astropy,tbabej/astropy,MSeifert04/astropy,pllim/astropy,funbaker/astropy,pllim/astropy,MSeifert04/astropy,MSeifert04/astropy,lpsinger/astropy,pllim/astropy,dhomeier/astropy,AustereCuriosity/astropy,astropy/astropy,stargaser/astropy,saimn/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,tbabej/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,tbabej/astropy,saimn/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,bsipocz/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,larrybradley/astropy,lpsinger/astropy,bsipocz/astropy
--- +++ @@ -11,9 +11,14 @@ # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) + astropy_path = os.path.abspath( + os.path.join(setup_path, '..', '..', '..', '..')) env = os.environ.copy() - env['PYTHONPATH'] = str(tmpdir) + ':' + env.get('PYTHONPATH', '') + paths = [str(tmpdir), astropy_path] + if env.get('PYTHONPATH'): + paths.append(env.get('PYTHONPATH')) + env['PYTHONPATH'] = ':'.join(paths) # Build the extension subprocess.check_call(
ecc666f7dfc7ace45692c8759acff6d46bc1c43e
tests/drivers/test-kml21.py
tests/drivers/test-kml21.py
import pyxb.binding.generate import os.path schema_path = '%s/../../pyxb/standard/schemas/kml21.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_file=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest class TestKML (unittest.TestCase): def testAngle180 (self): self.assertEqual(25.4, angle360(25.4)) self.assertRaises(BadTypeValueError, angle360, 420.0) self.assertRaises(BadTypeValueError, angle360, -361.0) if __name__ == '__main__': unittest.main()
import pyxb.binding.generate import os.path schema_path = '%s/../../pyxb/standard/schemas/kml.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_file=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest class TestKML (unittest.TestCase): def testAngle180 (self): self.assertEqual(25.4, angle360(25.4)) self.assertRaises(BadTypeValueError, angle360, 420.0) self.assertRaises(BadTypeValueError, angle360, -361.0) if __name__ == '__main__': unittest.main()
Change name to reference new schema name
Change name to reference new schema name
Python
apache-2.0
CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,balanced/PyXB,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,pabigot/pyxb,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,jonfoster/pyxb-upstream-mirror,balanced/PyXB,jonfoster/pyxb1,CantemoInternal/pyxb,jonfoster/pyxb2,CantemoInternal/pyxb,jonfoster/pyxb2
--- +++ @@ -1,7 +1,7 @@ import pyxb.binding.generate import os.path -schema_path = '%s/../../pyxb/standard/schemas/kml21.xsd' % (os.path.dirname(__file__),) +schema_path = '%s/../../pyxb/standard/schemas/kml.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_file=schema_path) rv = compile(code, 'test', 'exec') eval(rv)
493e6e96795fa812a6a3890ffde8004a2153cb75
util/plot.py
util/plot.py
from __future__ import division import numpy as NP import pylab as PL from mpl_toolkits.axes_grid1 import make_axes_locatable def centers2edges(x): """ Given the array of (assumed) uniformly spaced coordinate centers *x*, return the array of cell edge coordinates. """ delta = x[1] - x[0] return NP.linspace(x[0] - delta / 2, x[-1] + delta / 2, len(x) + 1) def add_colorbar(ax, im, side='right', size='5%', pad=0.1): """ Add colorbar to the axes *ax* with colors corresponding to the color mappable object *im*. Place the colorbar at the *side* of *ax* (options are `'right'`, `'left'`, `'top'`, or `'bottom'`). The width (or height) of the colorbar is specified by *size* and is relative to *ax*. Add space *pad* between *ax* and the colorbar. Return the colorbar instance. Reference: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html """ divider = make_axes_locatable(ax) cax = divider.append_axes(side, size=size, pad=pad) return PL.colorbar(im, cax=cax)
from __future__ import division import numpy as NP import pylab as PL from mpl_toolkits.axes_grid1 import make_axes_locatable def centers2edges(x): """ Given the array of (assumed) uniformly spaced coordinate centers *x*, return the array of cell edge coordinates. """ delta = x[1] - x[0] return NP.linspace(x[0] - delta / 2, x[-1] + delta / 2, len(x) + 1) def add_colorbar(ax, im, side='right', size='5%', pad=0.1): """ Add colorbar to the axes *ax* with colors corresponding to the color mappable object *im*. Place the colorbar at the *side* of *ax* (options are `'right'`, `'left'`, `'top'`, or `'bottom'`). The width (or height) of the colorbar is specified by *size* and is relative to *ax*. Add space *pad* between *ax* and the colorbar. Return the colorbar instance. Reference: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html """ divider = make_axes_locatable(ax) cax = divider.append_axes(side, size=size, pad=pad) cb = PL.colorbar(im, cax=cax) PL.axes(ax) return cb
Set axes back to input axes at end of add_colorbar.
Set axes back to input axes at end of add_colorbar.
Python
mit
butala/pyrsss
--- +++ @@ -29,4 +29,6 @@ """ divider = make_axes_locatable(ax) cax = divider.append_axes(side, size=size, pad=pad) - return PL.colorbar(im, cax=cax) + cb = PL.colorbar(im, cax=cax) + PL.axes(ax) + return cb
e349996bc98c57464f25152bdd0ab663398b6a46
deploy/travis/local_settings.py
deploy/travis/local_settings.py
# Kegbot local settings, for travis-ci.org build # NEVER set DEBUG to `True` in production. import os HOME = os.environ['HOME'] DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': HOME + '/kegbot-data/kegbot.sqlite'}} KEGBOT_ROOT = HOME + '/kegbot-data' MEDIA_ROOT = KEGBOT_ROOT + '/media' STATIC_ROOT = KEGBOT_ROOT + '/static' TIME_ZONE = 'America/Los_Angeles' CACHES = {'default': {'LOCATION': '127.0.0.1:11211', 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}} SECRET_KEY = 'testkey'
# Kegbot local settings, for travis-ci.org build # NEVER set DEBUG to `True` in production. import os HOME = os.environ['HOME'] DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': HOME + '/kegbot-data/kegbot.sqlite'}} KEGBOT_ROOT = HOME + '/kegbot-data' MEDIA_ROOT = KEGBOT_ROOT + '/media' STATIC_ROOT = KEGBOT_ROOT + '/static' TIME_ZONE = 'America/Los_Angeles' CACHES = {'default': {'LOCATION': '127.0.0.1:11211', 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache'}} SECRET_KEY = 'testkey' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_FROM_ADDRESS = 'no-reply@example.com'
Use console e-mail backend when running under Travis.
Use console e-mail backend when running under Travis.
Python
mit
Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server
--- +++ @@ -22,3 +22,5 @@ SECRET_KEY = 'testkey' +EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' +EMAIL_FROM_ADDRESS = 'no-reply@example.com'
eae216cc2d1bbe6e1c1aab1c4cf53d57b29b057c
froide/helper/csv_utils.py
froide/helper/csv_utils.py
from django.utils import six from django.http import StreamingHttpResponse def export_csv_response(queryset, fields, name='export.csv'): response = StreamingHttpResponse(export_csv(queryset, fields), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % name return response class FakeFile(object): # unicodecsv doesn't return values # so temp store them in here def write(self, string): self._last_string = string if six.PY3: self._last_string = self._last_string.encode('utf-8') def export_csv(queryset, fields): if six.PY3: import csv else: import unicodecsv as csv f = FakeFile() writer = csv.DictWriter(f, fields) writer.writeheader() yield f._last_string for obj in queryset: if hasattr(obj, 'get_dict'): d = obj.get_dict(fields) else: d = {} for field in fields: value = getattr(obj, field, '') if value is None: d[field] = "" else: d[field] = six.text_type(value) writer.writerow(d) yield f._last_string def export_csv_bytes(generator): return six.binary_type().join(generator)
from django.utils import six from django.http import StreamingHttpResponse def export_csv_response(generator, name='export.csv'): response = StreamingHttpResponse(generator, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % name return response class FakeFile(object): # unicodecsv doesn't return values # so temp store them in here def write(self, string): self._last_string = string if six.PY3: self._last_string = self._last_string.encode('utf-8') def export_csv(queryset, fields): if six.PY3: import csv else: import unicodecsv as csv f = FakeFile() writer = csv.DictWriter(f, fields) writer.writeheader() yield f._last_string for obj in queryset: if hasattr(obj, 'get_dict'): d = obj.get_dict(fields) else: d = {} for field in fields: value = getattr(obj, field, '') if value is None: d[field] = "" else: d[field] = six.text_type(value) writer.writerow(d) yield f._last_string def export_csv_bytes(generator): return six.binary_type().join(generator)
Fix export_csv_response function to take generator
Fix export_csv_response function to take generator
Python
mit
LilithWittmann/froide,catcosmo/froide,fin/froide,stefanw/froide,catcosmo/froide,catcosmo/froide,ryankanno/froide,catcosmo/froide,catcosmo/froide,ryankanno/froide,okfse/froide,fin/froide,CodeforHawaii/froide,CodeforHawaii/froide,okfse/froide,stefanw/froide,stefanw/froide,LilithWittmann/froide,okfse/froide,ryankanno/froide,ryankanno/froide,CodeforHawaii/froide,LilithWittmann/froide,LilithWittmann/froide,okfse/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,ryankanno/froide,fin/froide,fin/froide,CodeforHawaii/froide,stefanw/froide,okfse/froide
--- +++ @@ -2,9 +2,8 @@ from django.http import StreamingHttpResponse -def export_csv_response(queryset, fields, name='export.csv'): - response = StreamingHttpResponse(export_csv(queryset, fields), - content_type='text/csv') +def export_csv_response(generator, name='export.csv'): + response = StreamingHttpResponse(generator, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % name return response
ecc9efaf3bbbb3d6231d1217ff124d8237ac09bb
chef/role.py
chef/role.py
from chef.base import ChefObject class Role(ChefObject): """A model object for a Chef role.""" url = '/roles' attributes = [ 'description', ]
from chef.base import ChefObject class Role(ChefObject): """A model object for a Chef role.""" url = '/roles' attributes = [ 'description', 'run_list', ]
Add run_list to Role for testing.
Add run_list to Role for testing.
Python
apache-2.0
cread/pychef,Scalr/pychef,Scalr/pychef,cread/pychef,jarosser06/pychef,coderanger/pychef,coderanger/pychef,dipakvwarade/pychef,jarosser06/pychef,dipakvwarade/pychef
--- +++ @@ -6,5 +6,6 @@ url = '/roles' attributes = [ 'description', + 'run_list', ]
26598254cd48a716527eb4689ad96551c5a39790
ksp_login/__init__.py
ksp_login/__init__.py
__version__ = '0.6.0' __version_info__ = __version__.split('.') from django.utils.translation import ugettext_lazy as _ def __activate_social_auth_monkeypatch(): from social_core.backends.base import BaseAuth from social_core.backends.open_id import (OPENID_ID_FIELD, OpenIdAuth) from social_core.backends.livejournal import LiveJournalOpenId from social_core.backends.yahoo import YahooOpenId from social_core.backends.google import GoogleOpenId from social_core.backends.yandex import YandexOpenId BaseAuth.REQUIRED_FIELD_NAME = None BaseAuth.REQUIRED_FIELD_VERBOSE_NAME = None OpenIdAuth.REQUIRED_FIELD_NAME = OPENID_ID_FIELD OpenIdAuth.REQUIRED_FIELD_VERBOSE_NAME = _('OpenID identity') LiveJournalOpenId.REQUIRED_FIELD_NAME = 'openid_lj_user' LiveJournalOpenId.REQUIRED_FIELD_VERBOSE_NAME = _('LiveJournal username') # Reset to None in those OpenID backends where nothing is required. GoogleOpenId.REQUIRED_FIELD_NAME = None GoogleOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YahooOpenId.REQUIRED_FIELD_NAME = None YahooOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YandexOpenId.REQUIRED_FIELD_NAME = None YandexOpenId.REQUIRED_FIELD_VERBOSE_NAME = None __activate_social_auth_monkeypatch()
__version__ = '0.6.0' __version_info__ = tuple(map(int, __version__.split('.'))) from django.utils.translation import ugettext_lazy as _ def __activate_social_auth_monkeypatch(): from social_core.backends.base import BaseAuth from social_core.backends.open_id import (OPENID_ID_FIELD, OpenIdAuth) from social_core.backends.livejournal import LiveJournalOpenId from social_core.backends.yahoo import YahooOpenId from social_core.backends.google import GoogleOpenId from social_core.backends.yandex import YandexOpenId BaseAuth.REQUIRED_FIELD_NAME = None BaseAuth.REQUIRED_FIELD_VERBOSE_NAME = None OpenIdAuth.REQUIRED_FIELD_NAME = OPENID_ID_FIELD OpenIdAuth.REQUIRED_FIELD_VERBOSE_NAME = _('OpenID identity') LiveJournalOpenId.REQUIRED_FIELD_NAME = 'openid_lj_user' LiveJournalOpenId.REQUIRED_FIELD_VERBOSE_NAME = _('LiveJournal username') # Reset to None in those OpenID backends where nothing is required. GoogleOpenId.REQUIRED_FIELD_NAME = None GoogleOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YahooOpenId.REQUIRED_FIELD_NAME = None YahooOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YandexOpenId.REQUIRED_FIELD_NAME = None YandexOpenId.REQUIRED_FIELD_VERBOSE_NAME = None __activate_social_auth_monkeypatch()
Make version info tuple of ints.
Make version info tuple of ints.
Python
bsd-3-clause
koniiiik/ksp_login,koniiiik/ksp_login,koniiiik/ksp_login
--- +++ @@ -1,5 +1,5 @@ __version__ = '0.6.0' -__version_info__ = __version__.split('.') +__version_info__ = tuple(map(int, __version__.split('.'))) from django.utils.translation import ugettext_lazy as _ @@ -29,4 +29,5 @@ YandexOpenId.REQUIRED_FIELD_NAME = None YandexOpenId.REQUIRED_FIELD_VERBOSE_NAME = None + __activate_social_auth_monkeypatch()
d9fd011a2750a01cac67aa6ca37c0aedc2a7ad94
law/workflow/local.py
law/workflow/local.py
# -*- coding: utf-8 -*- """ Local workflow implementation. """ __all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
# -*- coding: utf-8 -*- """ Local workflow implementation. """ __all__ = ["LocalWorkflow"] from law.workflow.base import Workflow, WorkflowProxy class LocalWorkflowProxy(WorkflowProxy): workflow_type = "local" def __init__(self, *args, **kwargs): super(LocalWorkflowProxy, self).__init__(*args, **kwargs) self._has_run = False def complete(self): return self._has_run def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs def run(self): self._has_run = True class LocalWorkflow(Workflow): exclude_db = True workflow_proxy_cls = LocalWorkflowProxy
Add missing run method to LocalWorkflow.
Add missing run method to LocalWorkflow.
Python
bsd-3-clause
riga/law,riga/law
--- +++ @@ -15,10 +15,21 @@ workflow_type = "local" + def __init__(self, *args, **kwargs): + super(LocalWorkflowProxy, self).__init__(*args, **kwargs) + + self._has_run = False + + def complete(self): + return self._has_run + def requires(self): reqs = super(LocalWorkflowProxy, self).requires() reqs["branches"] = self.task.get_branch_tasks() return reqs + + def run(self): + self._has_run = True class LocalWorkflow(Workflow):
3b92d215a42a8c4047d2be57b7679b87a6bfb737
cnxmathml2svg.py
cnxmathml2svg.py
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from pyramid.config import Configurator __all__ = ('main',) def main(global_config, **settings): """Application factory""" config = Configurator(settings=settings) return config.make_wsgi_app()
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### from pyramid.config import Configurator from pyramid.response import Response __all__ = ('main',) def convert(request): """Convert the POST'd MathML to SVG""" return Response() def main(global_config, **settings): """Application factory""" config = Configurator(settings=settings) config.add_route('convert', '/', request_method='POST') config.add_view(convert, route_name='convert') return config.make_wsgi_app()
Add the conversion view to the app.
Add the conversion view to the app.
Python
agpl-3.0
Connexions/cnx-mathml2svg,pumazi/cnx-mathml2svg
--- +++ @@ -6,12 +6,19 @@ # See LICENCE.txt for details. # ### from pyramid.config import Configurator +from pyramid.response import Response + +__all__ = ('main',) -__all__ = ('main',) +def convert(request): + """Convert the POST'd MathML to SVG""" + return Response() def main(global_config, **settings): """Application factory""" config = Configurator(settings=settings) + config.add_route('convert', '/', request_method='POST') + config.add_view(convert, route_name='convert') return config.make_wsgi_app()
4dae2456d36a92951beaca2f57ddbed575103cf6
moksha/api/hub/consumer.py
moksha/api/hub/consumer.py
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. # Authors: Luke Macken <lmacken@redhat.com> class Consumer(object): """ A message consumer """ topic = None def consume(self, message): raise NotImplementedError
# This file is part of Moksha. # # Moksha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Moksha 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. """ :mod:`moksha.api.hub.consumer` - The Moksha Consumer API ======================================================== Moksha provides a simple API for creating "consumers" of message topics. This means that your consumer is instantiated when the MokshaHub is initially loaded, and receives each message for the specified topic through the :meth:`Consumer.consume` method. .. moduleauthor:: Luke Macken <lmacken@redhat.com> """ from moksha.hub.hub import MokshaHub class Consumer(object): """ A message consumer """ topic = None def __init__(self): self.hub = MokshaHub() def consume(self, message): raise NotImplementedError def send_message(self, topic, message): try: self.hub.send_message(topic, message) except Exception, e: log.error('Cannot send message: %s' % e) def stop(self): self.hub.close()
Add a send_message and stop methods to the Consumer, along with some module docs.
Add a send_message and stop methods to the Consumer, along with some module docs.
Python
apache-2.0
lmacken/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha
--- +++ @@ -14,11 +14,36 @@ # along with Moksha. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2008, Red Hat, Inc. -# Authors: Luke Macken <lmacken@redhat.com> + +""" +:mod:`moksha.api.hub.consumer` - The Moksha Consumer API +======================================================== +Moksha provides a simple API for creating "consumers" of message topics. + +This means that your consumer is instantiated when the MokshaHub is initially +loaded, and receives each message for the specified topic through the +:meth:`Consumer.consume` method. + +.. moduleauthor:: Luke Macken <lmacken@redhat.com> +""" + +from moksha.hub.hub import MokshaHub class Consumer(object): """ A message consumer """ topic = None + def __init__(self): + self.hub = MokshaHub() + def consume(self, message): raise NotImplementedError + + def send_message(self, topic, message): + try: + self.hub.send_message(topic, message) + except Exception, e: + log.error('Cannot send message: %s' % e) + + def stop(self): + self.hub.close()
d106719a0b7bcbd87989bd36f618f90c4df02c46
sequana/gui/browser.py
sequana/gui/browser.py
# coding: utf-8 from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): closing = QtCore.Signal() def __init(self): super().__init__() self.loadFinished.connec(self._results_available) def _results_available(self, ok): print("results") frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): print("done") self.closing.emit()
# coding: utf-8 from PyQt5 import QtCore from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): #closing = QtCore.Signal() def __init(self): super().__init__() self.loadFinished.connec(self._results_available) def _results_available(self, ok): frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): #print("done") pass #self.closing.emit()
Fix issue with signal on tars
Fix issue with signal on tars
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
--- +++ @@ -1,21 +1,22 @@ # coding: utf-8 from PyQt5 import QtCore - from PyQt5.QtWebKitWidgets import QWebView class MyBrowser(QWebView): - closing = QtCore.Signal() + #closing = QtCore.Signal() + def __init(self): super().__init__() self.loadFinished.connec(self._results_available) + def _results_available(self, ok): - print("results") frame = self.page().mainFrame() print(unicode(frame.toHtml()).encode('utf-8')) def closeEvent(self, event): - print("done") - self.closing.emit() + #print("done") + pass + #self.closing.emit()
a6b6d229aa83497f43f04104498394fbd5df9fb8
articles/models.py
articles/models.py
from django.db import models from django.urls import reverse class Tag(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name def get_absolute_url(self): return reverse('articles:tagged-list', args=[self.name]) class Article(models.Model): title = models.CharField(max_length=50) tags = models.ManyToManyField(Tag) content = models.TextField() views = models.PositiveIntegerField(default=0) likes = models.PositiveIntegerField(default=0) # DateTime first_commit = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:detail', args=[self.id]) def summary(self): return self.content[:self.content.find('\n')] def reading_time(self): return 5 # TODO
from django.db import models from django.urls import reverse class Tag(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name def get_absolute_url(self): return reverse('articles:tagged-list', kwargs={'tags_with_plus': self.name}) class Article(models.Model): title = models.CharField(max_length=50) tags = models.ManyToManyField(Tag) content = models.TextField() views = models.PositiveIntegerField(default=0) likes = models.PositiveIntegerField(default=0) # DateTime first_commit = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:detail', kwargs={'pk': self.pk}) def summary(self): return self.content[:self.content.find('\n')] def reading_time(self): return 5 # TODO
Use kwargs instead of args in reverse in get_absolute_url method
Use kwargs instead of args in reverse in get_absolute_url method
Python
bsd-3-clause
invzhi/invzhi.me,invzhi/invzhi.me
--- +++ @@ -9,7 +9,8 @@ return self.name def get_absolute_url(self): - return reverse('articles:tagged-list', args=[self.name]) + return reverse('articles:tagged-list', + kwargs={'tags_with_plus': self.name}) class Article(models.Model): @@ -27,7 +28,7 @@ return self.title def get_absolute_url(self): - return reverse('articles:detail', args=[self.id]) + return reverse('articles:detail', kwargs={'pk': self.pk}) def summary(self): return self.content[:self.content.find('\n')]
03b4e218e796bf2cc42015f70195fb4a5e13f33b
decision/__init__.py
decision/__init__.py
import os, logging from flask import Flask from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) app.logger.info("\nConfiguration\n%s\n" % app.config) # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) # Validate config for property_to_check in ['CASEWORK_URL', 'CHECK_URL']: if not app.config[property_to_check]: raise Exception('Missing %r configuation property.' % (property_to_check))
import os, logging from flask import Flask from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) app.logger.debug("\nConfiguration\n%s\n" % app.config) # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) # Validate config for property_to_check in ['CASEWORK_URL', 'CHECK_URL']: if not app.config[property_to_check]: raise Exception('Missing %r configuation property.' % (property_to_check))
Set config logging in init to debug
Set config logging in init to debug
Python
mit
LandRegistry/decision-alpha,LandRegistry/decision-alpha
--- +++ @@ -6,7 +6,7 @@ app.config.from_object(os.environ.get('SETTINGS')) -app.logger.info("\nConfiguration\n%s\n" % app.config) +app.logger.debug("\nConfiguration\n%s\n" % app.config) # Sentry exception reporting if 'SENTRY_DSN' in os.environ: @@ -16,8 +16,8 @@ app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) -# Validate config +# Validate config for property_to_check in ['CASEWORK_URL', 'CHECK_URL']: if not app.config[property_to_check]: raise Exception('Missing %r configuation property.' % (property_to_check)) - +
99cb654ec5730f6be33bb091aa3ac9e70963470c
hc/front/tests/test_add_channel.py
hc/front/tests/test_add_channel.py
from django.contrib.auth.models import User from django.test import TestCase from hc.api.models import Channel class AddChannelTestCase(TestCase): def setUp(self): self.alice = User(username="alice") self.alice.set_password("password") self.alice.save() def test_it_works(self): url = "/integrations/add/" form = {"kind": "email", "value": "alice@example.org"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 302 assert Channel.objects.count() == 1 def test_it_rejects_bad_kind(self): url = "/integrations/add/" form = {"kind": "dog", "value": "Lassie"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 400, r.status_code def test_instructions_work(self): self.client.login(username="alice", password="password") for frag in ("email", "webhook", "pd", "pushover", "slack", "hipchat"): url = "/integrations/add_%s/" % frag r = self.client.get(url) self.assertContains(r, "Integration Settings", status_code=200)
from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from hc.api.models import Channel class AddChannelTestCase(TestCase): def setUp(self): self.alice = User(username="alice") self.alice.set_password("password") self.alice.save() settings.PUSHOVER_API_TOKEN = "bogus_token" settings.PUSHOVER_SUBSCRIPTION_URL = "bogus_url" def test_it_works(self): url = "/integrations/add/" form = {"kind": "email", "value": "alice@example.org"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 302 assert Channel.objects.count() == 1 def test_it_rejects_bad_kind(self): url = "/integrations/add/" form = {"kind": "dog", "value": "Lassie"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 400, r.status_code def test_instructions_work(self): self.client.login(username="alice", password="password") for frag in ("email", "webhook", "pd", "pushover", "slack", "hipchat"): url = "/integrations/add_%s/" % frag r = self.client.get(url) self.assertContains(r, "Integration Settings", status_code=200)
Fix tests when Pushover is not configured
Fix tests when Pushover is not configured
Python
bsd-3-clause
healthchecks/healthchecks,iphoting/healthchecks,BetterWorks/healthchecks,BetterWorks/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,iphoting/healthchecks,iphoting/healthchecks,BetterWorks/healthchecks,BetterWorks/healthchecks,iphoting/healthchecks
--- +++ @@ -1,3 +1,4 @@ +from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from hc.api.models import Channel @@ -9,6 +10,9 @@ self.alice = User(username="alice") self.alice.set_password("password") self.alice.save() + + settings.PUSHOVER_API_TOKEN = "bogus_token" + settings.PUSHOVER_SUBSCRIPTION_URL = "bogus_url" def test_it_works(self): url = "/integrations/add/"
f65fd97940cb1f9c146de1b95c6e1e8652ae0c52
bonspy/__init__.py
bonspy/__init__.py
# -*- coding: utf-8 -*- from __future__ import ( print_function, division, generators, absolute_import, unicode_literals ) from .bonsai import BonsaiTree from .logistic import LogisticConverter
# -*- coding: utf-8 -*- from __future__ import ( print_function, division, generators, absolute_import, unicode_literals ) from bonspy.bonsai import BonsaiTree from bonspy.logistic import LogisticConverter
Use more robust absolute imports
Use more robust absolute imports
Python
bsd-3-clause
markovianhq/bonspy
--- +++ @@ -5,5 +5,5 @@ absolute_import, unicode_literals ) -from .bonsai import BonsaiTree -from .logistic import LogisticConverter +from bonspy.bonsai import BonsaiTree +from bonspy.logistic import LogisticConverter
0a73784ca3995b42b77d9a4cb3e6903154ef8914
bokeh/models/widgets/panels.py
bokeh/models/widgets/panels.py
""" Various kinds of panel widgets. """ from __future__ import absolute_import from ...properties import Bool, Int, String, Instance, List from ..widget import Widget from ..actions import Callback class Panel(Widget): """ A single-widget container with title bar and controls. """ title = String(help=""" An optional text title of the panel. """) child = Instance(Widget, help=""" The child widget. If you need more children, use a layout widget, e.g. ``HBox`` or ``VBox``. """) closable = Bool(False, help=""" Whether this panel is closeable or not. If True, an "x" button will appear. """) class Tabs(Widget): """ A panel widget with navigation tabs. """ tabs = List(Instance(Panel), help=""" The list of child panel widgets. """) active = Int(0, help=""" The index of the active tab. """) callback = Instance(Callback, help=""" A callback to run in the browser whenever the button is activated. """)
""" Various kinds of panel widgets. """ from __future__ import absolute_import from ...properties import Bool, Int, String, Instance, List from ..widget import Widget from ..callbacks import Callback class Panel(Widget): """ A single-widget container with title bar and controls. """ title = String(help=""" An optional text title of the panel. """) child = Instance(Widget, help=""" The child widget. If you need more children, use a layout widget, e.g. ``HBox`` or ``VBox``. """) closable = Bool(False, help=""" Whether this panel is closeable or not. If True, an "x" button will appear. """) class Tabs(Widget): """ A panel widget with navigation tabs. """ tabs = List(Instance(Panel), help=""" The list of child panel widgets. """) active = Int(0, help=""" The index of the active tab. """) callback = Instance(Callback, help=""" A callback to run in the browser whenever the button is activated. """)
Fix comflict (not merge conflict) because of those inter-related PRs.
Fix comflict (not merge conflict) because of those inter-related PRs.
Python
bsd-3-clause
khkaminska/bokeh,ericmjl/bokeh,ChinaQuants/bokeh,jplourenco/bokeh,clairetang6/bokeh,Karel-van-de-Plassche/bokeh,phobson/bokeh,srinathv/bokeh,rs2/bokeh,muku42/bokeh,Karel-van-de-Plassche/bokeh,KasperPRasmussen/bokeh,aavanian/bokeh,schoolie/bokeh,paultcochrane/bokeh,gpfreitas/bokeh,bokeh/bokeh,jplourenco/bokeh,aavanian/bokeh,ChinaQuants/bokeh,tacaswell/bokeh,phobson/bokeh,stonebig/bokeh,ptitjano/bokeh,DuCorey/bokeh,daodaoliang/bokeh,bokeh/bokeh,percyfal/bokeh,quasiben/bokeh,azjps/bokeh,ericdill/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,phobson/bokeh,DuCorey/bokeh,draperjames/bokeh,KasperPRasmussen/bokeh,azjps/bokeh,srinathv/bokeh,muku42/bokeh,xguse/bokeh,philippjfr/bokeh,matbra/bokeh,paultcochrane/bokeh,quasiben/bokeh,htygithub/bokeh,timsnyder/bokeh,stonebig/bokeh,matbra/bokeh,ericmjl/bokeh,azjps/bokeh,philippjfr/bokeh,rs2/bokeh,schoolie/bokeh,justacec/bokeh,aavanian/bokeh,ChinaQuants/bokeh,rs2/bokeh,philippjfr/bokeh,stonebig/bokeh,aiguofer/bokeh,DuCorey/bokeh,KasperPRasmussen/bokeh,daodaoliang/bokeh,ericdill/bokeh,evidation-health/bokeh,clairetang6/bokeh,draperjames/bokeh,justacec/bokeh,DuCorey/bokeh,muku42/bokeh,rs2/bokeh,gpfreitas/bokeh,ChinaQuants/bokeh,rothnic/bokeh,khkaminska/bokeh,ericmjl/bokeh,azjps/bokeh,tacaswell/bokeh,htygithub/bokeh,azjps/bokeh,jakirkham/bokeh,philippjfr/bokeh,gpfreitas/bokeh,percyfal/bokeh,justacec/bokeh,Karel-van-de-Plassche/bokeh,matbra/bokeh,deeplook/bokeh,ptitjano/bokeh,aavanian/bokeh,mindriot101/bokeh,aavanian/bokeh,ericdill/bokeh,deeplook/bokeh,phobson/bokeh,rothnic/bokeh,bokeh/bokeh,khkaminska/bokeh,rs2/bokeh,deeplook/bokeh,jplourenco/bokeh,bokeh/bokeh,srinathv/bokeh,khkaminska/bokeh,mindriot101/bokeh,dennisobrien/bokeh,maxalbert/bokeh,mindriot101/bokeh,schoolie/bokeh,xguse/bokeh,jakirkham/bokeh,stonebig/bokeh,phobson/bokeh,dennisobrien/bokeh,deeplook/bokeh,evidation-health/bokeh,jakirkham/bokeh,draperjames/bokeh,Karel-van-de-Plassche/bokeh,jplourenco/bokeh,matbra/bokeh,rothnic/bokeh,paultcochrane/bokeh,clairetang6/bokeh,tacaswell/bokeh,xguse/bokeh,timsnyder/bokeh,mindriot101/bokeh,KasperPRasmussen/bokeh,xguse/bokeh,maxalbert/bokeh,paultcochrane/bokeh,msarahan/bokeh,muku42/bokeh,gpfreitas/bokeh,htygithub/bokeh,KasperPRasmussen/bokeh,aiguofer/bokeh,dennisobrien/bokeh,aiguofer/bokeh,srinathv/bokeh,timsnyder/bokeh,msarahan/bokeh,rothnic/bokeh,daodaoliang/bokeh,evidation-health/bokeh,ericmjl/bokeh,dennisobrien/bokeh,maxalbert/bokeh,ptitjano/bokeh,percyfal/bokeh,ptitjano/bokeh,clairetang6/bokeh,percyfal/bokeh,ericdill/bokeh,htygithub/bokeh,draperjames/bokeh,timsnyder/bokeh,tacaswell/bokeh,schoolie/bokeh,maxalbert/bokeh,aiguofer/bokeh,draperjames/bokeh,schoolie/bokeh,DuCorey/bokeh,msarahan/bokeh,daodaoliang/bokeh,aiguofer/bokeh,msarahan/bokeh,bokeh/bokeh,quasiben/bokeh,timsnyder/bokeh,evidation-health/bokeh,philippjfr/bokeh,jakirkham/bokeh,dennisobrien/bokeh,percyfal/bokeh,jakirkham/bokeh,justacec/bokeh,ptitjano/bokeh
--- +++ @@ -5,7 +5,7 @@ from ...properties import Bool, Int, String, Instance, List from ..widget import Widget -from ..actions import Callback +from ..callbacks import Callback class Panel(Widget): """ A single-widget container with title bar and controls.
fbaf1a64621e8b72b7ee46b8c58a12ed96a0f41f
utils/summary_downloader.py
utils/summary_downloader.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from dateutil.parser import parse from dateutil.relativedelta import DAILY from dateutil.rrule import rrule class SummaryDownloader(): # base url for official schedule json page SCHEDULE_URL_BASE = "http://statsapi.web.nhl.com/api/v1/schedule" # url template for official json gamefeed page JSON_GAME_FEED_URL_TEMPLATE = ( "http://statsapi.web.nhl.com/api/v1/game/%s/feed/live") MAX_DOWNLOAD_WORKERS = 8 def __init__(self, tgt_dir, date, to_date='', threads=0): self.date = parse(date) if to_date: self.to_date = parse(to_date) else: self.to_date = self.date # preparing list of dates to download summary data for self.game_dates = list( rrule(DAILY, dtstart=self.date, until=self.to_date)) print(self.game_dates) if __name__ == '__main__': date = "1997/04/20" d = SummaryDownloader(r"d:\tmp", date)
#!/usr/bin/env python # -*- coding: utf-8 -*- from dateutil.parser import parse from dateutil.rrule import rrule, DAILY class SummaryDownloader(): # base url for official schedule json page SCHEDULE_URL_BASE = "http://statsapi.web.nhl.com/api/v1/schedule" # url template for official json gamefeed page JSON_GAME_FEED_URL_TEMPLATE = ( "http://statsapi.web.nhl.com/api/v1/game/%s/feed/live") MAX_DOWNLOAD_WORKERS = 8 def __init__(self, tgt_dir, date, to_date='', workers=0): # parsing start date for summary retrieval self.date = parse(date) # retrieving end date for summary retrieval if to_date: self.to_date = parse(to_date) else: self.to_date = self.date # preparing list of dates to download summary data for self.game_dates = list( rrule(DAILY, dtstart=self.date, until=self.to_date)) if workers: self.MAX_DOWNLOAD_WORKERS = workers def find_files_to_download(self): """ Identifies files to be downloaded. """ # making sure that the list of files to download is empty self.files_to_download = list() if __name__ == '__main__': date = "1997/04/20" to_date = "1998/01/31" d = SummaryDownloader(r"d:\tmp", date, to_date)
Add function to find downloadable files
Add function to find downloadable files
Python
mit
leaffan/pynhldb
--- +++ @@ -2,8 +2,7 @@ # -*- coding: utf-8 -*- from dateutil.parser import parse -from dateutil.relativedelta import DAILY -from dateutil.rrule import rrule +from dateutil.rrule import rrule, DAILY class SummaryDownloader(): @@ -16,9 +15,11 @@ MAX_DOWNLOAD_WORKERS = 8 - def __init__(self, tgt_dir, date, to_date='', threads=0): + def __init__(self, tgt_dir, date, to_date='', workers=0): + # parsing start date for summary retrieval self.date = parse(date) + # retrieving end date for summary retrieval if to_date: self.to_date = parse(to_date) else: @@ -26,11 +27,21 @@ # preparing list of dates to download summary data for self.game_dates = list( rrule(DAILY, dtstart=self.date, until=self.to_date)) - print(self.game_dates) + + if workers: + self.MAX_DOWNLOAD_WORKERS = workers + + def find_files_to_download(self): + """ + Identifies files to be downloaded. + """ + # making sure that the list of files to download is empty + self.files_to_download = list() if __name__ == '__main__': date = "1997/04/20" + to_date = "1998/01/31" - d = SummaryDownloader(r"d:\tmp", date) + d = SummaryDownloader(r"d:\tmp", date, to_date)
a490a85e5842bd31a99a94f2530dbbea2d1c2584
bot/game/launch.py
bot/game/launch.py
import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id bot.answerCallbackQuery(callback_query_id, url="https://alvarogzp.github.io/telegram-games/rock-paper-scissors.html")
import telegram def callback_query_handler(bot: telegram.Bot, update: telegram.Update): callback_query = update.callback_query game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id bot.answerCallbackQuery(callback_query_id, url="https://rawgit.com/alvarogzp/telegram-games/develop/games/rock-paper-scissors/game.html")
Update url to point to return develop branch html page
Update url to point to return develop branch html page
Python
apache-2.0
alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games
--- +++ @@ -6,4 +6,4 @@ game_short_name = callback_query.game_short_name if game_short_name == "rock_paper_scissors": callback_query_id = callback_query.id - bot.answerCallbackQuery(callback_query_id, url="https://alvarogzp.github.io/telegram-games/rock-paper-scissors.html") + bot.answerCallbackQuery(callback_query_id, url="https://rawgit.com/alvarogzp/telegram-games/develop/games/rock-paper-scissors/game.html")
49ebd8bee6cc91cf80715a7b2e01c4cfbe78d1da
tests/regression/bug_122.py
tests/regression/bug_122.py
import logging import sys import threading import time import spotify if len(sys.argv) != 3: sys.exit('Usage: %s USERNAME PASSWORD' % sys.argv[0]) username, password = sys.argv[1], sys.argv[2] def login(session, username, password): logged_in_event = threading.Event() def logged_in_listener(session, error_type): logged_in_event.set() session.on(spotify.SessionEvent.LOGGED_IN, logged_in_listener) session.login(username, password) if not logged_in_event.wait(10): raise RuntimeError('Login timed out') while session.connection.state != spotify.ConnectionState.LOGGED_IN: time.sleep(0.1) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) session = spotify.Session() loop = spotify.EventLoop(session) loop.start() login(session, username, password) logger.debug('Getting playlist') pl = session.get_playlist( 'spotify:user:durden20:playlist:1chOHrXPCFcShCwB357MFX') logger.debug('Got playlist %r %r', pl, pl._sp_playlist) logger.debug('Loading playlist %r %r', pl, pl._sp_playlist) pl.load() logger.debug('Loaded playlist %r %r', pl, pl._sp_playlist) print pl print pl.tracks
from __future__ import print_function import logging import sys import threading import time import spotify if len(sys.argv) != 3: sys.exit('Usage: %s USERNAME PASSWORD' % sys.argv[0]) username, password = sys.argv[1], sys.argv[2] def login(session, username, password): logged_in_event = threading.Event() def logged_in_listener(session, error_type): logged_in_event.set() session.on(spotify.SessionEvent.LOGGED_IN, logged_in_listener) session.login(username, password) if not logged_in_event.wait(10): raise RuntimeError('Login timed out') while session.connection.state != spotify.ConnectionState.LOGGED_IN: time.sleep(0.1) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) session = spotify.Session() loop = spotify.EventLoop(session) loop.start() login(session, username, password) logger.debug('Getting playlist') pl = session.get_playlist( 'spotify:user:durden20:playlist:1chOHrXPCFcShCwB357MFX') logger.debug('Got playlist %r %r', pl, pl._sp_playlist) logger.debug('Loading playlist %r %r', pl, pl._sp_playlist) pl.load() logger.debug('Loaded playlist %r %r', pl, pl._sp_playlist) print(pl) print(pl.tracks)
Fix flake8 warning when running on Python 3
Fix flake8 warning when running on Python 3
Python
apache-2.0
felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify,mopidy/pyspotify,jodal/pyspotify,jodal/pyspotify,kotamat/pyspotify,felix1m/pyspotify,felix1m/pyspotify,kotamat/pyspotify,mopidy/pyspotify
--- +++ @@ -1,3 +1,5 @@ +from __future__ import print_function + import logging import sys import threading @@ -45,5 +47,5 @@ pl.load() logger.debug('Loaded playlist %r %r', pl, pl._sp_playlist) -print pl -print pl.tracks +print(pl) +print(pl.tracks)
ba0471464ab3f6d29fcc12fa2de9231581c07944
tst/utils.py
tst/utils.py
from __future__ import print_function import sys import string import json from colors import * def is_posix_filename(name, extra_chars=""): CHARS = string.letters + string.digits + "._-" + extra_chars return all(c in CHARS for c in name) def cprint(color, msg, file=sys.stdout, end='\n'): data = msg.__str__() if hasattr(msg, '__str__') else msg print(color + data + RESET, file=file, end=end) def _assert(condition, msg): if condition: return cprint(LRED, msg) sys.exit(1) def to_unicode(obj, encoding='utf-8'): assert isinstance(obj, basestring), type(obj) if isinstance(obj, unicode): return obj for encoding in ['utf-8', 'latin1']: try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: pass assert False, "tst: non-recognized encoding" def data2json(data): def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif hasattr(obj, 'email'): return obj.email() return obj return json.dumps( data, default=date_handler, indent=2, separators=(',', ': '), sort_keys=True, ensure_ascii=False)
from __future__ import print_function import sys import string import json from colors import * def is_posix_filename(name, extra_chars=""): CHARS = string.letters + string.digits + "._-" + extra_chars return all(c in CHARS for c in name) def cprint(color, msg, file=sys.stdout, end='\n'): if type(msg) is unicode: data = msg elif type(msg) is str: data = msg.__str__() print(color + data + RESET, file=file, end=end) def _assert(condition, msg): if condition: return cprint(LRED, msg) sys.exit(1) def to_unicode(obj, encoding='utf-8'): assert isinstance(obj, basestring), type(obj) if isinstance(obj, unicode): return obj for encoding in ['utf-8', 'latin1']: try: obj = unicode(obj, encoding) return obj except UnicodeDecodeError: pass assert False, "tst: non-recognized encoding" def data2json(data): def date_handler(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() elif hasattr(obj, 'email'): return obj.email() return obj return json.dumps( data, default=date_handler, indent=2, separators=(',', ': '), sort_keys=True, ensure_ascii=False)
Fix cprint with unicode characters
Fix cprint with unicode characters
Python
agpl-3.0
daltonserey/tst,daltonserey/tst
--- +++ @@ -13,7 +13,10 @@ def cprint(color, msg, file=sys.stdout, end='\n'): - data = msg.__str__() if hasattr(msg, '__str__') else msg + if type(msg) is unicode: + data = msg + elif type(msg) is str: + data = msg.__str__() print(color + data + RESET, file=file, end=end)
685fa68b79b4d21f69fe55f66724191d30bbbaa8
contact/views.py
contact/views.py
from rest_framework import serializers from rest_framework.views import APIView from rest_framework.response import Response from django import http from .tasks import send_contact_form_inquiry # Serializers define the API representation. class ContactSerializer(serializers.Serializer): email = serializers.EmailField() name = serializers.CharField(max_length=255) content = serializers.CharField() source = serializers.CharField(max_length=255) organization = serializers.CharField(max_length=255, required=False) def create(self, validated_data): return validated_data class ContactAPIView(APIView): permission_classes = () def post(self, request, *args, **kwargs): serializer = ContactSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) # call async task to send email send_contact_form_inquiry.delay(**serializer.data) if request.GET.get('next') and not request.is_ajax(): # TODO should this be validated? return http.HttpResponseRedirect(request.GET.get('next')) data = {"status": "sent"} return Response(data)
from rest_framework import serializers from rest_framework.views import APIView from rest_framework.response import Response from django import http from .tasks import send_contact_form_inquiry # Serializers define the API representation. class ContactSerializer(serializers.Serializer): email = serializers.EmailField() name = serializers.CharField(max_length=255) content = serializers.CharField() source = serializers.CharField(max_length=255) organization = serializers.CharField(max_length=255, required=False) def create(self, validated_data): return validated_data class ContactAPIView(APIView): authentication_classes = [] permission_classes = [] def post(self, request, *args, **kwargs): serializer = ContactSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) # call async task to send email send_contact_form_inquiry.delay(**serializer.data) if request.GET.get('next') and not request.is_ajax(): # TODO should this be validated? return http.HttpResponseRedirect(request.GET.get('next')) data = {"status": "sent"} return Response(data)
Remove all permisson for contact API
Remove all permisson for contact API
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
--- +++ @@ -19,7 +19,8 @@ class ContactAPIView(APIView): - permission_classes = () + authentication_classes = [] + permission_classes = [] def post(self, request, *args, **kwargs): serializer = ContactSerializer(data=request.data, context={'request': request})
5523946b35d076c47be92d703cdb071c18f6d0ec
tests/test_subgenerators.py
tests/test_subgenerators.py
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run
Add test for decorated subgenerator
Add test for decorated subgenerator
Python
mit
FichteFoll/resumeback
--- +++ @@ -53,3 +53,21 @@ wrapper = func() wait_until_finished(wrapper) assert ts.run + + +def test_subgenerator_repurpose(): + ts = State() + val = 1234 + + @send_self + def func2(this): + assert (yield defer(this.send, val)) == val + ts.run = True + + @send_self + def func(this): + yield from func2.func(this) + + wrapper = func() + wait_until_finished(wrapper) + assert ts.run
a2b1d10e042d135c3c014622ffeabd7e96a46f9f
tests/test_update_target.py
tests/test_update_target.py
""" Tests for helper function for updating a target from a Vuforia database. """ import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ target_id = client.add_target( name='x', width=1, image=high_quality_image, ) client.update_target(target_id=target_id) result = client.get_target(target_id=target_id) expected_keys = { 'target_id', 'active_flag', 'name', 'width', 'tracking_rating', 'reco_rating', } assert result['target_record'].keys() == expected_keys def test_no_such_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ An ``UnknownTarget`` exception is raised when getting a target which does not exist. """ with pytest.raises(UnknownTarget): client.get_target(target_id='a')
""" Tests for helper function for updating a target from a Vuforia database. """ import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ # target_id = client.add_target( # name='x', # width=1, # image=high_quality_image, # ) # # client.update_target(target_id=target_id) # result = client.get_target(target_id=target_id) # expected_keys = { # 'target_id', # 'active_flag', # 'name', # 'width', # 'tracking_rating', # 'reco_rating', # } # assert result['target_record'].keys() == expected_keys # # def test_no_such_target( # self, # client: VWS, # high_quality_image: io.BytesIO, # ) -> None: # """ # An ``UnknownTarget`` exception is raised when getting a target which # does not exist. # """ # with pytest.raises(UnknownTarget): # client.get_target(target_id='a')
Comment out part done code
Comment out part done code
Python
mit
adamtheturtle/vws-python,adamtheturtle/vws-python
--- +++ @@ -23,32 +23,32 @@ """ Details of a target are returned by ``get_target``. """ - target_id = client.add_target( - name='x', - width=1, - image=high_quality_image, - ) - - client.update_target(target_id=target_id) - result = client.get_target(target_id=target_id) - expected_keys = { - 'target_id', - 'active_flag', - 'name', - 'width', - 'tracking_rating', - 'reco_rating', - } - assert result['target_record'].keys() == expected_keys - - def test_no_such_target( - self, - client: VWS, - high_quality_image: io.BytesIO, - ) -> None: - """ - An ``UnknownTarget`` exception is raised when getting a target which - does not exist. - """ - with pytest.raises(UnknownTarget): - client.get_target(target_id='a') + # target_id = client.add_target( + # name='x', + # width=1, + # image=high_quality_image, + # ) + # + # client.update_target(target_id=target_id) + # result = client.get_target(target_id=target_id) + # expected_keys = { + # 'target_id', + # 'active_flag', + # 'name', + # 'width', + # 'tracking_rating', + # 'reco_rating', + # } + # assert result['target_record'].keys() == expected_keys + # + # def test_no_such_target( + # self, + # client: VWS, + # high_quality_image: io.BytesIO, + # ) -> None: + # """ + # An ``UnknownTarget`` exception is raised when getting a target which + # does not exist. + # """ + # with pytest.raises(UnknownTarget): + # client.get_target(target_id='a')
cd0426dbbfc6f1573cf5d09485b8930eb498e1c6
mbuild/tests/test_utils.py
mbuild/tests/test_utils.py
import difflib import pytest from mbuild.tests.base_test import BaseTest from mbuild.utils.io import get_fn from mbuild.utils.validation import assert_port_exists class TestUtils(BaseTest): def test_assert_port_exists(self, ch2): assert_port_exists('up', ch2) with pytest.raises(ValueError): assert_port_exists('dog', ch2) def test_structure_reproducibility(self, alkane_monolayer): filename = 'monolayer-tmp.pdb' alkane_monolayer.save(filename) with open(get_fn('monolayer.pdb')) as file1: with open('monolayer-tmp.pdb') as file2: diff = difflib.ndiff(file1.readlines(), file2.readlines()) changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')] assert not changes
import difflib import numpy as np import pytest from mbuild.tests.base_test import BaseTest from mbuild.utils.io import get_fn, import_ from mbuild.utils.validation import assert_port_exists class TestUtils(BaseTest): def test_assert_port_exists(self, ch2): assert_port_exists('up', ch2) with pytest.raises(ValueError): assert_port_exists('dog', ch2) def test_structure_reproducibility(self, alkane_monolayer): filename = 'monolayer-tmp.pdb' alkane_monolayer.save(filename) with open(get_fn('monolayer.pdb')) as file1: with open('monolayer-tmp.pdb') as file2: diff = difflib.ndiff(file1.readlines(), file2.readlines()) changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')] assert not changes def test_fn(self): get_fn('benzene.mol2') with pytest.raises((IOError, OSError)): get_fn('garbage_file_name.foo') def test_import(self): assert np == import_('numpy') with pytest.raises(ImportError): import_('garbagepackagename')
Add some unit test on utils.io
Add some unit test on utils.io
Python
mit
iModels/mbuild,iModels/mbuild
--- +++ @@ -1,7 +1,10 @@ import difflib + +import numpy as np import pytest + from mbuild.tests.base_test import BaseTest -from mbuild.utils.io import get_fn +from mbuild.utils.io import get_fn, import_ from mbuild.utils.validation import assert_port_exists @@ -20,3 +23,15 @@ diff = difflib.ndiff(file1.readlines(), file2.readlines()) changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')] assert not changes + + def test_fn(self): + get_fn('benzene.mol2') + + with pytest.raises((IOError, OSError)): + get_fn('garbage_file_name.foo') + + def test_import(self): + assert np == import_('numpy') + + with pytest.raises(ImportError): + import_('garbagepackagename')
0b035ceaa611c13eac6e2cb01801ac46d9c2b13e
docs/__init__.py
docs/__init__.py
#! /usr/bin/env python3 def get_version(data): def all_same(s): return all(x == s[0] for x in s) def has_digit(s): return any(x.isdigit() for x in s) data = data.splitlines() return list( line for line, underline in zip(data, data[1:]) if (len(line) == len(underline) and all_same(underline) and has_digit(line) and "." in line), )[0]
#! /usr/bin/env python3 def get_version(data): def all_same(s): return all(x == s[0] for x in s) def has_digit(s): return any(x.isdigit() for x in s) data = data.splitlines() return list( line for line, underline in zip(data, data[1:]) if (len(line) == len(underline) and all_same(underline) and has_digit(line) and "." in line) )[0]
Fix syntax error in 3.7+
Fix syntax error in 3.7+ https://bugs.python.org/issue32012
Python
mit
Bystroushaak/pyDHTMLParser,Bystroushaak/pyDHTMLParser
--- +++ @@ -14,5 +14,5 @@ if (len(line) == len(underline) and all_same(underline) and has_digit(line) and - "." in line), + "." in line) )[0]
7b17a42713d0afedb594d184fb82fa3feab5681a
api/applications/urls.py
api/applications/urls.py
from django.conf.urls import url from api.applications import views urlpatterns = [ url(r'^$', views.ApplicationList.as_view(), name='application-list'), url(r'^(?P<client_id>\w+)/$', views.ApplicationDetail.as_view(), name='application-detail') ]
from django.conf.urls import url from api.applications import views urlpatterns = [ url(r'^$', views.ApplicationList.as_view(), name='application-list'), url(r'^(?P<client_id>\w+)/$', views.ApplicationDetail.as_view(), name='application-detail'), url(r'^(?P<client_id>\w+)/reset/$', views.ApplicationReset.as_view(), name='application-reset') ]
Add url for client secret resetting
Add url for client secret resetting
Python
apache-2.0
CenterForOpenScience/osf.io,samchrisinger/osf.io,SSJohns/osf.io,mfraezz/osf.io,alexschiller/osf.io,kwierman/osf.io,wearpants/osf.io,kwierman/osf.io,hmoco/osf.io,sloria/osf.io,binoculars/osf.io,brandonPurvis/osf.io,aaxelb/osf.io,ticklemepierce/osf.io,doublebits/osf.io,leb2dg/osf.io,brandonPurvis/osf.io,ticklemepierce/osf.io,amyshi188/osf.io,Johnetordoff/osf.io,abought/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,billyhunt/osf.io,billyhunt/osf.io,samanehsan/osf.io,crcresearch/osf.io,zamattiac/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,asanfilippo7/osf.io,billyhunt/osf.io,TomHeatwole/osf.io,amyshi188/osf.io,caseyrollins/osf.io,Ghalko/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,sloria/osf.io,mluke93/osf.io,rdhyee/osf.io,aaxelb/osf.io,kch8qx/osf.io,hmoco/osf.io,GageGaskins/osf.io,crcresearch/osf.io,zachjanicki/osf.io,laurenrevere/osf.io,chennan47/osf.io,abought/osf.io,caseyrollins/osf.io,pattisdr/osf.io,TomBaxter/osf.io,mfraezz/osf.io,kwierman/osf.io,KAsante95/osf.io,ticklemepierce/osf.io,adlius/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,brandonPurvis/osf.io,alexschiller/osf.io,TomBaxter/osf.io,rdhyee/osf.io,KAsante95/osf.io,felliott/osf.io,acshi/osf.io,brianjgeiger/osf.io,Ghalko/osf.io,samanehsan/osf.io,acshi/osf.io,doublebits/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,felliott/osf.io,cwisecarver/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,kch8qx/osf.io,samanehsan/osf.io,chennan47/osf.io,emetsger/osf.io,danielneis/osf.io,danielneis/osf.io,jnayak1/osf.io,kch8qx/osf.io,SSJohns/osf.io,cslzchen/osf.io,RomanZWang/osf.io,kch8qx/osf.io,adlius/osf.io,chrisseto/osf.io,acshi/osf.io,asanfilippo7/osf.io,hmoco/osf.io,laurenrevere/osf.io,billyhunt/osf.io,emetsger/osf.io,baylee-d/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,amyshi188/osf.io,leb2dg/osf.io,chennan47/osf.io,alexschiller/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,aaxelb/osf.io,RomanZWang/osf.io,alexschiller/osf.io,kch8qx/osf.io,aaxelb/osf.io,abought/osf.io,TomBaxter/osf.io,felliott/osf.io,jnayak1/osf.io,zamattiac/osf.io,mluo613/osf.io,adlius/osf.io,RomanZWang/osf.io,jnayak1/osf.io,monikagrabowska/osf.io,wearpants/osf.io,brandonPurvis/osf.io,abought/osf.io,mluke93/osf.io,mluo613/osf.io,asanfilippo7/osf.io,leb2dg/osf.io,billyhunt/osf.io,crcresearch/osf.io,erinspace/osf.io,amyshi188/osf.io,chrisseto/osf.io,sloria/osf.io,mluo613/osf.io,DanielSBrown/osf.io,acshi/osf.io,rdhyee/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,zamattiac/osf.io,zamattiac/osf.io,samchrisinger/osf.io,caneruguz/osf.io,wearpants/osf.io,Ghalko/osf.io,icereval/osf.io,doublebits/osf.io,GageGaskins/osf.io,cslzchen/osf.io,baylee-d/osf.io,RomanZWang/osf.io,danielneis/osf.io,alexschiller/osf.io,binoculars/osf.io,Ghalko/osf.io,saradbowman/osf.io,adlius/osf.io,laurenrevere/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,RomanZWang/osf.io,jnayak1/osf.io,cwisecarver/osf.io,samanehsan/osf.io,caneruguz/osf.io,caneruguz/osf.io,hmoco/osf.io,doublebits/osf.io,ticklemepierce/osf.io,monikagrabowska/osf.io,SSJohns/osf.io,cslzchen/osf.io,zachjanicki/osf.io,danielneis/osf.io,pattisdr/osf.io,monikagrabowska/osf.io,DanielSBrown/osf.io,mluke93/osf.io,Nesiehr/osf.io,mfraezz/osf.io,binoculars/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,caneruguz/osf.io,TomHeatwole/osf.io,mattclark/osf.io,mluo613/osf.io,erinspace/osf.io,SSJohns/osf.io,TomHeatwole/osf.io,acshi/osf.io,GageGaskins/osf.io,asanfilippo7/osf.io,GageGaskins/osf.io,brianjgeiger/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,icereval/osf.io,emetsger/osf.io,chrisseto/osf.io,samchrisinger/osf.io,emetsger/osf.io,wearpants/osf.io,chrisseto/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,felliott/osf.io,monikagrabowska/osf.io,KAsante95/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mluke93/osf.io,doublebits/osf.io,leb2dg/osf.io,rdhyee/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io
--- +++ @@ -4,5 +4,6 @@ urlpatterns = [ url(r'^$', views.ApplicationList.as_view(), name='application-list'), - url(r'^(?P<client_id>\w+)/$', views.ApplicationDetail.as_view(), name='application-detail') + url(r'^(?P<client_id>\w+)/$', views.ApplicationDetail.as_view(), name='application-detail'), + url(r'^(?P<client_id>\w+)/reset/$', views.ApplicationReset.as_view(), name='application-reset') ]
f23ee95c7b662dec71ed7fd527854a7f832e3603
Lib/test/test_ctypes.py
Lib/test/test_ctypes.py
# trivial test import _ctypes import ctypes
import unittest from test.test_support import run_suite import ctypes.test def test_main(): skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0) suites = [unittest.makeSuite(t) for t in testcases] run_suite(unittest.TestSuite(suites)) if __name__ == "__main__": test_main()
Replace the trivial ctypes test (did only an import) with the real test suite.
Replace the trivial ctypes test (did only an import) with the real test suite.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -1,4 +1,12 @@ -# trivial test +import unittest -import _ctypes -import ctypes +from test.test_support import run_suite +import ctypes.test + +def test_main(): + skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0) + suites = [unittest.makeSuite(t) for t in testcases] + run_suite(unittest.TestSuite(suites)) + +if __name__ == "__main__": + test_main()
c12ec403fe382484b1963738143fe1ea2cbdb000
opps/images/templatetags/images_tags.py
opps/images/templatetags/images_tags.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1,image.crop_y1), (image.crop_x2,image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
Fix pep8, E231 missing whitespace after ','
Fix pep8, E231 missing whitespace after ','
Python
mit
williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps,opps/opps
--- +++ @@ -26,8 +26,8 @@ if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: - new['crop'] = ((image.crop_x1,image.crop_y1), - (image.crop_x2,image.crop_y2)) + new['crop'] = ((image.crop_x1, image.crop_y1), + (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
075d6e6cfe225c7bc57b8cb2ea66be646a207f10
cars196_dataset.py
cars196_dataset.py
# -*- coding: utf-8 -*- """ Created on Fri Dec 23 19:02:49 2016 @author: sakurai """ from fuel.datasets import H5PYDataset from fuel.utils import find_in_data_path from fuel.schemes import SequentialScheme from fuel.streams import DataStream class Cars196Dataset(H5PYDataset): _filename = 'cars196/cars196.hdf5' def __init__(self, which_sets, **kwargs): super(Cars196Dataset, self).__init__( file_or_path=find_in_data_path(self._filename), which_sets=which_sets, **kwargs) if __name__ == '__main__': dataset = Cars196Dataset(['train']) st = DataStream( dataset, iteration_scheme=SequentialScheme(dataset.num_examples, 1)) it = st.get_epoch_iterator() it.next()
# -*- coding: utf-8 -*- """ Created on Fri Dec 23 19:02:49 2016 @author: sakurai """ from fuel.datasets import H5PYDataset from fuel.utils import find_in_data_path from fuel.schemes import SequentialScheme from fuel.streams import DataStream class Cars196Dataset(H5PYDataset): _filename = 'cars196/cars196.hdf5' def __init__(self, which_sets, **kwargs): super(Cars196Dataset, self).__init__( file_or_path=find_in_data_path(self._filename), which_sets=which_sets, **kwargs) def load_as_ndarray(which_sets=['train', 'test']): datasets = [] for split in which_sets: data = Cars196Dataset([split], load_in_memory=True).data_sources datasets.append(data) return datasets if __name__ == '__main__': dataset = Cars196Dataset(['train']) st = DataStream( dataset, iteration_scheme=SequentialScheme(dataset.num_examples, 1)) it = st.get_epoch_iterator() it.next()
Load datasets as raw ndarray
Load datasets as raw ndarray
Python
mit
ronekko/deep_metric_learning
--- +++ @@ -20,6 +20,15 @@ file_or_path=find_in_data_path(self._filename), which_sets=which_sets, **kwargs) + +def load_as_ndarray(which_sets=['train', 'test']): + datasets = [] + for split in which_sets: + data = Cars196Dataset([split], load_in_memory=True).data_sources + datasets.append(data) + return datasets + + if __name__ == '__main__': dataset = Cars196Dataset(['train'])
36a4b66d3f9f7de52760da5e3c7f7c5f9170bb2a
bockus/prod_settings/__init__.py
bockus/prod_settings/__init__.py
from bockus.settings import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.config() ALLOWED_HOSTS = [ '.booksonas.com', '.herokuapp.com', 'localhost', '127.0.0.1', ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECRET_KEY = get_env_variable("SECRET_KEY") INSTALLED_APPS += ( 'gunicorn', )
from bockus.settings import * import dj_database_url DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.config() ALLOWED_HOSTS = [ '.booksonas.com', '.herokuapp.com', 'localhost', '127.0.0.1', ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECRET_KEY = get_env_variable("SECRET_KEY") INSTALLED_APPS += ( 'gunicorn', )
Change debug setting for testing.
Change debug setting for testing.
Python
mit
phildini/bockus,phildini/bockus,phildini/bockus
--- +++ @@ -1,7 +1,7 @@ from bockus.settings import * import dj_database_url -DEBUG = False +DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.config()
d05b9effc6d230aeb2a13759a67df644d75140ca
cts/views.py
cts/views.py
from django.http import HttpResponse def health_view(request): return HttpResponse()
from django.http import HttpResponse def health_view(request): return HttpResponse("I am okay.", content_type="text/plain")
Return some text on a health check
Return some text on a health check
Python
bsd-3-clause
theirc/CTS,theirc/CTS,theirc/CTS,stbenjam/CTS,stbenjam/CTS,stbenjam/CTS,stbenjam/CTS,theirc/CTS
--- +++ @@ -2,4 +2,4 @@ def health_view(request): - return HttpResponse() + return HttpResponse("I am okay.", content_type="text/plain")
68cca0cab9f2cfde6098801936d631aa8255adeb
tt_dailyemailblast/tasks.py
tt_dailyemailblast/tasks.py
from celery.task import task from . import models from .send_backends import sync @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) sync.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) sync.sync_recipients_list(recipients_list, blast) @task def send_recipients(recipient_pk, recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) recipient = models.Recipient.objects.get(pk=recipient_pk) sync.sync_recipient(recipient, recipients_list, blast)
from celery.task import task from . import models from .send_backends import sync @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) sync.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) sync.sync_recipients_list(recipients_list, blast) @task def send_recipient(recipient_pk, recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) recipient = models.Recipient.objects.get(pk=recipient_pk) sync.sync_recipient(recipient, recipients_list, blast)
Fix typo causing send_recipient task to fail
Fix typo causing send_recipient task to fail
Python
apache-2.0
texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast
--- +++ @@ -18,7 +18,7 @@ @task -def send_recipients(recipient_pk, recipients_list_pk, blast_pk): +def send_recipient(recipient_pk, recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) recipient = models.Recipient.objects.get(pk=recipient_pk)
912c81e99adf89d0c39ac19d1705bad4426d134b
tt_dailyemailblast/utils.py
tt_dailyemailblast/utils.py
from armstrong.utils.backends import GenericBackend def get_template_names(blast, recipient_list, recipient): return [ 'tt_dailyemailblast/%s/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug, recipient.slug), 'tt_dailyemailblast/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug), 'tt_dailyemailblast/%s.html' % blast.blast_type.slug, ] def dispatch_to_backend(backend, default, *args): """Configure a GenericBackend and call it with `*args`. :param backend: Django setting name for the backend. :param default: Module path to the default backend. """ GenericBackend(backend, defaults=[default, ]).get_backend()(*args)
from armstrong.utils.backends import GenericBackend def get_template_names(blast, recipient_list, recipient): return [ 'tt_dailyemailblast/%s/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug, recipient.slug), 'tt_dailyemailblast/%s/%s.html' % (blast.blast_type.slug, recipient_list.slug), 'tt_dailyemailblast/%s.html' % blast.blast_type.slug, ] def dispatch_to_backend(backend, default, *args): """Configure a GenericBackend and call it with `*args`. :param backend: Django setting name for the backend. :param default: Module path to the default backend. """ GenericBackend(backend, defaults=[default, ]).get_backend(*args)
Fix get_backend doesn't actually return a backend
Fix get_backend doesn't actually return a backend
Python
apache-2.0
texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast
--- +++ @@ -17,4 +17,4 @@ :param backend: Django setting name for the backend. :param default: Module path to the default backend. """ - GenericBackend(backend, defaults=[default, ]).get_backend()(*args) + GenericBackend(backend, defaults=[default, ]).get_backend(*args)
c156dd50e8f6b699ba87b7e185207e9ad3654979
examples/ssl_server.py
examples/ssl_server.py
import secure_smtpd import asyncore, logging, time, signal, sys from secure_smtpd import SMTPServer, FakeCredentialValidator class SSLSMTPServer(SMTPServer): def __init__(self): pass def process_message(self, peer, mailfrom, rcpttos, message_data): print message_data def start(self): SMTPServer.__init__( self, ('0.0.0.0', 465), None, require_authentication=True, ssl=True, certfile='examples/server.crt', keyfile='examples/server.key', credential_validator=FakeCredentialValidator(), maximum_execution_time = 1.0 ) asyncore.loop() logger = logging.getLogger( secure_smtpd.LOG_NAME ) logger.setLevel(logging.INFO) server = SSLSMTPServer() server.start() # normal termination of this process will kill worker children in # process pool so this process (the parent) needs to idle here waiting # for termination signal. If you don't have a signal handler, then # Python multiprocess cleanup stuff doesn't happen, and children won't # get killed by sending SIGTERM to parent. def sig_handler(signal,frame): logger.info("Got signal %s, shutting down." % signal) sys.exit(0) signal.signal(signal.SIGTERM, sig_handler) while 1: time.sleep(1)
import logging from secure_smtpd import SMTPServer, FakeCredentialValidator, LOG_NAME class SSLSMTPServer(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, message_data): print message_data logger = logging.getLogger( LOG_NAME ) logger.setLevel(logging.INFO) server = SSLSMTPServer( ('0.0.0.0', 1025), None, require_authentication=True, ssl=True, certfile='examples/server.crt', keyfile='examples/server.key', credential_validator=FakeCredentialValidator(), maximum_execution_time = 1.0 ) server.run()
Use unprivlidged port to make testing easier.
Use unprivlidged port to make testing easier. Use new server run() method. Refactor example class to make things simpler.
Python
isc
bcoe/secure-smtpd
--- +++ @@ -1,46 +1,22 @@ -import secure_smtpd -import asyncore, logging, time, signal, sys -from secure_smtpd import SMTPServer, FakeCredentialValidator +import logging +from secure_smtpd import SMTPServer, FakeCredentialValidator, LOG_NAME class SSLSMTPServer(SMTPServer): - - def __init__(self): - pass - def process_message(self, peer, mailfrom, rcpttos, message_data): print message_data - - def start(self): - SMTPServer.__init__( - self, - ('0.0.0.0', 465), - None, - require_authentication=True, - ssl=True, - certfile='examples/server.crt', - keyfile='examples/server.key', - credential_validator=FakeCredentialValidator(), - maximum_execution_time = 1.0 - ) - asyncore.loop() -logger = logging.getLogger( secure_smtpd.LOG_NAME ) +logger = logging.getLogger( LOG_NAME ) logger.setLevel(logging.INFO) -server = SSLSMTPServer() -server.start() -# normal termination of this process will kill worker children in -# process pool so this process (the parent) needs to idle here waiting -# for termination signal. If you don't have a signal handler, then -# Python multiprocess cleanup stuff doesn't happen, and children won't -# get killed by sending SIGTERM to parent. +server = SSLSMTPServer( + ('0.0.0.0', 1025), + None, + require_authentication=True, + ssl=True, + certfile='examples/server.crt', + keyfile='examples/server.key', + credential_validator=FakeCredentialValidator(), + maximum_execution_time = 1.0 + ) -def sig_handler(signal,frame): - logger.info("Got signal %s, shutting down." % signal) - sys.exit(0) - -signal.signal(signal.SIGTERM, sig_handler) - -while 1: - time.sleep(1) - +server.run()
42285c696dc2bcbcc1aeb6ed0bd46b6418e4223f
program.py
program.py
import json import csv from collections import namedtuple from player_class import Players def main(): filename = get_data_file() data = load_file(filename) division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() player_score() # Import player picks into a Class def get_data_file(): base_folder = os.path.dirname(__file__) return os.path.join(base_folder, 'data', '2016_playerpicks.csv') def load_file(filename): with open(filename, 'r', encoding='utf-8') as fin: reader = csv.DictReader(fin) player_picks = [] for row in reader: p = Players.create_from_dict(row) player_picks.append(p) return player_picks # Get Division Standings for each team def division_standings(): pass # Get Playoff Standings for each team (need number 5 & 6 in each conference) def playoff_standings(): pass # Get individual statistics for each category def player_stats(): pass # Get points for for the number one team in each conference: def points_for(): pass # Get the tiebreaker information def tiebreaker(): pass # Calculate the player scores def player_score(): pass if __name__ == '__main__': main()
import json import csv import requests import secret base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/ def main(): division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() player_score() # Get Division Standings for each team def division_standings(): pass # Get Playoff Standings for each team (need number 5 & 6 in each conference) def playoff_standings(): pass # Get individual statistics for each category def player_stats(): response = requests.get('base_url/cumulative_player_stats.json', auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) all_stats = response.json() stats = all_stats["cumulativeplayerstats"]["playerstatsentry"] # Get points for for the number one team in each conference: def points_for(): pass # Get the tiebreaker information def tiebreaker(): pass # Calculate the player scores def player_score(): pass if __name__ == '__main__': main()
Add stub for pulling player_stats including a new base_url for MySportsFeed
Add stub for pulling player_stats including a new base_url for MySportsFeed
Python
mit
prcutler/nflpool,prcutler/nflpool
--- +++ @@ -1,13 +1,12 @@ import json import csv -from collections import namedtuple +import requests +import secret -from player_class import Players +base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/ def main(): - filename = get_data_file() - data = load_file(filename) division_standings() playoff_standings() playoff_standings() @@ -16,23 +15,6 @@ tiebreaker() player_score() - -# Import player picks into a Class -def get_data_file(): - base_folder = os.path.dirname(__file__) - return os.path.join(base_folder, 'data', - '2016_playerpicks.csv') - - -def load_file(filename): - with open(filename, 'r', encoding='utf-8') as fin: - reader = csv.DictReader(fin) - player_picks = [] - for row in reader: - p = Players.create_from_dict(row) - player_picks.append(p) - - return player_picks # Get Division Standings for each team @@ -47,7 +29,11 @@ # Get individual statistics for each category def player_stats(): - pass + response = requests.get('base_url/cumulative_player_stats.json', + auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) + + all_stats = response.json() + stats = all_stats["cumulativeplayerstats"]["playerstatsentry"] # Get points for for the number one team in each conference:
6a48f6c0a4dec53a0094706957eecef10c2a6001
medical_appointment/__openerp__.py
medical_appointment/__openerp__.py
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Appointment', 'summary': 'Add Appointment concept to medical_physician', 'version': '9.0.1.0.0', 'author': 'LasLabs, Odoo Community Association (OCA)', 'category': 'Medical', 'depends': [ 'medical_base_history', 'medical', ], 'data': [ 'views/medical_appointment_view.xml', 'views/medical_menu.xml', 'security/ir.model.access.csv', 'security/medical_security.xml', 'data/medical_appointment_data.xml', 'data/medical_appointment_sequence.xml', ], 'website': 'https://laslabs.com', 'licence': 'AGPL-3', 'installable': True, 'auto_install': False, }
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Appointment', 'summary': 'Add Appointment concept to medical_physician', 'version': '9.0.1.0.0', 'author': 'LasLabs, Odoo Community Association (OCA)', 'category': 'Medical', 'depends': [ 'medical_base_history', 'medical_physician', ], 'data': [ 'views/medical_appointment_view.xml', 'views/medical_menu.xml', 'security/ir.model.access.csv', 'security/medical_security.xml', 'data/medical_appointment_data.xml', 'data/medical_appointment_sequence.xml', ], 'website': 'https://laslabs.com', 'licence': 'AGPL-3', 'installable': True, 'auto_install': False, }
Add medical_physician requirement to medical_appointment
Add medical_physician requirement to medical_appointment
Python
agpl-3.0
laslabs/vertical-medical,laslabs/vertical-medical
--- +++ @@ -11,7 +11,7 @@ 'category': 'Medical', 'depends': [ 'medical_base_history', - 'medical', + 'medical_physician', ], 'data': [ 'views/medical_appointment_view.xml',
75486c41bd648e63f1baf118000300cb7dee164b
ovirt-guest-agent/setup.py
ovirt-guest-agent/setup.py
from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None)
from distutils.core import setup from glob import glob import os import sys import py2exe if len(sys.argv) == 1: sys.argv.append("py2exe") sys.argv.append("-b 1") class Target: def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" self.package_version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent " OVirtAgentTarget = Target(description="Ovirt Guest Agent", modules=["OVirtGuestService"]) DLL_EXCLUDES = ['POWRPROF.dll', 'KERNELBASE.dll', 'WTSAPI32.dll', 'MSWSOCK.dll'] for name in glob(os.getenv('windir') + '\*\API-MS-Win-*.dll'): DLL_EXCLUDES.append(name[name.rfind('\\') + 1:]) setup(service=[OVirtAgentTarget], options={'py2exe': { 'bundle_files': 1, 'dll_excludes': DLL_EXCLUDES}}, zipfile=None)
Add explicit package version to the oVirt GA executable
Add explicit package version to the oVirt GA executable We really need to track 2 different versions in case of oVirt GA: - the version of the oVirt GA package itself - RH(E)V specific version of the oVirt GA package This patch adds setting of the package_version. Change-Id: I2dea656facbf2aa33a733316136e0e4d1b8d4744 Signed-off-by: Lev Veyde <32edd3ccb8e9d69e90ee9ce8dbc368c1f61bdf7b@redhat.com>
Python
apache-2.0
oVirt/ovirt-guest-agent,oVirt/ovirt-guest-agent,oVirt/ovirt-guest-agent,oVirt/ovirt-guest-agent
--- +++ @@ -15,6 +15,7 @@ def __init__(self, **kw): self.__dict__.update(kw) self.version = "1.0.16" + self.package_version = "1.0.16" self.company_name = "Red Hat" self.copyright = "Copyright(C) Red Hat Inc." self.name = "Guest VDS Agent "
7c2ef2ce6b31d6188c4ea25d2c885d47a67ad5cb
OnlineParticipationDataset/pipelines.py
OnlineParticipationDataset/pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json,os from datetime import datetime from scrapy.exporters import JsonLinesItemExporter path = "downloads" class OnlineparticipationdatasetPipeline(object): def process_item(self, item, spider): return item class JsonWriterPipeline(object): def open_spider(self, spider): if not os.path.isdir(path): os.makedirs(path) self.file = open("downloads/items_"+spider.name+".json", 'wb') self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False) self.exporter.start_exporting() def close_spider(self, spider): self.exporter.finish_exporting() self.file.close() def process_item(self, item, spider): self.exporter.export_item(item) return item
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json,os from datetime import datetime from scrapy.exporters import JsonLinesItemExporter path = "downloads" class OnlineparticipationdatasetPipeline(object): def process_item(self, item, spider): return item class JsonWriterPipeline(object): def open_spider(self, spider): if not os.path.isdir(path): os.makedirs(path) self.file = open("downloads/items_"+spider.name+".json", 'wb') self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False) self.exporter.start_exporting() def close_spider(self, spider): self.exporter.finish_exporting() self.file.close() def process_item(self, item, spider): item['date_time'] = item['date_time'].isoformat() self.exporter.export_item(item) return item
Save datetime in JSON as ISO
Save datetime in JSON as ISO
Python
mit
Liebeck/OnlineParticipationDatasets
--- +++ @@ -31,5 +31,6 @@ self.file.close() def process_item(self, item, spider): + item['date_time'] = item['date_time'].isoformat() self.exporter.export_item(item) return item
b5059e1d525b0e774923fade7c1b2f183c499622
addons/web_calendar/contacts.py
addons/web_calendar/contacts.py
from openerp.osv import fields, osv class web_calendar_contacts(osv.osv): _name = 'web_calendar.contacts' _columns = { 'user_id': fields.many2one('res.users','Me'), 'partner_id': fields.many2one('res.partner','Contact'), 'active':fields.boolean('active'), } _defaults = { 'user_id': lambda self, cr, uid, ctx: uid, 'active' : True, }
from openerp.osv import fields, osv class web_calendar_contacts(osv.osv): _name = 'web_calendar.contacts' _columns = { 'user_id': fields.many2one('res.users','Me'), 'partner_id': fields.many2one('res.partner','Contact',required=True), 'active':fields.boolean('active'), } _defaults = { 'user_id': lambda self, cr, uid, ctx: uid, 'active' : True, }
Add required on field res.partner from model Contacts to avoid the creation of empty coworkers
[FIX] Add required on field res.partner from model Contacts to avoid the creation of empty coworkers bzr revid: jke@openerp.com-20131218091020-8upymhda9nd84fg8
Python
agpl-3.0
Gitlab11/odoo,havt/odoo,acshan/odoo,oihane/odoo,fdvarela/odoo8,ApuliaSoftware/odoo,hassoon3/odoo,tinkerthaler/odoo,chiragjogi/odoo,rowemoore/odoo,mmbtba/odoo,abdellatifkarroum/odoo,eino-makitalo/odoo,jusdng/odoo,Eric-Zhong/odoo,colinnewell/odoo,acshan/odoo,spadae22/odoo,minhtuancn/odoo,apocalypsebg/odoo,GauravSahu/odoo,hifly/OpenUpgrade,nagyistoce/odoo-dev-odoo,BT-astauder/odoo,fuselock/odoo,abdellatifkarroum/odoo,avoinsystems/odoo,SAM-IT-SA/odoo,shivam1111/odoo,ujjwalwahi/odoo,steedos/odoo,savoirfairelinux/odoo,dezynetechnologies/odoo,mustafat/odoo-1,hanicker/odoo,x111ong/odoo,sadleader/odoo,shingonoide/odoo,feroda/odoo,AuyaJackie/odoo,alqfahad/odoo,odootr/odoo,inspyration/odoo,rdeheele/odoo,RafaelTorrealba/odoo,Maspear/odoo,joariasl/odoo,alexteodor/odoo,tvibliani/odoo,provaleks/o8,QianBIG/odoo,cdrooom/odoo,charbeljc/OCB,ojengwa/odoo,bobisme/odoo,factorlibre/OCB,alexcuellar/odoo,JGarcia-Panach/odoo,osvalr/odoo,BT-fgarbely/odoo,thanhacun/odoo,incaser/odoo-odoo,guerrerocarlos/odoo,TRESCLOUD/odoopub,ehirt/odoo,bkirui/odoo,feroda/odoo,glovebx/odoo,fevxie/odoo,rowemoore/odoo,nagyistoce/odoo-dev-odoo,sve-odoo/odoo,jesramirez/odoo,sv-dev1/odoo,pedrobaeza/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,ramadhane/odoo,janocat/odoo,colinnewell/odoo,idncom/odoo,jusdng/odoo,shingonoide/odoo,feroda/odoo,KontorConsulting/odoo,BT-ojossen/odoo,kybriainfotech/iSocioCRM,csrocha/OpenUpgrade,bealdav/OpenUpgrade,avoinsystems/odoo,ovnicraft/odoo,florian-dacosta/OpenUpgrade,dfang/odoo,erkrishna9/odoo,factorlibre/OCB,pedrobaeza/odoo,lightcn/odoo,Nowheresly/odoo,VielSoft/odoo,VielSoft/odoo,Danisan/odoo-1,collex100/odoo,OpenUpgrade/OpenUpgrade,storm-computers/odoo,spadae22/odoo,janocat/odoo,gsmartway/odoo,bwrsandman/OpenUpgrade,ihsanudin/odoo,ShineFan/odoo,Ichag/odoo,ramitalat/odoo,shingonoide/odoo,oihane/odoo,leoliujie/odoo,shivam1111/odoo,jiangzhixiao/odoo,tvtsoft/odoo8,luistorresm/odoo,zchking/odoo,lombritz/odoo,BT-fgarbely/odoo,CatsAndDogsbvba/odoo,mszewczy/odoo,dezynetechnologies/odoo,rubencabrera/odoo,Drooids/odoo,ingadhoc/odoo,markeTIC/OCB,apanju/GMIO_Odoo,hubsaysnuaa/odoo,BT-rmartin/odoo,csrocha/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,omprakasha/odoo,papouso/odoo,fevxie/odoo,gvb/odoo,aviciimaxwell/odoo,ubic135/odoo-design,joshuajan/odoo,pedrobaeza/OpenUpgrade,stephen144/odoo,blaggacao/OpenUpgrade,luiseduardohdbackup/odoo,ApuliaSoftware/odoo,dariemp/odoo,ehirt/odoo,wangjun/odoo,draugiskisprendimai/odoo,numerigraphe/odoo,numerigraphe/odoo,apanju/odoo,dkubiak789/odoo,nagyistoce/odoo-dev-odoo,MarcosCommunity/odoo,takis/odoo,jfpla/odoo,ramadhane/odoo,numerigraphe/odoo,doomsterinc/odoo,fjbatresv/odoo,diagramsoftware/odoo,jpshort/odoo,diagramsoftware/odoo,ChanduERP/odoo,xujb/odoo,acshan/odoo,gsmartway/odoo,addition-it-solutions/project-all,BT-fgarbely/odoo,aviciimaxwell/odoo,joariasl/odoo,ThinkOpen-Solutions/odoo,virgree/odoo,srsman/odoo,cloud9UG/odoo,x111ong/odoo,QianBIG/odoo,ujjwalwahi/odoo,kirca/OpenUpgrade,gavin-feng/odoo,bplancher/odoo,joshuajan/odoo,slevenhagen/odoo-npg,VielSoft/odoo,cysnake4713/odoo,massot/odoo,hopeall/odoo,hassoon3/odoo,elmerdpadilla/iv,Nick-OpusVL/odoo,NL66278/OCB,vnsofthe/odoo,tvibliani/odoo,dgzurita/odoo,ehirt/odoo,klunwebale/odoo,abstract-open-solutions/OCB,stonegithubs/odoo,prospwro/odoo,Noviat/odoo,blaggacao/OpenUpgrade,tinkerthaler/odoo,NeovaHealth/odoo,gavin-feng/odoo,elmerdpadilla/iv,andreparames/odoo,microcom/odoo,stephen144/odoo,havt/odoo,sadleader/odoo,klunwebale/odoo,leorochael/odoo,nuuuboo/odoo,rowemoore/odoo,nhomar/odoo,hip-odoo/odoo,jeasoft/odoo,salaria/odoo,dkubiak789/odoo,demon-ru/iml-crm,waytai/odoo,janocat/odoo,realsaiko/odoo,tarzan0820/odoo,hifly/OpenUpgrade,Ernesto99/odoo,Daniel-CA/odoo,Endika/odoo,tinkhaven-organization/odoo,Daniel-CA/odoo,sergio-incaser/odoo,shivam1111/odoo,savoirfairelinux/OpenUpgrade,n0m4dz/odoo,ClearCorp-dev/odoo,rubencabrera/odoo,datenbetrieb/odoo,Elico-Corp/odoo_OCB,klunwebale/odoo,Kilhog/odoo,waytai/odoo,cysnake4713/odoo,charbeljc/OCB,OpenUpgrade/OpenUpgrade,Adel-Magebinary/odoo,SerpentCS/odoo,xzYue/odoo,ihsanudin/odoo,sergio-incaser/odoo,TRESCLOUD/odoopub,incaser/odoo-odoo,Adel-Magebinary/odoo,ygol/odoo,dalegregory/odoo,ojengwa/odoo,bkirui/odoo,minhtuancn/odoo,hoatle/odoo,Kilhog/odoo,goliveirab/odoo,shivam1111/odoo,arthru/OpenUpgrade,aviciimaxwell/odoo,sinbazhou/odoo,fevxie/odoo,thanhacun/odoo,sinbazhou/odoo,JCA-Developpement/Odoo,CopeX/odoo,luiseduardohdbackup/odoo,aviciimaxwell/odoo,cdrooom/odoo,tinkhaven-organization/odoo,jfpla/odoo,JonathanStein/odoo,slevenhagen/odoo,JGarcia-Panach/odoo,agrista/odoo-saas,Grirrane/odoo,abstract-open-solutions/OCB,collex100/odoo,stonegithubs/odoo,laslabs/odoo,mvaled/OpenUpgrade,srimai/odoo,virgree/odoo,sv-dev1/odoo,bguillot/OpenUpgrade,pplatek/odoo,Elico-Corp/odoo_OCB,jiachenning/odoo,makinacorpus/odoo,SAM-IT-SA/odoo,abenzbiria/clients_odoo,mkieszek/odoo,highco-groupe/odoo,jeasoft/odoo,realsaiko/odoo,funkring/fdoo,cpyou/odoo,CatsAndDogsbvba/odoo,savoirfairelinux/odoo,doomsterinc/odoo,Nowheresly/odoo,hoatle/odoo,christophlsa/odoo,gavin-feng/odoo,JonathanStein/odoo,dllsf/odootest,prospwro/odoo,windedge/odoo,xzYue/odoo,mkieszek/odoo,pplatek/odoo,leoliujie/odoo,addition-it-solutions/project-all,OpenUpgrade-dev/OpenUpgrade,Kilhog/odoo,ingadhoc/odoo,tvibliani/odoo,idncom/odoo,steedos/odoo,tangyiyong/odoo,prospwro/odoo,JCA-Developpement/Odoo,OpenUpgrade-dev/OpenUpgrade,poljeff/odoo,Maspear/odoo,dariemp/odoo,bguillot/OpenUpgrade,Daniel-CA/odoo,gorjuce/odoo,Grirrane/odoo,kirca/OpenUpgrade,savoirfairelinux/odoo,Maspear/odoo,Endika/odoo,markeTIC/OCB,doomsterinc/odoo,bealdav/OpenUpgrade,bguillot/OpenUpgrade,CubicERP/odoo,deKupini/erp,shivam1111/odoo,kybriainfotech/iSocioCRM,zchking/odoo,Gitlab11/odoo,cedk/odoo,Nick-OpusVL/odoo,javierTerry/odoo,spadae22/odoo,sinbazhou/odoo,rgeleta/odoo,laslabs/odoo,fjbatresv/odoo,janocat/odoo,nexiles/odoo,mszewczy/odoo,salaria/odoo,nitinitprof/odoo,VielSoft/odoo,oihane/odoo,JonathanStein/odoo,fossoult/odoo,srimai/odoo,arthru/OpenUpgrade,glovebx/odoo,hip-odoo/odoo,Ichag/odoo,RafaelTorrealba/odoo,jpshort/odoo,srsman/odoo,thanhacun/odoo,oasiswork/odoo,shaufi/odoo,grap/OpenUpgrade,damdam-s/OpenUpgrade,mustafat/odoo-1,ThinkOpen-Solutions/odoo,florian-dacosta/OpenUpgrade,hassoon3/odoo,rdeheele/odoo,chiragjogi/odoo,Eric-Zhong/odoo,ingadhoc/odoo,dsfsdgsbngfggb/odoo,CatsAndDogsbvba/odoo,naousse/odoo,guewen/OpenUpgrade,ApuliaSoftware/odoo,optima-ict/odoo,mlaitinen/odoo,glovebx/odoo,Noviat/odoo,storm-computers/odoo,brijeshkesariya/odoo,makinacorpus/odoo,javierTerry/odoo,apanju/odoo,jeasoft/odoo,dllsf/odootest,dariemp/odoo,Kilhog/odoo,JonathanStein/odoo,jfpla/odoo,markeTIC/OCB,Eric-Zhong/odoo,lightcn/odoo,bobisme/odoo,andreparames/odoo,Codefans-fan/odoo,fdvarela/odoo8,kittiu/odoo,guerrerocarlos/odoo,syci/OCB,blaggacao/OpenUpgrade,BT-rmartin/odoo,diagramsoftware/odoo,dariemp/odoo,Gitlab11/odoo,abenzbiria/clients_odoo,elmerdpadilla/iv,ecosoft-odoo/odoo,csrocha/OpenUpgrade,oasiswork/odoo,lsinfo/odoo,synconics/odoo,0k/odoo,alhashash/odoo,glovebx/odoo,demon-ru/iml-crm,BT-rmartin/odoo,christophlsa/odoo,fgesora/odoo,hubsaysnuaa/odoo,hip-odoo/odoo,JonathanStein/odoo,Nowheresly/odoo,dezynetechnologies/odoo,Gitlab11/odoo,Elico-Corp/odoo_OCB,naousse/odoo,CubicERP/odoo,odootr/odoo,ubic135/odoo-design,takis/odoo,lombritz/odoo,Danisan/odoo-1,dfang/odoo,steedos/odoo,dgzurita/odoo,minhtuancn/odoo,mmbtba/odoo,addition-it-solutions/project-all,x111ong/odoo,AuyaJackie/odoo,PongPi/isl-odoo,joariasl/odoo,x111ong/odoo,highco-groupe/odoo,janocat/odoo,gvb/odoo,xzYue/odoo,KontorConsulting/odoo,NL66278/OCB,MarcosCommunity/odoo,diagramsoftware/odoo,sadleader/odoo,aviciimaxwell/odoo,hbrunn/OpenUpgrade,draugiskisprendimai/odoo,kybriainfotech/iSocioCRM,optima-ict/odoo,synconics/odoo,dkubiak789/odoo,nuncjo/odoo,ramadhane/odoo,hip-odoo/odoo,lightcn/odoo,BT-fgarbely/odoo,cedk/odoo,havt/odoo,fevxie/odoo,minhtuancn/odoo,jfpla/odoo,Codefans-fan/odoo,andreparames/odoo,ovnicraft/odoo,bakhtout/odoo-educ,dsfsdgsbngfggb/odoo,virgree/odoo,BT-fgarbely/odoo,steedos/odoo,acshan/odoo,x111ong/odoo,oihane/odoo,ThinkOpen-Solutions/odoo,mkieszek/odoo,Bachaco-ve/odoo,ShineFan/odoo,pedrobaeza/OpenUpgrade,syci/OCB,Adel-Magebinary/odoo,Noviat/odoo,takis/odoo,windedge/odoo,alexteodor/odoo,0k/OpenUpgrade,ChanduERP/odoo,nagyistoce/odoo-dev-odoo,klunwebale/odoo,incaser/odoo-odoo,shaufi10/odoo,Grirrane/odoo,apocalypsebg/odoo,nuuuboo/odoo,ShineFan/odoo,0k/odoo,bkirui/odoo,jpshort/odoo,abenzbiria/clients_odoo,lightcn/odoo,xujb/odoo,papouso/odoo,Elico-Corp/odoo_OCB,tangyiyong/odoo,synconics/odoo,Antiun/odoo,srimai/odoo,florentx/OpenUpgrade,bwrsandman/OpenUpgrade,ThinkOpen-Solutions/odoo,oliverhr/odoo,OpenUpgrade/OpenUpgrade,mvaled/OpenUpgrade,abdellatifkarroum/odoo,lgscofield/odoo,mmbtba/odoo,srsman/odoo,apocalypsebg/odoo,avoinsystems/odoo,tarzan0820/odoo,tinkhaven-organization/odoo,deKupini/erp,SAM-IT-SA/odoo,lightcn/odoo,funkring/fdoo,Daniel-CA/odoo,gvb/odoo,NeovaHealth/odoo,n0m4dz/odoo,QianBIG/odoo,stephen144/odoo,takis/odoo,savoirfairelinux/OpenUpgrade,gorjuce/odoo,matrixise/odoo,windedge/odoo,doomsterinc/odoo,leoliujie/odoo,poljeff/odoo,nhomar/odoo-mirror,lightcn/odoo,sv-dev1/odoo,chiragjogi/odoo,apocalypsebg/odoo,brijeshkesariya/odoo,addition-it-solutions/project-all,ujjwalwahi/odoo,tinkhaven-organization/odoo,storm-computers/odoo,sysadminmatmoz/OCB,Noviat/odoo,ygol/odoo,nhomar/odoo,nuuuboo/odoo,jusdng/odoo,ChanduERP/odoo,xzYue/odoo,ClearCorp-dev/odoo,spadae22/odoo,Grirrane/odoo,odoo-turkiye/odoo,cysnake4713/odoo,bplancher/odoo,christophlsa/odoo,makinacorpus/odoo,odoo-turkiye/odoo,jpshort/odoo,mszewczy/odoo,florentx/OpenUpgrade,goliveirab/odoo,pedrobaeza/odoo,pplatek/odoo,mlaitinen/odoo,cloud9UG/odoo,BT-ojossen/odoo,nhomar/odoo,tinkerthaler/odoo,hbrunn/OpenUpgrade,nexiles/odoo,AuyaJackie/odoo,grap/OpenUpgrade,tinkerthaler/odoo,dkubiak789/odoo,christophlsa/odoo,laslabs/odoo,joshuajan/odoo,kittiu/odoo,xzYue/odoo,hoatle/odoo,jolevq/odoopub,alexcuellar/odoo,eino-makitalo/odoo,gsmartway/odoo,CubicERP/odoo,thanhacun/odoo,Noviat/odoo,JCA-Developpement/Odoo,kittiu/odoo,alexcuellar/odoo,collex100/odoo,matrixise/odoo,BT-astauder/odoo,odoo-turkiye/odoo,gorjuce/odoo,gavin-feng/odoo,ChanduERP/odoo,sv-dev1/odoo,savoirfairelinux/odoo,jeasoft/odoo,hbrunn/OpenUpgrade,bealdav/OpenUpgrade,rowemoore/odoo,papouso/odoo,poljeff/odoo,jpshort/odoo,jiachenning/odoo,CopeX/odoo,pplatek/odoo,hmen89/odoo,oliverhr/odoo,funkring/fdoo,Danisan/odoo-1,oliverhr/odoo,FlorianLudwig/odoo,tvtsoft/odoo8,PongPi/isl-odoo,glovebx/odoo,slevenhagen/odoo,shaufi10/odoo,idncom/odoo,bealdav/OpenUpgrade,erkrishna9/odoo,joshuajan/odoo,jusdng/odoo,fuhongliang/odoo,ujjwalwahi/odoo,diagramsoftware/odoo,Antiun/odoo,FlorianLudwig/odoo,Endika/OpenUpgrade,Ernesto99/odoo,dariemp/odoo,mustafat/odoo-1,csrocha/OpenUpgrade,demon-ru/iml-crm,prospwro/odoo,srimai/odoo,lsinfo/odoo,thanhacun/odoo,ihsanudin/odoo,waytai/odoo,shaufi10/odoo,simongoffin/website_version,alqfahad/odoo,SAM-IT-SA/odoo,SAM-IT-SA/odoo,lsinfo/odoo,jeasoft/odoo,mkieszek/odoo,nuncjo/odoo,QianBIG/odoo,0k/OpenUpgrade,tarzan0820/odoo,nuncjo/odoo,shingonoide/odoo,pedrobaeza/OpenUpgrade,PongPi/isl-odoo,Drooids/odoo,0k/odoo,Adel-Magebinary/odoo,sysadminmatmoz/OCB,zchking/odoo,fjbatresv/odoo,lgscofield/odoo,OpusVL/odoo,mlaitinen/odoo,FlorianLudwig/odoo,bkirui/odoo,mszewczy/odoo,ccomb/OpenUpgrade,sinbazhou/odoo,nuuuboo/odoo,alqfahad/odoo,slevenhagen/odoo,GauravSahu/odoo,TRESCLOUD/odoopub,joariasl/odoo,minhtuancn/odoo,Endika/OpenUpgrade,ramitalat/odoo,prospwro/odoo,matrixise/odoo,mkieszek/odoo,erkrishna9/odoo,bakhtout/odoo-educ,jeasoft/odoo,bakhtout/odoo-educ,gvb/odoo,ccomb/OpenUpgrade,GauravSahu/odoo,vnsofthe/odoo,salaria/odoo,nhomar/odoo,CatsAndDogsbvba/odoo,hmen89/odoo,fjbatresv/odoo,thanhacun/odoo,sergio-incaser/odoo,tinkerthaler/odoo,eino-makitalo/odoo,BT-ojossen/odoo,FlorianLudwig/odoo,pplatek/odoo,Nowheresly/odoo,wangjun/odoo,goliveirab/odoo,odoo-turkiye/odoo,rubencabrera/odoo,sve-odoo/odoo,draugiskisprendimai/odoo,ccomb/OpenUpgrade,deKupini/erp,arthru/OpenUpgrade,kifcaliph/odoo,hopeall/odoo,leorochael/odoo,ThinkOpen-Solutions/odoo,rowemoore/odoo,Bachaco-ve/odoo,damdam-s/OpenUpgrade,Endika/odoo,omprakasha/odoo,klunwebale/odoo,ihsanudin/odoo,highco-groupe/odoo,tarzan0820/odoo,dalegregory/odoo,luistorresm/odoo,steedos/odoo,blaggacao/OpenUpgrade,guewen/OpenUpgrade,guerrerocarlos/odoo,jolevq/odoopub,OpusVL/odoo,dgzurita/odoo,rgeleta/odoo,fuhongliang/odoo,JonathanStein/odoo,zchking/odoo,hanicker/odoo,alexcuellar/odoo,synconics/odoo,Noviat/odoo,Ernesto99/odoo,BT-fgarbely/odoo,ThinkOpen-Solutions/odoo,Adel-Magebinary/odoo,storm-computers/odoo,odootr/odoo,chiragjogi/odoo,apanju/odoo,florentx/OpenUpgrade,shivam1111/odoo,storm-computers/odoo,takis/odoo,nuncjo/odoo,patmcb/odoo,cpyou/odoo,mvaled/OpenUpgrade,fuselock/odoo,oasiswork/odoo,windedge/odoo,apocalypsebg/odoo,fuhongliang/odoo,AuyaJackie/odoo,idncom/odoo,draugiskisprendimai/odoo,tarzan0820/odoo,christophlsa/odoo,dalegregory/odoo,Drooids/odoo,CubicERP/odoo,juanalfonsopr/odoo,highco-groupe/odoo,patmcb/odoo,RafaelTorrealba/odoo,damdam-s/OpenUpgrade,slevenhagen/odoo-npg,fjbatresv/odoo,dariemp/odoo,javierTerry/odoo,jiangzhixiao/odoo,demon-ru/iml-crm,Danisan/odoo-1,ccomb/OpenUpgrade,dfang/odoo,massot/odoo,damdam-s/OpenUpgrade,bwrsandman/OpenUpgrade,abdellatifkarroum/odoo,shingonoide/odoo,juanalfonsopr/odoo,acshan/odoo,tvibliani/odoo,microcom/odoo,damdam-s/OpenUpgrade,mlaitinen/odoo,sv-dev1/odoo,diagramsoftware/odoo,dfang/odoo,savoirfairelinux/OpenUpgrade,rdeheele/odoo,makinacorpus/odoo,JGarcia-Panach/odoo,nagyistoce/odoo-dev-odoo,charbeljc/OCB,inspyration/odoo,ygol/odoo,KontorConsulting/odoo,Ernesto99/odoo,jusdng/odoo,waytai/odoo,storm-computers/odoo,microcom/odoo,MarcosCommunity/odoo,apanju/GMIO_Odoo,ThinkOpen-Solutions/odoo,joshuajan/odoo,ingadhoc/odoo,xujb/odoo,sve-odoo/odoo,hassoon3/odoo,optima-ict/odoo,savoirfairelinux/OpenUpgrade,feroda/odoo,gsmartway/odoo,cedk/odoo,alqfahad/odoo,eino-makitalo/odoo,osvalr/odoo,rubencabrera/odoo,gavin-feng/odoo,jaxkodex/odoo,csrocha/OpenUpgrade,Grirrane/odoo,eino-makitalo/odoo,RafaelTorrealba/odoo,ojengwa/odoo,Codefans-fan/odoo,florian-dacosta/OpenUpgrade,markeTIC/OCB,poljeff/odoo,doomsterinc/odoo,BT-astauder/odoo,dariemp/odoo,Codefans-fan/odoo,rubencabrera/odoo,funkring/fdoo,wangjun/odoo,florentx/OpenUpgrade,hanicker/odoo,shingonoide/odoo,VielSoft/odoo,grap/OpenUpgrade,tvibliani/odoo,osvalr/odoo,fuhongliang/odoo,goliveirab/odoo,gvb/odoo,mmbtba/odoo,factorlibre/OCB,ygol/odoo,erkrishna9/odoo,luiseduardohdbackup/odoo,Ichag/odoo,Ichag/odoo,datenbetrieb/odoo,osvalr/odoo,apanju/GMIO_Odoo,mvaled/OpenUpgrade,mlaitinen/odoo,dkubiak789/odoo,kybriainfotech/iSocioCRM,provaleks/o8,nitinitprof/odoo,bealdav/OpenUpgrade,sysadminmatmoz/OCB,laslabs/odoo,waytai/odoo,hopeall/odoo,blaggacao/OpenUpgrade,leorochael/odoo,Drooids/odoo,stephen144/odoo,Codefans-fan/odoo,rahuldhote/odoo,savoirfairelinux/odoo,Danisan/odoo-1,rahuldhote/odoo,lsinfo/odoo,AuyaJackie/odoo,datenbetrieb/odoo,kybriainfotech/iSocioCRM,nhomar/odoo-mirror,JGarcia-Panach/odoo,sebalix/OpenUpgrade,hbrunn/OpenUpgrade,brijeshkesariya/odoo,bkirui/odoo,Endika/odoo,jiachenning/odoo,MarcosCommunity/odoo,srimai/odoo,abstract-open-solutions/OCB,JGarcia-Panach/odoo,omprakasha/odoo,nuncjo/odoo,hbrunn/OpenUpgrade,Maspear/odoo,CatsAndDogsbvba/odoo,ygol/odoo,kirca/OpenUpgrade,spadae22/odoo,Endika/odoo,odooindia/odoo,leorochael/odoo,ovnicraft/odoo,leoliujie/odoo,slevenhagen/odoo,hifly/OpenUpgrade,florian-dacosta/OpenUpgrade,ihsanudin/odoo,microcom/odoo,srsman/odoo,glovebx/odoo,bakhtout/odoo-educ,lombritz/odoo,jiachenning/odoo,syci/OCB,odoousers2014/odoo,aviciimaxwell/odoo,charbeljc/OCB,makinacorpus/odoo,shaufi/odoo,SAM-IT-SA/odoo,hassoon3/odoo,incaser/odoo-odoo,vnsofthe/odoo,sve-odoo/odoo,rdeheele/odoo,OpenUpgrade-dev/OpenUpgrade,stephen144/odoo,fdvarela/odoo8,BT-rmartin/odoo,hopeall/odoo,bplancher/odoo,goliveirab/odoo,jolevq/odoopub,jusdng/odoo,javierTerry/odoo,sysadminmatmoz/OCB,nuncjo/odoo,kittiu/odoo,hubsaysnuaa/odoo,stonegithubs/odoo,dezynetechnologies/odoo,nhomar/odoo,JGarcia-Panach/odoo,ChanduERP/odoo,sv-dev1/odoo,ehirt/odoo,nhomar/odoo,virgree/odoo,odooindia/odoo,dalegregory/odoo,lgscofield/odoo,colinnewell/odoo,odoousers2014/odoo,apocalypsebg/odoo,colinnewell/odoo,ecosoft-odoo/odoo,Nick-OpusVL/odoo,mkieszek/odoo,highco-groupe/odoo,AuyaJackie/odoo,jaxkodex/odoo,provaleks/o8,goliveirab/odoo,goliveirab/odoo,hifly/OpenUpgrade,Nick-OpusVL/odoo,sebalix/OpenUpgrade,bakhtout/odoo-educ,Nowheresly/odoo,ingadhoc/odoo,dsfsdgsbngfggb/odoo,rahuldhote/odoo,SerpentCS/odoo,provaleks/o8,ubic135/odoo-design,NeovaHealth/odoo,kittiu/odoo,salaria/odoo,Endika/OpenUpgrade,rubencabrera/odoo,florentx/OpenUpgrade,dezynetechnologies/odoo,Codefans-fan/odoo,charbeljc/OCB,guewen/OpenUpgrade,draugiskisprendimai/odoo,bwrsandman/OpenUpgrade,ramitalat/odoo,OpenUpgrade/OpenUpgrade,bwrsandman/OpenUpgrade,cedk/odoo,minhtuancn/odoo,shaufi/odoo,dalegregory/odoo,sysadminmatmoz/OCB,janocat/odoo,patmcb/odoo,sebalix/OpenUpgrade,cloud9UG/odoo,sebalix/OpenUpgrade,addition-it-solutions/project-all,oasiswork/odoo,omprakasha/odoo,dsfsdgsbngfggb/odoo,xujb/odoo,slevenhagen/odoo-npg,oasiswork/odoo,nexiles/odoo,bobisme/odoo,naousse/odoo,sadleader/odoo,sebalix/OpenUpgrade,simongoffin/website_version,omprakasha/odoo,dgzurita/odoo,bakhtout/odoo-educ,Bachaco-ve/odoo,gorjuce/odoo,bplancher/odoo,guerrerocarlos/odoo,feroda/odoo,hubsaysnuaa/odoo,odoousers2014/odoo,patmcb/odoo,chiragjogi/odoo,markeTIC/OCB,provaleks/o8,gorjuce/odoo,shaufi10/odoo,numerigraphe/odoo,Bachaco-ve/odoo,pedrobaeza/odoo,papouso/odoo,incaser/odoo-odoo,arthru/OpenUpgrade,oliverhr/odoo,jpshort/odoo,mlaitinen/odoo,abstract-open-solutions/OCB,abstract-open-solutions/OCB,nagyistoce/odoo-dev-odoo,gsmartway/odoo,lombritz/odoo,CatsAndDogsbvba/odoo,rgeleta/odoo,florian-dacosta/OpenUpgrade,GauravSahu/odoo,alhashash/odoo,odoo-turkiye/odoo,TRESCLOUD/odoopub,klunwebale/odoo,kybriainfotech/iSocioCRM,fuhongliang/odoo,pedrobaeza/odoo,provaleks/o8,odooindia/odoo,alhashash/odoo,brijeshkesariya/odoo,Nick-OpusVL/odoo,ujjwalwahi/odoo,cloud9UG/odoo,mszewczy/odoo,Codefans-fan/odoo,florian-dacosta/OpenUpgrade,virgree/odoo,wangjun/odoo,GauravSahu/odoo,bobisme/odoo,Elico-Corp/odoo_OCB,JGarcia-Panach/odoo,alqfahad/odoo,guewen/OpenUpgrade,dgzurita/odoo,kifcaliph/odoo,factorlibre/OCB,ramadhane/odoo,odootr/odoo,jesramirez/odoo,PongPi/isl-odoo,ShineFan/odoo,bkirui/odoo,bplancher/odoo,pedrobaeza/OpenUpgrade,hmen89/odoo,BT-ojossen/odoo,blaggacao/OpenUpgrade,lgscofield/odoo,feroda/odoo,KontorConsulting/odoo,alexteodor/odoo,Ichag/odoo,dkubiak789/odoo,hanicker/odoo,Kilhog/odoo,realsaiko/odoo,leoliujie/odoo,ihsanudin/odoo,idncom/odoo,gvb/odoo,JCA-Developpement/Odoo,kirca/OpenUpgrade,ovnicraft/odoo,cedk/odoo,ujjwalwahi/odoo,SerpentCS/odoo,abdellatifkarroum/odoo,jiangzhixiao/odoo,doomsterinc/odoo,tangyiyong/odoo,Elico-Corp/odoo_OCB,apanju/GMIO_Odoo,hmen89/odoo,kirca/OpenUpgrade,BT-astauder/odoo,nitinitprof/odoo,OpusVL/odoo,shaufi/odoo,avoinsystems/odoo,ClearCorp-dev/odoo,odoousers2014/odoo,wangjun/odoo,spadae22/odoo,sve-odoo/odoo,syci/OCB,andreparames/odoo,hubsaysnuaa/odoo,salaria/odoo,patmcb/odoo,TRESCLOUD/odoopub,OpenUpgrade/OpenUpgrade,prospwro/odoo,salaria/odoo,dalegregory/odoo,alqfahad/odoo,factorlibre/OCB,tinkhaven-organization/odoo,n0m4dz/odoo,stephen144/odoo,cdrooom/odoo,jeasoft/odoo,nuuuboo/odoo,apanju/GMIO_Odoo,bealdav/OpenUpgrade,poljeff/odoo,datenbetrieb/odoo,dezynetechnologies/odoo,havt/odoo,apanju/odoo,oasiswork/odoo,Adel-Magebinary/odoo,hifly/OpenUpgrade,joshuajan/odoo,leorochael/odoo,naousse/odoo,NL66278/OCB,alhashash/odoo,kirca/OpenUpgrade,slevenhagen/odoo-npg,Antiun/odoo,makinacorpus/odoo,jesramirez/odoo,Drooids/odoo,ehirt/odoo,fuselock/odoo,chiragjogi/odoo,hanicker/odoo,ihsanudin/odoo,CopeX/odoo,brijeshkesariya/odoo,numerigraphe/odoo,bobisme/odoo,ovnicraft/odoo,abstract-open-solutions/OCB,apanju/odoo,sysadminmatmoz/OCB,jiangzhixiao/odoo,dllsf/odootest,dgzurita/odoo,Maspear/odoo,juanalfonsopr/odoo,vnsofthe/odoo,ojengwa/odoo,ecosoft-odoo/odoo,fossoult/odoo,tvtsoft/odoo8,minhtuancn/odoo,dalegregory/odoo,fjbatresv/odoo,RafaelTorrealba/odoo,Ichag/odoo,xzYue/odoo,andreparames/odoo,hoatle/odoo,apanju/GMIO_Odoo,nuuuboo/odoo,eino-makitalo/odoo,Daniel-CA/odoo,shaufi10/odoo,leoliujie/odoo,srimai/odoo,hifly/OpenUpgrade,alexteodor/odoo,ccomb/OpenUpgrade,ramitalat/odoo,slevenhagen/odoo,cysnake4713/odoo,abdellatifkarroum/odoo,nitinitprof/odoo,tvibliani/odoo,factorlibre/OCB,jesramirez/odoo,pplatek/odoo,simongoffin/website_version,hanicker/odoo,Endika/OpenUpgrade,Drooids/odoo,tangyiyong/odoo,MarcosCommunity/odoo,csrocha/OpenUpgrade,steedos/odoo,hifly/OpenUpgrade,vnsofthe/odoo,odootr/odoo,andreparames/odoo,alexteodor/odoo,aviciimaxwell/odoo,nagyistoce/odoo-dev-odoo,draugiskisprendimai/odoo,rahuldhote/odoo,elmerdpadilla/iv,papouso/odoo,guewen/OpenUpgrade,shaufi/odoo,CopeX/odoo,oihane/odoo,pedrobaeza/OpenUpgrade,takis/odoo,abstract-open-solutions/OCB,fgesora/odoo,agrista/odoo-saas,pedrobaeza/odoo,Eric-Zhong/odoo,cpyou/odoo,funkring/fdoo,CubicERP/odoo,ygol/odoo,kifcaliph/odoo,0k/OpenUpgrade,fossoult/odoo,Ernesto99/odoo,NeovaHealth/odoo,shaufi10/odoo,sysadminmatmoz/OCB,fgesora/odoo,sergio-incaser/odoo,simongoffin/website_version,BT-ojossen/odoo,virgree/odoo,luistorresm/odoo,hassoon3/odoo,christophlsa/odoo,slevenhagen/odoo,rgeleta/odoo,funkring/fdoo,alexcuellar/odoo,waytai/odoo,ramadhane/odoo,NeovaHealth/odoo,slevenhagen/odoo-npg,BT-fgarbely/odoo,klunwebale/odoo,srsman/odoo,nhomar/odoo-mirror,hopeall/odoo,elmerdpadilla/iv,Gitlab11/odoo,synconics/odoo,bobisme/odoo,microcom/odoo,stonegithubs/odoo,odootr/odoo,n0m4dz/odoo,x111ong/odoo,colinnewell/odoo,hmen89/odoo,jusdng/odoo,fuselock/odoo,markeTIC/OCB,florentx/OpenUpgrade,numerigraphe/odoo,0k/odoo,kirca/OpenUpgrade,dgzurita/odoo,tvtsoft/odoo8,lgscofield/odoo,grap/OpenUpgrade,ApuliaSoftware/odoo,havt/odoo,fdvarela/odoo8,Maspear/odoo,havt/odoo,poljeff/odoo,gsmartway/odoo,sv-dev1/odoo,guerrerocarlos/odoo,ChanduERP/odoo,Danisan/odoo-1,numerigraphe/odoo,gvb/odoo,abenzbiria/clients_odoo,xzYue/odoo,spadae22/odoo,xujb/odoo,lgscofield/odoo,x111ong/odoo,joariasl/odoo,takis/odoo,ramadhane/odoo,dsfsdgsbngfggb/odoo,leoliujie/odoo,jaxkodex/odoo,Antiun/odoo,PongPi/isl-odoo,MarcosCommunity/odoo,ovnicraft/odoo,realsaiko/odoo,brijeshkesariya/odoo,jesramirez/odoo,ClearCorp-dev/odoo,lombritz/odoo,patmcb/odoo,joariasl/odoo,NeovaHealth/odoo,agrista/odoo-saas,leorochael/odoo,ApuliaSoftware/odoo,fgesora/odoo,BT-rmartin/odoo,PongPi/isl-odoo,xujb/odoo,ehirt/odoo,oliverhr/odoo,slevenhagen/odoo,rgeleta/odoo,avoinsystems/odoo,tinkerthaler/odoo,luistorresm/odoo,sadleader/odoo,mmbtba/odoo,sinbazhou/odoo,Danisan/odoo-1,nexiles/odoo,odoousers2014/odoo,oliverhr/odoo,bakhtout/odoo-educ,abenzbiria/clients_odoo,nitinitprof/odoo,lgscofield/odoo,fjbatresv/odoo,lombritz/odoo,jiangzhixiao/odoo,optima-ict/odoo,mmbtba/odoo,mustafat/odoo-1,odooindia/odoo,sergio-incaser/odoo,tvibliani/odoo,ubic135/odoo-design,datenbetrieb/odoo,apanju/GMIO_Odoo,FlorianLudwig/odoo,bwrsandman/OpenUpgrade,odooindia/odoo,cedk/odoo,bguillot/OpenUpgrade,arthru/OpenUpgrade,jaxkodex/odoo,alexcuellar/odoo,dezynetechnologies/odoo,dfang/odoo,VielSoft/odoo,SAM-IT-SA/odoo,tvtsoft/odoo8,sinbazhou/odoo,n0m4dz/odoo,CubicERP/odoo,avoinsystems/odoo,jeasoft/odoo,dllsf/odootest,Nick-OpusVL/odoo,tvtsoft/odoo8,factorlibre/OCB,Daniel-CA/odoo,abdellatifkarroum/odoo,vnsofthe/odoo,ccomb/OpenUpgrade,GauravSahu/odoo,javierTerry/odoo,wangjun/odoo,fevxie/odoo,realsaiko/odoo,demon-ru/iml-crm,tangyiyong/odoo,tangyiyong/odoo,datenbetrieb/odoo,draugiskisprendimai/odoo,mszewczy/odoo,makinacorpus/odoo,massot/odoo,andreparames/odoo,tarzan0820/odoo,JonathanStein/odoo,tinkhaven-organization/odoo,chiragjogi/odoo,nexiles/odoo,fgesora/odoo,shingonoide/odoo,cysnake4713/odoo,prospwro/odoo,PongPi/isl-odoo,odootr/odoo,papouso/odoo,CopeX/odoo,Endika/odoo,matrixise/odoo,gavin-feng/odoo,javierTerry/odoo,KontorConsulting/odoo,ChanduERP/odoo,cloud9UG/odoo,colinnewell/odoo,javierTerry/odoo,mvaled/OpenUpgrade,jiangzhixiao/odoo,apocalypsebg/odoo,diagramsoftware/odoo,n0m4dz/odoo,mlaitinen/odoo,jfpla/odoo,brijeshkesariya/odoo,nhomar/odoo-mirror,jfpla/odoo,leorochael/odoo,hip-odoo/odoo,hopeall/odoo,bguillot/OpenUpgrade,jiachenning/odoo,Endika/OpenUpgrade,hbrunn/OpenUpgrade,windedge/odoo,collex100/odoo,papouso/odoo,ccomb/OpenUpgrade,bkirui/odoo,Daniel-CA/odoo,sebalix/OpenUpgrade,grap/OpenUpgrade,MarcosCommunity/odoo,CatsAndDogsbvba/odoo,steedos/odoo,Bachaco-ve/odoo,collex100/odoo,ecosoft-odoo/odoo,stonegithubs/odoo,Grirrane/odoo,fossoult/odoo,ecosoft-odoo/odoo,rahuldhote/odoo,gorjuce/odoo,ubic135/odoo-design,mustafat/odoo-1,fuselock/odoo,cpyou/odoo,ecosoft-odoo/odoo,datenbetrieb/odoo,deKupini/erp,n0m4dz/odoo,guewen/OpenUpgrade,guerrerocarlos/odoo,jolevq/odoopub,rowemoore/odoo,pedrobaeza/OpenUpgrade,fgesora/odoo,sergio-incaser/odoo,rgeleta/odoo,Kilhog/odoo,mvaled/OpenUpgrade,oliverhr/odoo,acshan/odoo,savoirfairelinux/OpenUpgrade,SerpentCS/odoo,ApuliaSoftware/odoo,Antiun/odoo,gorjuce/odoo,cdrooom/odoo,rdeheele/odoo,Nick-OpusVL/odoo,naousse/odoo,ingadhoc/odoo,kybriainfotech/iSocioCRM,osvalr/odoo,Bachaco-ve/odoo,inspyration/odoo,RafaelTorrealba/odoo,fgesora/odoo,fuselock/odoo,luiseduardohdbackup/odoo,srsman/odoo,xujb/odoo,KontorConsulting/odoo,odoousers2014/odoo,Eric-Zhong/odoo,alhashash/odoo,tinkhaven-organization/odoo,eino-makitalo/odoo,Noviat/odoo,juanalfonsopr/odoo,Endika/OpenUpgrade,fossoult/odoo,nexiles/odoo,doomsterinc/odoo,damdam-s/OpenUpgrade,mvaled/OpenUpgrade,Nowheresly/odoo,hopeall/odoo,odoo-turkiye/odoo,srimai/odoo,virgree/odoo,nexiles/odoo,VielSoft/odoo,ApuliaSoftware/odoo,optima-ict/odoo,shaufi/odoo,rahuldhote/odoo,fevxie/odoo,jolevq/odoopub,JCA-Developpement/Odoo,hip-odoo/odoo,kifcaliph/odoo,fuselock/odoo,0k/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,jiachenning/odoo,alqfahad/odoo,incaser/odoo-odoo,funkring/fdoo,NL66278/OCB,CopeX/odoo,MarcosCommunity/odoo,lsinfo/odoo,massot/odoo,jaxkodex/odoo,ojengwa/odoo,KontorConsulting/odoo,omprakasha/odoo,SerpentCS/odoo,Gitlab11/odoo,dfang/odoo,mustafat/odoo-1,nitinitprof/odoo,jaxkodex/odoo,Nowheresly/odoo,sinbazhou/odoo,alexcuellar/odoo,fossoult/odoo,0k/OpenUpgrade,hoatle/odoo,guewen/OpenUpgrade,hoatle/odoo,Adel-Magebinary/odoo,simongoffin/website_version,GauravSahu/odoo,rubencabrera/odoo,pedrobaeza/odoo,OpenUpgrade/OpenUpgrade,cpyou/odoo,hanicker/odoo,Kilhog/odoo,Ernesto99/odoo,rahuldhote/odoo,dsfsdgsbngfggb/odoo,grap/OpenUpgrade,addition-it-solutions/project-all,QianBIG/odoo,lsinfo/odoo,tarzan0820/odoo,luistorresm/odoo,damdam-s/OpenUpgrade,juanalfonsopr/odoo,bwrsandman/OpenUpgrade,colinnewell/odoo,ShineFan/odoo,nitinitprof/odoo,osvalr/odoo,Gitlab11/odoo,stonegithubs/odoo,Maspear/odoo,AuyaJackie/odoo,lightcn/odoo,markeTIC/OCB,jfpla/odoo,erkrishna9/odoo,oihane/odoo,luiseduardohdbackup/odoo,juanalfonsopr/odoo,CubicERP/odoo,agrista/odoo-saas,OpenUpgrade/OpenUpgrade,Endika/OpenUpgrade,grap/OpenUpgrade,savoirfairelinux/odoo,apanju/odoo,shaufi10/odoo,csrocha/OpenUpgrade,deKupini/erp,vnsofthe/odoo,Ichag/odoo,cloud9UG/odoo,pplatek/odoo,matrixise/odoo,luiseduardohdbackup/odoo,mmbtba/odoo,fuhongliang/odoo,Eric-Zhong/odoo,windedge/odoo,incaser/odoo-odoo,microcom/odoo,guerrerocarlos/odoo,optima-ict/odoo,ovnicraft/odoo,nhomar/odoo-mirror,jiangzhixiao/odoo,bobisme/odoo,synconics/odoo,SerpentCS/odoo,fossoult/odoo,ehirt/odoo,tinkerthaler/odoo,RafaelTorrealba/odoo,naousse/odoo,agrista/odoo-saas,idncom/odoo,jaxkodex/odoo,dkubiak789/odoo,ecosoft-odoo/odoo,ClearCorp-dev/odoo,dllsf/odootest,naousse/odoo,avoinsystems/odoo,bguillot/OpenUpgrade,feroda/odoo,SerpentCS/odoo,sebalix/OpenUpgrade,bguillot/OpenUpgrade,ygol/odoo,fevxie/odoo,janocat/odoo,FlorianLudwig/odoo,alhashash/odoo,ojengwa/odoo,bplancher/odoo,Antiun/odoo,omprakasha/odoo,shaufi/odoo,ojengwa/odoo,charbeljc/OCB,savoirfairelinux/OpenUpgrade,jpshort/odoo,oihane/odoo,syci/OCB,slevenhagen/odoo-npg,gsmartway/odoo,slevenhagen/odoo-npg,blaggacao/OpenUpgrade,rgeleta/odoo,0k/odoo,srsman/odoo,zchking/odoo,cedk/odoo,QianBIG/odoo,odoo-turkiye/odoo,ShineFan/odoo,wangjun/odoo,FlorianLudwig/odoo,charbeljc/OCB,zchking/odoo,christophlsa/odoo,ramitalat/odoo,luiseduardohdbackup/odoo,Ernesto99/odoo,BT-rmartin/odoo,kittiu/odoo,massot/odoo,arthru/OpenUpgrade,BT-astauder/odoo,zchking/odoo,Antiun/odoo,synconics/odoo,shivam1111/odoo,CopeX/odoo,Bachaco-ve/odoo,havt/odoo,collex100/odoo,syci/OCB,rowemoore/odoo,BT-ojossen/odoo,lsinfo/odoo,mustafat/odoo-1,osvalr/odoo,dsfsdgsbngfggb/odoo,hubsaysnuaa/odoo,laslabs/odoo,lombritz/odoo,luistorresm/odoo,nuuuboo/odoo,patmcb/odoo,ujjwalwahi/odoo,ShineFan/odoo,nuncjo/odoo,hoatle/odoo,mszewczy/odoo,poljeff/odoo,inspyration/odoo,BT-rmartin/odoo,laslabs/odoo,acshan/odoo,glovebx/odoo,ramitalat/odoo,fuhongliang/odoo,kittiu/odoo,hubsaysnuaa/odoo,cloud9UG/odoo,oasiswork/odoo,luistorresm/odoo,Eric-Zhong/odoo,tangyiyong/odoo,stonegithubs/odoo,ramadhane/odoo,NeovaHealth/odoo,gavin-feng/odoo,fdvarela/odoo8,ingadhoc/odoo,waytai/odoo,windedge/odoo,provaleks/o8,0k/OpenUpgrade,juanalfonsopr/odoo,collex100/odoo,Endika/odoo,thanhacun/odoo,joariasl/odoo,NL66278/OCB,apanju/odoo,kifcaliph/odoo,BT-ojossen/odoo,Drooids/odoo,idncom/odoo,OpusVL/odoo,salaria/odoo
--- +++ @@ -5,7 +5,7 @@ _columns = { 'user_id': fields.many2one('res.users','Me'), - 'partner_id': fields.many2one('res.partner','Contact'), + 'partner_id': fields.many2one('res.partner','Contact',required=True), 'active':fields.boolean('active'), } _defaults = {
2f31183c2ec71baa826282e10ce7e6b7decbdc75
Tools/idle/IdlePrefs.py
Tools/idle/IdlePrefs.py
# Color Prefs for idle class ColorPrefs: CNormal = "black", "white" # "purple", "white" CKeyword = "#ff7700", None CComment = "#dd0000", None CString = "#00aa00", None CDefinition = "#0000ff", None CHilite = "#000068", "#006868" CSync = None, None # None, "#ffff00" CTodo = None, None # None, "#cccccc" CBreak = "#ff7777", None CHit = "#ffffff", "#000000" CStdIn = None, None # None, "yellow" CStdOut = "blue", None CStdErr = "#007700", None CConsole = "#770000", None CError = None, "#ff7777" CCursor = None, "black"
# Color Prefs for idle class ColorPrefs: CNormal = "black", "white" # "purple", "white" CKeyword = "#ff7700", None CComment = "#dd0000", None CString = "#00aa00", None CDefinition = "#0000ff", None CHilite = "#000068", "#006868" CSync = None, None # None, "#ffff00" CTodo = None, None # None, "#cccccc" CBreak = "#ff7777", None CHit = "#ffffff", "#000000" CStdIn = None, None # None, "yellow" CStdOut = "blue", None CStdErr = "red", None CConsole = "#770000", None CError = None, "#ff7777" CCursor = None, "black"
Make the color for stderr red (i.e. the standard warning/danger/stop color) rather than green. Suggested by Sam Schulenburg.
Make the color for stderr red (i.e. the standard warning/danger/stop color) rather than green. Suggested by Sam Schulenburg.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -13,7 +13,7 @@ CHit = "#ffffff", "#000000" CStdIn = None, None # None, "yellow" CStdOut = "blue", None - CStdErr = "#007700", None + CStdErr = "red", None CConsole = "#770000", None CError = None, "#ff7777" CCursor = None, "black"
14503786d1ff3a91cee1b05698faf60e1f7bb371
edit.py
edit.py
# Open your $EDITOR to compose a message in weechat # # Usage: # /edit # # History: # 10-18-2015 # Version 1.0.0: initial release import os import os.path import subprocess import weechat def edit(data, buf, args): editor = os.environ.get("EDITOR", "vim") path = os.path.expanduser("~/.weechat/message.txt") open(path, "w+") cmd = [editor, path] code = subprocess.Popen(cmd).wait() if code != 0: weechat.command(buf, "/window refresh") return weechat.WEECHAT_RC_ERROR with open(path) as f: text = f.read() weechat.buffer_set(buf, "input", text) weechat.buffer_set(buf, "input_pos", str(len(text))) weechat.command(buf, "/window refresh") return weechat.WEECHAT_RC_OK def main(): if not weechat.register("edit", "Keith Smiley", "1.0.0", "MIT", "Open your $EDITOR to compose a message", "", ""): return weechat.WEECHAT_RC_ERROR weechat.hook_command("edit", "Open your $EDITOR to compose a message", "", "", "", "edit", "") if __name__ == "__main__": main()
# Open your $EDITOR to compose a message in weechat # # Usage: # /edit # # History: # 10-18-2015 # Version 1.0.0: initial release import os import os.path import subprocess import weechat def edit(data, buf, args): editor = os.environ.get("EDITOR", "vim") path = os.path.expanduser("~/.weechat/message.txt") open(path, "w+") cmd = [editor, path] code = subprocess.Popen(cmd).wait() if code != 0: os.remove(path) weechat.command(buf, "/window refresh") return weechat.WEECHAT_RC_ERROR with open(path) as f: text = f.read() weechat.buffer_set(buf, "input", text) weechat.buffer_set(buf, "input_pos", str(len(text))) os.remove(path) weechat.command(buf, "/window refresh") return weechat.WEECHAT_RC_OK def main(): if not weechat.register("edit", "Keith Smiley", "1.0.0", "MIT", "Open your $EDITOR to compose a message", "", ""): return weechat.WEECHAT_RC_ERROR weechat.hook_command("edit", "Open your $EDITOR to compose a message", "", "", "", "edit", "") if __name__ == "__main__": main()
Remove file after using it
Remove file after using it
Python
mit
keith/edit-weechat
--- +++ @@ -21,6 +21,7 @@ cmd = [editor, path] code = subprocess.Popen(cmd).wait() if code != 0: + os.remove(path) weechat.command(buf, "/window refresh") return weechat.WEECHAT_RC_ERROR @@ -29,6 +30,7 @@ weechat.buffer_set(buf, "input", text) weechat.buffer_set(buf, "input_pos", str(len(text))) + os.remove(path) weechat.command(buf, "/window refresh") return weechat.WEECHAT_RC_OK
ece48034dac3466e2ebf5ced85afc0a36cf4997b
api/base/content_negotiation.py
api/base/content_negotiation.py
from rest_framework.negotiation import BaseContentNegotiation class CustomClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ return parsers[0] def select_renderer(self, request, renderers, format_suffix): """ Select the third renderer in the `.renderer_classes` list for the browsable API, otherwise use the first renderer which has media_type "application/vnd.api+json" """ if 'text/html' in request.META.get('HTTP_ACCEPT', 'None'): return (renderers[2], renderers[2].media_type) return (renderers[0], renderers[0].media_type)
from rest_framework.negotiation import BaseContentNegotiation class CustomClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ content_type = request.QUERY_PARAMS.get('content_type', request.content_type) for parser in parsers: if parser.media_type == content_type: return parser return parsers[0] def select_renderer(self, request, renderers, format_suffix): """ Select the third renderer in the `.renderer_classes` list for the browsable API, otherwise use the first renderer which has media_type "application/vnd.api+json" """ if 'text/html' in request.META.get('HTTP_ACCEPT', 'None'): return (renderers[2], renderers[2].media_type) return (renderers[0], renderers[0].media_type)
Change select_parser to choose parser based on content_type instead of manadating a parser
Change select_parser to choose parser based on content_type instead of manadating a parser
Python
apache-2.0
ZobairAlijan/osf.io,haoyuchen1992/osf.io,ckc6cz/osf.io,danielneis/osf.io,abought/osf.io,SSJohns/osf.io,felliott/osf.io,cwisecarver/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,cslzchen/osf.io,doublebits/osf.io,samchrisinger/osf.io,acshi/osf.io,mluo613/osf.io,billyhunt/osf.io,mattclark/osf.io,doublebits/osf.io,cosenal/osf.io,brianjgeiger/osf.io,petermalcolm/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,acshi/osf.io,sloria/osf.io,acshi/osf.io,Johnetordoff/osf.io,icereval/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,Ghalko/osf.io,abought/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,kch8qx/osf.io,DanielSBrown/osf.io,ticklemepierce/osf.io,sbt9uc/osf.io,KAsante95/osf.io,mluke93/osf.io,pattisdr/osf.io,amyshi188/osf.io,alexschiller/osf.io,jmcarp/osf.io,caneruguz/osf.io,asanfilippo7/osf.io,cwisecarver/osf.io,GageGaskins/osf.io,mattclark/osf.io,ZobairAlijan/osf.io,sloria/osf.io,Ghalko/osf.io,adlius/osf.io,icereval/osf.io,baylee-d/osf.io,kch8qx/osf.io,emetsger/osf.io,petermalcolm/osf.io,aaxelb/osf.io,TomHeatwole/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,KAsante95/osf.io,caseyrollins/osf.io,Ghalko/osf.io,ZobairAlijan/osf.io,TomBaxter/osf.io,mattclark/osf.io,jnayak1/osf.io,brianjgeiger/osf.io,samchrisinger/osf.io,asanfilippo7/osf.io,rdhyee/osf.io,zachjanicki/osf.io,kwierman/osf.io,DanielSBrown/osf.io,GageGaskins/osf.io,sbt9uc/osf.io,sloria/osf.io,haoyuchen1992/osf.io,wearpants/osf.io,caseyrygt/osf.io,binoculars/osf.io,njantrania/osf.io,monikagrabowska/osf.io,erinspace/osf.io,njantrania/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,MerlinZhang/osf.io,jnayak1/osf.io,acshi/osf.io,cosenal/osf.io,mluo613/osf.io,ticklemepierce/osf.io,abought/osf.io,RomanZWang/osf.io,emetsger/osf.io,TomHeatwole/osf.io,brandonPurvis/osf.io,zachjanicki/osf.io,chrisseto/osf.io,cosenal/osf.io,caseyrygt/osf.io,TomBaxter/osf.io,hmoco/osf.io,kch8qx/osf.io,petermalcolm/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,KAsante95/osf.io,laurenrevere/osf.io,billyhunt/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,zamattiac/osf.io,SSJohns/osf.io,RomanZWang/osf.io,caneruguz/osf.io,mfraezz/osf.io,njantrania/osf.io,CenterForOpenScience/osf.io,jnayak1/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,crcresearch/osf.io,caseyrygt/osf.io,billyhunt/osf.io,caneruguz/osf.io,ticklemepierce/osf.io,petermalcolm/osf.io,RomanZWang/osf.io,KAsante95/osf.io,alexschiller/osf.io,cslzchen/osf.io,ckc6cz/osf.io,arpitar/osf.io,arpitar/osf.io,cwisecarver/osf.io,erinspace/osf.io,danielneis/osf.io,doublebits/osf.io,haoyuchen1992/osf.io,samanehsan/osf.io,leb2dg/osf.io,samanehsan/osf.io,Nesiehr/osf.io,adlius/osf.io,jnayak1/osf.io,arpitar/osf.io,zachjanicki/osf.io,adlius/osf.io,KAsante95/osf.io,binoculars/osf.io,jmcarp/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,kch8qx/osf.io,Johnetordoff/osf.io,binoculars/osf.io,ticklemepierce/osf.io,chennan47/osf.io,amyshi188/osf.io,baylee-d/osf.io,leb2dg/osf.io,zamattiac/osf.io,Ghalko/osf.io,brianjgeiger/osf.io,zamattiac/osf.io,TomHeatwole/osf.io,amyshi188/osf.io,ckc6cz/osf.io,saradbowman/osf.io,emetsger/osf.io,chrisseto/osf.io,baylee-d/osf.io,abought/osf.io,samchrisinger/osf.io,adlius/osf.io,MerlinZhang/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,billyhunt/osf.io,alexschiller/osf.io,SSJohns/osf.io,samanehsan/osf.io,aaxelb/osf.io,danielneis/osf.io,hmoco/osf.io,kwierman/osf.io,MerlinZhang/osf.io,MerlinZhang/osf.io,ckc6cz/osf.io,amyshi188/osf.io,leb2dg/osf.io,saradbowman/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io,pattisdr/osf.io,danielneis/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,cosenal/osf.io,felliott/osf.io,chennan47/osf.io,felliott/osf.io,aaxelb/osf.io,mluo613/osf.io,cslzchen/osf.io,felliott/osf.io,caseyrollins/osf.io,brandonPurvis/osf.io,samchrisinger/osf.io,wearpants/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,zachjanicki/osf.io,monikagrabowska/osf.io,DanielSBrown/osf.io,sbt9uc/osf.io,billyhunt/osf.io,kch8qx/osf.io,mluke93/osf.io,acshi/osf.io,laurenrevere/osf.io,zamattiac/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,jmcarp/osf.io,chennan47/osf.io,mfraezz/osf.io,chrisseto/osf.io,cslzchen/osf.io,TomBaxter/osf.io,chrisseto/osf.io,jmcarp/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,kwierman/osf.io,njantrania/osf.io,aaxelb/osf.io,emetsger/osf.io,monikagrabowska/osf.io,arpitar/osf.io,mluke93/osf.io,caseyrygt/osf.io,rdhyee/osf.io,doublebits/osf.io,asanfilippo7/osf.io,hmoco/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,wearpants/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,icereval/osf.io,wearpants/osf.io,mluo613/osf.io,GageGaskins/osf.io,mluo613/osf.io,mluke93/osf.io,erinspace/osf.io,sbt9uc/osf.io,doublebits/osf.io
--- +++ @@ -6,6 +6,10 @@ """ Select the first parser in the `.parser_classes` list. """ + content_type = request.QUERY_PARAMS.get('content_type', request.content_type) + for parser in parsers: + if parser.media_type == content_type: + return parser return parsers[0] def select_renderer(self, request, renderers, format_suffix):
2b58a34a6bde9c7db39fc436928e344284de633b
app/DataLogger/sqlite_logger.py
app/DataLogger/sqlite_logger.py
import sqlite3 import time class SQLiteLogger: def __init__(self, filename="g2x.db"): self.filename = filename self.connection = None def __enter__(self): try: with open(self.filename): self.connection = sqlite3.connect(self.filename) except IOError: self.connection = sqlite3.connect(self.filename) cursor = self.connection.cursor() cursor.execute('''CREATE TABLE readings (date real, device text, property text, value real)''') self.connection.commit() return self def __exit__(self, type, value, traceback): self.connection.close() self.connection = None def log(self, device, property, value, t=None): if t is None: t = time.time() values = (t, device, property, value) cursor = self.connection.cursor() cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values) self.connection.commit()
import sqlite3 import time class SQLiteLogger: def __init__(self, filename="g2x.db"): self.filename = filename self.connection = None def __enter__(self): self.open() return self def __exit__(self, type, value, traceback): self.close() def open(self): try: with open(self.filename): self.connection = sqlite3.connect(self.filename) except IOError: self.connection = sqlite3.connect(self.filename) cursor = self.connection.cursor() cursor.execute('''CREATE TABLE readings (date real, device text, property text, value real)''') self.connection.commit() def close(self): if self.connection is not None: self.connection.close() self.connection = None def log(self, device, property, value, t=None): if self.connection is not None: if t is None: t = time.time() values = (t, device, property, value) cursor = self.connection.cursor() cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values) self.connection.commit()
Allow logger to be opened and closed directly
Allow logger to be opened and closed directly
Python
mit
gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x
--- +++ @@ -8,6 +8,13 @@ self.connection = None def __enter__(self): + self.open() + return self + + def __exit__(self, type, value, traceback): + self.close() + + def open(self): try: with open(self.filename): self.connection = sqlite3.connect(self.filename) @@ -18,17 +25,17 @@ (date real, device text, property text, value real)''') self.connection.commit() - return self - - def __exit__(self, type, value, traceback): - self.connection.close() - self.connection = None + def close(self): + if self.connection is not None: + self.connection.close() + self.connection = None def log(self, device, property, value, t=None): - if t is None: - t = time.time() - values = (t, device, property, value) + if self.connection is not None: + if t is None: + t = time.time() + values = (t, device, property, value) - cursor = self.connection.cursor() - cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values) - self.connection.commit() + cursor = self.connection.cursor() + cursor.execute("INSERT INTO readings VALUES(?,?,?,?)", values) + self.connection.commit()
4c4b8f1a9d54d34dd9c2ee89367c7e290f94a12f
archive/archive_api/src/models/_base.py
archive/archive_api/src/models/_base.py
# -*- encoding: utf-8 from flask_restplus import fields, Model class TypedModel(Model): """ A thin wrapper around ``Model`` that adds a ``type`` field. """ def __init__(self, name, model_fields, *args, **kwargs): # When you use a model in ``@api.response``, it triggers an internal # cloning operation, which passes the ``model_fields`` parameter as # a list of 2-tuples. # # In that case, we should already have a ``type`` field, so we # can skip adding it. # if isinstance(model_fields, dict) and "type" not in model_fields: model_fields["type"] = fields.String( description="Type of the object", enum=[name], default=name ) super().__init__(name, model_fields, *args, **kwargs)
# -*- encoding: utf-8 from flask_restplus import fields, Model class TypedModel(Model): """ A thin wrapper around ``Model`` that adds a ``type`` field. """ def __init__(self, name, model_fields, *args, **kwargs): # When you use a model in ``@api.response``, it triggers an internal # cloning operation, which passes the ``model_fields`` parameter as # a list of 2-tuples. # # In that case, we should already have a ``type`` field, so we # can skip adding it. # if isinstance(model_fields, dict) and "type" not in model_fields: model_fields["type"] = fields.String( description="Type of the object", enum=[name], default=name, required=True ) super().__init__(name, model_fields, *args, **kwargs)
Make sure we ask callers for the "type" field
Make sure we ask callers for the "type" field
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
--- +++ @@ -21,7 +21,8 @@ model_fields["type"] = fields.String( description="Type of the object", enum=[name], - default=name + default=name, + required=True ) super().__init__(name, model_fields, *args, **kwargs)
d76e4f45f78dc34a22f641cc8c691ac8f35daf0c
src/exhaustive_search/euclidean_mst.py
src/exhaustive_search/euclidean_mst.py
""" Provides a solution (`solve`) to the EMST problem. """ # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) plen = len(points) if plen < 2: return [] if plen == 2: return [(points[0], points[1])]
""" Provides a solution (`solve`) to the EMST problem. """ from .graph import Graph # Euclidean Minimum Spanning Tree (MST) algorithm # # input: a list of n Point objects # # output: a list of (p, q) tuples, where p and q are each input Point # objects, and (p, q) should be connected in a minimum spanning tree # of the input points def solve(points): """ Solves the EMST problem """ # it's not a list if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) g = Graph(points) if g.num_edges() < 1: return [] return []
Use (still wrong) Graph implementation in MST.py
Use (still wrong) Graph implementation in MST.py
Python
isc
ciarand/exhausting-search-homework
--- +++ @@ -1,4 +1,6 @@ """ Provides a solution (`solve`) to the EMST problem. """ + +from .graph import Graph # Euclidean Minimum Spanning Tree (MST) algorithm # @@ -9,12 +11,13 @@ # of the input points def solve(points): """ Solves the EMST problem """ + # it's not a list if not isinstance(points, list): raise TypeError("solve expects a list of n Point objects, received %s" % points) - plen = len(points) - if plen < 2: + g = Graph(points) + + if g.num_edges() < 1: return [] - if plen == 2: - return [(points[0], points[1])] + return []
b60bcae61d2da4a6869db25f233e8bec40740ffc
test/test_notebook.py
test/test_notebook.py
import glob from nbconvert.preprocessors import ExecutePreprocessor import nbformat import pytest notebooks = sorted(glob.glob("*.ipynb")) @pytest.mark.parametrize("notebook", notebooks) def test_notebook_execution(notebook): with open(notebook) as fin: nb = nbformat.read(fin, as_version=4) ep = ExecutePreprocessor(timeout=2400, kernel_name="python3") ep.preprocess(nb, resources={}) @pytest.mark.parametrize("notebook", notebooks) def test_notebook_clear(notebook): with open(notebook) as fin: nb = nbformat.read(fin, as_version=4) for cell in nb.cells: if cell["cell_type"] == "code": assert cell["outputs"] == [] assert cell["execution_count"] is None
import glob from nbconvert.preprocessors import ExecutePreprocessor import nbformat import pytest notebooks = sorted(glob.glob("*.ipynb")) @pytest.mark.parametrize("notebook", notebooks) def test_notebook_execution(notebook): with open(notebook) as fin: nb = nbformat.read(fin, as_version=4) ep = ExecutePreprocessor(timeout=2400, kernel_name="python3") ep.preprocess(nb, resources={})
Remove requirement to clear notebooks
Remove requirement to clear notebooks
Python
mit
alanhdu/AccessibleML,adicu/AccessibleML
--- +++ @@ -14,14 +14,3 @@ ep = ExecutePreprocessor(timeout=2400, kernel_name="python3") ep.preprocess(nb, resources={}) - - -@pytest.mark.parametrize("notebook", notebooks) -def test_notebook_clear(notebook): - with open(notebook) as fin: - nb = nbformat.read(fin, as_version=4) - - for cell in nb.cells: - if cell["cell_type"] == "code": - assert cell["outputs"] == [] - assert cell["execution_count"] is None
9b1ecea92cc629bf659764cf45d63b1d911a24e3
plugins/urlgrabber.py
plugins/urlgrabber.py
from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand): triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"} def trigger_url(self, context, user, channel, match): if user == 'JustCommit': return try: url = match.group(1) response = requests.get(url) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e else: soup = BeautifulSoup(response.text) if soup.title and soup.title.text: title = soup.title.string title = title.replace('\n', '') # remove newlines title = title.replace('\x01', '') # remove dangerous control character \001 title = ' '.join(title.split()) # normalise all other whitespace # Truncate length if len(title) > 120: title = title[:117] + "..." return title else: print "URL has no title: %s" % url
from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand): triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"} def trigger_url(self, context, user, channel, match): if user == 'JustCommit': return try: url = match.group(1) agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36' response = requests.get(url, headers={ 'User-Agent': agent }) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e else: soup = BeautifulSoup(response.text) if soup.title and soup.title.text: title = soup.title.string title = title.replace('\n', '') # remove newlines title = title.replace('\x01', '') # remove dangerous control character \001 title = ' '.join(title.split()) # normalise all other whitespace # Truncate length if len(title) > 120: title = title[:117] + "..." return title else: print "URL has no title: %s" % url
Use a realistic User-Agent for reddit
Use a realistic User-Agent for reddit
Python
isc
ComSSA/KhlavKalash
--- +++ @@ -18,7 +18,8 @@ return try: url = match.group(1) - response = requests.get(url) + agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36' + response = requests.get(url, headers={ 'User-Agent': agent }) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e
27e4adcf0ccd36c7c2a079f04e19ed38e8a05edd
app/config.py
app/config.py
WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess' # In minutes CURRENT_TICKET_LIFETIME = 2 QUEUED_TICKET_LIFETIME = 2
WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess' # In minutes CURRENT_TICKET_LIFETIME = 720 QUEUED_TICKET_LIFETIME = 2
Set standard lifetime of tickets to 12 hours
Set standard lifetime of tickets to 12 hours
Python
apache-2.0
otto-de/gatekeeper,otto-de/gatekeeper,otto-de/gatekeeper,otto-de/gatekeeper
--- +++ @@ -2,5 +2,5 @@ SECRET_KEY = 'you-will-never-guess' # In minutes -CURRENT_TICKET_LIFETIME = 2 +CURRENT_TICKET_LIFETIME = 720 QUEUED_TICKET_LIFETIME = 2
95becdbbece636369754850ee14d664042c1f4c2
squadron/exthandlers/tests/test_virtualenv.py
squadron/exthandlers/tests/test_virtualenv.py
import os from ..virtualenv import ext_virtualenv def test_basic(tmpdir): tmpdir = str(tmpdir) abs_source = os.path.join(tmpdir, 'requirements.txt') with open(abs_source, 'w') as vfile: vfile.write('bottle\n') vfile.write('pytest\n') dest = os.path.join(tmpdir, 'env~virtualenv') finalfile = ext_virtualenv(abs_source, dest) assert os.path.exists(finalfile) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) lib_dir = os.path.join(finalfile, 'lib', 'python2.7', 'site-packages') assert os.path.exists(os.path.join(lib_dir, 'bottle.py')) assert os.path.exists(os.path.join(lib_dir, 'pytest.py'))
import os from ..virtualenv import ext_virtualenv def integration(tmpdir): tmpdir = str(tmpdir) abs_source = os.path.join(tmpdir, 'requirements.txt') with open(abs_source, 'w') as vfile: vfile.write('bottle\n') vfile.write('pytest\n') dest = os.path.join(tmpdir, 'env~virtualenv') finalfile = ext_virtualenv(abs_source, dest) assert os.path.exists(finalfile) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) assert os.path.exists(os.path.join(finalfile, 'bin', 'activate')) lib_dir = os.path.join(finalfile, 'lib', 'python2.7', 'site-packages') assert os.path.exists(os.path.join(lib_dir, 'bottle.py')) assert os.path.exists(os.path.join(lib_dir, 'pytest.py'))
Change the virtualenv test to an integration test
Change the virtualenv test to an integration test So that we're not downloading them constantly
Python
mit
gosquadron/squadron,gosquadron/squadron
--- +++ @@ -1,7 +1,7 @@ import os from ..virtualenv import ext_virtualenv -def test_basic(tmpdir): +def integration(tmpdir): tmpdir = str(tmpdir) abs_source = os.path.join(tmpdir, 'requirements.txt')
4d8ee930b772329b4c3ded17a5a04efb7dada977
tests/test__compat.py
tests/test__compat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import numpy as np import dask import dask.array as da import dask.array.utils as dau import dask_distance._compat @pytest.mark.parametrize("x", [ list(range(5)), np.random.randint(10, size=(15, 16)), da.random.randint(10, size=(15, 16), chunks=(5, 5)), ]) def test_asarray(x): d = dask_distance._compat._asarray(x) assert isinstance(d, da.Array) if not isinstance(x, (np.ndarray, da.Array)): x = np.asarray(x) dau.assert_eq(d, x)
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import numpy as np import dask.array as da import dask.array.utils as dau import dask_distance._compat @pytest.mark.parametrize("x", [ list(range(5)), np.random.randint(10, size=(15, 16)), da.random.randint(10, size=(15, 16), chunks=(5, 5)), ]) def test_asarray(x): d = dask_distance._compat._asarray(x) assert isinstance(d, da.Array) if not isinstance(x, (np.ndarray, da.Array)): x = np.asarray(x) dau.assert_eq(d, x)
Drop unused import from _compat tests
Drop unused import from _compat tests
Python
bsd-3-clause
jakirkham/dask-distance
--- +++ @@ -6,7 +6,6 @@ import numpy as np -import dask import dask.array as da import dask.array.utils as dau
ac0fe94d5ced669bb1e5b5c0645b0597bf96c895
tests/test_unicode.py
tests/test_unicode.py
import os from tests.test_pip import here, reset_env, run_pip def test_install_package_that_emits_unicode(): """ Install a package with a setup.py that emits UTF-8 output and then fails. This works fine in Python 2, but fails in Python 3 with: Traceback (most recent call last): ... File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/__init__.py", line 230, in call_subprocess line = console_to_str(stdout.readline()) File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/backwardcompat.py", line 60, in console_to_str return s.decode(console_encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128) Refs https://github.com/pypa/pip/issues/326 """ env = reset_env() to_install = os.path.abspath(os.path.join(here, 'packages', 'BrokenEmitsUTF8')) result = run_pip('install', to_install, expect_error=True) assert '__main__.FakeError: this package designed to fail on install' in result.stdout assert 'UnicodeDecodeError' not in result.stdout
import os from tests.test_pip import here, reset_env, run_pip def test_install_package_that_emits_unicode(): """ Install a package with a setup.py that emits UTF-8 output and then fails. This works fine in Python 2, but fails in Python 3 with: Traceback (most recent call last): ... File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/__init__.py", line 230, in call_subprocess line = console_to_str(stdout.readline()) File "/Users/marc/python/virtualenvs/py3.1-phpserialize/lib/python3.2/site-packages/pip-1.0.2-py3.2.egg/pip/backwardcompat.py", line 60, in console_to_str return s.decode(console_encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 17: ordinal not in range(128) Refs https://github.com/pypa/pip/issues/326 """ env = reset_env() to_install = os.path.abspath(os.path.join(here, 'packages', 'BrokenEmitsUTF8')) result = run_pip('install', to_install, expect_error=True, expect_temp=True, quiet=True) assert '__main__.FakeError: this package designed to fail on install' in result.stdout assert 'UnicodeDecodeError' not in result.stdout
Fix unicode tests to work with new temp file assertions
Fix unicode tests to work with new temp file assertions
Python
mit
pjdelport/pip,patricklaw/pip,fiber-space/pip,dstufft/pip,esc/pip,prasaianooz/pip,wkeyword/pip,nthall/pip,fiber-space/pip,graingert/pip,davidovich/pip,luzfcb/pip,cjerdonek/pip,jythontools/pip,RonnyPfannschmidt/pip,pjdelport/pip,techtonik/pip,pradyunsg/pip,mindw/pip,prasaianooz/pip,ianw/pip,qwcode/pip,erikrose/pip,zenlambda/pip,Carreau/pip,wkeyword/pip,mujiansu/pip,natefoo/pip,minrk/pip,benesch/pip,chaoallsome/pip,zorosteven/pip,James-Firth/pip,rouge8/pip,erikrose/pip,sigmavirus24/pip,zenlambda/pip,harrisonfeng/pip,zvezdan/pip,mattrobenolt/pip,Gabriel439/pip,Carreau/pip,rouge8/pip,jmagnusson/pip,natefoo/pip,esc/pip,prasaianooz/pip,benesch/pip,mindw/pip,graingert/pip,caosmo/pip,rbtcollins/pip,msabramo/pip,minrk/pip,mindw/pip,willingc/pip,James-Firth/pip,alex/pip,supriyantomaftuh/pip,benesch/pip,tdsmith/pip,qwcode/pip,zvezdan/pip,jmagnusson/pip,pfmoore/pip,habnabit/pip,yati-sagade/pip,xavfernandez/pip,KarelJakubec/pip,pradyunsg/pip,Gabriel439/pip,pypa/pip,tdsmith/pip,haridsv/pip,zorosteven/pip,squidsoup/pip,h4ck3rm1k3/pip,davidovich/pip,Ivoz/pip,ncoghlan/pip,qbdsoft/pip,Ivoz/pip,RonnyPfannschmidt/pip,jamezpolley/pip,KarelJakubec/pip,natefoo/pip,ncoghlan/pip,rbtcollins/pip,pjdelport/pip,blarghmatey/pip,jamezpolley/pip,techtonik/pip,willingc/pip,xavfernandez/pip,sigmavirus24/pip,RonnyPfannschmidt/pip,msabramo/pip,luzfcb/pip,ncoghlan/pip,alquerci/pip,mattrobenolt/pip,qbdsoft/pip,supriyantomaftuh/pip,chaoallsome/pip,erikrose/pip,cjerdonek/pip,willingc/pip,yati-sagade/pip,techtonik/pip,Gabriel439/pip,atdaemon/pip,mujiansu/pip,caosmo/pip,haridsv/pip,haridsv/pip,patricklaw/pip,zvezdan/pip,blarghmatey/pip,supriyantomaftuh/pip,xavfernandez/pip,rouge8/pip,atdaemon/pip,chaoallsome/pip,jythontools/pip,jythontools/pip,davidovich/pip,habnabit/pip,alex/pip,luzfcb/pip,graingert/pip,zorosteven/pip,esc/pip,h4ck3rm1k3/pip,alex/pip,h4ck3rm1k3/pip,ChristopherHogan/pip,pypa/pip,wkeyword/pip,squidsoup/pip,ChristopherHogan/pip,pfmoore/pip,harrisonfeng/pip,caosmo/pip,ianw/pip,James-Firth/pip,dstufft/pip,sbidoul/pip,nthall/pip,zenlambda/pip,rbtcollins/pip,mujiansu/pip,dstufft/pip,harrisonfeng/pip,ChristopherHogan/pip,habnabit/pip,jmagnusson/pip,atdaemon/pip,radiosilence/pip,yati-sagade/pip,squidsoup/pip,sigmavirus24/pip,nthall/pip,jasonkying/pip,qbdsoft/pip,fiber-space/pip,jamezpolley/pip,blarghmatey/pip,alquerci/pip,jasonkying/pip,jasonkying/pip,tdsmith/pip,KarelJakubec/pip,sbidoul/pip
--- +++ @@ -20,6 +20,6 @@ env = reset_env() to_install = os.path.abspath(os.path.join(here, 'packages', 'BrokenEmitsUTF8')) - result = run_pip('install', to_install, expect_error=True) + result = run_pip('install', to_install, expect_error=True, expect_temp=True, quiet=True) assert '__main__.FakeError: this package designed to fail on install' in result.stdout assert 'UnicodeDecodeError' not in result.stdout
2e95fa670bccd4b38aa1bf30932b152559c077f4
fuse_util.py
fuse_util.py
import sublime import os def getSetting(key,default=None): s = sublime.load_settings("Fuse.sublime-settings") return s.get(key, default) def getFusePathFromSettings(): path = getSetting("fuse_path_override") if path == "" or path == None: return "fuse" else: return path+"/fuse" def setSetting(key,value): s = sublime.load_settings("Fuse.sublime-settings") s.set(key, value) sublime.save_settings("Fuse.sublime-settings") def isSupportedSyntax(syntaxName): return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): base = os.path.basename(path) ext = os.path.splitext(base) if ext is None: return "" else: return ext[0] def getRowCol(view, pos): rowcol = view.rowcol(pos) rowcol = (rowcol[0] + 1, rowcol[1] + 1) return {"Line": rowcol[0], "Character": rowcol[1]}
import sublime import os def getSetting(key,default=None): s = sublime.load_settings("Fuse.sublime-settings") return s.get(key, default) def getFusePathFromSettings(): path = getSetting("fuse_path_override") if path == "" or path == None: return "fuse" else: return path+"/fuse" def setSetting(key,value): s = sublime.load_settings("Fuse.sublime-settings") s.set(key, value) sublime.save_settings("Fuse.sublime-settings") def isSupportedSyntax(syntaxName): return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): if path is None: return "" base = os.path.basename(path) ext = os.path.splitext(base) if ext is None: return "" else: return ext[0] def getRowCol(view, pos): rowcol = view.rowcol(pos) rowcol = (rowcol[0] + 1, rowcol[1] + 1) return {"Line": rowcol[0], "Character": rowcol[1]}
Handle that Path can be none
Handle that Path can be none
Python
mit
fusetools/Fuse.SublimePlugin,fusetools/Fuse.SublimePlugin
--- +++ @@ -21,6 +21,9 @@ return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): + if path is None: + return "" + base = os.path.basename(path) ext = os.path.splitext(base)
29696868de9a02f6621bcc506a378630fae2ae7a
polemarch/__init__.py
polemarch/__init__.py
''' ### Polemarch is ansible based service for orchestration infrastructure. * [Documentation](http://polemarch.readthedocs.io/) * [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues) * [Source Code](https://gitlab.com/vstconsulting/polemarch) ''' import os import warnings try: from vstutils.environment import prepare_environment, cmd_execution except ImportError: warnings.warn('"vstutils" was not installed', ImportWarning) prepare_environment = lambda *args, **kwargs: () cmd_execution = prepare_environment default_settings = { # ansible specific environment variables "ANSIBLE_HOST_KEY_CHECKING": 'False', "ANSIBLE_FORCE_COLOR": "true", # celery specific "C_FORCE_ROOT": "true", # django settings module "DJANGO_SETTINGS_MODULE": os.getenv( "DJANGO_SETTINGS_MODULE", 'polemarch.main.settings' ), # VSTUTILS settings "VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'), "VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'), } __version__ = "1.4.4" prepare_environment(**default_settings)
''' ### Polemarch is ansible based service for orchestration infrastructure. * [Documentation](http://polemarch.readthedocs.io/) * [Issue Tracker](https://gitlab.com/vstconsulting/polemarch/issues) * [Source Code](https://gitlab.com/vstconsulting/polemarch) ''' import os import warnings try: from vstutils.environment import prepare_environment, cmd_execution except ImportError: warnings.warn('"vstutils" was not installed', ImportWarning) prepare_environment = lambda *args, **kwargs: () cmd_execution = prepare_environment default_settings = { # ansible specific environment variables "ANSIBLE_HOST_KEY_CHECKING": 'False', "ANSIBLE_FORCE_COLOR": "true", # celery specific "C_FORCE_ROOT": "true", # django settings module "DJANGO_SETTINGS_MODULE": os.getenv( "DJANGO_SETTINGS_MODULE", 'polemarch.main.settings' ), # VSTUTILS settings "VST_PROJECT": os.getenv("VST_PROJECT", 'polemarch'), "VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'), } __version__ = "1.4.5" prepare_environment(**default_settings)
Update vstutils version and fix capability in settings.
Update vstutils version and fix capability in settings.
Python
agpl-3.0
vstconsulting/polemarch,vstconsulting/polemarch,vstconsulting/polemarch,vstconsulting/polemarch
--- +++ @@ -31,6 +31,6 @@ "VST_ROOT_URLCONF": os.getenv("VST_ROOT_URLCONF", 'vstutils.urls'), } -__version__ = "1.4.4" +__version__ = "1.4.5" prepare_environment(**default_settings)
a680f4ba60e79ff7f169916d380f92a47739ccf6
collect_menus_to_json.py
collect_menus_to_json.py
from CafeScraper.Scraper import Scraper import json scraper = Scraper() json_dump = json.dumps(list(scraper.cafes_dict.values()), default=lambda c: c.__dict__, sort_keys=True) print(json_dump) # save to file with open('menus.json', 'w') as fp: print(json_dump, file=fp) # # # for cafe in scraper.cafes: # #print(cafe) # json_dump = json.dumps(cafe, default=lambda c: c.__dict__) # print(json_dump)
from pathlib import Path from time import time from CafeScraper.Scraper import Scraper import json def collect_backup_and_dump(): ''' Get the new json ''' scraper = Scraper() json_dump = json.dumps(list(scraper.cafes_dict.values()), default=lambda c: c.__dict__, sort_keys=True) ''' Backup this json ''' # check if backup folder exists BACKUP_PATH_NAME = "backup_menu_json" cwd = Path('.') if not (cwd / BACKUP_PATH_NAME).exists(): # create it if it doesn't print("DEBUG: backup folder did not exist, creating now...") (cwd / BACKUP_PATH_NAME).mkdir(mode=0o744) # epoch time this new json was created in seconds rounded to the nearest integer new_backup_file_name = str(int(time())) + '_menus_save.json' absolute_path = str((cwd / BACKUP_PATH_NAME).absolute()) + '/' + new_backup_file_name with open(absolute_path, 'w') as fp: print(json_dump, file=fp) ''' Distribute the new json ''' with open('menus.json', 'w') as fp: print(json_dump, file=fp) if __name__ == '__main__': collect_backup_and_dump()
Backup all menus collected while keeping a main json file.
Backup all menus collected while keeping a main json file.
Python
mit
atbe/MSU-Cafe-Scraper,atbe/MSU-Cafe-Scraper
--- +++ @@ -1,17 +1,39 @@ +from pathlib import Path +from time import time + from CafeScraper.Scraper import Scraper import json -scraper = Scraper() -json_dump = json.dumps(list(scraper.cafes_dict.values()), default=lambda c: c.__dict__, sort_keys=True) -print(json_dump) +def collect_backup_and_dump(): -# save to file -with open('menus.json', 'w') as fp: - print(json_dump, file=fp) + ''' + Get the new json + ''' + scraper = Scraper() + json_dump = json.dumps(list(scraper.cafes_dict.values()), default=lambda c: c.__dict__, sort_keys=True) -# -# -# for cafe in scraper.cafes: -# #print(cafe) -# json_dump = json.dumps(cafe, default=lambda c: c.__dict__) -# print(json_dump) + ''' + Backup this json + ''' + # check if backup folder exists + BACKUP_PATH_NAME = "backup_menu_json" + cwd = Path('.') + if not (cwd / BACKUP_PATH_NAME).exists(): + # create it if it doesn't + print("DEBUG: backup folder did not exist, creating now...") + (cwd / BACKUP_PATH_NAME).mkdir(mode=0o744) + + # epoch time this new json was created in seconds rounded to the nearest integer + new_backup_file_name = str(int(time())) + '_menus_save.json' + absolute_path = str((cwd / BACKUP_PATH_NAME).absolute()) + '/' + new_backup_file_name + with open(absolute_path, 'w') as fp: + print(json_dump, file=fp) + + ''' + Distribute the new json + ''' + with open('menus.json', 'w') as fp: + print(json_dump, file=fp) + +if __name__ == '__main__': + collect_backup_and_dump()
63f7489066aeb23dbefc6f8de534ad05144431ad
boardinghouse/tests/test_sql.py
boardinghouse/tests/test_sql.py
""" Tests for the RAW sql functions. """ from django.conf import settings from django.test import TestCase from django.db.models import connection from boardinghouse.models import Schema class TestRejectSchemaColumnChange(TestCase): def test_exception_is_raised(self): Schema.objects.mass_create('a') cursor = connection.cursor() UPDATE = "UPDATE boardinghouse_schema SET schema='foo' WHERE schema='a'" self.assertRaises(Exception, cursor.execute, UPDATE)
""" Tests for the RAW sql functions. """ from django.conf import settings from django.test import TestCase from django.db import connection from boardinghouse.models import Schema class TestRejectSchemaColumnChange(TestCase): def test_exception_is_raised(self): Schema.objects.mass_create('a') cursor = connection.cursor() UPDATE = "UPDATE boardinghouse_schema SET schema='foo' WHERE schema='a'" self.assertRaises(Exception, cursor.execute, UPDATE)
Make test work with 1.7
Make test work with 1.7
Python
bsd-3-clause
luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse
--- +++ @@ -4,7 +4,7 @@ from django.conf import settings from django.test import TestCase -from django.db.models import connection +from django.db import connection from boardinghouse.models import Schema @@ -13,4 +13,4 @@ Schema.objects.mass_create('a') cursor = connection.cursor() UPDATE = "UPDATE boardinghouse_schema SET schema='foo' WHERE schema='a'" - self.assertRaises(Exception, cursor.execute, UPDATE) + self.assertRaises(Exception, cursor.execute, UPDATE)
e3adb0e716cd3f200baa037f6d5a1dd0bb598202
src/shield/__init__.py
src/shield/__init__.py
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from __future__ import absolute_import, division import inspect from . import registry class _method_wrapper(object): """A placeholder object used to wrap methods until the rules decorator comes around and adds everything to the shield registry.""" def __init__(self, fn, permissions, owner, target): self.permissions = permissions self.owner = owner self.target = target self.fn = fn def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) class rule: def __init__(self, owner, permissions, target=None): """owner: The owner of the permissions. permissions: The set of permissions that the owner has target: The model that we are checking if the owner has permissions for """ self.owner = owner self.permissions = permissions self.target = target def __call__(self, fn): return _method_wrapper(fn, self.permissions, self.owner, self.target) def rules(cls): """Add all permission methods on the decorated object to our registry.""" # This is called after the class object is instantiated and all methods are # wrapped with the decorator. Iterate over all of our personal wrapped # methods, unwrap them, and add them to the registry. mems = inspect.getmembers(cls, lambda x: isinstance(x, _method_wrapper)) for name, member in mems: # Unwrap each method # Add the member to the registry for perm in member.permissions: registry.registry[(member.owner, perm, member.target)] = member.fn # Now that the method has been added to the registry, unwrap the method # since we don't need the wrapper anymore. setattr(cls, name, member.fn)
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from __future__ import absolute_import, division from . import registry class rule: """Add the decorated rule to our registry""" def __init__(self, *perms, **kwargs): """owner: The owner of the permissions. permissions: The set of permissions that the owner has target: The model that we are checking if the owner has permissions for """ # Owner is a mandatory kwarg param self.owner = kwargs['owner'] # Target is an optional param used to denote what registry the # decorated function goes into self.target = kwargs.get('target') # The permission list! self.permissions = perms def __call__(self, fn): """Add the passed function to the registry """ for perm in self.permissions: # If we have no target, this goes into the general registry # otherwise it goes into the targeted registry if self.target is None: registry.general[(self.owner, perm)] = fn else: registry.targeted[(self.owner, perm, self.target)] = fn # We really have no reason to keep the wrapper now that we have added # the function to the registry return fn
Delete the class method shenannigans
Delete the class method shenannigans
Python
mit
concordusapps/python-shield
--- +++ @@ -1,53 +1,38 @@ # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from __future__ import absolute_import, division -import inspect from . import registry -class _method_wrapper(object): - """A placeholder object used to wrap methods until the rules decorator - comes around and adds everything to the shield registry.""" +class rule: + """Add the decorated rule to our registry""" - def __init__(self, fn, permissions, owner, target): - self.permissions = permissions - self.owner = owner - self.target = target - self.fn = fn - - def __call__(self, *args, **kwargs): - return self.fn(*args, **kwargs) - - -class rule: - - def __init__(self, owner, permissions, target=None): + def __init__(self, *perms, **kwargs): """owner: The owner of the permissions. permissions: The set of permissions that the owner has target: The model that we are checking if the owner has permissions for """ - self.owner = owner - self.permissions = permissions - self.target = target + # Owner is a mandatory kwarg param + self.owner = kwargs['owner'] + + # Target is an optional param used to denote what registry the + # decorated function goes into + self.target = kwargs.get('target') + + # The permission list! + self.permissions = perms def __call__(self, fn): - return _method_wrapper(fn, self.permissions, self.owner, self.target) + """Add the passed function to the registry + """ + for perm in self.permissions: + # If we have no target, this goes into the general registry + # otherwise it goes into the targeted registry + if self.target is None: + registry.general[(self.owner, perm)] = fn + else: + registry.targeted[(self.owner, perm, self.target)] = fn - -def rules(cls): - """Add all permission methods on the decorated object to our registry.""" - # This is called after the class object is instantiated and all methods are - # wrapped with the decorator. Iterate over all of our personal wrapped - # methods, unwrap them, and add them to the registry. - - mems = inspect.getmembers(cls, lambda x: isinstance(x, _method_wrapper)) - - for name, member in mems: - # Unwrap each method - # Add the member to the registry - for perm in member.permissions: - registry.registry[(member.owner, perm, member.target)] = member.fn - - # Now that the method has been added to the registry, unwrap the method - # since we don't need the wrapper anymore. - setattr(cls, name, member.fn) + # We really have no reason to keep the wrapper now that we have added + # the function to the registry + return fn