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 |
|---|---|---|---|---|---|---|---|---|---|
863828c37eca9046a7dd169114e2a6c3e02e28aa | proxy-firewall.py | proxy-firewall.py | #!/usr/bin/python
"""
Set the firewall to allow access to configured HTTP(S) proxies.
This is only necessary until rBuilder handles the EC2 image posting
and registration process.
"""
import os, sys, urllib, urlparse
from conary.conarycfg import ConaryConfiguration
def main(args):
cfg = ConaryConfiguration(False... | #!/usr/bin/python
"""
Set the firewall to allow access to configured HTTP(S) proxies.
This is only necessary until rBuilder handles the EC2 image posting
and registration process.
"""
import os, sys, urllib, urlparse
from conary.conarycfg import ConaryConfiguration
def main(args):
cfg = ConaryConfiguration(False... | Fix proxy URIs with credentials in them | Fix proxy URIs with credentials in them
| Python | apache-2.0 | sassoftware/jobmaster,sassoftware/jobmaster,sassoftware/jobmaster |
607728b17c0a79725d997b458a53d1b3d1394a59 | pymue/__init__.py | pymue/__init__.py | from _pymue import peng, Team, DistanceMatrix, SeenTable, GuestTupleGenerator
| from _pymue import peng, Team, DistanceMatrix, SeenTable, GuestTupleGenerator, GuestPair
def pair_pprint(pair):
return "(%s, %s)" % (pair.first, pair.second)
GuestPair.__repr__ = pair_pprint
| Add string representation to GuestPair | Add string representation to GuestPair
Signed-off-by: Jan Losinski <577c4104c61edf9f052c616c0c23e67bef4a9955@wh2.tu-dresden.de>
| Python | bsd-3-clause | janLo/meet-and-eat-distribution-tool,janLo/meet-and-eat-distribution-tool,eXma/meet-and-eat-distribution-tool,eXma/meet-and-eat-distribution-tool,janLo/meet-and-eat-distribution-tool,eXma/meet-and-eat-distribution-tool |
641e31fcb05016e5fb27e8f115a763b72c7638f3 | python/tag_img.py | python/tag_img.py | import requests
import json
# Tag an image based on detected visual content which mean running a CNN on top of it.
# https://pixlab.io/#/cmd?id=tagimg for more info.
# Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info.
img = 'https://s-... | import requests
import json
# Tag an image based on detected visual content which mean running a CNN on top of it.
# https://pixlab.io/#/cmd?id=tagimg for more info.
# Target Image: Change to any link or switch to POST if you want to upload your image directly, refer to the sample set for more info.
img = 'https://s-... | Tag an image based on detected visual content | Tag an image based on detected visual content | Python | bsd-2-clause | symisc/pixlab,symisc/pixlab,symisc/pixlab |
bf6f77d90c3749983eb0b5358fb2f9fedb7d53da | app/main.py | app/main.py | import spark
import motion
from bot import process_command
from config import config
from flask import Flask
from flask import request
from flask import jsonify
from threading import Thread
import time
import sys
app = Flask(__name__)
def on_motion_detected():
print("motion detected!")
def run_motion_detection(... | import spark
import motion
from bot import process_command
from config import config
from flask import Flask
from flask import request
from flask import jsonify
from threading import Thread
import time
import sys
app = Flask(__name__)
def on_motion_detected():
print("motion detected!")
def run_motion_detection(... | Use Python 3.6 compatible API for threading | Use Python 3.6 compatible API for threading
| Python | mit | alwye/spark-pi,alwye/spark-pi |
dc65920f52ca584608633cc511590b41b590f79e | billjobs/permissions.py | billjobs/permissions.py | from rest_framework import permissions
class CustomUserAPIPermission(permissions.BasePermission):
"""
Set custom permission for UserAPI
* GET : only accessible by admin
* POST : is public, everyone can create a user
"""
def has_permission(self, request, view):
"""
Define pe... | from rest_framework import permissions
from rest_framework.compat import is_authenticated
class CustomUserAPIPermission(permissions.BasePermission):
"""
Set custom permission for UserAPI
* GET : only accessible by admin
* POST : is public, everyone can create a user
"""
def has_permission(... | Create permission for admin and user can access GET, PUT, DELETE method, user can access is instance only | Create permission for admin and user can access GET, PUT, DELETE method, user can access is instance only
| Python | mit | ioO/billjobs |
96e60f1b56f37d1b953d63bf948cde33d1e04e65 | halaqat/settings/shaha.py | halaqat/settings/shaha.py | from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
PROJECT_ROOT = os.path.dirnam... | from .base_settings import *
import dj_database_url
import os
ALLOWED_HOSTS = ['shaha-halaqat.herokuapp.com', '0.0.0.0']
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/... | Add heroku app url to ALLOWED_HOSTS | Add heroku app url to ALLOWED_HOSTS
| Python | mit | EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat |
054503e406146eeff5f8d5437eb7db581eaeb0f2 | oscar_adyen/__init__.py | oscar_adyen/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from django_adyen import urlpatterns
from . import views
urlpatterns = [
url(r'^payment-done/$', views.PaymentResultView.as_view(),
name='payment-result'),
url(r'^notify/$', views.NotificationView.as_vi... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from django_adyen import urlpatterns
urlpatterns = [
url(r'^payment-done/$', 'oscar_adyen.views.payment_result',
name='payment-result'),
url(r'^notify/$', 'oscar_adyen.views.notification',
name='... | Allow importing oscar_adyen.mixins without importing oscar_adyen.views | Allow importing oscar_adyen.mixins without importing oscar_adyen.views
| Python | mit | machtfit/adyen |
3f92ca011d08d69c5443994c79958a5d1f3b7415 | werobot/session/saekvstorage.py | werobot/session/saekvstorage.py | # -*- coding: utf-8 -*-
from . import SessionStorage
class SaeKVDBStorage(SessionStorage):
"""
SaeKVDBStorage 使用SAE 的 KVDB 来保存你的session ::
import werobot
from werobot.session.saekvstorage import SaeKVDBStorage
session_storage = SaeKVDBStorage()
robot = werobot.WeRoBot(token=... | # -*- coding: utf-8 -*-
from . import SessionStorage
class SaeKVDBStorage(SessionStorage):
"""
SaeKVDBStorage 使用SAE 的 KVDB 来保存你的session ::
import werobot
from werobot.session.saekvstorage import SaeKVDBStorage
session_storage = SaeKVDBStorage()
robot = werobot.WeRoBot(token=... | Add param doc of SAEKVStorage | Add param doc of SAEKVStorage
| Python | mit | whtsky/WeRoBot,FlyRabbit/WeRoBot,whtsky/WeRoBot,adrianzhang/WeRoBot,notwin/WeRoBot,weberwang/WeRoBot,Infixz/WeRoBot,weberwang/WeRoBot,chenjiancan/WeRoBot,Zeacone/WeRoBot,tdautc19841202/WeRoBot,one-leaf/WeRoBot,Zhenghaotao/WeRoBot,kmalloc/WeRoBot,FlyRabbit/WeRoBot,whtsky/WeRoBot,adam139/WeRobot,adam139/WeRobot |
cee2f2132cb54d5089f44bb48c9a19bd538dc72a | src/commoner_i/urls.py | src/commoner_i/urls.py | from django.conf.urls.defaults import patterns, include, handler500, url
from django.conf import settings
from django.contrib import admin
handler500 # Pyflakes
urlpatterns = patterns(
'',
# Profile view
url(r'^p/(?P<username>\w+)/$', 'commoner_i.views.badge',
name='profile_badge'),
)
| from django.conf.urls.defaults import patterns, include, handler500, handler404, url
from django.conf import settings
from django.contrib import admin
urlpatterns = patterns(
'',
# Profile view
url(r'^p/(?P<username>\w+)/$', 'commoner_i.views.badge',
name='profile_badge'),
)
| Use the default 404/500 handlers for i.cc.net. | Use the default 404/500 handlers for i.cc.net.
| Python | agpl-3.0 | cc-archive/commoner,cc-archive/commoner |
b5ea9f83fc9422c165663920af1317365a3e6c4d | mangopaysdk/types/payinexecutiondetailsdirect.py | mangopaysdk/types/payinexecutiondetailsdirect.py | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
# Mode3DSType { DEFAULT, FORCE }
self.SecureMode... | from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType ... | Add SecureModeRedirectURL attribute to PayInExecutionDetailsDirect | Add SecureModeRedirectURL attribute to PayInExecutionDetailsDirect
| Python | mit | Mangopay/mangopay2-python-sdk,chocopoche/mangopay2-python-sdk |
c1fd0f12810be544d12d4bea8ccd0ce9f8a190cc | 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,... | 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,... | Add hub user info to page | Add hub user info to page
| Python | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab |
ab79661216ff972bd696eb568c68ebd221c9a003 | seabird/modules/url.py | seabird/modules/url.py | import asyncio
import re
import aiohttp
import lxml.html
from seabird.plugin import Plugin
class URLPlugin(Plugin):
url_regex = re.compile(r'https?://[^ ]+')
def irc_privmsg(self, msg):
for match in URLPlugin.url_regex.finditer(msg.trailing):
url = match.group(0)
# As a fal... | import asyncio
import re
import aiohttp
import lxml.html
from seabird.plugin import Plugin
class URLMixin:
"""Simple marker class to mark a plugin as a url plugin
A URL plugin requires only one thing:
- A method named url_match which takes a msg and url as an argument and
returns True if the url ... | Add a method for plugins to add their own URL handlers | Add a method for plugins to add their own URL handlers
| Python | mit | belak/pyseabird,belak/python-seabird |
8e9dc62f01f4b6ccaab819d21d92f3d6c53e3e1c | src/common/constants.py | src/common/constants.py | """
Constants used to make the VWS mock and wrapper.
"""
from constantly import ValueConstant, Values
class ResultCodes(Values):
"""
Constants representing various VWS result codes.
"""
AUTHENTICATION_FAILURE = ValueConstant('AuthenticationFailure')
SUCCESS = ValueConstant('Success')
FAIL = ... | """
Constants used to make the VWS mock and wrapper.
"""
from constantly import ValueConstant, Values
class ResultCodes(Values):
"""
Constants representing various VWS result codes.
See
https://library.vuforia.com/articles/Solution/How-To-Interperete-VWS-API-Result-Codes
"""
SUCCESS = Value... | Add all documented result codes | Add all documented result codes
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python |
c1ac7c357d5a7ce3e96af9b4356fc2f0493e2b1d | apps/people/admin.py | apps/people/admin.py | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Person, Team
@admin.register(Person)
class PersonAdmin(SearchMetaBaseAdmin):
prepopulated_fields = {"url_title": ("first_name", "last_name",)}
filter_horizontal = ("teams",)
fieldsets = (
... | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Person, Team
@admin.register(Person)
class PersonAdmin(SearchMetaBaseAdmin):
prepopulated_fields = {"url_title": ("first_name", "last_name",)}
filter_horizontal = ("teams",)
fieldsets = (
... | Fix usage of `url_title` in TeamAdmin. | Fix usage of `url_title` in TeamAdmin.
| Python | mit | onespacemedia/cms-people,onespacemedia/cms-people |
42a523393d6ec2d5dfc80d1b82e2c703e1afa29b | calc.py | calc.py | """calc.py: A simple calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command =... | """calc.py: A simple calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command =... | Update usage string for min | Update usage string for min
| Python | bsd-3-clause | mkuiper/calc-1 |
d8913869c466bea4e301e8502decdc01f6d9987e | cowserver.py | cowserver.py | from flask import Flask
from flask_talisman import Talisman
from flask_seasurf import SeaSurf
from redditflair.redditflair import redditflair, limiter
from redissession import RedisSessionInterface
from database import db, User, Specials
import os.path
content_security_policy = {
'script-src': '\'unsafe-inline\'',
'... | from flask import Flask
from flask_talisman import Talisman
from flask_seasurf import SeaSurf
from redditflair.redditflair import redditflair, limiter
from redissession import RedisSessionInterface
from database import db, User, Specials
import os.path
content_security_policy = {
'script-src': '\'unsafe-inline\'',
'... | Disable SQLALCHEMY_TRACK_MODIFICATIONS to fix deprecation warning and meet recommendation | Disable SQLALCHEMY_TRACK_MODIFICATIONS to fix deprecation warning and meet recommendation
| Python | mit | competitiveoverwatch/RankVerification,competitiveoverwatch/RankVerification |
d9ef4c798e50de12cc4ab41fa470cd0e04d77322 | opendebates/tests/test_context_processors.py | opendebates/tests/test_context_processors.py | import urlparse
from django.test import TestCase, override_settings
from django.conf import settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
... | import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
... | Remove unused import in test | Remove unused import in test
| Python | apache-2.0 | ejucovy/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates |
c4eef5919fa60c87b59d60c1bd005f97183ce057 | aiozk/test/test_connection.py | aiozk/test/test_connection.py | from unittest import mock
import pytest
import aiozk.connection
@pytest.fixture
def connection(event_loop):
connection = aiozk.connection.Connection(
host='zookeeper.test',
port=2181,
watch_handler=mock.MagicMock(),
read_timeout=30,
loop=mock.MagicMock(wraps=event_loop))
... | from unittest import mock
import pytest
import aiozk.connection
@pytest.fixture
def connection(event_loop):
connection = aiozk.connection.Connection(
host='zookeeper.test',
port=2181,
watch_handler=mock.MagicMock(),
read_timeout=30,
loop=event_loop)
connection.writer... | Modify and add tests for the revised connection.close | Modify and add tests for the revised connection.close
| Python | mit | tipsi/aiozk,tipsi/aiozk |
72ed64fad2d03ba97f12d5ad4802bcb956a1f29b | temba/chatbase/tasks.py | temba/chatbase/tasks.py | from __future__ import print_function, unicode_literals
import logging
from celery.task import task
from temba.orgs.models import Org
from .models import Chatbase
logger = logging.getLogger(__name__)
@task(track_started=True, name='send_chatbase_event')
def send_chatbase_event(org, channel, msg, contact):
try... | from __future__ import print_function, unicode_literals
import logging
from celery.task import task
from temba.orgs.models import Org
from .models import Chatbase
logger = logging.getLogger(__name__)
@task(track_started=True, name='send_chatbase_event')
def send_chatbase_event(org, channel, msg, contact):
try... | Change dict declaration to inline | Change dict declaration to inline
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro |
6a58c7f0eb1b92ec12d0e48d7fd3f2586de20755 | sal/management/commands/update_admin_user.py | sal/management/commands/update_admin_user.py | '''
Creates an admin user if there aren't any existing superusers
'''
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from optparse import make_option
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, pars... | """Creates an admin user if there aren't any existing superusers."""
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, par... | Fix exception handling in management command. Clean up. | Fix exception handling in management command. Clean up.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal |
8a51446ee8833c3472d9f97cc29a58dd42d872b8 | core/tests/test_utils.py | core/tests/test_utils.py | from django.test import TestCase
from core import utils
class SlugifyOC(TestCase):
def test_oc_slugify(self):
lst = (
('test.this.value', 'test-this-value'),
('Plone.OpenComparison', 'plone-opencomparison'),
('Run from here', 'run-from-here'),
('Jump_the ... | from django.test import TestCase
from core import utils
class SlugifyOC(TestCase):
def test_oc_slugify(self):
lst = (
('test.this.value', 'test-this-value'),
('Plone.OpenComparison', 'plone-opencomparison'),
('Run from here', 'run-from-here'),
('Jump_the ... | Fix to account for casing diffs between Mac OS X and Linux | Fix to account for casing diffs between Mac OS X and Linux
| Python | mit | QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages,pydanny/djangopackages |
d1e9586fbbadd8278d1d4023490df3348915b217 | migrations/versions/0082_set_international.py | migrations/versions/0082_set_international.py | """empty message
Revision ID: 0082_set_international
Revises: 0080_fix_rate_start_date
Create Date: 2017-05-05 15:26:34.621670
"""
# revision identifiers, used by Alembic.
from datetime import datetime
revision = '0082_set_international'
down_revision = '0080_fix_rate_start_date'
from alembic import op
import sqla... | """empty message
Revision ID: 0082_set_international
Revises: 0081_noti_status_as_enum
Create Date: 2017-05-05 15:26:34.621670
"""
from datetime import datetime
from alembic import op
# revision identifiers, used by Alembic.
revision = '0082_set_international'
down_revision = '0081_noti_status_as_enum'
def upgrade... | Update the script to set the international flag to do the notifications and notification_history in separate loops. It takes about 1.5 minutes to update 27,000 notifications and 27,000 notification_history. The update is a row level lock so will only affect updates to the same row. This is unlikely as the data being up... | Update the script to set the international flag to do the notifications and notification_history in separate loops.
It takes about 1.5 minutes to update 27,000 notifications and 27,000 notification_history. The update is a row level lock so will only affect updates to the same row.
This is unlikely as the data being up... | Python | mit | alphagov/notifications-api,alphagov/notifications-api |
a121b79cd9260f17e85f3a611a47bb913170b353 | scripts/poweron/DRAC.py | scripts/poweron/DRAC.py | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | Change path to the supplemental pack | CA-40618: Change path to the supplemental pack
Signed-off-by: Javier Alvarez-Valle <cf4c8668a0b4c5e013f594a6940d05b3d4d9ddcf@citrix.com>
| Python | lgpl-2.1 | djs55/xcp-networkd,sharady/xcp-networkd,johnelse/xcp-rrdd,sharady/xcp-networkd,robhoes/squeezed,djs55/xcp-rrdd,simonjbeaumont/xcp-rrdd,koushikcgit/xcp-networkd,koushikcgit/xcp-networkd,koushikcgit/xcp-rrdd,djs55/xcp-networkd,simonjbeaumont/xcp-rrdd,johnelse/xcp-rrdd,koushikcgit/xcp-rrdd,djs55/xcp-rrdd,djs55/squeezed,ko... |
b414d74a639151785ef02a9d390e1398b7167886 | app/forms/simple_form.py | app/forms/simple_form.py | from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
class SimpleForm(Form):
name = StringField('Your name', validators=[Required()])
submit = SubmitField('Submit')
| from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required
class SimpleForm(FlaskForm):
name = StringField('Your name', validators=[Required()])
submit = SubmitField('Submit')
| Change Form to FlaskForm (prevent deprecated) | Change Form to FlaskForm (prevent deprecated)
| Python | mit | rustyworks/flask-structure,rustyworks/flask-structure |
029edcfe1769dd65fa2fac566abb5686c5986890 | backdrop/core/records.py | backdrop/core/records.py | import datetime
class Record(object):
def __init__(self, data):
self.data = data
self.meta = {}
if "_timestamp" in self.data:
days_since_week_start = datetime.timedelta(
days=self.data['_timestamp'].weekday())
week_start = self.data['_timestamp'] - ... | import datetime
class Record(object):
def __init__(self, data):
self.data = data
self.meta = {}
if "_timestamp" in self.data:
day_of_week = self.data['_timestamp'].weekday()
delta_from_week_start = datetime.timedelta(days=day_of_week)
week_start = self... | Refactor for clarity around _week_start_at | Refactor for clarity around _week_start_at
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop |
e4841c674545892dfc6a8390574cec7c2836e004 | main.py | main.py | from SimpleCV import *
winsize = (640,480)
display = Display(winsize)
video = VirtualCamera('stefan_eye.mp4', 'video')
while display.isNotDone():
a = video.getImage()
a.rotate(90).invert().toGray().binarize().save(display)
| from SimpleCV import *
winsize = (640,480)
display = Display(winsize)
video = VirtualCamera('stefan_eye.mp4', 'video')
while display.isNotDone():
image = video.getImage().rotate(90).crop(850,50,400,400)
image2 = image.colorDistance(Color.RED)
blobs = image2.findBlobs()
image3 = image2.grayscale()
if... | Add code to accomodate a new '3 circles' approach | Add code to accomodate a new '3 circles' approach
| Python | mit | ColdSauce/Iris |
e120c264f16f89b197ff3416deaefb7f553611db | pages/urlconf_registry.py | pages/urlconf_registry.py | """Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a widget for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested widget was not found
... | """Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a urlconf for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested urlconf was not found... | Fix typos in urlconf registry | Fix typos in urlconf registry
| Python | bsd-3-clause | batiste/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,rem... |
ed6a69dc2efefdb8cf5e32c9c71b122b6357b1fa | parks/test/test_finder.py | parks/test/test_finder.py | #!/usr/bin/env python
"""Unit tests for the 'finder' module."""
| #!/usr/bin/env python
"""Unit tests for the 'finder' module."""
def test_tbd():
"""Placeholder for the first test."""
assert True
| Add a placeholder test so pytest will not report an error | Add a placeholder test so pytest will not report an error
| Python | mit | friendlycode/gr-parks,friendlycode/gr-parks,friendlycode/gr-parks,friendlycode/gr-parks |
d7c6a7f78c8620e0e01e57eb082860e90f782a30 | parsl/tests/test_swift.py | parsl/tests/test_swift.py | #!/usr/bin/env python3.5
import parsl
from parsl import *
parsl.set_stream_logger()
from parsl.executors.swift_t import *
def foo(x, y):
return x * y
def slow_foo(x, y):
import time
time.sleep(x)
return x * y
def bad_foo(x, y):
time.sleep(x)
return x * y
def test_simple():
print("... | #!/usr/bin/env python3.5
from nose.tools import assert_raises
import parsl
from parsl import *
parsl.set_stream_logger()
from parsl.executors.swift_t import *
def foo(x, y):
return x * y
def slow_foo(x, y):
import time
time.sleep(x)
return x * y
def bad_foo(x, y):
time.sleep(x)
return x ... | Make `test_except` swift test pass | Make `test_except` swift test pass
Currently it is expected to fail. This asserts that the correct
exception is raised. Fixes #155.
| Python | apache-2.0 | Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl |
9d1a5932ad25b075b095f170c1b374e46b6f740b | setup/create_players.py | setup/create_players.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from db import commit_db_item
from db.player import Player
def migrate_players(plr_src_file=None):
if not plr_src_file:
plr_src_file = os.path.join(
os.path.dirname(__file__), 'nhl_players.json')
migration_data = json.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from db import commit_db_item
from db.player import Player
from db.team import Team
from utils.player_finder import PlayerFinder
def migrate_players(plr_src_file=None):
if not plr_src_file:
plr_src_file = os.path.join(
os.p... | Add stub to search for players remotely | Add stub to search for players remotely
| Python | mit | leaffan/pynhldb |
c1f221b638405af81c637ddd79bd8c9eef24b488 | main.py | main.py | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
... | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
... | Apply modification from Feb 5 | Apply modification from Feb 5
| Python | mit | rschiang/pineapple.py |
fc263902e845c21aa3379bf985cef693d30bc56b | senlin/tests/functional/test_policy_type.py | senlin/tests/functional/test_policy_type.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Fix functional test for policy type listing | Fix functional test for policy type listing
This patch fixes the funtional test for policy type listing. We have
changed the names of builtin policy types.
Change-Id: I9f04ab2a4245e8946db3a0255658676cc5f600ab
| Python | apache-2.0 | stackforge/senlin,openstack/senlin,stackforge/senlin,Alzon/senlin,tengqm/senlin-container,tengqm/senlin-container,openstack/senlin,Alzon/senlin,openstack/senlin |
ae0e2a481f91e94cf05ac2df63f1d66f76a5e442 | indra/preassembler/grounding_mapper/gilda.py | indra/preassembler/grounding_mapper/gilda.py | """This module implements a client to the Gilda grounding web service,
and contains functions to help apply it during the course of INDRA assembly."""
import requests
from .mapper import GroundingMapper
grounding_service_url = 'http://grounding.indra.bio/ground'
def ground_statements(stmts):
"""Set grounding fo... | """This module implements a client to the Gilda grounding web service,
and contains functions to help apply it during the course of INDRA assembly."""
import requests
from .mapper import GroundingMapper
grounding_service_url = 'http://grounding.indra.bio'
def get_gilda_models():
"""Return a list of strings for ... | Refactor Gilda module and add function to get models | Refactor Gilda module and add function to get models
| Python | bsd-2-clause | bgyori/indra,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra |
c7cc0e24ea5d4cbb44665c1267a771f08f1bda4f | cityhallmonitor/signals/handlers.py | cityhallmonitor/signals/handlers.py | from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils import timezone
from cityhallmonitor.models import DirtyFieldsModel, \
Matter, MatterAttachment
@receiver(pre_save, sender=DirtyFieldsModel)
def handle_pre_save(sender, instance, *args, **kwargs):
... | from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils import timezone
from cityhallmonitor.models import DirtyFieldsModel, \
Matter, MatterAttachment, MatterSponsor
@receiver(pre_save, sender=DirtyFieldsModel)
def handle_pre_save(sender, instance, *ar... | Add post_save handler for MatterSponsor | Add post_save handler for MatterSponsor
| Python | mit | NUKnightLab/cityhallmonitor,NUKnightLab/cityhallmonitor,NUKnightLab/cityhallmonitor,NUKnightLab/cityhallmonitor |
6420eca5e458f981aa9f506bfa6354eba50e1e49 | processing/face_detect.py | processing/face_detect.py | import cv2
class FaceDetector:
def __init__(self, face_cascade_path):
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
# detect faces in the image
rectangles = self.faceCascade.detectMultiScale(i... | import cv2
class FaceDetector:
def __init__(self, face_cascade_path):
self.faceCascade = cv2.CascadeClassifier(face_cascade_path)
def detect(self, image, scale_factor=1.1, min_neighbors=5, min_size=(30, 30)):
rectangles = self.faceCascade.detectMultiScale(image, scaleFactor=scale_factor,
... | Align Face and Feature Mapping | Align Face and Feature Mapping
| Python | bsd-3-clause | javaTheHutts/Java-the-Hutts |
38ed00b38d9cb005f9b25643afa7ce480da6febe | examples/enable/resize_tool_demo.py | examples/enable/resize_tool_demo.py | """
This demonstrates the most basic drawing capabilities using Enable. A new
component is created and added to a container.
"""
from enable.example_support import DemoFrame, demo_main
from enable.api import Component, Container, Window
from enable.tools.resize_tool import ResizeTool
class Box(Component):
resiz... | """
This demonstrates the resize tool.
"""
from enable.example_support import DemoFrame, demo_main
from enable.api import Component, Container, Window
from enable.tools.resize_tool import ResizeTool
class Box(Component):
resizable = ""
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
... | Fix resize tool demo comments. | Fix resize tool demo comments.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable |
6502087c63df816e3a4d4b256af7685f638b477d | account_check/migrations/8.0.0.0/pre-migrate.py | account_check/migrations/8.0.0.0/pre-migrate.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
import logging
import openupgradelib
_logger = log... | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
import logging
import openupgradelib
_logger = log... | Set last id in sequence | [FIX] Set last id in sequence
| Python | agpl-3.0 | csrocha/account_check,csrocha/account_check |
b4806b4650f576c7b5cd7f33742ccb108e37321c | StartWithPython/StartWithPython/Theory/Loops/Range.py | StartWithPython/StartWithPython/Theory/Loops/Range.py | # -------------------------------------------------------------------------------------------------
# RANGE
# -------------------------------------------------------------------------------------------------
print('\n\t\tRANGE\n')
for x in range(10): # to make an action ('n') times
... | # -------------------------------------------------------------------------------------------------
# RANGE
# -------------------------------------------------------------------------------------------------
print('\n\t\tRANGE\n')
for x in range(10): # to make an actio... | Add some range application with list | Add some range application with list
| Python | mit | CaptainMich/Python_Project |
091f3c6eafcf2041517463e48f7209716a925b9f | website/files/utils.py | website/files/utils.py |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node settings of the project to copy files to
:param Folder parent: The parent of to attach the clone of src to, if ap... |
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node to copy files to
:param Folder parent: The parent of to attach the clone of src to, if applicable
"""
ass... | Update the most recent fileversions region for copied files across regions | Update the most recent fileversions region for copied files across regions
[#PLAT-1100]
| Python | apache-2.0 | aaxelb/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,adlius/osf.io,adlius/osf.io,cslzchen/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,mfraezz/osf.io,mfraezz/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,cas... |
0989682ad858a6f14a1d387c24511b228881d645 | flake8_docstrings.py | flake8_docstrings.py | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flakes8
"""
import pep257
__version__ = '0.2.0'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
def __init__(... | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flakes8
"""
import pep257
__version__ = '0.2.1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
def __init__(... | Use different pep257 entry point | Use different pep257 entry point
The check_source() function of pep257.py does not handle AllError and
EnvironmentError exceptions. We can use instead the check() function
and ignore any errors that do not belong to the pep257.Error class and
thus are of no use to Flake8.
| Python | mit | PyCQA/flake8-docstrings |
dafbe424546020cc5a53eae5d10391d3dbf81870 | test/style_test.py | test/style_test.py | import glob
import os
import pep8
class TestCodeFormat:
def test_pep8(self):
def match(*p):
s = ['theanets'] + list(p) + ['*.py']
return glob.glob(os.path.join(*s))
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(match() + match('... | import glob
import os
import pep8
class TestCodeFormat:
def test_pep8(self):
def match(*p):
s = ['downhill'] + list(p) + ['*.py']
return glob.glob(os.path.join(*s))
pep8style = pep8.StyleGuide(config_file='setup.cfg')
result = pep8style.check_files(match())
... | Update style test to work with this package. | Update style test to work with this package.
| Python | mit | rodrigob/downhill,lmjohns3/downhill |
93dfefff12569c180e20fefc9380358753c6771e | molo/core/tests/test_import_from_git_view.py | molo/core/tests/test_import_from_git_view.py | import pytest
from django.test import TestCase
from django.core.urlresolvers import reverse
from molo.core.tests.base import MoloTestCaseMixin
@pytest.mark.django_db
class TestImportFromGit(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
self.user = self.login()
def test_wagt... | import pytest
from django.test import TestCase
from django.core.urlresolvers import reverse
from molo.core.tests.base import MoloTestCaseMixin
@pytest.mark.django_db
class TestImportFromGit(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
self.user = self.login()
def test_wagt... | Fix import UI django view's tests | Fix import UI django view's tests
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo |
a8b9e999a34039d64a2fe27b53a938feeb07a013 | flask_app.py | flask_app.py | from flask import Flask, abort, jsonify
from flask_caching import Cache
from flask_cors import CORS
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
cors = CORS(app, resources={r"/*": {"origins": "*"}})
@app.route('/')
@cache.cached(timeout=3600)
def nbis_list_entities():
re... | from flask import Flask, abort, jsonify
from flask_caching import Cache
from flask_cors import CORS
import main
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
cors = CORS(app, resources={r"/*": {"origins": "*"}})
@app.route('/api/')
@cache.cached(timeout=3600)
def nbis_list_entities():
... | Put API under /api/ by default | Put API under /api/ by default
| Python | bsd-3-clause | talavis/kimenu |
a3bb5ca86cbba530718e55f97407d7c5d3ad0a57 | stagecraft/apps/organisation/admin.py | stagecraft/apps/organisation/admin.py | from django.contrib import admin
from .models import NodeType, Node
class NodeTypeAdmin(admin.ModelAdmin):
list_display = ('name',)
class NodeAdmin(admin.ModelAdmin):
list_display = ('name', 'abbreviation',)
admin.site.register(NodeType, NodeTypeAdmin)
admin.site.register(Node, NodeAdmin)
| from django.contrib import admin
from .models import NodeType, Node
class NodeTypeAdmin(admin.ModelAdmin):
list_display = ('name',)
class ParentInline(admin.TabularInline):
model = Node.parents.through
verbose_name = 'Parent relationship'
verbose_name_plural = 'Parents'
extra = 1
fk_name = ... | Improve Django Admin interface for Organisations | Improve Django Admin interface for Organisations
We have a lot of nodes now so adding some way of filtering by type and
searching by name seemed wise.
I've switched the multiselect box to pick parents for an interface that
is a little more sane when we have over a 1000 possible parents.
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft |
a01d306a887eabc912a9e57af0ad862e6c45f652 | saleor/cart/__init__.py | saleor/cart/__init__.py | from __future__ import unicode_literals
from django.utils.translation import pgettext
from satchless import cart
from satchless.item import ItemList, ClassifyingPartitioner
from ..product.models import DigitalShip
class ShippedGroup(ItemList):
'''
Group for shippable products.
'''
pass
class Digit... | from __future__ import unicode_literals
from django.utils.translation import pgettext
from satchless import cart
from satchless.item import ItemList, ClassifyingPartitioner
from ..product.models import DigitalShip
class ShippedGroup(ItemList):
'''
Group for shippable products.
'''
pass
class Digit... | Use clear cart method from satchless | Use clear cart method from satchless
https://github.com/mirumee/satchless/commit/3acaa8f6a27d9ab259a2d66fc3f7416a18fab1ad
This reverts commit 2ad16c44adb20e9ba023e873149d67068504c34c.
| Python | bsd-3-clause | dashmug/saleor,taedori81/saleor,avorio/saleor,avorio/saleor,tfroehlich82/saleor,arth-co/saleor,laosunhust/saleor,dashmug/saleor,rchav/vinerack,arth-co/saleor,Drekscott/Motlaesaleor,taedori81/saleor,rchav/vinerack,josesanch/saleor,arth-co/saleor,KenMutemi/saleor,paweltin/saleor,KenMutemi/saleor,jreigel/saleor,Drekscott/... |
5b50b96b35c678ca17b069630875a9d86e2cbca3 | scripts/i18n/commons.py | scripts/i18n/commons.py | # -*- coding: utf-8 -*-
msg = {
'en': {
'commons-file-moved' : u'[[:File:%s|File]] moved to [[:commons:File:%s|commons]].',
'commons-file-now-available' : u'File is now available on Wikimedia Commons.',
'commons-nowcommons-template' : 'en': u'{{subst:ncd|%s}}',
},
'qqq... | # -*- coding: utf-8 -*-
msg = {
'en': {
'commons-file-moved' : u'[[:File:%s|File]] moved to [[:commons:File:%s|commons]].',
'commons-file-now-available' : u'File is now available on Wikimedia Commons.',
},
'qqq': {
'commons-file-now-available' : u'Edit summary when the bot has moved... | Remove the template for now. | Remove the template for now.
git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@9344 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
| Python | mit | legoktm/pywikipedia-rewrite |
11ab81f67df3f7579cb1b85d87499480c3cea351 | wafer/pages/serializers.py | wafer/pages/serializers.py | from rest_framework import serializers
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
def create(self, validated_data):
# TODO: Implement
return super(PageSerializer, self).create(validated_data)
| from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
... | Add create & update methods for page API | Add create & update methods for page API
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
9eafc01ef8260a313f2e214924cfd5bda706c1c0 | cactusbot/handler.py | cactusbot/handler.py | """Handle handlers."""
import logging
class Handlers(object):
"""Handlers."""
def __init__(self, *handlers):
self.handlers = handlers
def handle(self, event, packet):
"""Handle incoming data."""
for handler in self.handlers:
if hasattr(handler, "on_" + event):
... | """Handle handlers."""
import logging
class Handlers(object):
"""Handlers."""
def __init__(self, *handlers):
self.logger = logging.getLogger(__name__)
self.handlers = handlers
def handle(self, event, packet):
"""Handle incoming data."""
for handler in self.handlers:
... | Add exception logging to Handlers | Add exception logging to Handlers
| Python | mit | CactusDev/CactusBot |
801a209eb208c629d4ea84199b7779e8c6a0396d | tests/sentry/interfaces/user/tests.py | tests/sentry/interfaces/user/tests.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import mock
from exam import fixture
from sentry.testutils import TestCase
from sentry.interfaces import User
from sentry.models import Event
class UserTest(TestCase):
@fixture
def event(self):
return mock.Mock(spec=Event())
@fixtu... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import mock
from exam import fixture
from sentry.testutils import TestCase
from sentry.interfaces import User
from sentry.models import Event
class UserTest(TestCase):
@fixture
def event(self):
return mock.Mock(spec=Event())
@fixtu... | Fix text to prove that behavior | Fix text to prove that behavior
| Python | bsd-3-clause | imankulov/sentry,BayanGroup/sentry,songyi199111/sentry,ifduyue/sentry,kevinlondon/sentry,JackDanger/sentry,zenefits/sentry,pauloschilling/sentry,kevinlondon/sentry,TedaLIEz/sentry,looker/sentry,camilonova/sentry,gg7/sentry,daevaorn/sentry,gg7/sentry,ngonzalvez/sentry,JamesMura/sentry,mitsuhiko/sentry,mvaled/sentry,wong... |
3befcbaf3a78a46edc31cc1910fcd8e0a9381102 | money_conversion/money.py | money_conversion/money.py |
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
| from currency_rates import rates
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
def to_currency(self, new_currency):
new_currency = new_c... | Add to_currency method in order to be able to convert to a new currency | Add to_currency method in order to be able to convert to a new currency
| Python | mit | mdsrosa/money-conversion-py |
121c76f6af1987ba8ebef4f506604d37e6608a64 | scalaBee.py | scalaBee.py | #!/usr/bin/env python
## Arguments: numerOfTests program arg1Init-arg1Final arg2Init-arg2Final arg3Init-arg3Final...
## Ex: ./scalaBee 2 ./examples/omp_pi 1,2,4,8 100000,1000000,10000000,100000000
# Importing everything needed
import os
import sys
## Showing initial message
print "=================\nStarting ScalaBe... | #!/usr/bin/env python
# Arguments: numerOfTests program arg1Init-arg1Final arg2Init-arg2Final arg3Init-arg3Final...
# Ex: python scalaBee.py 2 ./examples/omp_pi 1,2,4,8 100000,1000000,10000000,100000000
# Importing everything needed
import os, sys, time
## Showing initial message
print "=================\nStarting S... | ADD - Python script looping correctly | ADD - Python script looping correctly
| Python | mit | danielholanda/ScalaBee,danielholanda/ScalaBee |
4607e0d837829621a2da32581137cc6dcab306f5 | nix/tests.py | nix/tests.py | __author__ = 'gicmo'
import unittest
import nix.core
class TestFile(unittest.TestCase):
def setUp(self):
self.nix_file = nix.core.File.open('test.h5')
assert(self.nix_file.version == '1.0')
def basic_test(self):
b = self.nix_file.create_block('foo', 'bar')
assert(b)
as... | __author__ = 'gicmo'
import unittest
import nix.core
class TestFile(unittest.TestCase):
def setUp(self):
self.nix_file = nix.core.File.open('test.h5')
assert(self.nix_file.version == '1.0')
def basic_test(self):
b = self.nix_file.create_block('foo', 'bar')
assert(b)
as... | Add a test for nix.core.DataArray.label | [test] Add a test for nix.core.DataArray.label
| Python | bsd-3-clause | stoewer/nixpy,stoewer/nixpy |
b20e236bd40c0d3c1d06aa1393f02b98e13e58bb | subscriptions/management/commands/add_missed_call_service_audio_notification_to_active_subscriptions.py | subscriptions/management/commands/add_missed_call_service_audio_notification_to_active_subscriptions.py | from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call servic... | from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand
from subscriptions.models import Subscription
class Command(BaseCommand):
help = ("Active subscription holders need to be informed via audio file "
"about the new missed call service.")
def ... | Remove unused import and fix typo | Remove unused import and fix typo
| Python | bsd-3-clause | praekelt/seed-staged-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging |
c61929f0d0d8dbf53ef3c9ff2a98cf8f249bfca4 | handlers/base_handler.py | handlers/base_handler.py | from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
if offset < 0:
raise IndexError("File offset must be greater than 0")
... | from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
return self.file[offset:offset + size]
| Revert "Add bounds checking to BaseHandler.read()" | Revert "Add bounds checking to BaseHandler.read()"
This reverts commit 045ead44ef69d6ebf2cb0dddf084762efcc62995.
| Python | mit | drx/rom-info |
f106a434df84497e12cfbdf1e693e28b6c567711 | kubespawner/utils.py | kubespawner/utils.py | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurab... | """
Misc. general utility functions, not tied to Kubespawner directly
"""
from concurrent.futures import ThreadPoolExecutor
import random
from jupyterhub.utils import DT_MIN, DT_MAX, DT_SCALE
from tornado import gen, ioloop
from traitlets.config import SingletonConfigurable
class SingletonExecutor(SingletonConfigurab... | Add docstrings to exponential backoff | Add docstrings to exponential backoff
| Python | bsd-3-clause | yuvipanda/jupyterhub-kubernetes-spawner,jupyterhub/kubespawner |
ea22192c9debe171db5d4b6b83d581fe079d6fa4 | ipython/profile_bots/startup/05-import-company.py | ipython/profile_bots/startup/05-import-company.py | """Set up access to important employer data for IPython"""
from dataclasses import dataclass
@dataclass
class EmployerData:
name: str
wwts = EmployerData('wwts')
| """Set up access to important employer data for IPython"""
from dataclasses import dataclass
from tools.issues import issues
@dataclass
class EmployerData:
name: str
wwts = EmployerData('wwts')
def issue_branch(issue):
name = issues.one(issue).branch_name()
print(name)
| Add functuion to ibots to name a branch | Add functuion to ibots to name a branch
| Python | mit | jalanb/jab,jalanb/dotjab,jalanb/jab,jalanb/dotjab |
9e131c863c7ff147b95a016b0dfd52c03c60341e | tests/test_cmd_write.py | tests/test_cmd_write.py | from cfgen import cfgen
from nose.tools import assert_equals
import os
def setup():
os.chdir("test_dir")
clean()
def test_cmd_write():
cfgen.cmd_write("test.cfg")
with open("test.cfg") as actual, open("test.cfg.expected") as expected:
actual_lines = actual.read().splitlines()
... | from cfgen import cfgen
from nose.tools import assert_equals
import os
def setup():
test_root_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(test_root_dir + "/test_dir")
clean()
def test_cmd_write():
cfgen.cmd_write("test.cfg")
with open("test.cfg") as actual, open("test.cfg.e... | Fix running tests form command line | Fix running tests form command line
| Python | mit | rzhilkibaev/cfgen |
dc887df974cc9a060b048543d6280c5492ef8ac8 | main/main.py | main/main.py | #_*_ coding: UTF-8 _*_
from flask import render_template
from application import app
import data_models
import views
import funds
import projects
import grants
import pledges
import suppliers
import supplier_funds
import internal_transfers
import purchases
import users
import roles
import partners
import foreign_tra... | #_*_ coding: UTF-8 _*_
from flask import render_template
from application import app
import db
import data_models
import views
import properties
import renderers
import funds
import projects
import grants
import pledges
import suppliers
import supplier_funds
import internal_transfers
import purchases
import users
im... | Add receent activity to dashboard | Add receent activity to dashboard
| Python | mit | keith-lewis100/pont-workbench,keith-lewis100/pont-workbench,keith-lewis100/pont-workbench |
9cb485e97873eff66ba283f30765bb9c66a3c864 | djangae/core/management/__init__.py | djangae/core/management/__init__.py | import argparse
import djangae.sandbox as sandbox
def execute_from_command_line(argv=None):
"""Wraps Django's `execute_from_command_line` to initialize a djangae
sandbox before running a management command.
Note: The '--sandbox' arg must come first. All other args are forwarded to
Django as no... | import sys
import argparse
import djangae.sandbox as sandbox
def execute_from_command_line(argv=None):
"""Wraps Django's `execute_from_command_line` to initialize a djangae
sandbox before running a management command.
Note: The '--sandbox' arg must come first. All other args are forwarded to
D... | Support no-args for djangae.core.management.execute_from_commandline - matches django implementation. | Support no-args for djangae.core.management.execute_from_commandline - matches django implementation.
| Python | bsd-3-clause | kirberich/djangae,nealedj/djangae,asendecka/djangae,stucox/djangae,martinogden/djangae,chargrizzle/djangae,stucox/djangae,armirusco/djangae,leekchan/djangae,armirusco/djangae,trik/djangae,jscissr/djangae,grzes/djangae,SiPiggles/djangae,trik/djangae,kirberich/djangae,armirusco/djangae,trik/djangae,asendecka/djangae,stuc... |
eaea466e29725c04ccb31a24807668dee1a09a91 | courses/developingapps/python/devenv/server.py | courses/developingapps/python/devenv/server.py |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | Fix ImportError and use bytes in outstream | Fix ImportError and use bytes in outstream
| Python | apache-2.0 | turbomanage/training-data-analyst,GoogleCloudPlatform/training-data-analyst,GoogleCloudPlatform/training-data-analyst,turbomanage/training-data-analyst,GoogleCloudPlatform/training-data-analyst,GoogleCloudPlatform/training-data-analyst,GoogleCloudPlatform/training-data-analyst,turbomanage/training-data-analyst,turboman... |
b914fee46220633c81f244e388c9385614db7d60 | karspexet/ticket/tasks.py | karspexet/ticket/tasks.py | import logging
from django.conf import settings
from django.core.mail import send_mail
from django.contrib.sites.models import Site
from django.template.loader import render_to_string
from django.template import Context
logger = logging.getLogger(__file__)
def send_ticket_email_to_customer(reservation, email, name=N... | import logging
from django.conf import settings
from django.core.mail import send_mail
from django.contrib.sites.models import Site
from django.template.loader import render_to_string
logger = logging.getLogger(__file__)
def send_ticket_email_to_customer(reservation, email, name=None):
'''Send an email to the cu... | Use dict in render_to_string when sending email | Use dict in render_to_string when sending email
Building a Context manually like this is deprecated in Django 1.11, so
let's not do it this way.
| Python | mit | Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet |
f2db056d4da23b96034f7c3ac5c4c12dd2853e91 | luigi_slack/slack_api.py | luigi_slack/slack_api.py | import json
from slackclient import SlackClient
class SlackBotConf(object):
def __init__(self):
self.username = 'Luigi-slack Bot'
class SlackAPI(object):
def __init__(self, token, bot_conf=SlackBotConf()):
self.client = SlackClient(token)
self._all_channels = self._get_channels()
... | import json
from slackclient import SlackClient
class SlackBotConf(object):
def __init__(self):
self.username = 'Luigi-slack Bot'
class SlackAPI(object):
def __init__(self, token, bot_conf=SlackBotConf()):
self.client = SlackClient(token)
self._all_channels = self._get_channels()
... | Validate token when fetching channels | Validate token when fetching channels
| Python | mit | bonzanini/luigi-slack |
80e84d2970114bcf7362c7d280dc12131e55871a | main.py | main.py | from multiprocessing import freeze_support
from ELiDE.app import ELiDEApp
import sys
import os
wd = os.getcwd()
sys.path.extend([wd + '/LiSE', wd + '/ELiDE', wd + '/allegedb'])
def get_application_config(*args):
return wd + '/ELiDE.ini'
if __name__ == '__main__':
freeze_support()
app = ELiDEApp()
a... | from multiprocessing import freeze_support
import sys
import os
wd = os.getcwd()
sys.path.extend([wd + '/LiSE', wd + '/ELiDE', wd + '/allegedb'])
def get_application_config(*args):
return wd + '/ELiDE.ini'
if __name__ == '__main__':
freeze_support()
from ELiDE.app import ELiDEApp
app = ELiDEApp()
... | Fix extra blank window on Windows via PyInstaller | Fix extra blank window on Windows via PyInstaller
| Python | agpl-3.0 | LogicalDash/LiSE,LogicalDash/LiSE |
bb522a33096d7db252c02fda02e6419548094813 | runtests.py | runtests.py | #!/usr/bin/env python
# Adapted from https://raw.githubusercontent.com/hzy/django-polarize/master/runtests.py
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
settings.configure(
DATABASES={
'default': {
... | #!/usr/bin/env python
# Adapted from https://raw.githubusercontent.com/hzy/django-polarize/master/runtests.py
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
import django
if django.VERSION < (1, 6):
extra_settings = {
'TEST_RUNNER': 'discover_ru... | Use discover runner on older djangos | Use discover runner on older djangos
| Python | bsd-3-clause | limbera/django-nap,MarkusH/django-nap |
4ea6a11341c2bbd978d5e0e416c398a442158da6 | whip/web.py | whip/web.py | """
Whip's REST API
"""
# pylint: disable=missing-docstring
from socket import inet_aton
from flask import Flask, abort, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db ... | """
Whip's REST API
"""
# pylint: disable=missing-docstring
from flask import Flask, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
... | Handle IPv6 in REST API | Handle IPv6 in REST API
| Python | bsd-3-clause | wbolster/whip |
43004cfd537c801475bf7e3b3c80dee4da18712f | backend/hook_manager.py | backend/hook_manager.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Université Catholique de Louvain.
#
# This file is part of INGInious.
#
# INGInious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Université Catholique de Louvain.
#
# This file is part of INGInious.
#
# INGInious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the... | Allow hooks to return values (and simplify the code) | Allow hooks to return values (and simplify the code)
| Python | agpl-3.0 | layus/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious |
bb77b9554108c6a9739dd058a12484d15f10d3a2 | candidates/views/helpers.py | candidates/views/helpers.py | from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponseRedirect
from slugify import slugify
from ..election_specific import AREA_POST_DATA
from ..models import (
PopItPerson, membership_covers_date
)
def get_redirect_to_post(election, post_data):
sho... | from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponseRedirect
from slugify import slugify
from ..election_specific import AREA_POST_DATA
from ..models import (
PopItPerson, membership_covers_date
)
def get_redirect_to_post(election, post_data):
sho... | Fix a stupid bug in get_people_from_memberships | Fix a stupid bug in get_people_from_memberships
The rebinding of the function's election_data parameter was breaking
the listing of candidates for a post.
| Python | agpl-3.0 | openstate/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextre... |
b2268ae4ecad477c46a4b99ec17511e2e535b9d0 | globus_cli/commands/task/generate_submission_id.py | globus_cli/commands/task/generate_submission_id.py | import click
from globus_cli.parsing import common_options
from globus_cli.safeio import FORMAT_TEXT_RAW, formatted_print
from globus_cli.services.transfer import get_client
@click.command(
"generate-submission-id",
short_help="Get a submission ID",
help=(
"Generate a new task submission ID for u... | import click
from globus_cli.parsing import common_options
from globus_cli.safeio import FORMAT_TEXT_RAW, formatted_print
from globus_cli.services.transfer import get_client
@click.command(
"generate-submission-id",
short_help="Get a submission ID",
help=(
"""\
Generate a new task submission ... | Clarify that submission ID != task ID | Clarify that submission ID != task ID
Calling this out in the helptext will hopefully help avoid people
conflating these two quite as easily. (An imperfect solution for an
imperfect world.)
| Python | apache-2.0 | globus/globus-cli,globus/globus-cli |
5d50ab9457ef52d3b0a4d75966143245ed5ca305 | sdks/python/apache_beam/runners/worker/channel_factory.py | sdks/python/apache_beam/runners/worker/channel_factory.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Increase keepalive timeout to 5 minutes. | Increase keepalive timeout to 5 minutes.
| Python | apache-2.0 | chamikaramj/beam,chamikaramj/beam,apache/beam,robertwb/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,chamika... |
1540d76aff3d01ea4d94eacab362a82458e65dd7 | AFQ/tests/test_dki.py | AFQ/tests/test_dki.py | from AFQ import dki
import numpy.testing as npt
def test_fit_dki_inputs():
data_files = ["String in a list"]
bval_files = "just a string"
bvec_files = "just another string"
npt.assert_raises(ValueError, dki.fit_dki, data_files, bval_files,
bvec_files)
| import tempfile
import numpy.testing as npt
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from AFQ import dki
def test_fit_dki_inputs():
data_files = ["String in a list"]
bval_files = "just a string"
bvec_files = "just another string"
npt.assert_raises(ValueError, dki.fit_dki, data_files, ... | Add smoke-testing of the DKI fit. | TST: Add smoke-testing of the DKI fit.
| Python | bsd-2-clause | yeatmanlab/pyAFQ,arokem/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ |
522e5e04b2a75a1c4c863116d8ada8c04e122c1a | scheduler.py | scheduler.py | import logging
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
raven_client = RavenClient()
logger = logging.getLogger(__name__)
# When testing changes, set the "TEST_SCHEDULE" envvar... | import logging
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
raven_client = RavenClient()
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_... | Use logging directly in main | Use logging directly in main
| Python | apache-2.0 | royrapoport/destalinator,TheConnMan/destalinator,randsleadershipslack/destalinator,royrapoport/destalinator,TheConnMan/destalinator,randsleadershipslack/destalinator |
98bf53dd350869e31c89f14cb0ebfa6a467dd0ec | events/migrations/0017_auto_20160208_1729.py | events/migrations/0017_auto_20160208_1729.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-08 15:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0016_auto_20160205_1754'),
]
operations = [
migrations.AlterField(
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-08 15:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0016_auto_20160205_1754'),
]
operations = [
migrations.AlterField(
... | Revert "Remove redundant migration operation." | Revert "Remove redundant migration operation."
This reverts commit 9d34264d275acd32122de3567e60b24a417d6098.
| Python | mit | City-of-Helsinki/linkedevents,aapris/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents,aapris/linkedevents,tuomas777/linkedevents,aapris/linkedevents |
4562f84191cde7b43ffb7e028eb33996789b1ea4 | foomodules/link_harvester/common_handlers.py | foomodules/link_harvester/common_handlers.py | import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "descript... | import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "descript... | Discard title and description from wurstball | Discard title and description from wurstball
| Python | mit | horazont/xmpp-crowd |
487382ab2aafe1c92aa64192432379b4f3809732 | pywkeeper.py | pywkeeper.py | from Crypto.Cipher import AES
import json
import os
KEY_LENGTH = 256
BLOCK_LENGTH = 16
KEY_FILE = 'key'
ENCRYPTED_FILE = 'data'
DECRYPTED_FILE = 'tmp'
EOT_CHAR = '\x04'
def get_cipher(iv):
try:
key = open(KEY_FILE, 'rb').read()
except IOError:
key = input("Please enter the decryption key: ")... | #!/usr/bin/env python
from Crypto.Cipher import AES
import json
import os
import optparse
KEY_LENGTH = 256
BLOCK_LENGTH = 16
KEY_FILE = 'key'
ENCRYPTED_FILE = 'data'
DECRYPTED_FILE = 'tmp'
EOT_CHAR = '\x04'
def main(options, arguments):
pass
def get_cipher(iv):
try:
key = open(KEY_FILE, 'rb').read(... | Add option parser and main method | Add option parser and main method
| Python | unlicense | kvikshaug/pwkeeper |
8548befae1c2fa2f0e607a39917f789c0a078235 | Misc/Vim/syntax_test.py | Misc/Vim/syntax_test.py | """Test file for syntax highlighting of editors.
Meant to cover a wide range of different types of statements and expressions.
Not necessarily sensical.
"""
assert True
def foo(): pass
foo() # Uncoloured
while False: pass
1 and 2
if False: pass
from sys import path
# Comment
# XXX catch your attention
'single-quote'... | """Test file for syntax highlighting of editors.
Meant to cover a wide range of different types of statements and expressions.
Not necessarily sensical or comprehensive (assume that if one exception is
highlighted that all are, for instance).
Highlighting extraneous whitespace at the end of the line is not represente... | Remove line meant to test trailing whitespace since that kind of whitespace is automatically removed. | Remove line meant to test trailing whitespace since that kind of whitespace is
automatically removed.
Also annotate what each line is meant to test.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
fdf0d3240f7c2ccdfdd65d223f7949c98c9dc527 | multi_import/exporter.py | multi_import/exporter.py | import tablib
from multi_import.fields import FieldHelper
__all__ = [
'Exporter',
]
class Exporter(FieldHelper):
def __init__(self, queryset, serializer):
self.queryset = queryset
self.serializer = serializer()
def export_dataset(self, template=False):
dataset = tablib.Dataset(... | import tablib
from multi_import.fields import FieldHelper
__all__ = [
'Exporter',
]
class Exporter(FieldHelper):
def __init__(self, queryset, serializer):
self.queryset = queryset
self.serializer = serializer()
def export_dataset(self, template=False):
dataset = tablib.Dataset(... | Fix for formula interpretation triggering in Excel | Fix for formula interpretation triggering in Excel
| Python | mit | sdelements/django-multi-import |
09ebeb873c83d51053ef6aa2d7c6ce47b4be5070 | ckanext/archiver/helpers.py | ckanext/archiver/helpers.py | from ckan.plugins import toolkit as tk
def archiver_resource_show(resource_id):
data_dict = {'id': resource_id}
return tk.get_action('archiver_resource_show')(data_dict)
def archiver_is_resource_broken_html(resource):
archival = resource.get('archiver')
if not archival:
return '<!-- No archi... | from ckan.plugins import toolkit as tk
def archiver_resource_show(resource_id):
data_dict = {'id': resource_id}
return tk.get_action('archiver_resource_show')(data_dict)
def archiver_is_resource_broken_html(resource):
archival = resource.get('archiver')
if not archival:
return tk.literal('<!... | Hide comments meant as unseen | Hide comments meant as unseen
| Python | mit | ckan/ckanext-archiver,datagovuk/ckanext-archiver,datagovuk/ckanext-archiver,ckan/ckanext-archiver,datagovuk/ckanext-archiver,ckan/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver |
4ebc13ac1913dfe3fcd7bdb7c7235b7b88718574 | fastdraw/api/commands.py | fastdraw/api/commands.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2014 PolyBeacon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2014 PolyBeacon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | Add documentation for goto command | Add documentation for goto command
Change-Id: I94e280eef509abe65f552b6e78f21eabfe4192e3
Signed-off-by: Sarah Liske <e262b8a15d521183e33ead305fd79e90e1942cdd@polybeacon.com>
| Python | apache-2.0 | kickstandproject/fastdraw |
16d99a20088e81045e34999b6045e9222d510cd5 | app.py | app.py | # -*- coding: UTF-8 -*-
"""
trytond_async.celery
Implementation of the celery app
This module is named celery because of the way celery workers lookup
the app when `--proj` argument is passed to the worker. For more details
see the celery documentation at:
http://docs.celeryproject.org/en/late... | # -*- coding: UTF-8 -*-
"""
trytond_async.celery
Implementation of the celery app
This module is named celery because of the way celery workers lookup
the app when `--proj` argument is passed to the worker. For more details
see the celery documentation at:
http://docs.celeryproject.org/en/late... | Use raven for logging if available | Use raven for logging if available
| Python | bsd-3-clause | fulfilio/trytond-async,tarunbhardwaj/trytond-async |
9121c8c074a31fd3668f8281c7f093360ed72988 | salad/cli.py | salad/cli.py | import sys
import argparse
from lettuce.bin import main as lettuce_main
from lettuce import world
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
BROWSER_CHOICES = [browser.lower()
for browser in DesiredCapabilities.__dict__.keys()
if not browser.st... | import sys
import argparse
from lettuce.bin import main as lettuce_main
from lettuce import world
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
BROWSER_CHOICES = [browser.lower()
for browser in DesiredCapabilities.__dict__.keys()
if not browser.st... | Use parse_known_args and pass leftovers to lettuce | Use parse_known_args and pass leftovers to lettuce
Seems to be more reliable at handling weird argument ordering than
REMAINDER was
| Python | bsd-3-clause | salad/salad,salad/salad,beanqueen/salad,beanqueen/salad |
a9b1d08e2e248b606ef269ebc7e3fb44698d3efc | a_john_shots/__init__.py | a_john_shots/__init__.py | #!/bin/env python
# A-John-Shots - Python module/library for saving Security Hash Algorithms into JSON format.
# Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publi... | #!/bin/env python
# A-John-Shots - Python module/library for saving Security Hash Algorithms into JSON format.
# Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com>
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO... | Update licence header + Introduction of docstrings | Update licence header + Introduction of docstrings
| Python | mit | funilrys/A-John-Shots |
3ca03031599e2a1673c6349710489938f60f6a4d | rwt/tests/test_launch.py | rwt/tests/test_launch.py | from rwt import launch
def test_with_path(tmpdir, capfd):
params = ['-c', 'import sys; print(sys.path)' ]
launch.with_path(str(tmpdir), params)
out, err = capfd.readouterr()
assert str(tmpdir) in out
| import sys
import subprocess
import textwrap
from rwt import launch
def test_with_path(tmpdir, capfd):
params = ['-c', 'import sys; print(sys.path)']
launch.with_path(str(tmpdir), params)
out, err = capfd.readouterr()
assert str(tmpdir) in out
def test_with_path_overlay(tmpdir, capfd):
params = ['-c', 'import... | Add test for with_path_overlay also. | Add test for with_path_overlay also.
| Python | mit | jaraco/rwt |
954dd1a5ebafbe32c092265f5f508158f8b2742d | straight/plugin/loader.py | straight/plugin/loader.py | """Facility to load plugins."""
import sys
import os
from importlib import import_module
class StraightPluginLoader(object):
"""Performs the work of locating and loading straight plugins.
This looks for plugins in every location in the import path.
"""
def _findPluginFilePaths(self, namespace)... | """Facility to load plugins."""
import sys
import os
from importlib import import_module
class StraightPluginLoader(object):
"""Performs the work of locating and loading straight plugins.
This looks for plugins in every location in the import path.
"""
def _findPluginFilePaths(self, namespace)... | Add docstring to load() method | Add docstring to load() method
| Python | mit | ironfroggy/straight.plugin,pombredanne/straight.plugin |
be52bd5e578c54a816f8b786da5d8cf22fcc3ca8 | paver_ext/python_requirements.py | paver_ext/python_requirements.py | # ============================================================================
# PAVER EXTENSION/UTILITY: Read PIP requirements files
# ============================================================================
# REQUIRES: paver >= 1.0
# DESCRIPTION:
# Provides some utility functions for paver.
#
# SEE ALSO:
# * h... | # ============================================================================
# PAVER EXTENSION/UTILITY: Read PIP requirements files
# ============================================================================
# REQUIRES: paver >= 1.0
# REQUIRES: pkg_resources, fulfilled when setuptools or distribute is installed
# ... | Use pkg_resources.parse_requirements() to simplify parsing. | Use pkg_resources.parse_requirements() to simplify parsing.
| Python | bsd-2-clause | jenisys/behave,jenisys/behave |
dcf11d2d26519cdea10813530d2bde85f8fe8180 | Python/Tests/TestData/DjangoProject/Oar/views.py | Python/Tests/TestData/DjangoProject/Oar/views.py | from django.template import Context, loader
# Create your views here.
from django.http import HttpResponse
from Oar.models import Poll
from django.http import HttpResponse
def main(request):
return HttpResponse('<html><body>Hello world!</body></html>')
def index(request):
latest_poll_list = Poll.objects.all(... | from django.template import Context, loader
# Create your views here.
from django.http import HttpResponse
from Oar.models import Poll
from django.http import HttpResponse
def main(request):
return HttpResponse('<html><body>Hello world!</body></html>')
def index(request):
latest_poll_list = Poll.objects.all(... | Use a dict instead of Context instance in DjangoDebuggerTests test project, to avoid a TypeError in latest version of Django. | Use a dict instead of Context instance in DjangoDebuggerTests test project, to avoid a TypeError in latest version of Django.
| Python | apache-2.0 | int19h/PTVS,huguesv/PTVS,zooba/PTVS,Microsoft/PTVS,Microsoft/PTVS,zooba/PTVS,Microsoft/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS,int19h/PTVS,Microsoft/PTVS,Microsoft/PTVS,Microsoft/PTVS,int19h/PTVS,zooba/PTVS,zooba/PTVS,huguesv/PTVS,huguesv/PTVS,int19h/PTVS,huguesv/PTVS,int19h/PTVS,huguesv/PTVS,huguesv/PTVS |
bb3dfe39075876107fa992a66c16a5566a442d23 | polymorphic_auth/tests.py | polymorphic_auth/tests.py | from django.test import TestCase
# Create your tests here.
| import re
from django.contrib.admin.sites import AdminSite
from django_webtest import WebTest
from django.core.urlresolvers import reverse
from .usertypes.email.models import EmailUser
class TestUserAdminBaseFieldsets(WebTest):
"""
Tests a fix applied to ensure `base_fieldsets` are not
lost in `UserChildA... | Add regression test for base_fieldsets fix. | Add regression test for base_fieldsets fix.
| Python | mit | ixc/django-polymorphic-auth |
7d81de637288ca694c139b3a7830f6e8ca00aa01 | gargoyle/__init__.py | gargoyle/__init__.py | """
gargoyle
~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from gargoyle.manager import gargoyle
try:
VERSION = __import__('pkg_resources').get_distribution('gargoyle-yplan').version
except Exception, e:
VERSION = 'unknown'
__all__ = ('gargoyle', 'auto... | """
gargoyle
~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
from gargoyle.manager import gargoyle
try:
VERSION = __import__('pkg_resources').get_distribution('gargoyle-yplan').version
except Exception, e:
VERSION = 'unknown'
__all__ = ('gargoyle', 'auto... | Switch to using python standard library importlib | Switch to using python standard library importlib
Available in Python 2.7+, which is all that Gargoyle now supports. The Django version is removed in 1.9.
| Python | apache-2.0 | nkovshov/gargoyle,YPlan/gargoyle,nkovshov/gargoyle,YPlan/gargoyle,roverdotcom/gargoyle,nkovshov/gargoyle,YPlan/gargoyle,roverdotcom/gargoyle,roverdotcom/gargoyle |
9baae7a5c633399fe25ca6961e992b50adcd72b4 | jacquard/service/base.py | jacquard/service/base.py | import abc
import copy
import werkzeug.routing
class Endpoint(metaclass=abc.ABCMeta):
@abc.abstractproperty
def url(self):
pass
@abc.abstractclassmethod
def handle(self, **kwargs):
pass
def __call__(self, **kwargs):
return self.handle(**kwargs)
@property
def defa... | import abc
import copy
import werkzeug.routing
class Endpoint(metaclass=abc.ABCMeta):
@abc.abstractproperty
def url(self):
pass
@abc.abstractclassmethod
def handle(self, **kwargs):
pass
def __call__(self, **kwargs):
return self.handle(**kwargs)
@property
def defa... | Use a level of indirection for helpful error messages | Use a level of indirection for helpful error messages
| Python | mit | prophile/jacquard,prophile/jacquard |
9c40c070b6c55d6eda2cabf4c1ebe062cebcfe8f | flask_controllers/GameModes.py | flask_controllers/GameModes.py | from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from python_cowbull_game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
textonly = request.args.get('textmode',... | from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
from flask_helpers.ErrorHandler import ErrorHandler
from Game.GameObject import GameObject
class GameModes(MethodView):
def get(self):
textonly = request.args.get('textmode', None)
... | Update to use inheritance for GameObject | Update to use inheritance for GameObject
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server |
a1d9e1ed4ac8b7542b6430f84b2ed9197d45d577 | fireplace/cards/wog/priest.py | fireplace/cards/wog/priest.py | from ..utils import *
##
# Minions
| from ..utils import *
##
# Minions
class OG_234:
"Darkshire Alchemist"
play = Heal(TARGET, 5)
class OG_335:
"Shifting Shade"
deathrattle = Give(CONTROLLER, Copy(RANDOM(ENEMY_DECK)))
##
# Spells
class OG_094:
"Power Word: Tentacles"
play = Buff(TARGET, "OG_094e")
OG_094e = buff(+2, +6)
| Implement Darkshire Alchemist, Shifting Shade, Power Word: Tentacles | Implement Darkshire Alchemist, Shifting Shade, Power Word: Tentacles
| Python | agpl-3.0 | jleclanche/fireplace,NightKev/fireplace,beheh/fireplace |
e3d00e6c3e62e5cfa457529fc2dddfb814382db6 | packages/dcos-integration-test/extra/test_metronome.py | packages/dcos-integration-test/extra/test_metronome.py | def test_metronome(dcos_api_session):
job = {
'description': 'Test Metronome API regressions',
'id': 'test.metronome',
'run': {
'cmd': 'ls',
'docker': {'image': 'busybox:latest'},
'cpus': 1,
'mem': 512,
'user': 'nobody',
... | def test_metronome(dcos_api_session):
job = {
'description': 'Test Metronome API regressions',
'id': 'test.metronome',
'run': {
'cmd': 'ls',
'docker': {'image': 'busybox:latest'},
'cpus': 1,
'mem': 512,
'disk' 0,
'user':... | Fix the Metronome integration test | Fix the Metronome integration test
| Python | apache-2.0 | dcos/dcos,amitaekbote/dcos,branden/dcos,mesosphere-mergebot/mergebot-test-dcos,surdy/dcos,mesosphere-mergebot/mergebot-test-dcos,surdy/dcos,kensipe/dcos,mellenburg/dcos,mellenburg/dcos,GoelDeepak/dcos,dcos/dcos,mellenburg/dcos,mesosphere-mergebot/dcos,kensipe/dcos,amitaekbote/dcos,kensipe/dcos,GoelDeepak/dcos,mesospher... |
f57c9643a32cca012fdccac40899c6de38e35af9 | ass/ets/__init__.py | ass/ets/__init__.py |
from bundles import Environment, Assets, Bundle, Manifest
import filters as f
from options import Option, Options, Undefined, dict_getter
|
from bundles import Environment, Assets, Bundle, Manifest
import filters as f
from options import Option, Options, Undefined, dict_getter
from pipeable import worker
| Make @worker available for import on ass.ets. | Make @worker available for import on ass.ets.
| Python | bsd-2-clause | kaste/ass.ets,kaste/ass.ets |
c1dff6850a0d39c39b0c337f4f5473efb77fc075 | tests/utils/test_forms.py | tests/utils/test_forms.py | import unittest
from app import create_app, db
from app.utils.forms import RedirectForm
class TestRedirectForm(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_ctx = self.app.app_context()
self.redirect_form = RedirectForm()
self.app_ctx.push()
... | import unittest
from app import create_app, db
from app.utils.forms import RedirectForm
class FormTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
... | Move setUp and tearDown methods into general FormTestCase class | Move setUp and tearDown methods into general FormTestCase class
| Python | mit | Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger |
fdd1604ae64d72dc2391abe137adba07da830bcd | imagersite/imager_profile/models.py | imagersite/imager_profile/models.py | """Models."""
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
# friends = models.ManyToManyField('... | """Models."""
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ActiveUserManager(models.Manager):
"""Manager to grab active users."""
def get_query_set(self):
"""Return only active users."""
re... | Add ability to access all 'objects' and only 'active' users | Add ability to access all 'objects' and only 'active' users
| Python | mit | DZwell/django-imager |
16e9987e680a6a44acdb14bd7554414dfe261056 | sale_automatic_workflow/models/stock_move.py | sale_automatic_workflow/models/stock_move.py | # -*- coding: utf-8 -*-
# © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class StockMove(models.Model):
_inherit = 'stock.move'
@api.m... | # -*- coding: utf-8 -*-
# © 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>
# © 2013 Camptocamp SA (author: Guewen Baconnier)
# © 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class StockMove(models.Model):
_inherit = 'stock.move'
@api.m... | Fix API type & method name for picking values | Fix API type & method name for picking values
| Python | agpl-3.0 | kittiu/sale-workflow,kittiu/sale-workflow |
c83a680603b83edafe61f6d41b34989c70a4e4ae | clowder/clowder/cli/save_controller.py | clowder/clowder/cli/save_controller.py | from cement.ext.ext_argparse import expose
from clowder.cli.abstract_base_controller import AbstractBaseController
class SaveController(AbstractBaseController):
class Meta:
label = 'save'
stacked_on = 'base'
stacked_type = 'nested'
description = 'Create version of clowder.yaml for... | import os
import sys
from cement.ext.ext_argparse import expose
import clowder.util.formatting as fmt
from clowder.cli.abstract_base_controller import AbstractBaseController
from clowder.util.decorators import valid_clowder_yaml_required
from clowder.commands.util import (
validate_groups,
validate_projects_e... | Add `clowder save` logic to Cement controller | Add `clowder save` logic to Cement controller
| Python | mit | JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder |
b6ee793158d549f3d04d42ecbeb1c63605d6258f | src/setup.py | src/setup.py | import distutils.core
import distutils.extension
import Cython.Distutils
import numpy as np
compile_args = ['-O3', '-march=native', '-ffast-math', '-std=c++14', '-fopenmp']
ext_module = distutils.extension.Extension('spectrum_match', ['spectrum_match.pyx', 'SpectrumMatch.cpp'],
... | import distutils.core
import distutils.extension
import Cython.Distutils
import numpy as np
compile_args = ['-O3', '-march=native', '-ffast-math', '-fno-associative-math', '-std=c++14', '-fopenmp']
ext_module = distutils.extension.Extension('spectrum_match', ['spectrum_match.pyx', 'SpectrumMatch.cpp'],
... | Add C++ compilation flag to ensure deterministic behavior | Add C++ compilation flag to ensure deterministic behavior
More information: https://github.com/spotify/annoy/pull/205
| Python | apache-2.0 | bittremieux/ANN-SoLo,bittremieux/ANN-SoLo |
7bece2c307cb05504c4b778446a4867ab8b6c196 | indra/tests/test_ontmapper.py | indra/tests/test_ontmapper.py | from indra.statements import Influence, Concept
from indra.preassembler.ontology_mapper import OntologyMapper, wm_ontomap
def test_map():
c1 = Concept('x', db_refs={'UN': [('entities/x', 1.0)]})
c2 = Concept('y', db_refs={'BBN': 'entities/y'})
c3 = Concept('z')
stmts = [Influence(c1, c3), Influence(c2... | from indra.statements import Influence, Concept
from indra.preassembler.ontology_mapper import OntologyMapper, wm_ontomap
def test_map():
c1 = Concept('x', db_refs={'UN': [('entities/x', 1.0)]})
c2 = Concept('y', db_refs={'BBN': 'entities/y'})
c3 = Concept('z')
stmts = [Influence(c1, c3), Influence(c2... | Add simple test for WM ontology mapping | Add simple test for WM ontology mapping
| Python | bsd-2-clause | pvtodorov/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,bgyori/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra |
1f3164f95f0ce40bac38ac384bf5fdd181ab5fa1 | importlib_metadata/__init__.py | importlib_metadata/__init__.py | from .api import (
Distribution, PackageNotFoundError, distribution, distributions,
entry_points, files, metadata, requires, version)
# Import for installation side-effects.
from . import _hooks # noqa: F401
__all__ = [
'Distribution',
'PackageNotFoundError',
'distribution',
'distributions',... | from .api import (
Distribution, PackageNotFoundError, distribution, distributions,
entry_points, files, metadata, requires, version)
# Import for installation side-effects.
__import__('importlib_metadata._hooks')
__all__ = [
'Distribution',
'PackageNotFoundError',
'distribution',
'distributi... | Use imperative import to avoid lint (import order) and as a good convention when side-effects is the intention. | Use imperative import to avoid lint (import order) and as a good convention when side-effects is the intention.
| Python | apache-2.0 | python/importlib_metadata |
fe92323dfa1067d552abefa60910e758500f0920 | virtool/handlers/files.py | virtool/handlers/files.py | import virtool.file
from virtool.handlers.utils import json_response
async def find(req):
db = req.app["db"]
cursor = db.files.find({"eof": True}, virtool.file.LIST_PROJECTION)
found_count = await cursor.count()
documents = [virtool.file.processor(d) for d in await cursor.to_list(15)]
return j... | import os
import virtool.file
import virtool.utils
from virtool.handlers.utils import json_response, not_found
async def find(req):
db = req.app["db"]
cursor = db.files.find({"ready": True}, virtool.file.LIST_PROJECTION)
found_count = await cursor.count()
documents = [virtool.file.processor(d) for... | Add uploaded file removal endpoint | Add uploaded file removal endpoint
| Python | mit | igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.