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 |
|---|---|---|---|---|---|---|---|---|---|
1667e4c28d969af615d028a4b828cc2c868957bc | tests/git_code_debt/list_metrics_test.py | tests/git_code_debt/list_metrics_test.py |
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.mark.integration
def test_list_metricssmoke():
# This test is just to make sure... |
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.yield_fixture
def print_mock():
with mock.patch.object(__builtin__, 'print', au... | Add integration test for --color never. | Add integration test for --color never.
| Python | mit | Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt |
14be519ba4bb09957865f1810c88c02f6b359c48 | tests/utilities/test_customtreeview.py | tests/utilities/test_customtreeview.py | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.utilities.customtreeview import CustomizedTreeView
class CustomTreeViewTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
def tearDown(self):
s... | from __future__ import absolute_import, print_function
import pytest
from addie.utilities.customtreeview import CustomizedTreeView
@pytest.fixture
def custom_tree_view(qtbot):
return CustomizedTreeView(None)
def test_get_selected_items(qtbot, custom_tree_view):
"""Test get_selected_items in tree of Customiz... | Refactor CustomTreeView test to use pytest-qt | Refactor CustomTreeView test to use pytest-qt
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR |
f3763c417d745463361b054fd4ffa0ddf35833eb | src/server/Universe.py | src/server/Universe.py | class Universe:
def __init__(self, height=100000000, width=100000000):
self.entities = []
self.height = height
self.width = width
self.teams = []
self.state = []
def add(self, entity):
self.entities.append(entity)
def remove(self, entity):
self.entities.remove(entity)
... | class Universe:
def __init__(self, height=100000000, width=100000000):
self.entities = []
self.height = height
self.width = width
self.teams = []
self.state = []
self.maxID = 0
def add(self, entity):
maxID += 1
entity.id = maxID
self.entities.append(entity)
def remove... | Add ID to Entity upon creation | Add ID to Entity upon creation
| Python | mit | cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim |
79d868ed68148b1e8f7c046b1ae9bb4b5a413c99 | base/components/accounts/admin.py | base/components/accounts/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.submitted_by = request.user
... | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form,... | Move the super() up on ContributorMixin. | Move the super() up on ContributorMixin.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
1da9b6538294744aa1d68ec6f48bebbbf5d714bb | bot/action/standard/admin/fail.py | bot/action/standard/admin/fail.py | from bot.action.core.action import Action
class FailAction(Action):
def process(self, event):
raise NotARealError("simulated error")
class NotARealError(Exception):
pass
| from bot.action.core.action import Action
class FailAction(Action):
def process(self, event):
if event.command_args == "fatal":
raise NotARealFatalError("simulated fatal error")
raise NotARealError("simulated error")
class NotARealError(Exception):
pass
class NotARealFatalError... | Allow to simulate fatal errors | Allow to simulate fatal errors
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
f0d629ae8b4568b2aceaf38779c8b07832e860b0 | teamspeak_web_utils.py | teamspeak_web_utils.py | import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_status = soup.find_all(class_='register_linklabel')[2].span
return not r... | import re
from bs4 import BeautifulSoup
import cfscrape
def nplstatus():
scraper = cfscrape.create_scraper()
data = scraper.get('http://npl.teamspeakusa.com/ts3npl.php').content
soup = BeautifulSoup(data, 'html.parser')
raw_status = soup.find_all(class_='register_linklabel')[2].span
return not r... | Clean string returned by website | Clean string returned by website
=> remove newline-characters and strip
| Python | mit | Thor77/TeamspeakIRC |
75eb6f93fff381953788a98aac8ee61bbf36c900 | apps/storybase/templatetags/verbatim.py | apps/storybase/templatetags/verbatim.py | """
Handlebars templates use constructs like:
{{if condition}} print something{{/if}}
This, of course, completely screws up Django templates,
because Django thinks {{ and }} mean something.
Wrap {% verbatim %} and {% endverbatim %} around those
blocks of Handlebars templates and this will try its best
to output ... | """
Handlebars templates use constructs like:
{{if condition}} print something{{/if}}
This, of course, completely screws up Django templates,
because Django thinks {{ and }} mean something.
Wrap {% verbatim %} and {% endverbatim %} around those
blocks of Handlebars templates and this will try its best
to output ... | Move register outside of guard | Move register outside of guard
Even if we don't load the ``verbatim`` tag backbport, the module
still needs to have a ``register`` variable.
Addresses #660
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase |
d7b532e83b30e429a9c87b52799c30dda6c4628c | plasmapy/physics/tests/test_dimensionless.py | plasmapy/physics/tests/test_dimensionless.py | from plasmapy.physics.dimensionless import (beta)
import astropy.units as u
B = 1.0 * u.T
n_i = 5e19 * u.m ** -3
T_e = 1e6 * u.K
def test_beta():
# Check that beta is dimensionless
float(beta(T_e, n_i, B))
| from plasmapy.physics.dimensionless import (beta)
import astropy.units as u
import numpy as np
B = 1.0 * u.T
n = 5e19 * u.m ** -3
T = 1e6 * u.K
def test_beta_dimensionless():
# Check that beta is dimensionless
float(beta(T, n, B))
def quantum_theta_dimensionless():
# Check that quantum theta is dimens... | Add test for beta passing through nans | Add test for beta passing through nans
| Python | bsd-3-clause | StanczakDominik/PlasmaPy |
4bfa6627b14c3e00e32b10a2806f02d4fafd6509 | chipy_org/libs/social_auth_pipelines.py | chipy_org/libs/social_auth_pipelines.py | from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with this email already exists. If they do, don't cr... | from django.contrib.auth import get_user_model
from django.utils.translation import ugettext
from social_auth.exceptions import AuthAlreadyAssociated
from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email
def associate_by_email(*args, **kwargs):
"""Check if a user with ... | Fix false positive for the social login | Fix false positive for the social login
| Python | mit | brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chicagopython/chipy.or... |
02095500794565fc84aee8272bfece1b39bc270f | examples/example_architecture_upload.py | examples/example_architecture_upload.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import datetime
from teamscale_client import TeamscaleClient
from teamscale_client.constants import CoverageFormats
TEAMSCALE_URL = "http://localhost:8080"
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import datetime
from teamscale_client import TeamscaleClient
from teamscale_client.constants import CoverageFormats
TEAMSCALE_URL = "http://localhost:8080"
... | Update example for architecture upload | Update example for architecture upload
| Python | apache-2.0 | cqse/teamscale-client-python |
e93c29e7d3bbb66da000ec46e1908b36c2c497e1 | lab_assistant/storage/__init__.py | lab_assistant/storage/__init__.py | from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_op... | from copy import deepcopy
from simpleflake import simpleflake
from lab_assistant import conf, utils
__all__ = [
'get_storage',
'store',
'retrieve',
'retrieve_all',
'clear',
]
def get_storage(path=None, name='Experiment', **opts):
if not path:
path = conf.storage['path']
_op... | Store results under correct experiment key | Store results under correct experiment key
| Python | mit | joealcorn/lab_assistant |
77f4fca43b1d4be85894ad565801d8a333008fdc | Lib/test/test_pep263.py | Lib/test/test_pep263.py | #! -*- coding: koi8-r -*-
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.assertEqual(
u"\".e... | #! -*- coding: koi8-r -*-
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it.
import unittest
from test import test_support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
u"".encode("utf-8"),
'\xd0\x9f\xd0\xb8\x... | Add a comment explaining -kb. | Add a comment explaining -kb.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
aaad392fedca6b3f9879240591877f6a64d907c3 | wordcloud/wordcloud.py | wordcloud/wordcloud.py | import os
from operator import itemgetter
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitline... | import os
from operator import itemgetter
from haystack.query import SearchQuerySet
from pombola.hansard import models as hansard_models
BASEDIR = os.path.dirname(__file__)
# normal english stop words and hansard-centric words to ignore
STOP_WORDS = open(os.path.join(BASEDIR, 'stopwords.txt'), 'rU').read().splitline... | Make maximum number of words a parameter | Make maximum number of words a parameter
| Python | agpl-3.0 | geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola |
baaa7e4818ac71898ff3b601d006f5e23d444bee | pyes/exceptions.py | pyes/exceptions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
... | Add exception type for script_fields related errors | Add exception type for script_fields related errors | Python | bsd-3-clause | jayzeng/pyes,rookdev/pyes,haiwen/pyes,mavarick/pyes,haiwen/pyes,mouadino/pyes,haiwen/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes,mavarick/pyes,aparo/pyes,aparo/pyes,mouadino/pyes,Fiedzia/pyes,mavarick/pyes,HackLinux/pyes,aparo/pyes,rookdev/pyes,Fiedzia/pyes,jayzeng/pyes,HackLinux/pyes |
032256c7e13cd6630b7c6da16c083ad5b622aa64 | pynuts/__init__.py | pynuts/__init__.py | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with da... | """__init__ file for Pynuts."""
import flask
from flask.ext.sqlalchemy import SQLAlchemy
import document
import view
class Pynuts(flask.Flask):
"""Create the Pynuts class.
:param import_name: Flask application name
:param config: Flask application configuration
:param reflect: Create models with da... | Add views in Pynuts init | Add views in Pynuts init
| Python | bsd-3-clause | Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts |
0de68abab608680d4ef390fea572828fb12b6abd | rounding/common.py | rounding/common.py | '''
Created on Oct 6, 2013
@author: dmaust
'''
import math
class RounderBase(object):
'''
Abstract base class for rounding
'''
def __init__(self, precision=0):
'''
Constructor
'''
self.precision = precision
self.cumulative_error = 0
def _get_fract... | '''
Created on Oct 6, 2013
@author: dmaust
'''
import math
class RounderBase(object):
'''
Abstract base class for rounding
'''
def __init__(self, precision=0):
'''
Constructor
'''
self.precision = precision
self.cumulative_error = 0
self.count = 0
... | Add average_roundoff to rounding base class. | Add average_roundoff to rounding base class.
| Python | apache-2.0 | dmaust/rounding |
b6a3890efc1716877eff7cce7f451df82cc3ca5c | services/heroku.py | services/heroku.py | import foauth.providers
class Heroku(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://heroku.com/'
docs_url = 'https://devcenter.heroku.com/articles/platform-api-reference'
category = 'Code'
# URLs to interact with the API
authorize_url = 'https://id.heroku.... | import foauth.providers
class Heroku(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'https://heroku.com/'
docs_url = 'https://devcenter.heroku.com/articles/platform-api-reference'
category = 'Code'
# URLs to interact with the API
authorize_url = 'https://id.heroku.... | Rewrite Heroku's scope handling a bit to better match reality | Rewrite Heroku's scope handling a bit to better match reality
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org |
c8422778e31888cbc02dc764af875114916e5f88 | smsviewer/views.py | smsviewer/views.py | from pyramid.view import view_config
from lxml import etree
@view_config(route_name='index', renderer='index.mako')
def my_view(request):
smsfile = "sms.xml"
with open(smsfile) as f:
tree = etree.parse(f)
root = tree.getroot()
return {"messages": sorted([e for e in root if e.get("contact_nam... | from pyramid.view import view_config
from lxml import etree
@view_config(route_name='index', renderer='index.mako')
def my_view(request):
smsfile = "sms.xml"
with open(smsfile) as f:
tree = etree.parse(f)
root = tree.getroot()
els = root.xpath("*[@contact_name='Lacey Shankle']")
return ... | Use xpath to find messages instead of a loop | Use xpath to find messages instead of a loop
| Python | mit | spiffytech/smsviewer,spiffytech/smsviewer |
dea4ed78fef278c2cb87b052c98a67940339835a | tagalog/_compat.py | tagalog/_compat.py | try:
from urlparse import urlparse
except ImportError: # Python3
from urllib import parse as urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| try:
from urlparse import urlparse
except ImportError: # Python3
from urllib.parse import urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| Fix compat module for Python 3 | Fix compat module for Python 3
| Python | mit | nickstenning/tagalog,alphagov/tagalog,alphagov/tagalog,nickstenning/tagalog |
aa78db30ad56262e7961013b523e69dacec26d60 | tests/util_test.py | tests/util_test.py | #!/usr/bin/python
import unittest
from decimal import Decimal
from blivet import util
class MiscTest(unittest.TestCase):
longMessage = True
def test_power_of_two(self):
self.assertFalse(util.power_of_two(None))
self.assertFalse(util.power_of_two("not a number"))
self.assertFalse(uti... | #!/usr/bin/python
import unittest
from decimal import Decimal
from blivet import util
class MiscTest(unittest.TestCase):
# Disable this warning, which will only be triggered on python3. For
# python2, the default is False.
longMessage = True # pylint: disable=pointless-class-attribute-override
... | Disable a pointless override warning. | Disable a pointless override warning.
This is a valid warning, but only on python3. On python2, the default
is False. I don't want to crud up the code with a bunch of conditionals
for stuff like this.
| Python | lgpl-2.1 | AdamWill/blivet,vpodzime/blivet,rvykydal/blivet,dwlehman/blivet,dwlehman/blivet,jkonecny12/blivet,rhinstaller/blivet,vpodzime/blivet,rhinstaller/blivet,rvykydal/blivet,vojtechtrefny/blivet,jkonecny12/blivet,vojtechtrefny/blivet,AdamWill/blivet |
1d9b0ac91bca0dd19f83507f9e27414334fdb756 | bin/commands/restash.py | bin/commands/restash.py | """Restash changes."""
import re
import sys
from subprocess import check_output, PIPE, Popen
from utils.messages import error
def restash(stash='stash@{0}'):
"""Restashes a stash reference."""
if re.match('^stash@{.*}$', stash) is None:
error('{} is not a valid stash reference'.format(stash))
... | """Restash changes."""
import os
import re
import sys
from subprocess import check_output, PIPE, Popen
from utils.messages import error
def _is_valid_stash(stash):
"""Determines if a stash reference is valid."""
if re.match('^stash@{.*}$', stash) is None:
return False
with open(os.devnull, 'w'... | Fix error messages for bad stash references | Fix error messages for bad stash references
| Python | mit | Brickstertwo/git-commands |
c7f7337b8f86786cd74f46cee9cff7f6d8eb8ec3 | config/test/__init__.py | config/test/__init__.py | from SCons.Script import *
import subprocess
import sys
import shlex
def run_tests(env):
subprocess.call(shlex.split(env.get('TEST_COMMAND')))
sys.exit(0)
def generate(env):
env.CBAddVariables(('TEST_COMMAND', 'Command to run for `test` target',
'tests/testHarness -C tests --no-c... | from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
subprocess.call(shlex.split(env.get('TEST_COMMAND')))
sys.exit(0)
def generate(env):
import os
cmd = 'tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-fa... | Use color output for tests outside of dockbot | Use color output for tests outside of dockbot
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang |
8639f4e32be8e264cca0831ecacec2d4a177cceb | citrination_client/models/design/target.py | citrination_client/models/design/target.py | from citrination_client.base.errors import CitrinationClientError
class Target(object):
"""
The optimization target for a design run. Consists of
the name of the output column to optimize and the objective
(either "Max" or "Min")
"""
def __init__(self, name, objective):
"""
Co... | from citrination_client.base.errors import CitrinationClientError
class Target(object):
"""
The optimization target for a design run. Consists of
the name of the output column to optimize and the objective
(either "Max" or "Min")
"""
def __init__(self, name, objective):
"""
Co... | Fix docstring for Target values | Fix docstring for Target values
| Python | apache-2.0 | CitrineInformatics/python-citrination-client |
ce04fc96bf6653419acb81db0f1894934517f33b | fireplace/cards/blackrock/collectible.py | fireplace/cards/blackrock/collectible.py | from ..utils import *
##
# Minions
# Flamewaker
class BRM_002:
events = [
OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2)
]
# Imp Gang Boss
class BRM_006:
events = [
Damage(SELF).on(Summon(CONTROLLER, "BRM_006t"))
]
##
# Spells
# Solemn Vigil
class BRM_001:
action = [Draw(CONTROLLER) * 2]
def c... | from ..utils import *
##
# Minions
# Flamewaker
class BRM_002:
events = [
OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2)
]
# Imp Gang Boss
class BRM_006:
events = [
Damage(SELF).on(Summon(CONTROLLER, "BRM_006t"))
]
# Dark Iron Skulker
class BRM_008:
action = [Hit(ENEMY_MINIONS - DAMAGED, 2)]
# ... | Implement Dark Iron Skulker and Volcanic Lumberer | Implement Dark Iron Skulker and Volcanic Lumberer
| Python | agpl-3.0 | oftc-ftw/fireplace,NightKev/fireplace,Meerkov/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,Ragowit/fireplace,Meerkov/fireplace,amw2104/fireplace,amw2104/fireplace,jleclanche/fireplace,liujimj/fireplace,beheh/fireplace,butozerca/fireplace,butozerca/fi... |
87b5fe729ef398722c2db1c8eb85a96f075ef82c | examples/GoBot/gobot.py | examples/GoBot/gobot.py | from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
import math
import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15))
self.r... | """
GoBot Example
"""
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
"""
GoBot
"""
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN... | Fix linting errors in GoBot | Fix linting errors in GoBot
| Python | apache-2.0 | cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot |
b7438eb833887c207cc8b848e549a30c7a981373 | polling_stations/apps/data_finder/forms.py | polling_stations/apps/data_finder/forms.py | from django import forms
from localflavor.gb.forms import GBPostcodeField
class PostcodeLookupForm(forms.Form):
postcode = GBPostcodeField(label="Enter your postcode")
class AddressSelectForm(forms.Form):
address = forms.ChoiceField(
choices=(),
label="",
initial="",
widget=... | from django import forms
from django.utils.translation import gettext_lazy as _
from localflavor.gb.forms import GBPostcodeField
class PostcodeLookupForm(forms.Form):
postcode = GBPostcodeField(label=_("Enter your postcode"))
class AddressSelectForm(forms.Form):
address = forms.ChoiceField(
choices... | Mark "Enter your postcode" for translation in a form field label | Mark "Enter your postcode" for translation in a form field label
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
bb82e3a8519009311ede80f877844565c49384b4 | examples/qidle/qidle.py | examples/qidle/qidle.py | #! /usr/bin/python3
# -*- coding: utf-8 -*-
from qidle import main
import logging
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
main()
| #! /usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from qidle import main
import logging
if __name__ == '__main__':
filename = None
if sys.platform == 'win32':
filename = 'qidle.log'
logging.basicConfig(level=logging.INFO, filename=filename)
main()
| Add a log file on windows | Add a log file on windows
| Python | mit | pyQode/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python,mmolero/pyqode.python |
e1f15a29bb947666740ec250120e3bdf451f0477 | pythonwarrior/towers/beginner/level_006.py | pythonwarrior/towers/beginner/level_006.py | # --------
# |C @ S aa|
# --------
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.")
level.tip("You can walk backward by passing 'backward' as an argument to walk_. Same goes for feel, rescue_ and attack_. Archers have a limited attack distance.")
level... | # --------
# |C @ S aa|
# --------
level.description("The wall behind you feels a bit further away in this room. And you hear more cries for help.")
level.tip("You can walk backward by passing 'backward' as an argument to warrior.walk_. Same goes for warrior.feel, warrior.rescue_ and warrior.attack_. Archers have a ... | Update description of the level 06 | Update description of the level 06 | Python | mit | arbylee/python-warrior |
72358efa2bf9ff45377ef8ab3478b9433c67c574 | candidates/feeds.py | candidates/feeds.py | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from .models import LoggedAction
class RecentChangesFeed(Feed):
title = "YourNextMP recent changes"
description = "Changes to YNMP candidates"
link = "/feeds/chan... | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from .models import LoggedAction
class RecentChangesFeed(Feed):
title = "YourNextMP recent changes"
description = "Changes to YNMP candidates"
link = "/feeds/chan... | Remove IP address from feed description | Remove IP address from feed description
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yourn... |
20cc6c1edca69c946261c6bd8587d6cf5bb7a6e8 | tests/core/eth-module/test_eth_contract.py | tests/core/eth-module/test_eth_contract.py | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, ... | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, ... | Replace duplicate test with valid address kwarg | Replace duplicate test with valid address kwarg
| Python | mit | pipermerriam/web3.py |
16765ebf41e2c7adea3ed1c1021bf1ca9db83d15 | fmn/lib/__init__.py | fmn/lib/__init__.py | """ fedmsg-notifications internal API """
import fmn.lib.models
import logging
log = logging.getLogger(__name__)
def recipients(session, config, valid_paths, message):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"... | """ fedmsg-notifications internal API """
import fmn.lib.models
import inspect
import logging
log = logging.getLogger(__name__)
def recipients(session, config, valid_paths, message):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of re... | Use inspect to get the list of arguments each filter accepts | Use inspect to get the list of arguments each filter accepts | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn |
0d8a9a83fdd896aa5690c1c32db1d1658748a94a | tests/test_schemaorg.py | tests/test_schemaorg.py | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.... | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.... | Add test coverage for expected nutrient retrieval behaviour | Add test coverage for expected nutrient retrieval behaviour
| Python | mit | hhursev/recipe-scraper |
1f3f0b50d8cd740e09983b3dbd8796f1e4afa66c | linkatos/message.py | linkatos/message.py | import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = url_re.search(message)
if answer is not None:
answer = answer.group(1).strip()
return ans... | import re
url_re = re.compile("(?:\s|^)<(https?://[\w./?+&+%$!#=\-_]+)>(?:\s|$)")
purge_re = re.compile("(purge) (\d+)")
list_re = re.compile("list")
def extract_url(message):
"""
Returns the first url in a message. If there aren't any returns None
"""
answer = url_re.search(message)
if answer is... | Change location of regex compilation | refactor: Change location of regex compilation
| Python | mit | iwi/linkatos,iwi/linkatos |
e5c8379c987d2d7ae60d5f9321bb96f278549167 | apel/parsers/__init__.py | apel/parsers/__init__.py | '''
Copyright (C) 2012 STFC
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 writi... | '''
Copyright (C) 2012 STFC
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 writi... | Add HTCondorParser to init imports | Add HTCondorParser to init imports
| Python | apache-2.0 | apel/apel,tofu-rocketry/apel,tofu-rocketry/apel,stfc/apel,apel/apel,stfc/apel |
fdcc7f0e45fe5f0d284f47941238a92cbe9a1b36 | attest/tests/__init__.py | attest/tests/__init__.py | from attest import Tests
suite = lambda mod: 'attest.tests.' + mod + '.suite'
all = Tests([suite('asserts'),
suite('collections'),
suite('classy'),
suite('reporters'),
suite('eval'),
])
| from attest import Tests
all = Tests('.'.join((__name__, mod, 'suite'))
for mod in ('asserts',
'collections',
'classy',
'reporters',
'eval'))
| Simplify our own test suite | Simplify our own test suite
| Python | bsd-2-clause | dag/attest |
012f93ae03aded72b64ac9bbfb6d2995199d4d8f | tests/test_api_views.py | tests/test_api_views.py | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory = APIRequ... | import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import django
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.webview.views import DocumentList, status
django.setup()
class APIViewTests(TestCase):
def setUp(self):
self.factory =... | Add test for status view | Add test for status view
| Python | apache-2.0 | erinspace/scrapi,erinspace/scrapi,felliott/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi |
0168836c6bb2c04ac7a9d4ac6682fca47512ea4c | tests/test_cli_parse.py | tests/test_cli_parse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix, sample):
runner = CliRunner()
with tempfile.NamedTempor... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
@pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom'])
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefi... | Add tests for parse CLI with pos_kind | Add tests for parse CLI with pos_kind
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
b1a91fc4e843197a12be653aa60d5cdf32f31423 | tests/test_recursion.py | tests/test_recursion.py | from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
assert uwhois.get_registrar_w... | from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
server, port = uwhois.get_who... | Fix test for the fork | Fix test for the fork
| Python | mit | Rafiot/uwhoisd,Rafiot/uwhoisd |
754d2949ce0c2fa2b36615af755b3b8aaf9876b5 | tests/test_resources.py | tests/test_resources.py | import pytest
from micromanager.resources import Resource
from micromanager.resources import BQDataset
from micromanager.resources import Bucket
from micromanager.resources import SQLInstance
test_cases = [
(
{'resource_kind': 'storage#bucket'},
Bucket
),
(
{'resource_kind': 'sql#i... | import pytest
from .util import load_test_data
from .util import discovery_cache
from .mock import HttpMockSequenceEx
from googleapiclient.http import HttpMockSequence
from micromanager.resources import Resource
from micromanager.resources.gcp import GcpBigqueryDataset
from micromanager.resources.gcp import GcpComp... | Update tests after lots of work on Resources | Update tests after lots of work on Resources
| Python | apache-2.0 | forseti-security/resource-policy-evaluation-library |
0b32ae7a09dd961f379104b6628eaf5700cca785 | tests/test_unlocking.py | tests/test_unlocking.py | # Tests for SecretStorage
# Author: Dmitry Shachnev, 2018
# License: 3-clause BSD, see LICENSE file
import unittest
from secretstorage import dbus_init, get_any_collection
from secretstorage.util import BUS_NAME
from secretstorage.exceptions import LockedException
@unittest.skipIf(BUS_NAME == "org.freedesktop.secre... | # Tests for SecretStorage
# Author: Dmitry Shachnev, 2018
# License: 3-clause BSD, see LICENSE file
import unittest
from secretstorage import dbus_init, Collection
from secretstorage.util import BUS_NAME
from secretstorage.exceptions import LockedException
@unittest.skipIf(BUS_NAME == "org.freedesktop.secrets",
... | Add test coverage for Item.ensure_not_locked() method | Add test coverage for Item.ensure_not_locked() method
| Python | bsd-3-clause | mitya57/secretstorage |
bbeb9b780908cf1322722669f1c68259345fe261 | readthedocs/v3/routers.py | readthedocs/v3/routers.py | from rest_framework.routers import DefaultRouter
from rest_framework_extensions.routers import NestedRouterMixin
class DefaultRouterWithNesting(NestedRouterMixin, DefaultRouter):
pass
| from rest_framework.routers import DefaultRouter, APIRootView
from rest_framework_extensions.routers import NestedRouterMixin
class DocsAPIRootView(APIRootView):
# Overridden only to add documentation for BrowsableAPIRenderer.
"""
Read the Docs APIv3 root endpoint.
Full documentation at [https://do... | Add documentation to the root view of BrowsableAPI | Add documentation to the root view of BrowsableAPI
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org |
20696d6f236afc1bc0e2b3db570363540e70ca84 | test/test_serve.py | test/test_serve.py | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run()
class TestServe(unittest.TestCase):
def test_simple(self):
... | import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run(host='127.0.0.1')
class TestServe(unittest.TestCase):
def test_sim... | Use ip instead of localhost for travis | Use ip instead of localhost for travis
| Python | mit | witchard/grole |
bfbb1e4fb8324df9a039c18359c053190f9e7e64 | dusty/commands/manage_config.py | dusty/commands/manage_config.py | import textwrap
from prettytable import PrettyTable
from ..config import get_config, save_config_value
from .. import constants
from ..log import log_to_client
def _eligible_config_keys_for_setting():
config = get_config()
return [key for key in sorted(constants.CONFIG_SETTINGS.keys())
if key ... | import textwrap
from prettytable import PrettyTable
from ..config import get_config, save_config_value
from .. import constants
from ..log import log_to_client
def _eligible_config_keys_for_setting():
config = get_config()
return [key for key in sorted(constants.CONFIG_SETTINGS.keys())
if key ... | Make config list able to handle long values | Make config list able to handle long values
| Python | mit | gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty |
d34fbc70d5873d159c311caed41b745b05534ce9 | lib/solution.py | lib/solution.py | class Solution:
def __init__(self, nr):
self.nr = nr
self.test = False
self.input = ""
self.solution = ["(not calculated)", "(not calculated)"]
self.calculated = [False, False]
def __str__(self):
return "Solution 1: {}\nSolution 2: {}".format(self.solution[0], se... | class Solution:
def __init__(self, nr):
self.nr = nr
self.test = False
self.input = ""
self.solution = ["(not calculated)", "(not calculated)"]
self.calculated = [False, False]
def __str__(self):
return "Solution 1: {}\nSolution 2: {}".format(self.solution[0], se... | Read Input: Read file complete or by lines | Read Input: Read file complete or by lines
| Python | mit | unstko/adventofcode2016 |
0f8b6f4a12c23e5498e8135a3f39da40c4333788 | tests/hexdumper.py | tests/hexdumper.py | # This hack by: Raymond Hettinger
class hexdumper:
"""Given a byte array, turn it into a string. hex bytes to stdout."""
def __init__(self):
self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \
for x in range(256)])
def dump(self, src, length=8):
result=[]
for i in xrange(0, len(src... | # This hack by: Raymond Hettinger
class hexdumper:
"""Given a byte array, turn it into a string. hex bytes to stdout."""
def __init__(self):
self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \
for x in range(256)])
# pretty dumping hate machine.
def dump(self, src, length=8):
re... | Add a function which allows packet dumps to be produced easily for inserting into regression tests. | Add a function which allows packet dumps to be produced
easily for inserting into regression tests.
| Python | bsd-3-clause | gvnn3/PCS,gvnn3/PCS |
06e84c25bb783490c963963ccb44cf07d521a197 | spam_lists/exceptions.py | spam_lists/exceptions.py | # -*- coding: utf-8 -*-
class SpamBLError(Exception):
''' Base exception class for spambl module '''
class UnknownCodeError(SpamBLError):
''' Raise when trying to use an unexpected value of dnsbl return code '''
class UnathorizedAPIKeyError(SpamBLError):
''' Raise when trying to use an unathorize... | # -*- coding: utf-8 -*-
class SpamBLError(Exception):
'''There was an error during testing a url or host'''
class UnknownCodeError(SpamBLError):
'''The classification code from the service was not recognized'''
class UnathorizedAPIKeyError(SpamBLError):
'''The API key used to query the service wa... | Reword docstrings for exception classes | Reword docstrings for exception classes
| Python | mit | piotr-rusin/spam-lists |
4ca292e53710dd4ef481e7fa5965e22d3f94e65b | l10n_br_account_payment_order/models/cnab_return_move_code.py | l10n_br_account_payment_order/models/cnab_return_move_code.py | # Copyright 2020 Akretion
# @author Magno Costa <magno.costa@akretion.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, api, fields
class CNABReturnMoveCode(models.Model):
"""
CNAB return code, each Bank can has a list of Codes
"""
_name = 'cnab.retu... | # Copyright 2020 Akretion
# @author Magno Costa <magno.costa@akretion.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, api, fields
class CNABReturnMoveCode(models.Model):
"""
CNAB return code, each Bank can has a list of Codes
"""
_name = 'cnab.retu... | Index and code improve cnab.return.move.code | [REF] Index and code improve cnab.return.move.code
Signed-off-by: Luis Felipe Mileo <c9a5b4d335634d99740001a1172b3e56e4fc5aa8@kmee.com.br>
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil |
440fcebdcc06c0fbb26341764a0df529cec6587d | flask_wiki/frontend/frontend.py | flask_wiki/frontend/frontend.py | from flask import Flask, render_template, abort, redirect, url_for
from flask.ext.script import Manager
from jinja2 import TemplateNotFound
app = Flask(__name__)
app.config['TESTING'] = True
manager = Manager(app)
@app.route('/', endpoint='frontend-index')
def root():
# Redirect Base URL for the real Index Page... | from flask import Flask, render_template, abort, redirect, url_for
from flask.ext.script import Manager
from jinja2 import TemplateNotFound
app = Flask(__name__)
app.config['TESTING'] = True
manager = Manager(app)
@app.route('/', endpoint='frontend-index')
def root():
# Redirect Base URL for the real Index Page.... | Support for angular + API added. | Support for angular + API added.
| Python | bsd-2-clause | gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki,gcavalcante8808/flask-wiki |
fb6e5b11492675b7a7c94424737c91acbb541d69 | tests/test_message_body.py | tests/test_message_body.py | from tddcommitmessage.messagebody import MessageBody
from tddcommitmessage import Kind
def test_message_is_wrapped_in_quotes():
msg = MessageBody(Kind.red, 'Forty-two')
assert str(msg) == '"RED Forty-two"'
def test_message_with_double_quote_is_wrapped_with_single():
msg = MessageBody(Kind.red, 'But what a... | from tddcommitmessage.messagebody import MessageBody
from tddcommitmessage import Kind
def test_message_is_wrapped_in_quotes():
msg = MessageBody(Kind.red, 'Forty-two')
assert str(msg) == '"RED Forty-two"'
def test_first_letter_capitalised():
msg = MessageBody(Kind.red, 'forty-two')
assert str(msg) ==... | REFACTOR Change order of tests. | REFACTOR Change order of tests.
| Python | mit | matatk/tdd-bdd-commit,matatk/tdd-bdd-commit |
8ac142af2afc577a47197fe9bc821cb796883f38 | virtual_machine.py | virtual_machine.py | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
se... | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
se... | Check for autoincrement before executing the instruction | Check for autoincrement before executing the instruction
| Python | bsd-3-clause | darbaga/simple_compiler |
de60844c82c9b569228aa830d36235b5a377859d | rpath_tools/client/sysdisco/descriptors.py | rpath_tools/client/sysdisco/descriptors.py | #!/usr/bin/python
from xml.etree import cElementTree as etree
from conary import conarycfg
from conary import conaryclient
from rpath_tools.client.utils.config_descriptor_cache import ConfigDescriptorCache
class Descriptors(object):
def __init__(self):
self.cfg = conarycfg.ConaryConfiguration(True)
... | #!/usr/bin/python
from xml.etree import cElementTree as etree
from conary import conarycfg
from conary import conaryclient
from rpath_tools.client.utils.config_descriptor_cache import ConfigDescriptorCache
class Descriptors(object):
def __init__(self):
self.cfg = conarycfg.ConaryConfiguration(True)
... | Fix descriptor module to support assimilation | Fix descriptor module to support assimilation
| Python | apache-2.0 | sassoftware/rpath-tools,sassoftware/rpath-tools |
853744e82f2740a47a3f36e003ea8d2784bafff6 | accelerator/tests/factories/user_deferrable_modal_factory.py | accelerator/tests/factories/user_deferrable_modal_factory.py | import swapper
from datetime import (
datetime,
timedelta,
)
from factory import SubFactory
from factory.django import DjangoModelFactory
from simpleuser.tests.factories.user_factory import UserFactory
from .deferrable_modal_factory import DeferrableModalFactory
UserDeferrableModal = swapper.load_model('accel... | import swapper
from datetime import (
datetime,
timedelta,
)
from factory import SubFactory
from factory.django import DjangoModelFactory
from pytz import utc
from simpleuser.tests.factories.user_factory import UserFactory
from .deferrable_modal_factory import DeferrableModalFactory
UserDeferrableModal = swa... | Fix bare datetime.now() in factory | [AC-8673] Fix bare datetime.now() in factory
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator |
e0b7217caaf4b94c879f43f2ee95584c469687db | csrv/model/read_o8d.py | csrv/model/read_o8d.py | # Read an OCTGN deck
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
... | # Read an OCTGN deck
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
... | Fix o8d importer to read card IDs to make the sanitized cards | Fix o8d importer to read card IDs to make the sanitized cards
| Python | apache-2.0 | mrroach/CentralServer,mrroach/CentralServer,mrroach/CentralServer |
eac2211956d49d9da957492bbac1bcdc85b1e40d | openprescribing/frontend/management/commands/load_development_data.py | openprescribing/frontend/management/commands/load_development_data.py | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in local development'
def handle(self, *args, **options):
... | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.models import ImportLog, PPUSaving
from frontend.tests.test_api_spending import ApiTestBase, TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in lo... | Add extra development data so the All England page loads | Add extra development data so the All England page loads
Previously the absence of the PPU ImportLog entry caused the page to
throw an error.
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing |
fa2ecdc0bcb30415699baf4f014b390d4473d43c | photutils/psf/__init__.py | photutils/psf/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains tools to perform point-spread-function (PSF)
photometry.
"""
from .epsf import * # noqa
from .epsf_stars import * # noqa
from .groupstars import * # noqa
from .matching import * # noqa
from .models import * # noqa
from .p... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains tools to perform point-spread-function (PSF)
photometry.
"""
from . import epsf
from .epsf import * # noqa
from . import epsf_stars
from .epsf_stars import * # noqa
from . import groupstars
from .groupstars import * # noqa
... | Fix Sphinx warnings about duplicate objects | Fix Sphinx warnings about duplicate objects
| Python | bsd-3-clause | astropy/photutils,larrybradley/photutils |
6055b7eb6b34ed22eb3c7cd17a975d4728be1360 | msmbuilder/tests/test_sampling.py | msmbuilder/tests/test_sampling.py | import numpy as np
from msmbuilder.decomposition import tICA
from msmbuilder.io.sampling import sample_dimension
def test_sample_dimension():
np.random.seed(42)
X = np.random.randn(500, 5)
data = [X, X, X]
tica = tICA(n_components=2, lag_time=1).fit(data)
tica_trajs = {k: tica.partial_transform(... | import numpy as np
from msmbuilder.decomposition import tICA
from msmbuilder.io.sampling import sample_dimension
def test_sample_dimension():
np.random.seed(42)
X = np.random.randn(500, 5)
data = [X, X, X]
tica = tICA(n_components=2, lag_time=1).fit(data)
tica_trajs = {k: tica.partial_transform(... | Add test for new edge sampling | Add test for new edge sampling
I think it would've failed before | Python | lgpl-2.1 | Eigenstate/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msmbuilder/msmbuilder,Eigenstate/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,brookehus/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msmbuilder/msmbuilder,brookehus/msmbuilder,msmbuilder/msmbuilder,Eigenstate/msmbui... |
cebd4f1ee9a87cc2652ebf8981df20121ec257b2 | steel/fields/numbers.py | steel/fields/numbers.py | import struct
from steel.fields import Field
__all__ = ['Integer']
class Integer(Field):
"An integer represented as a sequence and bytes"
# These map a number of bytes to a struct format code
size_formats = {
1: 'B', # char
2: 'H', # short
4: 'L', # long
8: 'Q', # lon... | import struct
from steel.fields import Field
__all__ = ['Integer']
class Integer(Field):
"An integer represented as a sequence and bytes"
# These map a number of bytes to a struct format code
size_formats = {
1: 'B', # char
2: 'H', # short
4: 'L', # long
8: 'Q', # lon... | Raise ValueError instead of struct.error | Raise ValueError instead of struct.error
The protocol for field encoding and decoding is to raise ValueError, so this is a necessary translation.
| Python | bsd-3-clause | gulopine/steel-experiment |
fc73dfb33f4e19d649672f19a1dc4cf09b229d29 | echo_server.py | echo_server.py | #! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
... | #! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket
def response_ok():
"""Return byte string 200 ok response."""
return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')
def reponse_error(error... | Add response_ok and response_error methods which return byte strings. | Add response_ok and response_error methods which return byte strings.
| Python | mit | bm5w/network_tools |
de2e3dd947660b4b1222820141c5c7cd66098349 | django_split/models.py | django_split/models.py | from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
user = models.ForeignKey('auth.User', related_name=None)
group = models.IntegerField()
class Meta:
unique_together = (
('experiment', 'user'),
)
class Experimen... | from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
user = models.ForeignKey(
'auth.User',
related_name='django_split_experiment_groups',
)
group = models.IntegerField()
class Meta:
unique_together = (
... | Add an explicit related name | Add an explicit related name
| Python | mit | prophile/django_split |
4299f4f410f768066aaacf885ff0a38e8af175c9 | intro-django/readit/books/forms.py | intro-django/readit/books/forms.py | from django import forms
from .models import Book
class ReviewForm(forms.Form):
"""
Form for reviewing a book
"""
is_favourite = forms.BooleanField(
label = 'Favourite?',
help_text = 'In your top 100 books of all time?',
required = False,
)
review = forms.CharField(
widget = forms.Textarea,
min_lengt... | from django import forms
from .models import Book
class ReviewForm(forms.Form):
"""
Form for reviewing a book
"""
is_favourite = forms.BooleanField(
label = 'Favourite?',
help_text = 'In your top 100 books of all time?',
required = False,
)
review = forms.CharField(
widget = forms.Textarea,
min_lengt... | Add custom form validation enforcing that each new book is unique | Add custom form validation enforcing that each new book is unique
| Python | mit | nirajkvinit/python3-study,nirajkvinit/python3-study,nirajkvinit/python3-study,nirajkvinit/python3-study |
ddeffc09ce1eab426fe46129bead712059f93f45 | docker/settings/web.py | docker/settings/web.py | from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
# Needed to serve 404 pages properly
# NOTE: it may introduce some strange behavior
DEBUG = False
WebDevSettings.load_settings(__name__)
| from .docker_compose import DockerBaseSettings
class WebDevSettings(DockerBaseSettings):
pass
WebDevSettings.load_settings(__name__)
| Remove DEBUG=False that's not needed anymore | Remove DEBUG=False that's not needed anymore
Now we are serving 404s via El Proxito and forcing DEBUG=False is not
needed anymore.
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org |
01e1900a139d7525a0803d5a160a9d91210fe219 | csv2kmz/csv2kmz.py | csv2kmz/csv2kmz.py | import os
import argparse
from buildkmz import create_kmz_from_csv
def main():
""" Build file as per user inputs
"""
args = get_cmd_args()
iPath = args.input
sPath = args.styles
oDir = args.output
create_kmz_from_csv(iPath,sPath,oDir)
def get_cmd_args():
"""Get, proc... | import os
import argparse
import logging
from buildkmz import create_kmz_from_csv
def main():
""" Build file as per user inputs
"""
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)
args = get_cmd_args()
iPath = args.input
sPath = args.s... | Add logging output when called from command line | Add logging output when called from command line | Python | mit | aguinane/csvtokmz |
984c395e3f43764a4d8125aea7556179bb4766dd | test/_mysqldb_test.py | test/_mysqldb_test.py | '''
$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 211
Server version: 5.6.15 Homebrew
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks... | import mysql.connector
from luigi.contrib.mysqldb import MySqlTarget
import unittest
host = 'localhost'
port = 3306
database = 'luigi_test'
username = None
password = None
table_updates = 'table_updates'
def _create_test_database():
con = mysql.connector.connect(user=username,
p... | Remove the doc that describes the setup. Setup is automated now | Remove the doc that describes the setup. Setup is automated now
| Python | apache-2.0 | moritzschaefer/luigi,kalaidin/luigi,riga/luigi,foursquare/luigi,dylanjbarth/luigi,Dawny33/luigi,harveyxia/luigi,graingert/luigi,slvnperron/luigi,harveyxia/luigi,sahitya-pavurala/luigi,hadesbox/luigi,rayrrr/luigi,humanlongevity/luigi,Tarrasch/luigi,Magnetic/luigi,percyfal/luigi,torypages/luigi,stroykova/luigi,theoryno3/... |
a48f651435d212907cb34164470a9028ba161300 | test/test_vasp_raman.py | test/test_vasp_raman.py | # -*- coding: utf-8 -*-
import os
import time
import unittest
import vasp_raman
class VaspRamanTester(unittest.TestCase):
def testMAT_m_VEC(self):
self.assertTrue(False)
| # -*- coding: utf-8 -*-
import os
import time
import unittest
import vasp_raman
class VaspRamanTester(unittest.TestCase):
def testT(self):
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
mref = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
mres = vasp_raman.T(m)
for i in range(len(m)):
self.... | Add a test for vasp_raman.T | Add a test for vasp_raman.T
| Python | mit | raman-sc/VASP,raman-sc/VASP |
eed78d3a671aee0fcc0760f15087085f2918da6c | travis_ci/settings.py | travis_ci/settings.py | """GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'... | """GeoKey settings."""
from geokey.core.settings.dev import *
DEFAULT_FROM_EMAIL = 'no-reply@travis-ci.org'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'geokey',
'... | Add "localhost" in the allowed hosts for testing purposes | Add "localhost" in the allowed hosts for testing purposes
| Python | mit | ExCiteS/geokey-epicollect,ExCiteS/geokey-epicollect |
0e46b47a3053e63f50d6fd90b1ba810e4694c9be | blo/__init__.py | blo/__init__.py | from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, db_file_path, template_dir=""):
self.template_dir = template_dir
# create tables
self.db_file_path = db_file_path
self.db_control = DBControl(self.db_file_path)
self.db_c... | import configparser
from blo.BloArticle import BloArticle
from blo.DBControl import DBControl
class Blo:
def __init__(self, config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
self.template_dir = config['TEMPLATE']['TEMPLATE_DIR']
self.db_file_path... | Implement system configurations load from file. | Implement system configurations load from file.
| Python | mit | 10nin/blo,10nin/blo |
91d24b3ce272ff166d1e828f0822e7b9a0124d2c | tests/test_dataset.py | tests/test_dataset.py | import pytest
from zfssnap import Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = '... | import pytest
from zfssnap import autotype, Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ss... | Fix broken tests after moving _autoconvert to autotype | Fix broken tests after moving _autoconvert to autotype
| Python | mit | hkbakke/zfssnap,hkbakke/zfssnap |
a0a1606d115efd3521ac957aa9a39efec60eda8c | tests/test_issuers.py | tests/test_issuers.py | from mollie.api.objects.issuer import Issuer
from .utils import assert_list_object
def test_get_issuers(client, response):
"""Get all the iDeal issuers via the include querystring parameter."""
response.get('https://api.mollie.com/v2/methods/ideal?include=issuers', 'method_get_ideal_with_includes')
issu... | from mollie.api.objects.issuer import Issuer
from .utils import assert_list_object
def test_get_issuers(client, response):
"""Get all the iDeal issuers via the include querystring parameter."""
response.get('https://api.mollie.com/v2/methods/ideal?include=issuers', 'method_get_ideal_with_includes')
issu... | Test the first item of the list, not the last | Test the first item of the list, not the last
| Python | bsd-2-clause | mollie/mollie-api-python |
1ccd9e7f15cfaccfadf7e4e977dbde724885cab9 | tests/test_sync_call.py | tests/test_sync_call.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Tests for synchronous call helper
"""
import time
from switchy import sync_caller
from switchy.apps.players import To... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Tests for synchronous call helper
"""
import time
from switchy import sync_caller
from switchy.apps.players import To... | Add a `PlayRec` app unit test | Add a `PlayRec` app unit test
Merely checks that all sessions are recorded as expected and that the call
is hung up afterwards. None of the recorded audio content is verified.
| Python | mpl-2.0 | sangoma/switchy,wwezhuimeng/switch |
8793b1a2c4adf480534cf2a669337032edf77020 | golang/main.py | golang/main.py | #!/usr/bin/env python
from evolution_master.runners import pkg, download
# Install for Arch
with pkg.pacman() as pkg_man:
pkg_man.install('go')
# Install for Debian & Ubuntu
with pkg.apt() as pkg_man:
pkg_man.install('golang')
# Install for OSX
with pkg.brew() as pkg_man:
pkg_man.install('go')
# Instal... | from evolution_master.runners import pkg, download
# Install for Arch
with pkg.pacman() as pkg_man:
pkg_man.install('go')
# Install for Debian & Ubuntu
with pkg.apt() as pkg_man:
pkg_man.install('golang')
# Install for OSX
with pkg.brew() as pkg_man:
pkg_man.install('go')
# Install for Windows
with dow... | Remove header, this will be imported by a runner | Remove header, this will be imported by a runner | Python | mit | hatchery/Genepool2,hatchery/genepool |
6f24aa5e1e1ff78e95ed17ff75acc2646280bdd8 | typedmarshal/util.py | typedmarshal/util.py | def pretty_print_recursive(obj, indent=0):
def i_print(s):
print(' ' * indent + s)
if obj is None:
i_print('None')
elif isinstance(obj, (int, float, str)):
i_print(f'{obj}')
elif isinstance(obj, list):
for l in obj:
pretty_print_recursive(l, indent=indent+2)
... | def pretty_print_recursive(obj, indent=0):
def i_print(s):
print(' ' * indent + s)
if obj is None:
i_print('None')
elif isinstance(obj, (int, float, str)):
i_print(f'{obj}')
elif isinstance(obj, list):
for l in obj:
pretty_print_recursive(l, indent=indent+2)
... | Add None identifier / repr print | Add None identifier / repr print
| Python | bsd-3-clause | puhitaku/typedmarshal |
4c8dd2b074d2c2227729ff0bd87cf60d06e97485 | retry.py | retry.py | # Define retry util function
class RetryException(Exception):
pass
def retry(func, max_retry=10):
"""
@param func: The function that needs to be retry
(to pass function with arguments use partial object)
@param max_retry: Maximum retry of `func` function, default is `10`
@return... | # Helper script with retry utility function
# set logging for `retry` channel
import logging
logger = logging.getLogger('retry')
# Define Exception class for retry
class RetryException(Exception):
DESCRIPTION = "Exception ({}) raised after {} tries."
def __init__(self, exception, max_retry):
self.ex... | Extend custom exception and add additional logging | Extend custom exception and add additional logging | Python | mit | duboviy/misc |
c2138a35123969651212b1d9cd6cdefef89663ec | openedx/core/djangoapps/programs/migrations/0003_auto_20151120_1613.py | openedx/core/djangoapps/programs/migrations/0003_auto_20151120_1613.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('programs', '0002_programsapiconfig_cache_ttl'),
]
operations = [
migrations.AddField(
model_name='programsapicon... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('programs', '0002_programsapiconfig_cache_ttl'),
]
operations = [
migrations.AddField(
model_name='programsapicon... | Modify existing Programs migration to account for help_text change | Modify existing Programs migration to account for help_text change
Prevents makemigrations from creating a new migration for the programs app.
| Python | agpl-3.0 | shurihell/testasia,fintech-circle/edx-platform,doganov/edx-platform,synergeticsedx/deployment-wipro,proversity-org/edx-platform,stvstnfrd/edx-platform,shurihell/testasia,amir-qayyum-khan/edx-platform,RPI-OPENEDX/edx-platform,analyseuc3m/ANALYSE-v1,kmoocdev2/edx-platform,devs1991/test_edx_docmode,UOMx/edx-platform,solas... |
f2eb45ea24429fd3e4d32a490dbe3f8a2f383d9f | scuole/stats/models/base.py | scuole/stats/models/base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
from .postsecondary_readiness import PostSecondaryReadinessBase
@python_2_unicode_compatible
class S... | Add postsecondary stats to the StatsBase model | Add postsecondary stats to the StatsBase model
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole |
26d3b8eb1992b19aebe8f0e3eae386e8b95822fb | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages, Command
import os
packages = find_packages()
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, Command
import os
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno =... | Switch to distutils, fix install for py3.4 | Switch to distutils, fix install for py3.4
setuptools is goddamned terrible | Python | mit | njvack/scorify |
fcd6af0a2a02ef87eedd78aa3c09836cc0799a29 | utils/python_version.py | utils/python_version.py | #! /usr/bin/env python
"""Print Python interpreter path and version."""
import sys
sys.stdout.write(sys.executable + '\n')
sys.stdout.write(sys.version + '\n')
sys.stdout.flush()
| #! /usr/bin/env python
"""Print Python interpreter path and version."""
import sys
sys.stdout.write('%s\n' % sys.executable)
sys.stdout.write('%s\n' % sys.version)
try:
import icu # pylint: disable=g-import-not-at-top
sys.stdout.write('ICU %s\n' % icu.ICU_VERSION)
sys.stdout.write('Unicode %s\n' % icu.UNICOD... | Print ICU and Unicode version, if available | Print ICU and Unicode version, if available
| Python | apache-2.0 | googlei18n/language-resources,googlei18n/language-resources,googlei18n/language-resources,googlei18n/language-resources,google/language-resources,google/language-resources,google/language-resources,google/language-resources,googlei18n/language-resources,googlei18n/language-resources,google/language-resources,google/lan... |
38c33a772532f33751dbbebe3ee0ecd0ad993616 | alembic/versions/1fbbb727e1dc_change_last_ip_to_inet.py | alembic/versions/1fbbb727e1dc_change_last_ip_to_inet.py | """Change last_ip to inet.
Revision ID: 1fbbb727e1dc
Revises: 2dd8b091742b
Create Date: 2015-08-31 20:54:43.824788
"""
# revision identifiers, used by Alembic.
revision = '1fbbb727e1dc'
down_revision = '2dd8b091742b'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade... | """Change last_ip to inet.
Revision ID: 1fbbb727e1dc
Revises: 2dd8b091742b
Create Date: 2015-08-31 20:54:43.824788
"""
# revision identifiers, used by Alembic.
revision = '1fbbb727e1dc'
down_revision = '2dd8b091742b'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade... | Fix migrations from text to inet. | Fix migrations from text to inet.
| Python | agpl-3.0 | MSPARP/newparp,MSPARP/newparp,MSPARP/newparp |
89cda8553c662ac7b435516d888706e3f3193cb7 | sir/__main__.py | sir/__main__.py | import argparse
from .schema import SCHEMA
def reindex(args):
known_entities = SCHEMA.keys()
if args['entities'] is not None:
entities = []
for e in args['entities']:
entities.extend(e.split(','))
unknown_entities = set(known_entities) - set(entities)
if unknown_e... | import argparse
from .schema import SCHEMA
def reindex(args):
known_entities = SCHEMA.keys()
if args['entities'] is not None:
entities = []
for e in args['entities']:
entities.extend(e.split(','))
unknown_entities = set(entities) - set(known_entities)
if unknown_e... | Fix the unknown entity type test | Fix the unknown entity type test
We want to check if any user-supplied entity name is unkown, not if any
of the known types are not in the user-supplied list
| Python | mit | jeffweeksio/sir |
bcc206b46c089ea7f7ea5dfbc5c8b11a1fe72447 | movie_time_app/models.py | movie_time_app/models.py | from django.db import models
# Create your models here.
class Movie(models.Model):
movie_id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=200)
poster = models.ImageField(null=True, blank=True)
year = models.IntegerField(null=True)
genres = models.CharField(max_length=2... | from django.db import models
# Create your models here.
class Movie(models.Model):
movie_id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=200)
poster = models.ImageField(null=True, blank=True)
year = models.IntegerField(null=True)
genres = models.CharField(max_length=2... | Add self-rating flag for movies. Removed LikedOrNot table | Add self-rating flag for movies. Removed LikedOrNot table
| Python | mit | osama-haggag/movie-time,osama-haggag/movie-time |
59761e83b240fe7573370f542ea6e877c5850907 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup, Extension
uinput = Extension('libuinput',
sources = ['src/uinput.c'])
setup(name='python-steamcontroller',
version='1.0',
description='Steam Controller userland driver',
author='Stany MARCEL',
author_email='stanypub@gm... | #!/usr/bin/env python
from distutils.core import setup, Extension
uinput = Extension('libuinput',
sources = ['src/uinput.c'])
setup(name='python-steamcontroller',
version='1.0',
description='Steam Controller userland driver',
author='Stany MARCEL',
author_email='stanypub@gm... | Add json to from vdf scripts | Add json to from vdf scripts
Signed-off-by: Stany MARCEL <3e139d47b96f775f4bc13af807cbc2ea7c67e72b@gmail.com>
| Python | mit | ynsta/steamcontroller,oneru/steamcontroller,oneru/steamcontroller,ynsta/steamcontroller |
29cb760030021f97906d5eaec1c0b885e8bb2930 | example/gravity.py | example/gravity.py | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... | Add what the example should output. | Add what the example should output. | Python | bsd-2-clause | caseywstark/dimensionful |
c3799230344487a199d75af9df401ab12e2e6cfa | setup.py | setup.py | from distutils.core import setup
setup(
name='data_processing',
version='0.1-pre',
packages=['data_processing'],
url='https://github.com/openego/data_processing',
license='GNU GENERAL PUBLIC LICENSE Version 3',
author='open_eGo development group',
author_email='',
description='Data proc... | from distutils.core import setup
setup(
name='data_processing',
version='0.1-pre',
packages=['data_processing'],
url='https://github.com/openego/data_processing',
license='GNU GENERAL PUBLIC LICENSE Version 3',
author='open_eGo development group',
author_email='',
description='Data proc... | Fix dependency and update version number | Fix dependency and update version number
| Python | agpl-3.0 | openego/data_processing |
9c7aedc3b29d823d79409c5246290362a3c7ffdc | examples/arabic.py | examples/arabic.py | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Other dependencies: bidi.algorithm, arabic_reshaper
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
d = path.dirname(__file... | #!/usr/bin/env python
"""
Create wordcloud with Arabic
===============
Generating a wordcloud from Arabic text
Dependencies:
- bidi.algorithm
- arabic_reshaper
Dependencies installation:
pip install python-bidi arabic_reshape
"""
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshape... | Add some instructions for downloading the requirements | Add some instructions for downloading the requirements
| Python | mit | amueller/word_cloud |
596e850189e8c8590ac4b8c401de5930ce711929 | puppetboard/default_settings.py | puppetboard/default_settings.py | import os
PUPPETDB_HOST = 'localhost'
PUPPETDB_PORT = 8080
PUPPETDB_SSL_VERIFY = True
PUPPETDB_KEY = None
PUPPETDB_CERT = None
PUPPETDB_TIMEOUT = 20
DEFAULT_ENVIRONMENT = 'production'
SECRET_KEY = os.urandom(24)
DEV_LISTEN_HOST = '127.0.0.1'
DEV_LISTEN_PORT = 5000
DEV_COFFEE_LOCATION = 'coffee'
UNRESPONSIVE_HOURS = 2
... | import os
PUPPETDB_HOST = 'localhost'
PUPPETDB_PORT = 8080
PUPPETDB_SSL_VERIFY = True
PUPPETDB_KEY = None
PUPPETDB_CERT = None
PUPPETDB_TIMEOUT = 20
DEFAULT_ENVIRONMENT = 'production'
SECRET_KEY = os.urandom(24)
DEV_LISTEN_HOST = '127.0.0.1'
DEV_LISTEN_PORT = 5000
DEV_COFFEE_LOCATION = 'coffee'
UNRESPONSIVE_HOURS = 2
... | Add clientversion to graphing facts | Add clientversion to graphing facts
| Python | apache-2.0 | puppet-community/puppetboard,johnzimm/xx-puppetboard,tparkercbn/puppetboard,mterzo/puppetboard,stoyansbg/puppetboard,mterzo/puppetboard,holstvoogd/puppetboard,johnzimm/xx-puppetboard,johnzimm/puppetboard,tparkercbn/puppetboard,mterzo/puppetboard,stoyansbg/puppetboard,james-powis/puppetboard,tparkercbn/puppetboard,voxpu... |
655db4e1c8aefea1699516339dd80e1c6a75d67d | setup.py | setup.py | from distutils.core import setup
import sys
import os
import re
PACKAGENAME = 'OpSimSummary'
packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
PACKAGENAME)
versionFile = os.path.join(packageDir, 'version.py')
# Obtain the package version
with open(versionFile, 'r') as f:... | from distutils.core import setup
import sys
import os
import re
PACKAGENAME = 'OpSimSummary'
packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'opsimsummary')
versionFile = os.path.join(packageDir, 'version.py')
# Obtain the package version
with open(versionFile, 'r') as... | Revert "Revert "Revert "Changed back due to problems, will fix later""" | Revert "Revert "Revert "Changed back due to problems, will fix later"""
This reverts commit 4b35247fe384d4b2b206fa7650398511a493253c.
| Python | mit | rbiswas4/simlib |
f607cf2f024c299953a0d3eb523b6be493792d0f | tasks.py | tasks.py | # -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf .coverage dist build")
@task(clean, default=True)
def test(context):
context.run("pytest")
@task(test)
def install(context):
context.run("python setup.py develop")
@task(test)
def release(context):
con... | # -*- coding: utf-8 -*-
from invoke import task
@task
def clean(context):
context.run("rm -rf dist build .coverage .pytest_cache .mypy_cache")
@task(clean, default=True)
def test(context):
context.run("pytest")
@task(test)
def install(context):
context.run("python setup.py develop")
@task(test)
def... | Clean cache files after pytest & mypy | Clean cache files after pytest & mypy
| Python | apache-2.0 | miso-belica/sumy,miso-belica/sumy |
1f545f9e921e10448b4018550620f9dc4d56931c | survey/models/__init__.py | survey/models/__init__.py | # -*- coding: utf-8 -*-
"""
Permit to import everything from survey.models without knowing the details.
"""
import sys
from .answer import Answer
from .category import Category
from .question import Question
from .response import Response
from .survey import Survey
__all__ = ["Category", "Answer", "Category", "... | # -*- coding: utf-8 -*-
"""
Permit to import everything from survey.models without knowing the details.
"""
from .answer import Answer
from .category import Category
from .question import Question
from .response import Response
from .survey import Survey
__all__ = ["Category", "Answer", "Category", "Response", "Surv... | Fix F401 'sys' imported but unused | Fix F401 'sys' imported but unused
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey |
42964d986a0e86c3c93ad152d99b5a4e5cbc2a8e | plots/mapplot/_shelve.py | plots/mapplot/_shelve.py | '''
Cache results to disk.
'''
import inspect
import os
import shelve
class shelved:
def __init__(self, func):
self._func = func
# Put the cache file in the same directory as the caller.
funcdir = os.path.dirname(inspect.getfile(self._func))
cachedir = os.path.join(funcdir, '_she... | '''
Cache results to disk.
'''
import inspect
import os
import shelve
class shelved:
def __init__(self, func):
self._func = func
# Put the cache file in the same directory as the caller.
funcdir = os.path.dirname(inspect.getfile(self._func))
cachedir = os.path.join(funcdir, '_she... | Revert "Maybe fixed weakref error by explicitly closing shelf." This did not fix the weakref error. Maybe it's something in cartopy. | Revert "Maybe fixed weakref error by explicitly closing shelf."
This did not fix the weakref error. Maybe it's something in cartopy.
This reverts commit 30d5b38cbc7a771e636e689b281ebc09356c3a49.
| Python | agpl-3.0 | janmedlock/HIV-95-vaccine |
3736d7fb32e20a64591f949d6ff431430447d421 | stock.py | stock.py | class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1] if self.price_history else None
def update(self, timestamp, price):
if price < 0:
raise ValueError("price should no... | import bisect
import collections
PriceEvent = collections.namedtuple("PriceEvent", ["timestamp", "price"])
class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price_history = []
@property
def price(self):
return self.price_history[-1].price if self.price_history el... | Add a named tuple PriceEvent sub class and update methods accordingly. | Add a named tuple PriceEvent sub class and update methods accordingly.
| Python | mit | bsmukasa/stock_alerter |
b6c8dd224279ad0258b1130f8105059affa7553f | Challenges/chall_04.py | Challenges/chall_04.py | #!/urs/local/bin/python3
# Python challenge - 4
# http://www.pythonchallenge.com/pc/def/linkedlist.php
import urllib.request
import re
def main():
'''
http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
44827
45439
...
'''
base_url = 'http://www.pythonchallenge.com/pc/def/l... | #!/usr/local/bin/python3
# Python challenge - 4
# http://www.pythonchallenge.com/pc/def/linkedlist.html
# http://www.pythonchallenge.com/pc/def/linkedlist.php
# Keyword: peak
import urllib.request
import re
def main():
'''
html page shows: linkedlist.php
php page comment: urllib may help. DON'T TRY ALL N... | Refactor code, fix shebang path | Refactor code, fix shebang path
| Python | mit | HKuz/PythonChallenge |
b85a92df83563e38b84340574cde2f9dc06b563c | rest_framework_docs/api_docs.py | rest_framework_docs/api_docs.py | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.utils.module_loading import import_string
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
... | from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.utils.module_loading import import_string
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
... | Exclude Endpoints with a <format> parameter | Exclude Endpoints with a <format> parameter
| Python | bsd-2-clause | ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs |
a22b21e4a06525f081c6a7ce92ddc2102d7ddce8 | 5-convert-to-mw.py | 5-convert-to-mw.py | #!/usr/bin/python
from subprocess import call
import os
from os.path import join, getsize
wikiHtml = "/var/www/sp/wiki-html"
LOwikiHtml = "/var/www/sp/5-libre-wiki-html"
wikiFiles = "/var/www/sp/6-wiki-files"
for f in os.listdir(wikiHtml):
if f.endswith(".html"):
# soffice --headless --convert-to html:HTML /path... | #!/usr/bin/python
from subprocess import call
import os
from os.path import join, getsize
scriptPath = os.path.realpath(__file__)
wikiHtml = scriptPath + "/usr/sharepoint-content"
LibreOfficeOutput = scriptPath + "/usr/LibreOfficeOutput"
WikitextOutput = scriptPath + "/usr/WikitextOutput"
for f in os.listdir(wikiHtm... | Fix paths in LibreOffice and Perl converter | Fix paths in LibreOffice and Perl converter
| Python | mit | jamesmontalvo3/Sharepoint-to-MediaWiki,jamesmontalvo3/Sharepoint-to-MediaWiki |
d7133922de24c6553417eb1e25c65bb51e7451f7 | airship/__init__.py | airship/__init__.py | import os
import json
from flask import Flask, render_template
def channels_json(station, escaped=False):
channels = [{"name": channel} for channel in station.channels()]
jsonbody = json.dumps(channels)
if escaped:
jsonbody = jsonbody.replace("</", "<\\/")
return jsonbody
def make_airship(s... | import os
import json
from flask import Flask, render_template
def channels_json(station, escaped=False):
channels = [{"name": channel} for channel in station.channels()]
jsonbody = json.dumps(channels)
if escaped:
jsonbody = jsonbody.replace("</", "<\\/")
return jsonbody
def make_airship(s... | Create a route for fetching grefs | Create a route for fetching grefs
| Python | mit | richo/airship,richo/airship,richo/airship |
c5683cb2bf8635c6ad26aac807f47c8f1fb4c68a | http_prompt/cli.py | http_prompt/cli.py | import click
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.styles.from_pygments import style_from_pygments
from pygments.styles import get_style_by_name
from .completer import HttpPromptCompleter
from .co... | import click
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.styles.from_pygments import style_from_pygments
from pygments.styles import get_style_by_name
from .completer import HttpPromptCompleter
from .co... | Fix incomplete URL from command line | Fix incomplete URL from command line
| Python | mit | eliangcs/http-prompt,Yegorov/http-prompt |
3055fa16010a1b855142c2e5b866d76daee17c8f | markdown_gen/test/attributes_test.py | markdown_gen/test/attributes_test.py |
import unittest
import markdown_gen.MardownGen as md
class AttributesTests(unittest.TestCase):
def test_italic(self):
expected = "*italic text*"
self.assertEqual(expected, md.gen_italic("italic text"))
expected = "_italic text alternative_"
self.assertEqual(expected, md.gen_it... |
import unittest
import markdown_gen.MardownGen as md
class AttributesTests(unittest.TestCase):
def test_italic(self):
expected = "*italic text*"
self.assertEqual(expected, md.gen_italic("italic text"))
expected = "_italic text alternative_"
self.assertEqual(expected, md.gen_it... | Add test for bold and italic text | Add test for bold and italic text | Python | epl-1.0 | LukasWoodtli/PyMarkdownGen |
23c29c4964286fc2ca8fb3a957a6e7810edb9d17 | alexia/template/context_processors.py | alexia/template/context_processors.py | from __future__ import unicode_literals
from alexia.apps.organization.models import Organization
def organization(request):
return {
'organizations': Organization.objects.all(),
'current_organization': request.organization,
}
def permissions(request):
if request.user.is_superuser:
... | from __future__ import unicode_literals
from alexia.apps.organization.models import Organization
def organization(request):
return {
'organizations': Organization.objects.all(),
'current_organization': request.organization,
}
def permissions(request):
if request.user.is_superuser:
... | Fix AttributeError: 'AnonymousUser' object has no attribute 'membership_set' | Fix AttributeError: 'AnonymousUser' object has no attribute 'membership_set'
| Python | bsd-3-clause | Inter-Actief/alexia,Inter-Actief/alexia,Inter-Actief/alexia,Inter-Actief/alexia |
540bffe17ede75bc6afd9b2d45e343e0eac4552b | rna-transcription/rna_transcription.py | rna-transcription/rna_transcription.py | DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
# Check validity - `difference` returns elements in dna not in DNA
if set(dna).difference(DNA):
return ""
return "".join([TRANS[n] for n in dna])
| TRANS = {"G": "C", "C":"G", "T":"A", "A":"U"}
def to_rna(dna):
try:
return "".join([TRANS[n] for n in dna])
except KeyError:
return ""
# Old version: it's slightly slower for valid DNA, but slightly faster for invalid DNA
DNA = {"A", "C", "T", "G"}
TRANS = {"G": "C", "C":"G", "T":"A", "A":"... | Add an exception based version | Add an exception based version
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
b7b67a0327feddc977a404178aae03e47947dd20 | bluebottle/bluebottle_drf2/pagination.py | bluebottle/bluebottle_drf2/pagination.py | from rest_framework.pagination import PageNumberPagination
class BluebottlePagination(PageNumberPagination):
page_size = 10
| from rest_framework.pagination import PageNumberPagination
class BluebottlePagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
| Make it possible to send a page_size parameter to all paged endpoints. | Make it possible to send a page_size parameter to all paged endpoints.
BB-9512 #resolve
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
d675dbcab18d56ae4c2c2f05d342159c1032b7b4 | polling_stations/apps/data_importers/management/commands/import_fake_exeter.py | polling_stations/apps/data_importers/management/commands/import_fake_exeter.py | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
from pathlib import Path
def make_base_folder_path():
base_folder_path = Path.cwd() / Path("test_data/pollingstations_data/EXE")
return str(base_folder_path)
class Command(BaseXpressDemocracyClubCsvImporter):
local_files =... | from django.contrib.gis.geos import Point
from addressbase.models import UprnToCouncil
from data_importers.mixins import AdvanceVotingMixin
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
from pathlib import Path
from pollingstations.models import AdvanceVotingStation
def make_base... | Add Advance Voting stations to fake Exeter importer | Add Advance Voting stations to fake Exeter importer
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
7f212a9bacfce6612c6ec435174bf9c3eddd4652 | pagoeta/apps/events/serializers.py | pagoeta/apps/events/serializers.py | from hvad.contrib.restframework import TranslatableModelSerializer
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import Category, TargetGroup, TargetAge, Event
from pagoeta.apps.core.functions import get_absolute_uri
from pagoeta.apps.places.serializers import PlaceList... | from hvad.contrib.restframework import TranslatableModelSerializer
from rest_framework import serializers
from rest_framework.reverse import reverse
from .models import Category, TargetGroup, TargetAge, Event
from pagoeta.apps.core.functions import get_absolute_uri
from pagoeta.apps.places.serializers import PlaceList... | Change camelCasing strategy for `target_age` and `target_group` | Change camelCasing strategy for `target_age` and `target_group`
| Python | mit | zarautz/pagoeta,zarautz/pagoeta,zarautz/pagoeta |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.