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__')"
]
c... | #!/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... | 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='__m... |
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,
E... | from __future__ import absolute_import
from pyelasticsearch.client import ElasticSearch
from pyelasticsearch.exceptions import (Timeout, ConnectionError,
ElasticHttpError,
InvalidJsonResponseError,
E... | 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', 'C... |
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... | """
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... | 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 = DjangoW... |
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.adm... | 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&functio... | 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 M... |
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):
... | 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.pipeli... |
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 update... | #!/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 update... | 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('applicat... | 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.cor... | 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__ == '__ma... | 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,seber... | ---
+++
@@ -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[... | # -*- 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[... | 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"
... | #!/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"
... | 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 = SummaryDownloa... |
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... | 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... | 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/... | ---
+++
@@ -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... | # 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 tes... | 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,selahs... | ---
+++
@@ -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,... |
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:`li... | 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:... | 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... |
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",
]))
d... | 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 witho... | 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 pyt... |
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 a... | # 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 a... | 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'... | 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'... | 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('po... |
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 re... | # 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 ... | 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 += ... | 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 += ... | 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
urlpat... | # -*- 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
urlpat... | 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... |
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.app... | """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.app... | 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 ... |
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 ... | 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 ... |
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] == "... | """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 +... | 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/... | ---
+++
@@ -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... | 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 InvalidSubj... | 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):
+ ... |
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.DictWrite... | 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.DictWrite... | 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:
... | 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.d... | 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 se... |
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.fr... | 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.fr... | 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... | 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... | 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_c... |
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.sit... | 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 = {
... | 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):... |
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.autodisco... | 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_objec... | 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('R... |
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)
... | 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_... | 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',... |
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 =... | 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, ... | 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_pu... |
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_lengt... | 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_lengt... | 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', sub... | 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('t... | 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/Cur... | ---
+++
@@ -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('testc... |
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 = la... |
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 = l... | 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 *a... |
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 agree... | 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,psac... | ---
+++
@@ -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... |
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 i... | """
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 inc... | 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... |
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.l... | 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
bu... | 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 @@
bu... |
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_S... | 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-... | 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 djang... | """
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 djang... | 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_remainin... |
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_Den... | # 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_Den... | 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",
+ ... |
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(s... | 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(s... | 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)
-
... |
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, ... | """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 ... | 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 logg... |
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 jso... | 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(ApiIntegrationT... | 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 re... |
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 = ... | # 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 = ... | 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,D... | ---
+++
@@ -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) + '... |
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.... | 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.Te... | 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)
... |
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]
retu... | 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]
retu... | 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'
MED... | # 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'
MED... | 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; filen... | 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(objec... | 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/froi... | ---
+++
@@ -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'... |
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... | __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 soc... | 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_NAM... |
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["b... | # -*- 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, ... | 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(LocalWork... |
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):
""... | # -*- 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 co... | 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, **sett... |
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... | # 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... | 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 ... |
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")
... | # 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().m... | 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_availab... |
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 =... | 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})... | 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 @@
... |
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... | 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['SENTR... | 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.StreamHand... |
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):
... | 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()
... | 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()
+
+ s... |
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="... | """ 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... | 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/b... | ---
+++
@@ -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... | #!/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
... | 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_di... |
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(callbac... | 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(callbac... | 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.ans... |
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, ... | 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(... | 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._... | 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)... | 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.Email... | 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.Email... | 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)
... | 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)
... | 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... |
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_qua... | """
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_qua... | 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... |
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):
... | 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 py... | 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.n... |
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) ... | #! /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) ... | 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.... | 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/os... | ---
+++
@@ -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'),
+ ... |
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]
+ ... |
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 = {}
... | #!/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 = {}
... | 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),
+ ... |
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'... | # -*- 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'... | 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
+ ... |
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_... | 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_e... | 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.DailyEm... | 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.DailyEm... | 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)
recip... |
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,
... | 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,
... | 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
... | 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.... | 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):
- ... |
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()
# Imp... | 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 f... | 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)
... |
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': ... | # -*- 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': ... | 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 Ha... |
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... | 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... | 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 Onl... | # -*- 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 Onl... | 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'),
}
_defaul... | 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'),
... | 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... | ---
+++
@@ -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 # N... | # 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 # N... | 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, "... |
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 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")
... | 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... |
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, req... | 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_typ... | 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,bill... | ---
+++
@@ -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
... |
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... | 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):
... | 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... |
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
#... | # -*- 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
#... | 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... |
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(... | """ 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 t... | 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(point... |
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 = Ex... | 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 = Ex... | 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 ... |
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... | 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... | 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(... |
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')
f... | 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')
... | 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), chu... | #!/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)),... | 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 "... | 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 "... | 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,zenlam... | ---
+++
@@ -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__.Fa... |
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... | 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... | 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.enviro... | '''
### 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.enviro... | 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.cafe... | 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 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... |
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')
... | """
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')
cur... | 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()
... |
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 s... | # -*- 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.
permis... | 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
- com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.