commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
c9f7c36e8f6bdf32a39f1ac8cd9ebbcf80df4a20 | saleor/dashboard/category/forms.py | saleor/dashboard/category/forms.py | from django import forms
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
parent = TreeNodeChoiceField(queryset=Categ... | from django import forms
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
parent = TreeNodeChoiceField(queryset=Categ... | Fix getting category's descendants before save | Fix getting category's descendants before save
| Python | bsd-3-clause | taedori81/saleor,laosunhust/saleor,taedori81/saleor,josesanch/saleor,laosunhust/saleor,maferelo/saleor,rodrigozn/CW-Shop,josesanch/saleor,paweltin/saleor,tfroehlich82/saleor,car3oon/saleor,arth-co/saleor,rodrigozn/CW-Shop,avorio/saleor,paweltin/saleor,maferelo/saleor,KenMutemi/saleor,rchav/vinerack,itbabu/saleor,avorio... |
663f839ef539759143369f84289b6e27f21bdcce | setup.py | setup.py | #/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $
from distutils.core import setup
description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""
def getVersion():
import os
packageSeedFile = os.path.join("src", "lib", "_version.py")
ns = {"__... | #/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $
from distutils.core import setup
description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""
def getVersion():
import os
packageSeedFile = os.path.join("lib", "_version.py")
ns = {"__name__"... | Use lib/ instead of src/lib. | Use lib/ instead of src/lib.
| Python | bsd-3-clause | olix0r/tx-jersey |
08c47c647fffa0953c01214c81d8e5f41fe45ddc | setup.py | setup.py | from distutils.core import setup
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='pandocfilters',
version='1.4.2',
description='Utilities for writing pandoc filters in python',
long_description=read('README.rst'),
author='John MacFa... | from distutils.core import setup
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='pandocfilters',
version='1.4.2',
description='Utilities for writing pandoc filters in python',
long_description=read('README.rst'),
author='John MacFa... | Add python_requires to help pip, update classifiers | Add python_requires to help pip, update classifiers | Python | bsd-3-clause | AugustH/pandocfilters,jgm/pandocfilters |
1cbd0ce39e2e4d2b704787989bf9deb99c68aaa9 | setup.py | setup.py | from distutils.core import setup
import py2exe
setup(
console=[{'script':'check_forbidden.py','version':'1.1.0',}],
)
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
'''
| from distutils.core import setup
import py2exe
setup(
console=[{'script': 'check_forbidden.py', 'version': '1.1.3', }],
options={'py2exe': {'bundle_files': 2}}
)
'''
cd dropbox/codes/check_forbidden
py -3.4 setup.py py2exe
'''
| Reduce the number of files in dist folder | Reduce the number of files in dist folder
| Python | mit | ShunSakurai/check_forbidden,ShunSakurai/check_forbidden |
6a0877dc49b6fbcd6ca3475e2329aabfdb066c09 | serrano/resources/field/stats.py | serrano/resources/field/stats.py | from django.core.urlresolvers import reverse
from avocado.events import usage
from .base import FieldBase
class FieldStats(FieldBase):
"Field Stats Resource"
def get(self, request, pk):
uri = request.build_absolute_uri
instance = request.instance
if instance.simple_type == 'number':
... | from django.core.urlresolvers import reverse
from avocado.events import usage
from .base import FieldBase
class FieldStats(FieldBase):
"Field Stats Resource"
def get(self, request, pk):
uri = request.build_absolute_uri
instance = request.instance
if instance.simple_type == 'number':
... | Return empty response when StopIteration is raised on exhausted iterator | Return empty response when StopIteration is raised on exhausted iterator
| Python | bsd-2-clause | chop-dbhi/serrano,rv816/serrano_night,rv816/serrano_night,chop-dbhi/serrano |
6007130b702c7ac7bb0d431cc48a7bf56875fb79 | setup.py | setup.py | #!/usr/bin/env python
# Copyright (c) The ppd team
# See LICENSE for details.
from distutils.core import setup
setup(
name='ppd',
version='0.1.0',
description='Organizes pentesting information',
author='Matt Haggard',
author_email='haggardii@gmail.com',
url='https://github.com/iffy/ppd',
... | #!/usr/bin/env python
# Copyright (c) The ppd team
# See LICENSE for details.
from distutils.core import setup
setup(
name='ppd',
version='0.1.0',
description='Organizes pentesting information',
author='Matt Haggard',
author_email='haggardii@gmail.com',
url='https://github.com/iffy/ppd',
... | Add ordereddict as required package (for 2.6) | Add ordereddict as required package (for 2.6)
| Python | apache-2.0 | iffy/ppd |
60574e2f88e32565eb2a5de1258651527515ff3b | setup.py | setup.py | from distutils.core import setup
setup(
name='django-browserid',
version='0.5.1',
packages=['django_browserid'],
author='Paul Osman, Michael Kelly',
author_email='mkelly@mozilla.com',
url='https://github.com/mozilla/django-browserid',
install_requires='requests>=0.9.1',
package_data={'d... | from distutils.core import setup
setup(
name='django-browserid',
version='0.5.1',
packages=['django_browserid', 'django_browserid.tests'],
author='Paul Osman, Michael Kelly',
author_email='mkelly@mozilla.com',
url='https://github.com/mozilla/django-browserid',
install_requires='requests>=0.... | Include `tests` subpackage in installation | Include `tests` subpackage in installation
The tests subpackage has helpers that are useful for running tests in
django projects, such as `mock_browserid`. Include this subpackage in
the distutils script so that it won't be ignored by pip, easy_install,
etc.
| Python | mpl-2.0 | ericholscher/django-browserid,mozilla/django-browserid,Osmose/django-browserid,mozilla/django-browserid,Osmose/django-browserid,Osmose/django-browserid,mozilla/django-browserid,ericholscher/django-browserid,ericholscher/django-browserid |
7a803d1a5e2b388283afdc1ba9c3378753ce62ee | setup.py | setup.py | # encoding: utf-8
from distutils.core import setup
setup(
name='json-store',
version='1.1',
packages=['json_store',],
scripts=['bin/shelve2json.py',],
description="A shelve-like store using JSON serialization.",
long_description="JSON store is a simple replacement for shelve. It writes"
... | # encoding: utf-8
from distutils.core import setup
setup(
name='json-store',
version='1.1',
packages=['json_store'],
scripts=['bin/shelve2json.py'],
description="A shelve-like store using JSON serialization.",
long_description="JSON store is a simple replacement for shelve. It writes"
... | Add 2.7 to PyPI trove classifiers | Add 2.7 to PyPI trove classifiers
| Python | mit | brainsik/json-store,brainsik/json-store,brainsik/json-store-ci-demo,brainsik/json-store-ci-demo,brainsik/json-store-ci-demo |
5b5746b0b6641b29de3ae866310fb0494e051073 | setup.py | setup.py | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
packages = []
package_dir = "dbbackup"
for dirpath, dirnames, filenames in os.walk(package_dir):
# ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
... | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
packages = []
package_dir = "dbbackup"
for dirpath, dirnames, filenames in os.walk(package_dir):
# ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
... | Add pypandoc to create RST for pypi | Add pypandoc to create RST for pypi
| Python | bsd-3-clause | bahoo/django-dbbackup,bahoo/django-dbbackup |
db1f0a09f5620bd2da188b261391e02d2d88b500 | snakeeyes/blueprints/page/views.py | snakeeyes/blueprints/page/views.py | from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
@page.route('/')
def home():
return render_template('page/home.html')
@page.route('/terms')
def terms():
return render_template('page/terms.html')
@page.ro... | from flask import Blueprint, render_template
from snakeeyes.extensions import redis
page = Blueprint('page', __name__, template_folder='templates')
@page.get('/')
def home():
return render_template('page/home.html')
@page.get('/terms')
def terms():
return render_template('page/terms.html')
@page.get('/... | Use new Flask 2.0 .get() decorator function | Use new Flask 2.0 .get() decorator function
| Python | mit | nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask |
affca524ec3163716a78a365ac5781ec3130ad50 | smithers/smithers/conf/server.py | smithers/smithers/conf/server.py | from os import getenv
GEOIP_DB_FILE = '/usr/local/share/GeoIP/GeoIP2-City.mmdb'
STATSD_HOST = 'graphite1.private.phx1.mozilla.com'
STATSD_PORT = 8125
STATSD_PREFIX = 'glow-workers-{}'.format(getenv('DJANGO_SERVER_ENV'))
| from os import getenv
GEOIP_DB_FILE = '/usr/local/share/GeoIP/GeoIP2-City.mmdb'
STATSD_HOST = 'graphite1.private.phx1.mozilla.com'
STATSD_PORT = 8125
STATSD_PREFIX = 'glow-workers-{}'.format(getenv('DJANGO_SERVER_ENV'))
COUNTRY_MIN_SHARE = 1 # basically off
| Disable country minimum share limit. | Disable country minimum share limit.
| Python | mpl-2.0 | almossawi/mrburns,almossawi/mrburns,almossawi/mrburns,almossawi/mrburns,mozilla/mrburns,mozilla/mrburns,mozilla/mrburns |
1ee168e4cebd20d1a4f18bb477389da519b2f3be | tapiriik/messagequeue/__init__.py | tapiriik/messagequeue/__init__.py | from kombu import Connection
from tapiriik.settings import RABBITMQ_BROKER_URL
mq = Connection(RABBITMQ_BROKER_URL)
mq.connect() | from kombu import Connection
from tapiriik.settings import RABBITMQ_BROKER_URL
mq = Connection(RABBITMQ_BROKER_URL, transport_options={'confirm_publish': True})
mq.connect()
| Enable MQ publish confirmations for scheduler | Enable MQ publish confirmations for scheduler
| Python | apache-2.0 | campbellr/tapiriik,cpfair/tapiriik,cmgrote/tapiriik,abs0/tapiriik,abhijit86k/tapiriik,campbellr/tapiriik,cmgrote/tapiriik,cpfair/tapiriik,cpfair/tapiriik,brunoflores/tapiriik,brunoflores/tapiriik,cgourlay/tapiriik,brunoflores/tapiriik,cgourlay/tapiriik,mduggan/tapiriik,cpfair/tapiriik,cmgrote/tapiriik,abhijit86k/tapiri... |
b33c1b70bcb7a5303c1731cb6699466610ee54af | pyedgar/__init__.py | pyedgar/__init__.py | # -*- coding: utf-8 -*-
"""
pyEDGAR SEC data library.
=====================================
pyEDGAR is a general purpose library for all sorts of interactions with the SEC
data sources, primarily the EDGAR distribution system.
Files from the SEC reside at https://www.sec.gov/Archives/edgar/data/CIK/ACCESSION.txt
:c... | # -*- coding: utf-8 -*-
"""
pyEDGAR SEC data library.
=====================================
pyEDGAR is a general purpose library for all sorts of interactions with the SEC
data sources, primarily the EDGAR distribution system.
Files from the SEC reside at https://www.sec.gov/Archives/edgar/data/CIK/ACCESSION.txt
:c... | Remove top level imports to avoid cyclical import | Remove top level imports to avoid cyclical import
| Python | mit | gaulinmp/pyedgar |
af6c260bb27f6b1c5f56ffbd0616b30b9afdbd7b | tests/user_utils_test.py | tests/user_utils_test.py | """Tests for user utility functions."""
from drudge import Vec, sum_, prod_
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compare... | """Tests for user utility functions."""
import time
import types
from unittest.mock import MagicMock
from drudge import Vec, sum_, prod_, TimeStamper
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3... | Add tests for the time stamping facility | Add tests for the time stamping facility
| Python | mit | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge |
ab19ad1810855db9beea913e93b483fcf3e73a07 | src/sentry/api/authentication.py | src/sentry/api/authentication.py | from django.contrib.auth.models import AnonymousUser
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed
from sentry.models import ProjectKey
class KeyAuthentication(BasicAuthentication):
def authenticate_credentials(self, userid, password):
... | from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed
from sentry.models import ProjectKey
class KeyAuthentication(BasicAuthentication):
d... | Use a constant time comparison in the API auth | Use a constant time comparison in the API auth | Python | bsd-3-clause | JamesMura/sentry,Kryz/sentry,jean/sentry,Natim/sentry,mvaled/sentry,alexm92/sentry,Kryz/sentry,hongliang5623/sentry,JamesMura/sentry,wong2/sentry,drcapulet/sentry,felixbuenemann/sentry,korealerts1/sentry,ifduyue/sentry,fotinakis/sentry,fotinakis/sentry,llonchj/sentry,nicholasserra/sentry,looker/sentry,pauloschilling/se... |
51a4618fdf78c174af428b11f5f58b5aae88b583 | examples/MNIST/mnist.py | examples/MNIST/mnist.py | import os
import gzip
import pickle
import urllib
import sys
'''Adapted from theano tutorial'''
def load_mnist(data_file = './mnist.pkl.gz'):
if not os.path.exists(data_file):
origin = ('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz')
print('Downloading data from %s' % origin)
... | import os
import gzip
import pickle
import sys
# Python 2/3 compatibility.
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
'''Adapted from theano tutorial'''
def load_mnist(data_file = './mnist.pkl.gz'):
if not os.path.exists(data_file):
origin = ... | Make MNIST example py3 compatible. | Make MNIST example py3 compatible.
| Python | mit | Pandoro/DeepFried2,elPistolero/DeepFried2,yobibyte/DeepFried2,lucasb-eyer/DeepFried2,VisualComputingInstitute/Beacon8 |
82cd8b267f2a66d5e9871c4eb3ec4ce8cc2106d6 | utils.py | utils.py | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
app... | Tweak the way that on_production_server is determined | Tweak the way that on_production_server is determined
| Python | bsd-3-clause | potatolondon/djangoappengine-1-4,potatolondon/djangoappengine-1-4 |
5fd157d37f532e4aadd51475b9b3654bb42febd9 | rbtools/clients/tests/test_cvs.py | rbtools/clients/tests/test_cvs.py | """Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
... | """Unit tests for CVSClient."""
from __future__ import unicode_literals
import kgb
from rbtools.clients import RepositoryInfo
from rbtools.clients.cvs import CVSClient
from rbtools.clients.tests import SCMClientTestCase
class CVSClientTests(kgb.SpyAgency, SCMClientTestCase):
"""Unit tests for CVSClient."""
... | Update the CVS unit tests to use build_client(). | Update the CVS unit tests to use build_client().
This updates the CVS unit tests to build a `CVSClient` in each test
where it's needed, rather than in `setUp()`. This is in prepration for
new tests that will need to handle client construction differently.
Testing Done:
CVS unit tests pass.
Reviewed at https://review... | Python | mit | reviewboard/rbtools,reviewboard/rbtools,reviewboard/rbtools |
e004e5610526d2762027c586cfb8a0a81a1ec00d | examples/task_call.py | examples/task_call.py | import sys
sys.path.append('../py')
from iroha import *
from iroha.iroha import *
d = IDesign()
mod = IModule(d, "mod")
callee_tab = ITable(mod)
task = design_tool.CreateSiblingTask(callee_tab)
entry_insn = IInsn(task)
st1 = IState(callee_tab)
st1.insns.append(entry_insn)
callee_tab.states.append(st1)
callee_tab.ini... | import sys
sys.path.append('../py')
from iroha import *
from iroha.iroha import *
d = IDesign()
mod = IModule(d, "mod")
callee_tab = ITable(mod)
task = design_tool.CreateSiblingTask(callee_tab)
entry_insn = IInsn(task)
st1 = IState(callee_tab)
st1.insns.append(entry_insn)
callee_tab.states.append(st1)
callee_tab.ini... | Add a state not to call the task continuously. | Add a state not to call the task continuously.
| Python | bsd-3-clause | nlsynth/iroha,nlsynth/iroha |
a2333c2009f935731665de51ff1a28121c6a234d | migrations/versions/0313_email_access_validated_at.py | migrations/versions/0313_email_access_validated_at.py | """
Revision ID: 0313_email_access_validated_at
Revises: 0312_populate_returned_letters
Create Date: 2020-01-28 18:03:22.237386
"""
from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto gen... | """
Revision ID: 0313_email_access_validated_at
Revises: 0312_populate_returned_letters
Create Date: 2020-01-28 18:03:22.237386
"""
from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto gen... | Fix typo where wrong column name was checked for being null | Fix typo where wrong column name was checked for being null
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
aa014a472a39c12cf3141dd337ecc2ed1ea2cd55 | django_summernote/test_settings.py | django_summernote/test_settings.py | import django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_summernote.db',
}
}
__MIDDLEWARE__ = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
... | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_summernote.db',
}
}
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib... | Drop old django version support (1.10) | Drop old django version support (1.10)
| Python | mit | summernote/django-summernote,summernote/django-summernote,summernote/django-summernote |
ce8bb976d113da8fbc423437d065d34199dbe57b | packages/fsharp-3.0.py | packages/fsharp-3.0.py |
class FsharpPackage(GitHubTarballPackage):
def __init__(self):
GitHubTarballPackage.__init__(self,
'fsharp', 'fsharp',
'3.0.13',
'3.0.13',
configure = '')
def build(self):
self.sh ('autoreconf')
self.sh ('./configure --prefix="%{prefix}"')
self.sh ('make')
FsharpPackage()
|
class FsharpPackage(GitHubTarballPackage):
def __init__(self):
GitHubTarballPackage.__init__(self,
'fsharp', 'fsharp',
'3.0.13',
'893b8a3a9326b0a2008b5f7322dd8002b8065a69',
configure = '')
def build(self):
self.sh ('autoreconf')
self.sh ('./configure --prefix="%{prefix}"')
self.sh ('make')
Fsha... | Use the full commit hash so that we can download from github.com. | Use the full commit hash so that we can download from github.com.
| Python | mit | mono/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild |
d989f5513df5a8a28c6bb1c251554afd8fe5f228 | camera.py | camera.py | #!/usr/bin/env python
"""Test Raspberry Pi camera!"""
# http://picamera.readthedocs.org/en/release-1.10/index.html
import picamera
import sys
from fractions import Fraction
from time import sleep
filename = sys.argv[1]
camera = picamera.PiCamera()
camera.vflip = True
camera.hflip = True
camera.framerate = Fraction... | #!/usr/bin/env python
"""Test Raspberry Pi camera!"""
# http://picamera.readthedocs.org/en/release-1.10/index.html
import picamera
import sys
from fractions import Fraction
from time import sleep
filename = sys.argv[1]
camera = picamera.PiCamera()
camera.vflip = True
camera.hflip = True
## Low light
#camera.framer... | Change settings for normal light. | Change settings for normal light.
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie |
9328069cf7c871d701d0299e8665ef60572e8061 | fandjango/decorators.py | fandjango/decorators.py | from functools import wraps
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from utils import redirect_to_facebook_authorization
def facebook_authorization_required(redirect_uri=False):
"""
Redirect Facebook canvas views to authorization if r... | from functools import wraps
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core.handlers.wsgi import WSGIRequest
from django.conf import settings
from utils import redirect_to_facebook_authorization
def facebook_authorization_required(redirect_uri=False):
"""
Re... | Fix a bug that caused the "facebook_authorization_required" decorator to be incompatible with Django libraries that modify the order of arguments given to views. | Fix a bug that caused the "facebook_authorization_required" decorator to be incompatible
with Django libraries that modify the order of arguments given to views.
| Python | mit | jgorset/fandjango,jgorset/fandjango |
94caedce74bad7a1e4a2002dd725a220a8fc8a8e | django_prometheus/migrations.py | django_prometheus/migrations.py | from django.db import connections
from django.db.migrations.executor import MigrationExecutor
from prometheus_client import Gauge
unapplied_migrations = Gauge(
'django_migrations_unapplied_total',
'Count of unapplied migrations by database connection',
['connection'])
applied_migrations = Gauge(
'djan... | from django.db import connections
from django.db.migrations.executor import MigrationExecutor
from prometheus_client import Gauge
unapplied_migrations = Gauge(
'django_migrations_unapplied_total',
'Count of unapplied migrations by database connection',
['connection'])
applied_migrations = Gauge(
'djan... | Fix pep8 violation in 29e3a0c. | Fix pep8 violation in 29e3a0c.
| Python | apache-2.0 | korfuri/django-prometheus,obytes/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus |
f96b4f3516905b13267d6c918f22e76556b4b56a | salt/modules/cmd.py | salt/modules/cmd.py | '''
Module for shelling out commands, inclusion of this module should be
configurable for security reasons
'''
| '''
Module for shelling out commands, inclusion of this module should be
configurable for security reasons
'''
def echo(text):
'''
Return a string - used for testing the connection
'''
return text
| Add a simple test function | Add a simple test function
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
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 |
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... |
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 |
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 |
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 |
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 |
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,... |
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 |
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 |
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 |
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... |
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 |
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 |
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... |
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 |
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... |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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... |
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 |
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 |
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... |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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... |
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 |
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 |
f1cc57acd774eace69da7ec0ae9a516207d8ff5c | pyrfc3339/__init__.py | pyrfc3339/__init__.py | """
pyRFC3339 parses and generates :RFC:`3339`-compliant timestamps using Python :class:`datetime.datetime` objects.
>>> from pyrfc3339 import generate, parse
>>> from datetime import datetime
>>> import pytz
>>> generate(datetime.utcnow().replace(tzinfo=pytz.utc)) #doctest:+ELLIPSIS
'...T...Z'
>>> parse('2009-01-01T1... | """
pyRFC3339 parses and generates :RFC:`3339`-compliant timestamps using Python :class:`datetime.datetime` objects.
>>> from pyrfc3339 import generate, parse
>>> from datetime import datetime
>>> import pytz
>>> generate(datetime.utcnow().replace(tzinfo=pytz.utc)) #doctest:+ELLIPSIS
'...T...Z'
>>> parse('2009-01-01T1... | Fix imports for Python 3 | Fix imports for Python 3
| Python | mit | kurtraschke/pyRFC3339 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.