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 |
|---|---|---|---|---|---|---|---|---|---|---|
4814ef9d78070c14ab4685b802543ba0afa26754 | django/users/views.py | django/users/views.py | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
query... | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
query... | Use Python 3 style for super | Use Python 3 style for super
| Python | bsd-3-clause | FreeMusicNinja/freemusic.ninja,FreeMusicNinja/freemusic.ninja | ---
+++
@@ -23,4 +23,4 @@
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
- return super(UserViewSet, self).retrieve(request, pk)
+ return super().retrieve(request, pk) |
760a663ab1c079ea03f022c169f7d2d05346dc02 | scipy/ndimage/io.py | scipy/ndimage/io.py | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of... | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of... | Update PIL error install URL | DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779.
| Python | bsd-3-clause | anielsen001/scipy,dominicelse/scipy,aarchiba/scipy,gdooper/scipy,gfyoung/scipy,gertingold/scipy,woodscn/scipy,aeklant/scipy,Gillu13/scipy,rgommers/scipy,pyramania/scipy,scipy/scipy,mikebenfield/scipy,jakevdp/scipy,perimosocordiae/scipy,sriki18/scipy,anielsen001/scipy,person142/scipy,lhilt/scipy,aeklant/scipy,behzadnour... | ---
+++
@@ -24,8 +24,8 @@
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
- " http://pypi.python.org/pypi/PIL/ for installation"
- ... |
115197d42b380ae65de75d74a4d28933eb8defde | testproj/testproj/testapp/models.py | testproj/testproj/testapp/models.py | from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeFie... | from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeFie... | Fix warning about default value for boolean field | Fix warning about default value for boolean field
| Python | bsd-3-clause | artscoop/webstack-django-sorting,artscoop/webstack-django-sorting | ---
+++
@@ -7,7 +7,7 @@
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
- is_secret = models.BooleanField()
+ is_secret = models.BooleanField(default=False)
def __unicode__(... |
f0b4b954b8562f621caba98317f03a63d0d01c83 | globus_sdk/version.py | globus_sdk/version.py | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.3.0"
| # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.4.0"
| Update to v1.4.0 for release | Update to v1.4.0 for release
Changelog:
- #261 Add OAuthTokenResponse.by_scopes
- #257, #260 Make `cryptography` a strict requirement,
`globus-sdk[jwt]` is no longer neecessary
- #255 Simplify OAuthTokenResponse.decode_id_token to not require the
client as an argument
- #259 Add (beta) SearchClient class
| Python | apache-2.0 | sirosen/globus-sdk-python,globus/globus-sdk-python,globusonline/globus-sdk-python,globus/globus-sdk-python | ---
+++
@@ -1,3 +1,3 @@
# single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
-__version__ = "1.3.0"
+__version__ = "1.4.0" |
d017a5daeb6849975e57d81246680f9b4e161757 | popit/test_settings.py | popit/test_settings.py | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRE... | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRE... | Put more bits into the settings for the PopIt API | Put more bits into the settings for the PopIt API
| Python | agpl-3.0 | mysociety/popit-django,mysociety/popit-django,ciudadanointeligente/popit-django,mysociety/popit-django,ciudadanointeligente/popit-django,ciudadanointeligente/popit-django | ---
+++
@@ -34,5 +34,20 @@
]
# Testing related
-TEST_POPIT_API_URL = 'http://localhost:3000/api'
+TEST_POPIT_API_HOST_IP = '127.0.0.1'
+TEST_POPIT_API_PORT = '3000'
+TEST_POPIT_API_SUBDOMAIN = 'popit-django-test'
+# create the url to use for testing the database.
+# See http://xip.io/ for details on the ... |
e5fd0b527877f5fab1d1a2e76ce32062a4a8d697 | bika/lims/browser/batch/samples.py | bika/lims/browser/batch/samples.py | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
s... | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
s... | Fix exception - batch is not required field of AR | Fix exception - batch is not required field of AR
| Python | agpl-3.0 | DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,rockfruit/bika.lims,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims | ---
+++
@@ -24,6 +24,7 @@
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
- if ar.getBatch().UID() == self.context.UID():
- samples[sample.getId()] = sample
+ batch = ar.getBatch()... |
e2f118ea3d1f9e092567802610915d76d083e9f7 | tests/scoring_engine/test_worker.py | tests/scoring_engine/test_worker.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.work... | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
as... | Modify test worker unit test | Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | ---
+++
@@ -9,26 +9,25 @@
class TestWorker(object):
+ def setup(self):
+ self.worker = Worker()
+
def test_init(self):
- worker = Worker()
- assert isinstance(worker.worker_queue, WorkerQueue) is True
+ assert isinstance(self.worker.worker_queue, WorkerQueue) is True
de... |
12dc601f18c000630081694cdad461a33db96f64 | django_backend_test/django_backend_test/__init__.py | django_backend_test/django_backend_test/__init__.py | from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa | Update init file to start celery | Update init file to start celery
| Python | mit | semorale/backend-test,semorale/backend-test,semorale/backend-test | ---
+++
@@ -0,0 +1,5 @@
+from __future__ import absolute_import
+
+# This will make sure the app is always imported when
+# Django starts so that shared_task will use this app.
+from .celery import app as celery_app # noqa | |
0a8350d98005ef25ea1de4b743d6346bbae9b173 | citrination_client/base/errors.py | citrination_client/base/errors.py | class CitrinationClientError(Exception):
pass
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified. Please check for available PyCC updates"):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavail... | class CitrinationClientError(Exception):
def __init__(self, message=None, server_response=None):
if message is not None and server_response is not None:
message = "{}\nCitrination returned: {}".format(message, server_response)
super(CitrinationClientError, self).__init__(message)
class... | Add Optional Server Response Parameter To Error Classes | Add Optional Server Response Parameter To Error Classes
| Python | apache-2.0 | CitrineInformatics/python-citrination-client | ---
+++
@@ -1,37 +1,41 @@
class CitrinationClientError(Exception):
- pass
+
+ def __init__(self, message=None, server_response=None):
+ if message is not None and server_response is not None:
+ message = "{}\nCitrination returned: {}".format(message, server_response)
+ super(Citrinatio... |
943699de02c3d8f4f8e26370fbbff2dec8a2d5ea | api/identifiers/urls.py | api/identifiers/urls.py | from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
]
| from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
]
| Add identifier list to identifier views for use with embeds in registrations | Add identifier list to identifier views for use with embeds in registrations
[#OSF-6628]
| Python | apache-2.0 | saradbowman/osf.io,alexschiller/osf.io,wearpants/osf.io,erinspace/osf.io,alexschiller/osf.io,mluo613/osf.io,rdhyee/osf.io,icereval/osf.io,chrisseto/osf.io,mluo613/osf.io,chennan47/osf.io,emetsger/osf.io,hmoco/osf.io,hmoco/osf.io,hmoco/osf.io,baylee-d/osf.io,baylee-d/osf.io,sloria/osf.io,SSJohns/osf.io,erinspace/osf.io,... | ---
+++
@@ -4,4 +4,5 @@
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
+ url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
] |
99449881029eb29255d0dd9b2b4eb4e4ddd36af8 | recorder.py | recorder.py | #!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add... | #!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
met... | Use built-in Flask server when debugging - websockets won't work. | Use built-in Flask server when debugging - websockets won't work.
| Python | bsd-3-clause | openxc/web-logging-example,openxc/web-logging-example | ---
+++
@@ -1,9 +1,7 @@
#!/usr/bin/env python
-from gevent.pywsgi import WSGIServer
from flask import Flask
import views
-from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
@@ -31,5 +29,4 @@
if __name__ == '__main__':
app = create_app()
... |
42357c1c7b864668fbf2eb7dd0510b94ad8f295c | FAUSTPy/__init__.py | FAUSTPy/__init__.py | #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) ... | #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) ... | Add package meta-data (author, email, etc.). | Add package meta-data (author, email, etc.).
| Python | mit | marcecj/faust_python | ---
+++
@@ -15,4 +15,13 @@
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
+__author__ = "Marc Joliet"
+__copyright__ = "Copyright 2013, Marc Joliet"
+__credits__ = ["Marc Joliet"]
+__license__ = "MIT"
+__version__ = "0.1"
+__maintainer__ ... |
b21750ad60b84bf87f15c3d25ffa0317091a10dc | pyoracc/test/model/test_corpus.py | pyoracc/test/model/test_corpus.py | import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.success... | import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.success... | Comment about number of tests | Comment about number of tests
| Python | mit | UCL/pyoracc | ---
+++
@@ -31,5 +31,6 @@
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
+ # there is a total of 2868 files in the corpus
assert corpus.successes == 2477
assert corpus.failures == 391 |
202cfd21d04f9d8ec9fec3b921f6b4d85df5560d | Tools/px4params/xmlout.py | Tools/px4params/xmlout.py | from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createEle... | import xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
... | Change to V2 spec of param meta data | Change to V2 spec of param meta data
Had to switch to ElementTree to get attribute support
| Python | mit | darknight-007/Firmware,jlecoeur/Firmware,PX4/Firmware,PX4/Firmware,Aerotenna/Firmware,jlecoeur/Firmware,dagar/Firmware,jlecoeur/Firmware,krbeverx/Firmware,PX4/Firmware,mcgill-robotics/Firmware,PX4/Firmware,dagar/Firmware,mcgill-robotics/Firmware,dagar/Firmware,acfloria/Firmware,Aerotenna/Firmware,Aerotenna/Firmware,mje... | ---
+++
@@ -1,30 +1,46 @@
-from xml.dom.minidom import getDOMImplementation
+import xml.etree.ElementTree as ET
import codecs
+def indent(elem, level=0):
+ i = "\n" + level*" "
+ if len(elem):
+ if not elem.text or not elem.text.strip():
+ elem.text = i + " "
+ if not elem.tail or ... |
ef6f42a592e79b2693685895d8a654c4f8d9e166 | jupyterlab/labhubapp.py | jupyterlab/labhubapp.py | from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args,... | import os
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(s... | Add api_token from environment, if it's present. | Add api_token from environment, if it's present.
| Python | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -1,3 +1,4 @@
+import os
from .labapp import LabApp
try:
@@ -7,6 +8,7 @@
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
+
def init_webapp(self, *args, **kwargs):
super().init_webapp(*... |
647cb620ffc1ec353a5c9c9d8b5a2965b50647bb | ui/transformations/TransformBox.py | ui/transformations/TransformBox.py | """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
... | """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
... | Put the transform box in the overlay render for better interaction. | Put the transform box in the overlay render for better interaction.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | ---
+++
@@ -33,7 +33,7 @@
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
- self.transformBox.SetDefaultRenderer(self.widget.renderer)
+ self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
self.transformBox.I... |
db1643b27ce3da3af85f90b941f37a8f356c4acb | lcp/settings/staging.py | lcp/settings/staging.py | import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os... | import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os... | Connect to Postgres over TCP. | Connect to Postgres over TCP.
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | ---
+++
@@ -12,5 +12,6 @@
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
+ 'HOST': '127.0.0.1',
}
} |
eb4032b7467a28ee61496c64f84ddef066b908d5 | random_fact_scraper.py | random_fact_scraper.py | #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import requests
from flask import Flask
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
... | #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import json
import requests
from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromst... | Return facts in JSON format. | [upd] Return facts in JSON format.
| Python | mit | marcelombc/randomfactscraper | ---
+++
@@ -2,8 +2,9 @@
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
+import json
import requests
-from flask import Flask
+from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@@ -12,9 +13,14 @@
def main():
page = requests.get("ht... |
f966522875e473276170f59933b288ea207b68a1 | backend/django/apps/accounts/urls.py | backend/django/apps/accounts/urls.py | """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an imp... | """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an imp... | Create url config for accounts | Create url config for accounts
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop | ---
+++
@@ -16,7 +16,6 @@
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
-
from .views import AccountViewSet
router = routers.SimpleRouter() |
4ec5a83837fada00f77c25ff0f4725714a88420a | bokeh/models/tests/test_renderers.py | bokeh/models/tests/test_renderers.py | from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_lab... | from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_lab... | Fix direct glyph selection with select method | Fix direct glyph selection with select method
| Python | bsd-3-clause | xguse/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,aavanian/bokeh,evidation-health/bokeh,matbra/bokeh,KasperPRasmussen/bokeh,philippjfr/bokeh,timsnyder/bokeh,htygithub/bokeh,tacaswell/bokeh,paultcochrane/bokeh,bokeh/bokeh,justacec/bokeh,DuCorey/bokeh,msarahan/bokeh,htygithub/bokeh,jakirkham/bokeh,jplourenco/boke... | ---
+++
@@ -12,9 +12,9 @@
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
- p = figure()
- p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
- renderer = p.renderers[-1]
+ plot = figur... |
633248dd521b6868937d3fb838d39264fc170c61 | greengraph/test/map_integration.py | greengraph/test/map_integration.py | from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(senso... | from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patc... | Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet. | Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.
| Python | apache-2.0 | paulsbrookes/greengraph | ---
+++
@@ -5,37 +5,16 @@
from matplotlib import image as img
from StringIO import StringIO
-with open('image.txt','r') as source:
- text = source.read()
+patch_get = Mock()
+patch_get.content = ''
-lat=51
-long=30
-satellite=True
-zoom=10
-size=(400,400)
-sensor=False
-
-params=dict(
- sensor= str(sensor... |
abd0a6854c90c3647d17dfb3ea980fa49aa5372f | pwndbg/commands/segments.py | pwndbg/commands/segments.py | from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
... | from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invok... | Add fsbase and gsbase commands | Add fsbase and gsbase commands
| Python | mit | cebrusfs/217gdb,anthraxx/pwndbg,chubbymaggie/pwndbg,anthraxx/pwndbg,disconnect3d/pwndbg,0xddaa/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,pwndbg/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,ce... | ---
+++
@@ -1,6 +1,7 @@
from __future__ import print_function
import gdb
import pwndbg.regs
+import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
@@ -14,3 +15,20 @@
segment('fsbase')
segment('gsbase')
+
+@pwndbg.commands.OnlyWhen... |
85a7b6e39f472ae9465b8fb80e2443da352fee67 | fullcalendar/admin.py | fullcalendar/admin.py | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineA... | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineA... | Remove list filter based on event category | Remove list filter based on event category
| Python | mit | jonge-democraten/mezzanine-fullcalendar | ---
+++
@@ -14,7 +14,6 @@
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
- list_filter = ('event_category',)
search_fields = ('title', 'description', 'content')
fieldsets = ( |
c502ead77b9f82205eebdbf9863649160302a681 | scripts/generate_token.py | scripts/generate_token.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the AP... | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the AP... | Change to positional argument for generate-token | Change to positional argument for generate-token
| Python | mit | Proj-P/project-p-api,Proj-P/project-p-api | ---
+++
@@ -32,7 +32,7 @@
def main():
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument('-n', '--name', type=str, required=True,
+ parser.add_argument('name', type=str,
help='Name describing a sensor\'s location')
args = parser.parse_args()
|
a437139ea22cdbf1ea0e47949311a6618b233b74 | csvdiff/error.py | csvdiff/error.py | # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = True
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = False
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| Reset debug flag to False. | Reset debug flag to False.
| Python | bsd-3-clause | larsyencken/csvdiff | ---
+++
@@ -8,7 +8,7 @@
import sys
-DEBUG = True
+DEBUG = False
class FatalError(Exception): |
5735c779d44f763e5f993090d92514338d67cc7f | lib/strider/__init__.py | lib/strider/__init__.py | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.p... | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.p... | Fix buglet in the destroy path. | Fix buglet in the destroy path.
| Python | apache-2.0 | bradparks/strider,mhollick/strider,gcristofol/strider,jsmartin/strider,mpdehaan/strider | ---
+++
@@ -18,7 +18,7 @@
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
- return [ self.destroy(x) for x in instances ]
+ return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentPa... |
148314dad481385a794e44c115d556117816b2ab | importkit/__init__.py | importkit/__init__.py | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
import semantix.utils.lang.yaml
class SemantixLangLoaderError(Exception):
pass
def load(filen... | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception):
pass
def load(... | Add support for data URI scheme | caos: Add support for data URI scheme
It is now possible to use `data:' backend URIs:
meta_backend_uri = 'data:application/x-yaml,<YAML DOCUMENT DATA>'
| Python | mit | sprymix/importkit | ---
+++
@@ -10,7 +10,7 @@
from .import_ import ImportContext
# Import languages to register them
-import semantix.utils.lang.yaml
+from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception): |
2ec8d3bf7db7427010ad08644690b1d88a5ffe92 | jenkinsapi/plugins.py | jenkinsapi/plugins.py | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DE... | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DE... | Add trailing newline in file | Add trailing newline in file
| Python | mit | salimfadhley/jenkinsapi,imsardine/jenkinsapi,JohnLZeller/jenkinsapi,aerickson/jenkinsapi,jduan/jenkinsapi,domenkozar/jenkinsapi,imsardine/jenkinsapi,aerickson/jenkinsapi,imsardine/jenkinsapi,salimfadhley/jenkinsapi,JohnLZeller/jenkinsapi,mistermocha/jenkinsapi,zaro0508/jenkinsapi,zaro0508/jenkinsapi,zaro0508/jenkinsapi... | ---
+++
@@ -54,4 +54,3 @@
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
- |
30f8317838a2e984e54fe22042fd3ffff10f82e6 | waterbutler/core/streams/file.py | waterbutler/core/streams/file.py | import os
import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/o... | import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
... | Update FileStreamReader for new python 3.5 async | Update FileStreamReader for new python 3.5 async
| Python | apache-2.0 | RCOSDP/waterbutler,felliott/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,TomBaxter/waterbutler,Johnetordoff/waterbutler | ---
+++
@@ -1,5 +1,4 @@
import os
-import asyncio
from waterbutler.core.streams import BaseStream
@@ -28,18 +27,13 @@
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
- data = self.file_pointer.read(self.read_size)
- if not data:
- break
- ... |
8ece892f01c4b32f7fa0a34c88bfdf8ea969e5ce | kobo/apps/__init__.py | kobo/apps/__init__.py | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it'... | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it'... | Add explanatory comment for odd use of `delay()` | Add explanatory comment for odd use of `delay()`
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi | ---
+++
@@ -15,6 +15,9 @@
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
+ # Push this onto the task queue with `delay()` instead of calling
+ # it directly because a direct call in the absence of any Celer... |
bf2b6bad53edbf649bdd16830de17fd974ee7443 | lambdawebhook/hook.py | lambdawebhook/hook.py | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secr... | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secr... | Send json content-type to Jenkins | Send json content-type to Jenkins
| Python | bsd-3-clause | pristineio/lambda-webhook | ---
+++
@@ -24,11 +24,12 @@
if verified:
response = requests.post(event['jenkins_url'],
headers={
+ 'Content-Type': 'application/json',
'X-GitHub-Delivery': event['x_github_delivery'],
... |
43238e5a0f7b3782ebadad43deffc4d768e8f79a | scikits/learn/machine/manifold_learning/regression/neighbors/__init__.py | scikits/learn/machine/manifold_learning/regression/neighbors/__init__.py |
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
| Fix typo in class name. | Fix typo in class name.
It was preventing import to work properly.
From: Fabian Pedregosa <fabian.pedregosa@inria.fr>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@342 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8
| Python | bsd-3-clause | shenzebang/scikit-learn,alexsavio/scikit-learn,PatrickOReilly/scikit-learn,mugizico/scikit-learn,jayflo/scikit-learn,aminert/scikit-learn,glennq/scikit-learn,YinongLong/scikit-learn,fengzhyuan/scikit-learn,arahuja/scikit-learn,adamgreenhall/scikit-learn,mblondel/scikit-learn,pianomania/scikit-learn,ilo10/scikit-learn,i... | ---
+++
@@ -9,7 +9,7 @@
from neighbors import *
from utilities import *
-__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
+__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest |
101e80eb956778e4df74b27eefc07acb926a2974 | alarme/extras/action/rf_transmitter.py | alarme/extras/action/rf_transmitter.py | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_... | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_... | Fix extra code sending after loop in rf transmitter | Fix extra code sending after loop in rf transmitter
| Python | mit | insolite/alarme,insolite/alarme,insolite/alarme | ---
+++
@@ -26,7 +26,6 @@
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
- self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
|
b1fa16fd4b4cc3b6983290fb38d0be54c2a21742 | test_project/test_app/migrations/0002_initial_data.py | test_project/test_app/migrations/0002_initial_data.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='test_app'... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
# StackOverflow says it is very wrong to loaddata here... | Add comment about how bad this is | Add comment about how bad this is
| Python | mit | mpasternak/django-multiseek,mpasternak/django-multiseek,mpasternak/django-multiseek,mpasternak/django-multiseek | ---
+++
@@ -9,6 +9,10 @@
def load_fixture(apps, schema_editor):
+ # StackOverflow says it is very wrong to loaddata here, we should get
+ # "old" models and then load... but, this is only a simple test app
+ # so whatever. Just don't use loaddata command in your migrations or
+ # don't be suprised wh... |
1ac4e00f3d06955da90bddf03a6e478ddeb4d220 | core/modules/html_has_same_domain.py | core/modules/html_has_same_domain.py | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
... | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
... | Undo underperformaing change to code | Undo underperformaing change to code
| Python | bsd-2-clause | mjkim610/phishing-detection,jaeyung1001/phishing_site_detection | ---
+++
@@ -12,8 +12,6 @@
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
- if ("naver" in tag.text.lower()):
- return "P", mod
if cnt >= 1:
return "S", mod |
de310ce3cdd37a372f92559b7ddcf0397b9fb016 | src/convert_dir_to_CLAHE.py | src/convert_dir_to_CLAHE.py | #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=H... | #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=H... | Adjust FIJI script for applying CLAHE to a directory | Adjust FIJI script for applying CLAHE to a directory
| Python | mit | seung-lab/Julimaps,seung-lab/Julimaps | ---
+++
@@ -9,30 +9,30 @@
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
-dir = "/usr/people/tmacrina/Desktop/test/"
+dir = "/usr/people/tmacrina/seungmount/rese... |
d731ad50b863d32740bec857d46cc0c80e440185 | tests/melopy_tests.py | tests/melopy_tests.py | #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy.melopy import *
class MelopyTests(TestCase):
def test_dummy(self):
assert True
| #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy import *
class LibraryFunctionsTests(TestCase):
def test_frequency_from_key(self):
key = 49
assert frequency_from_key(key) == 440
def test_frequency_from_note(self):
note = 'A4'... | Add tests for the library methods. All except 2 pass right now. | Add tests for the library methods. All except 2 pass right now.
The two that don't pass, fail because I have changed what their output
should be. In the docs, it is shown that the output of
`generate_minor_scale`, given 'C4', is:
['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4']
This is incorrect. The actual minor s... | Python | mit | jdan/Melopy,juliowaissman/Melopy | ---
+++
@@ -5,7 +5,51 @@
from nose.tools import *
-from melopy.melopy import *
+from melopy import *
+
+class LibraryFunctionsTests(TestCase):
+ def test_frequency_from_key(self):
+ key = 49
+ assert frequency_from_key(key) == 440
+
+ def test_frequency_from_note(self):
+ note = 'A4'
+... |
25af2e47b5b107ce4a0be4963b70bbf04b22c142 | tests/test_element.py | tests/test_element.py | import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.... | import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, ... | Add basic element pickle cycle test | Add basic element pickle cycle test
| Python | lgpl-2.1 | dwhswenson/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,gph82/mdtraj,dwhswenson/mdtraj,jchodera/mdtraj,rmcgibbo/mdtraj,leeping/mdtraj,gph82/mdtraj,leeping/mdtraj,jchodera/mdtraj,rmcgibbo/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,dwhswenson/mdtraj,mdtraj/mdtraj,gph82/mdtraj,leeping/mdtraj,leeping/mdtraj,mattwthompson/m... | ---
+++
@@ -1,5 +1,6 @@
import mdtraj as md
import pytest
+import pickle
from mdtraj import element
from mdtraj.testing import eq
@@ -29,3 +30,10 @@
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
+
+
+def test_element_pickle():
+ """Test that every Element object can pickle ... |
abb34fe5541448dbeb07e5e0e96e51a310de94ab | todolist.py | todolist.py | # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""Fill... | # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
import sys
tests = unittest.TestLoader().discover('tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.errors or... | Fix return code for failing tests | Fix return code for failing tests
Previous the even if tests failed the return code would not indicate
this to the caller of 'flask test' in this case.
| Python | mit | polyfunc/flask-todolist,rtzll/flask-todolist,rtzll/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist,polyfunc/flask-todolist,polyfunc/flask-todolist,0xfoo/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist | ---
+++
@@ -9,8 +9,11 @@
def test():
"""Runs the unit tests."""
import unittest
+ import sys
tests = unittest.TestLoader().discover('tests')
- unittest.TextTestRunner(verbosity=2).run(tests)
+ result = unittest.TextTestRunner(verbosity=2).run(tests)
+ if result.errors or result.failures:
+... |
949f390a083d8fd166a43a0cd2afa63feb7d86b1 | forum/models.py | forum/models.py | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length... | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length... | Order revisions by their creation date. | Order revisions by their creation date.
| Python | mit | xfix/NextBoard | ---
+++
@@ -46,3 +46,6 @@
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
+
+ class Meta:
+ ordering = ['date_created'] |
7a9fc08f3cf32f0bc8ccf49f0301437079c115c9 | logger/__init__.py | logger/__init__.py | #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from... | #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = ["logger... | Add the loggers submodule to __all__ | Add the loggers submodule to __all__
| Python | bsd-2-clause | Vgr255/logging | ---
+++
@@ -12,7 +12,7 @@
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
-__all__ = []
+__all__ = ["loggers"]
from . import loggers
|
3aee3f32dec40dc42ea857b64eb0f31dae0db07f | wluopensource/osl_comments/urls.py | wluopensource/osl_comments/urls.py | from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
| from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
(r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redire... | Add reference to comment edited in urlconf | Add reference to comment edited in urlconf
| Python | bsd-3-clause | jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website | ---
+++
@@ -3,6 +3,7 @@
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
+ (r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
|
b6233dff3cec42696f2ea0eea286ded48f02e79b | rllib/optimizers/rollout.py | rllib/optimizers/rollout.py | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_siz... | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_siz... | Fix bad sample count assert | [rllib] Fix bad sample count assert
| Python | apache-2.0 | richardliaw/ray,ray-project/ray,robertnishihara/ray,richardliaw/ray,pcmoritz/ray-1,robertnishihara/ray,ray-project/ray,pcmoritz/ray-1,robertnishihara/ray,pcmoritz/ray-1,pcmoritz/ray-1,robertnishihara/ray,pcmoritz/ray-1,richardliaw/ray,ray-project/ray,richardliaw/ray,pcmoritz/ray-1,richardliaw/ray,ray-project/ray,robert... | ---
+++
@@ -23,7 +23,6 @@
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
- assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
traje... |
acdb2445a5ead7d6ae116f839b1710c65ff08137 | nimp/utilities/paths.py | nimp/utilities/paths.py | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.spli... | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.spli... | Make safe_makedirs resilient to race conditions. | Make safe_makedirs resilient to race conditions.
| Python | mit | dontnod/nimp | ---
+++
@@ -33,6 +33,12 @@
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
- if not os.path.exists(path):
+
+ try:
os.makedirs(path)
+ except FileExistsError:
+ # Maybe someone else created the directory for us; if so, ignore error
+ ... |
184d0400f2304b0fe7adf07471526bc66b4eea64 | libs/ConfigHelpers.py | libs/ConfigHelpers.py |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.wri... |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.wri... | Add documenation link to config file | Add documenation link to config file
| Python | apache-2.0 | moloch--/RootTheBox,moloch--/RootTheBox,moloch--/RootTheBox,moloch--/RootTheBox | ---
+++
@@ -11,6 +11,7 @@
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
+ fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last up... |
6b183d7541dddc7531b3a37e8550952ec1b12dca | go/apps/urls.py | go/apps/urls.py | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.... | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.... | Fix typo in jsbox URLs. | Fix typo in jsbox URLs.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -18,5 +18,5 @@
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
- include('go.apps.jsbos.urls', namespace='jsbox')),
+ include('go.apps.jsbox.urls', namespace='jsbox')),
) |
6269ebe131405b444976d5d8108112ec5f8dccd5 | python/animationBase.py | python/animationBase.py | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9)
try:
print "Press Ctrl + C to stop executing"
while True:
n... | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
... | Set framerate to 60 fps | Set framerate to 60 fps
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix | ---
+++
@@ -11,16 +11,16 @@
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
-ball = Ball(5, 9)
+ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
- ball.updateValues(0.1)
+ ball.updateValues(1 / 60)
ball.drawOnMatr... |
a400c0bee935df7ee19766b04af0e57a655437fd | {{cookiecutter.app_name}}/setup.py | {{cookiecutter.app_name}}/setup.py | import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) fo... | import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) fo... | Use the proper entrypoint name. | Use the proper entrypoint name.
| Python | mit | coddingtonbear/cookiecutter-jirafs-plugin | ---
+++
@@ -43,7 +43,7 @@
include_package_data=True,
packages=find_packages(),
entry_points={
- '{{cookiecutter.app_name}}': [
+ 'jirafs_plugins': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
}, |
3ffd3eb8f32fbac7df0f6967b9d6f0437ff3a317 | movieman2/__init__.py | movieman2/__init__.py | import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
| import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| Load API_KEY from django settings.py file as an alternative | Load API_KEY from django settings.py file as an alternative
| Python | mit | simon-andrews/movieman2,simon-andrews/movieman2 | ---
+++
@@ -1,4 +1,5 @@
import os
import tmdbsimple
+from django.conf import settings
-tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
+tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY |
8cd29246d496cfbb45df15f0f4cfcca5ffc56630 | alg_bellman_ford_shortest_path.py | alg_bellman_ford_shortest_path.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c'... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def update_distance(v, v_neighbor, w_graph_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
distance_d[v_neighbor] = (
... | Implement update_distance(), init setup for Bellman-Ford alg | Implement update_distance(), init setup for Bellman-Ford alg
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -2,11 +2,25 @@
from __future__ import print_function
from __future__ import division
+import numpy as np
+
+
+def update_distance(v, v_neighbor, w_graph_d, previous_d):
+ if (distance_d[v_neighbor] >
+ distance_d[v] + w_graph_d[v][v_neighbor]):
+ distance_d[v_neighbor] = (
+ ... |
d40ecbfdee31f690463e20189b2e7552dd8406dd | ping_publisher/run.py | ping_publisher/run.py | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
... | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
... | Handle sleeping in main loop | Handle sleeping in main loop
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display | ---
+++
@@ -31,8 +31,8 @@
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
- time.sleep(1)
if __name__ == '__main__':
while True:
iterate_all_destinations()
+ time.sleep(1) |
5dc2ee040b5de973233ea04a310f7b6b3b0b9de9 | mangacork/__init__.py | mangacork/__init__.py | import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
import mangacork.views
| import os
import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views
| Add config for different env | Add config for different env
| Python | mit | ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork | ---
+++
@@ -1,3 +1,4 @@
+import os
import logging
from flask import Flask
@@ -5,5 +6,6 @@
log = logging.getLogger(__name__)
app = Flask(__name__)
+app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views |
97d4603032803aa52230726d35e1a84b3250245d | dummy.py | dummy.py | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test(... | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHE... | Add stress test for wrapping stdout | Add stress test for wrapping stdout
| Python | mit | thenoviceoof/booger,thenoviceoof/booger | ---
+++
@@ -8,6 +8,7 @@
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
+ print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY |
8d778a0eea84f06fdf832de0f458bceaabd1b644 | jacquard/cli.py | jacquard/cli.py | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='stor... | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='stor... | Fix help messages for commands | Fix help messages for commands
| Python | mit | prophile/jacquard,prophile/jacquard | ---
+++
@@ -28,7 +28,7 @@
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
- command_help = getattr(entry_point, 'help', entry_point.name)
+ command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.... |
06ef7333ea7c584166b1a7361e1d41143a0c85c8 | moveon/managers.py | moveon/managers.py | from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
... | from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class S... | Add the query to get the near stations | Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box. | Python | agpl-3.0 | SeGarVi/moveon-web,SeGarVi/moveon-web,SeGarVi/moveon-web | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
@@ -11,6 +12,11 @@
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
+
+ ... |
59066fc1def071aa51a87a6393c8bdf34f081188 | opps/core/__init__.py | opps/core/__init__.py | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
... | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
... | Add haystack connections simples engine om opps | Add haystack connections simples engine om opps
| Python | mit | YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,jeanmask/opps | ---
+++
@@ -28,6 +28,10 @@
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
+# Haystack
+getattr(settings, 'HAYSTACK_CONNECTIONS', {
+ 'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
+
# redactor
getattr... |
aaad7fe2f7d90a7f20ec794b374855f72c2dc155 | pgroonga/migrations/0001_enable.py | pgroonga/migrations/0001_enable.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres... | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres... | Remove long-running update query in initial migration. | pgroonga: Remove long-running update query in initial migration.
This query doesn't add any value, because it'll be overwritten in
migration 0002 anyway. And because it isn't batched, it can take
several minutes to run on servers with hundreds of thousands to
millions of messages of history. During that time, it's i... | Python | apache-2.0 | zulip/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip,andersk/zulip,showell/zulip,kou/zulip,rht/zulip,shubhamdhama/zulip,tommyip/zulip,timabbott/zulip,tommyip/zulip,dhcrzf/zulip,rht/zulip,punchagan/zulip,jackrzhang/zulip,timabbott/zulip,rishig/zulip,punchagan/zulip,eeshangarg/zulip,showell/zulip,hackerkid/zulip,tima... | ---
+++
@@ -20,8 +20,6 @@
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-UPDATE zerver_message SET search_pgroonga = subject || ' ' || rendered_content;
-
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 ... |
3ecc57fa3f62943061fbeb26c7ecce02c17daf4e | tests/test_config.py | tests/test_config.py | import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configura... | import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configura... | Add a test case for settings discovery | Add a test case for settings discovery
| Python | isc | hobarrera/todoman,Sakshisaraswat/todoman,pimutils/todoman,rimshaakhan/todoman,AnubhaAgrawal/todoman,asalminen/todoman | ---
+++
@@ -33,3 +33,26 @@
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
+
+
+def test_xdg_existant(runner, tmpdir, config):
+ conf_path = tmpdir.mkdir('todoman')
+ with conf_path.join('todoman.c... |
4c19fea0ff628666e24b2a4d133fa25903a155ff | tests/test_people.py | tests/test_people.py | from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person(... | from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_co... | Remove test for parent class | Remove test for parent class
| Python | mit | Alweezy/alvin-mutisya-dojo-project | ---
+++
@@ -1,17 +1,5 @@
from models.people import Person, Fellow, Staff
from unittest import TestCase
-
-
-class PersonTestCases(TestCase):
- """Tests the functionality of the person parent class
- """
- def setUp(self):
- """Passes an instance of class Person to all the methods in this class
- ... |
7ccacd1390e3f3ee86a1d21534db2c775003e432 | writeboards/models.py | writeboards/models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = mod... | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
... | Add writeboard specific fields to model | Add writeboard specific fields to model | Python | mit | rizumu/django-paste-organizer | ---
+++
@@ -5,13 +5,19 @@
from tagging.fields import TagField
class Writeboard(models.model):
+ """
+ Plaintext password field could simply be filled in with a reminder of.
+ """
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=T... |
df4d4f2972d8d1a91ce4353343c6279580985e3c | index.py | index.py | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
... | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
... | Change print statement about config | Change print statement about config
| Python | mit | pkakelas/eagle | ---
+++
@@ -7,7 +7,7 @@
config_file = open('config/config.json')
config = json.load(config_file)
else:
- print('Please copy the config.json file to config-local.json and fill in the file.')
+ print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(... |
ef8af3637666d854298681a4cdd2f529463c257c | lymph/web/handlers.py | lymph/web/handlers.py | import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
d... | import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@prope... | Add support for PATCH http method | Add support for PATCH http method
| Python | apache-2.0 | kstrempel/lymph,alazaro/lymph,lyudmildrx/lymph,lyudmildrx/lymph,vpikulik/lymph,mamachanko/lymph,Drahflow/lymph,mouadino/lymph,alazaro/lymph,itakouna/lymph,itakouna/lymph,torte/lymph,mamachanko/lymph,dushyant88/lymph,mamachanko/lymph,alazaro/lymph,mouadino/lymph,deliveryhero/lymph,itakouna/lymph,lyudmildrx/lymph,mouadin... | ---
+++
@@ -3,7 +3,7 @@
from werkzeug.exceptions import MethodNotAllowed
-http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
+http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object): |
e39b59ab345d9d72a31d739218d68072d3794cf6 | networkzero/config.py | networkzero/config.py | # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQU... | # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQU... | Speed up the broadcast frequency | Speed up the broadcast frequency
| Python | mit | tjguk/networkzero,tjguk/networkzero,tjguk/networkzero | ---
+++
@@ -11,14 +11,19 @@
#
# Beacons will broadcast adverts at this frequency
#
-BEACON_ADVERT_FREQUENCY_S = 5
+BEACON_ADVERT_FREQUENCY_S = 2
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring... |
d8d92bac1c75e68de3460f82cab6b9a124dd95b5 | Python/SimonSpeckCiphers/setup.py | Python/SimonSpeckCiphers/setup.py | from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('README.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonsp... | from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonsp... | Fix Readme Name In Setup | Fix Readme Name In Setup
| Python | mit | inmcm/Simon_Speck_Ciphers,inmcm/Simon_Speck_Ciphers | ---
+++
@@ -4,7 +4,7 @@
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
- long_description=open('README.md').read(),
+ long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scr... |
d0be9009da99ef8530a0d2927350663b3b89547a | pep8ify/pep8ify.py | pep8ify/pep8ify.py | #!/usr/bin/env python
import sys
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_... | #!/usr/bin/env python
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8... | Use `raise SystemExit` intead of `sys.exit`. | Clean-up: Use `raise SystemExit` intead of `sys.exit`.
| Python | apache-2.0 | spulec/pep8ify | ---
+++
@@ -1,6 +1,4 @@
#!/usr/bin/env python
-
-import sys
from lib2to3.main import main
@@ -16,7 +14,7 @@
def _main():
- sys.exit(main("pep8ify.fixes"))
+ raise SystemExit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main() |
a9b368a642b21335504210f2a60403659aae688f | apps/common/src/python/mediawords/workflow/client.py | apps/common/src/python/mediawords/workflow/client.py | from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient insta... | from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient insta... | Set the default namespace to lowercase "default" | Set the default namespace to lowercase "default"
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | ---
+++
@@ -3,7 +3,7 @@
from mediawords.util.network import wait_for_tcp_port_to_open
-def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
+def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
|
fc73b74f07254eace14fa761c85524512b3d1222 | opps/images/models.py | opps/images/models.py | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
fil... | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filenam... | Add tag on image lib | Add tag on image lib
| Python | mit | williamroot/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps | ---
+++
@@ -6,6 +6,8 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
+
+from taggit.managers import TaggableManager
from opps.core.models import Publishable
@@ -20,10 +22,12 @@
class Image(Publishable):
- title = models.CharFiel... |
60d79b03fbb6c1ad70b16d323fe7fa4a77cb0abe | notification/tests.py | notification/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from django.core.urlresolvers import reverse
from account.factories import AccountFactory, DEFAULT_PASSWORD
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
... | Add test to list of notification page. | Add test to list of notification page.
| Python | agpl-3.0 | Fleeg/fleeg-platform,Fleeg/fleeg-platform | ---
+++
@@ -1,3 +1,16 @@
from django.test import TestCase
+from django.core.urlresolvers import reverse
-# Create your tests here.
+from account.factories import AccountFactory, DEFAULT_PASSWORD
+
+
+class TestNotification(TestCase):
+ def setUp(self):
+ account = AccountFactory.create()
+ self.us... |
6f729e4c2d9497e0bf9844022667635836cb4a7b | appengine/services/admin_tasks.py | appengine/services/admin_tasks.py | """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with... | """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with... | Update TaskCalcImpact to also set deleted | Update TaskCalcImpact to also set deleted | Python | apache-2.0 | GoogleDeveloperExperts/experts-app-backend | ---
+++
@@ -21,6 +21,8 @@
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
+ if ar.deleted is None:
+ ar.deleted = False
ar.put()
ar_count += 1
|
84d9e707e872782c3cc9b81b098a9027239ed625 | alembic/versions/2507366cb6f2_.py | alembic/versions/2507366cb6f2_.py | """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from alembic import op
import sqlalchemy as sa
from models.person import Person
from utils.nlp.utils.transli... | """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from os.path import abspath, dirname, join
import sys
from alembic import op
import sqlalchemy as sa
parent... | Fix broken alembic revision generation | Fix broken alembic revision generation
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | ---
+++
@@ -10,9 +10,14 @@
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
+from os.path import abspath, dirname, join
+import sys
+
from alembic import op
import sqlalchemy as sa
+parentdir = dirname(dirname(dirname(abspath(__file__))))
+sys.path.insert(0,parentdir)
from models.person import Person... |
cf17b796cbd8b13c8138802b012f8293b269ab20 | apps/data/tests/test_factories.py | apps/data/tests/test_factories.py | from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater... | from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater... | Fix random strings minimal expected length | Fix random strings minimal expected length
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel | ---
+++
@@ -12,8 +12,8 @@
repository = factories.RepositoryFactory()
- self.assertGreater(len(repository.name), 1)
- self.assertGreater(len(repository.url), 1)
+ self.assertGreater(len(repository.name), 0)
+ self.assertGreater(len(repository.url), 0)
self.assertEqual(... |
dc4fb4de0f7a13c33914477f5014cc3490ffbcd1 | config.py | config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = False
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_... | Read URL and Token from environment | Read URL and Token from environment
| Python | mit | alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend | ---
+++
@@ -5,14 +5,14 @@
class Config(object):
DEBUG = True
- WTF_CSRF_ENABLED = False
+ WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIF... |
67db0605c054ee0ed6e2a55f818c0c9e4aec9e0d | client/sources/ok_test/__init__.py | client/sources/ok_test/__init__.py | from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
... | from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
... | Fix loading bug in ok_test | Fix loading bug in ok_test
| Python | apache-2.0 | Cal-CS-61A-Staff/ok-client,jathak/ok-client,jackzhao-mj/ok-client | ---
+++
@@ -29,8 +29,8 @@
test = importing.load_module(file).test
try:
- return models.OkTest(SUITES, args.verbose, args.interactive,
- args.timeout, **test)
+ return {file: models.OkTest(SUITES, args.verbose, args.interactive,
+ args.t... |
0725be7d78e8049dd3e3cc1819644443a1a1da3b | backend/uclapi/gunicorn_config.py | backend/uclapi/gunicorn_config.py | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking c... | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking c... | Update gunicorn graceful timeout value to match general timeout | Hotfix: Update gunicorn graceful timeout value to match general timeout
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | ---
+++
@@ -15,3 +15,4 @@
proc_name = "uclapi_gunicorn"
timeout = 600
+greaceful_timeout = 600 |
2d0c87826904889e79f21ae86c4fe7bc1fbc733c | funcs.py | funcs.py | from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()... | from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()... | Fix code generation for function pointer argument . | Fix code generation for function pointer argument .
| Python | mit | cournape/cython-codegen,cournape/cython-codegen | ---
+++
@@ -13,8 +13,8 @@
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
- return (generic_as_arg(tp.typ.returns) % '' ) + \
- '(*)' + '(%s)' % ", ".join(args)
+ return generic... |
e27fd32ecb89f5f2de1a784e902fe64d1b73d33c | {{cookiecutter.app_name}}/urls.py | {{cookiecutter.app_name}}/urls.py | from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name ... | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lo... | Use briefer url views import. | Use briefer url views import.
| Python | bsd-3-clause | wildfish/cookiecutter-django-crud,janusnic/cookiecutter-django-crud,wildfish/cookiecutter-django-crud,janusnic/cookiecutter-django-crud | ---
+++
@@ -1,13 +1,13 @@
from django.conf.urls import patterns, url
-from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
+from . import views
urlpatterns = patter... |
fb0354a22ac3be04729d929540504e374c192a6c | go/apps/bulk_message/definition.py | go/apps/bulk_message/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def perform_... | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_di... | Disable bulk send action when a bulk send conversation has no suitable channels attached. | Disable bulk send action when a bulk send conversation has no suitable channels attached.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -11,6 +11,14 @@
needs_group = True
needs_running = True
+ def check_disabled(self):
+ channels = self._conv.get_channels()
+ for channel in channels:
+ if channel.supports_generic_sends():
+ return None
+ return ("This action needs channels capa... |
0704dd1002e7ef546b718abec41a55c256a49cb2 | examples/test_fail.py | examples/test_fail.py | """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
self.assert_elem... | """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
print("\n(This t... | Update test that fails on purpose. | Update test that fails on purpose.
| Python | mit | mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot | ---
+++
@@ -8,4 +8,5 @@
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
- self.assert_element("div#ARMY_OF_ROBOTS", timeout=0.7)
+ print("\n(This test fails on purpose)")
+ self.assert_element("div#ARMY_OF_ROBOTS", timeout=1) |
39421ab0e74bbcab610aead0924a177a164404a6 | Cura/Qt/MainWindow.py | Cura/Qt/MainWindow.py | from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgro... | from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
... | Add some debug markers for more clearly finding our own rendering code | Add some debug markers for more clearly finding our own rendering code
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -3,6 +3,7 @@
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
+from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
@@ -31,8 +32,16 @@
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=se... |
4696c2458956fcb5c1cfef168461659262de04c1 | Demo/scripts/mpzpi.py | Demo/scripts/mpzpi.py | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import ... | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import ... | Update to use python ints and int/long unification. | Update to use python ints and int/long unification.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -8,27 +8,25 @@
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
-from mpz import mpz
def main():
- mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
- k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
- while 1:
- # Next approximation
- p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
- a,... |
e95ce817417d8d54c5cc561d7d7f70952550bd0e | robotpy_ext/misc/asyncio_policy.py | robotpy_ext/misc/asyncio_policy.py | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import BaseDefaultEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asynci... | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio e... | Update asyncio policy to match newer asyncio version | Update asyncio policy to match newer asyncio version
| Python | bsd-3-clause | Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities | ---
+++
@@ -2,7 +2,7 @@
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
-from asyncio.events import BaseDefaultEventLoopPolicy
+from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpi... |
1a581a262e4cc388d8b62acdc73d0a7feffdd4ad | Lib/feaTools/writers/baseWriter.py | Lib/feaTools/writers/baseWriter.py | class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, nam... | class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, nam... | Add a rawText method stub to the base writer | Add a rawText method stub to the base writer
I think this is the only missing method in the base writer.
| Python | mit | anthrotype/feaTools,jamesgk/feaTools,typesupply/feaTools,moyogo/feaTools | ---
+++
@@ -53,3 +53,6 @@
def subtableBreak(self):
pass
+
+ def rawText(self, text):
+ pass |
d372a08dda5c5dd956853d4fd1cefae423340a0f | Lib/test/test_json.py | Lib/test/test_json.py | """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__":
test_... | """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
test.test_support.run_doctest(json... | Add the examples in the json module docstring as a doctest | Add the examples in the json module docstring as a doctest
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -11,6 +11,7 @@
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
+ test.test_support.run_doctest(json)
if __name__ == "__main__": |
a444fe6125bac990267fb35f93024abd7386d44a | index.py | index.py | import bottle
import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('index', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottl... | import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="... | Fix the debug mode activation | Fix the debug mode activation
| Python | mit | djolaq/wine-bottle,djolaq/wine-bottle | ---
+++
@@ -1,4 +1,3 @@
-import bottle
import pymongo
import cellarDAO
@@ -8,7 +7,7 @@
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
- return template('index', dict(bottles = bottle_list))
+ return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/... |
aaaaa25b575677a3c0fb7f2dd515a21c5643e995 | falcom/tree/test/test_tree.py | falcom/tree/test/test_tree.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest... | Move tests into new Given class | Move tests into new Given class
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | ---
+++
@@ -8,15 +8,6 @@
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
-
- def test_empty_tree_has_null_value (self):
- t = Tree()
- assert_that(t.value, is_(none()))
-
- def test_cannot_modify_value_for_empty_tree (self):
- t = Tree()
- assert_th... |
50f95bd55a6f9ae6530b93b37655c265be79e1e0 | froide/campaign/validators.py | froide/campaign/validators.py | from django.forms import ValidationError
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='... | from django.forms import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
... | Add fallback error message on campaign validation | Add fallback error message on campaign validation | Python | mit | fin/froide,fin/froide,fin/froide,fin/froide | ---
+++
@@ -1,4 +1,6 @@
from django.forms import ValidationError
+from django.utils.translation import gettext_lazy as _
+
from .models import Campaign
@@ -11,4 +13,7 @@
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
- ... |
af4ad27ddf4d5da23590f6b2e297b9d834fa292e | icekit/project/settings/glamkit.py | icekit/project/settings/glamkit.py | from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += ('sponsors', )
| from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += (
'sponsors',
'icekit_events',
'icekit_events.event_types.simple',
'icekit_events.page_types.eventlistingfordate',
)
| Add ICEKit Events to list of GLAMKit installed apps | Add ICEKit Events to list of GLAMKit installed apps
Add ICEKit events, SimpleEvent event type, and listing page for date
apps to those installed by default for GLAMKit.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -2,4 +2,10 @@
# DJANGO ######################################################################
-INSTALLED_APPS += ('sponsors', )
+INSTALLED_APPS += (
+ 'sponsors',
+
+ 'icekit_events',
+ 'icekit_events.event_types.simple',
+ 'icekit_events.page_types.eventlistingfordate',
+) |
f69a2dc9530fef44e5b67d64496bcec9eceaf0e4 | config.py | config.py | import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure... | import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure... | Make the secure session cookie setting case-insensitive | Make the secure session cookie setting case-insensitive
| Python | mit | LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend | ---
+++
@@ -6,7 +6,7 @@
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
-session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
+session_cookie_secure = os.environ['... |
ea504e682263bb6c7681bf690bed8a34e0ee1612 | chandra_aca/tests/test_dark_scale.py | chandra_aca/tests/test_dark_scale.py | import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| Update path to dark_temp_scale in test | Update path to dark_temp_scale in test
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | ---
+++
@@ -1,9 +1,9 @@
import numpy as np
-from .. import dark_scale
+from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
- scale = dark_scale.dark_temp_scale(-10., -14)
+ scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
- scale = dark_scale.dark_temp_scale(-10.... |
d19ad115124179d75cf00806f2861f17f01f5ff9 | drogher/package/base.py | drogher/package/base.py | import re
class Package(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if... | import re
class Package(object):
barcode = ''
barcode_pattern = ''
shipper = ''
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.... | Test for pattern and barcode before matching barcode | Test for pattern and barcode before matching barcode
| Python | bsd-3-clause | jbittel/drogher | ---
+++
@@ -2,9 +2,9 @@
class Package(object):
- barcode = None
- barcode_pattern = None
- shipper = None
+ barcode = ''
+ barcode_pattern = ''
+ shipper = ''
def __init__(self, barcode):
self.barcode = barcode
@@ -20,7 +20,9 @@
@property
def matches_barcode(self):
-... |
b9df853ec27106a31d67600483bec660d274d674 | saleor/menu/models.py | saleor/menu/models.py | from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Pe... | from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu... | Save sorting order on MenuItem | Save sorting order on MenuItem
| Python | bsd-3-clause | maferelo/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
@@ -37,3 +38,16 @@
def __str__(self):
return self.name
+
+ def get_ordering_queryset(... |
350380095b84bce5bd06e1ac046d9036fd7ab0cd | bluebottle/partners/serializers.py | bluebottle/partners/serializers.py | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):... | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = seria... | Use a simpler serializer that does not require people_requested/people_registered annotations / fields | Use a simpler serializer that does not require people_requested/people_registered annotations / fields
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle | ---
+++
@@ -1,6 +1,6 @@
from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
-from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
+from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
fro... |
ded371a8cb63077e57cfcde401df56bddf078f5a | project/user/forms.py | project/user/forms.py | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[... | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[... | Create basic password reset form | Create basic password reset form
| Python | mit | dylanshine/streamschool,dylanshine/streamschool | ---
+++
@@ -37,6 +37,11 @@
return True
+class ResetPasswordForm(Form):
+ email = TextField(
+ 'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
+
+
class ChangePasswordForm(Form):
password = PasswordField(
'password', |
59069062b1cf8af3790fea8c9a44972b1b1218e7 | services/models/unit_connection.py | services/models/unit_connection.py | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_in... | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.... | Add missing connection section type value HIGHLIGHT | Add missing connection section type value HIGHLIGHT
| Python | agpl-3.0 | City-of-Helsinki/smbackend,City-of-Helsinki/smbackend | ---
+++
@@ -9,6 +9,7 @@
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
+ (8, 'HIGHLIGHT'),
)
|
0a5d7873ee536b41907424df2477db3a0b2a0287 | scripts/remove_after_use/node_preprint_es.py | scripts/remove_after_use/node_preprint_es.py | from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Tempora... | from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Tempora... | Fix ES index script with updated param | Fix ES index script with updated param
| Python | apache-2.0 | mattclark/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,felliott/osf.io,aaxelb/osf.io,cslzchen/osf.io,baylee-d/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,felliott/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,mattclark/osf.io,adlius/osf.io,brianjgeiger/osf.io,CenterForO... | ---
+++
@@ -22,7 +22,7 @@
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
- search.search.update_node(p.node, bulk=Fa... |
f4d0b9162241df8c87fb5f918f32f3310361b834 | tests/test_member_access.py | tests/test_member_access.py | from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vecto... | from hypothesis import given
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
... | Make member_access into an Hypothesis test | tests/member_access: Make member_access into an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -1,18 +1,14 @@
from hypothesis import given
-import pytest # type: ignore
from ppb_vector import Vector
-from utils import vectors
+from utils import floats, vectors
-@pytest.fixture()
-def vector():
- return Vector(10, 20)
-
-
-def test_class_member_access(vector):
- assert vector.x == 10
-... |
d93af9d0dcf09cd49071fc7f46d40e8fda30f96e | python/setup_fsurfer_backend.py | python/setup_fsurfer_backend.py | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suc... | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suc... | Include new script in packaging | Include new script in packaging
| Python | apache-2.0 | OSGConnect/freesurfer_workflow,OSGConnect/freesurfer_workflow | ---
+++
@@ -17,6 +17,7 @@
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
+ 'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
|
12cfaa0bf758a78d854e917f357ac2913d4e73c6 | tools/win32build/doall.py | tools/win32build/doall.py | import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd =... | import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller... | Handle python version in prepare_bootstrap script. | Handle python version in prepare_bootstrap script.
| Python | bsd-3-clause | BabeNovelty/numpy,matthew-brett/numpy,empeeu/numpy,hainm/numpy,GrimDerp/numpy,tdsmith/numpy,mhvk/numpy,rmcgibbo/numpy,mindw/numpy,ogrisel/numpy,stefanv/numpy,trankmichael/numpy,brandon-rhodes/numpy,GaZ3ll3/numpy,GrimDerp/numpy,ajdawson/numpy,jschueller/numpy,tdsmith/numpy,endolith/numpy,sonnyhu/numpy,rgommers/numpy,cow... | ---
+++
@@ -4,7 +4,7 @@
PYVER = "2.5"
# Bootstrap
-subprocess.check_call(['python', 'prepare_bootstrap.py'])
+subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER) |
9a154b8893a3306e5350a9118e9cfb582d295322 | traccar_graphql/schema.py | traccar_graphql/schema.py | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.env... | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.env... | Handle sign in failure from traccar | Handle sign in failure from traccar
| Python | mit | sunhoww/traccar_graphql | ---
+++
@@ -10,16 +10,19 @@
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
- me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerT... |
66035a6e3e7729c53278193d4307751b36ace6eb | fullcalendar/admin.py | fullcalendar/admin.py | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineA... | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineA... | Change to stacked inline for occurrences, also display location. | Change to stacked inline for occurrences, also display location.
| Python | mit | jonge-democraten/mezzanine-fullcalendar | ---
+++
@@ -1,17 +1,17 @@
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
-from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
+from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.