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 |
|---|---|---|---|---|---|---|---|---|---|
3071684f73e736950023be9f47c93dd31c50be1c | send2trash/compat.py | send2trash/compat.py | # Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = sys.version_info[0] >= 3
if PY3:
text_typ... | # Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = sys.version_info[0] >= 3
if PY3:
text_typ... | Fix newly-introduced crash under Windows | Fix newly-introduced crash under Windows
ref #14
| Python | bsd-3-clause | hsoft/send2trash |
8a6002015cf873d3054bd20d8d287a3fe7be6b84 | server.py | server.py | from tornado import ioloop, web, websocket
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message("You said: " + message)
def on_close(self):
print("WebSocket closed")
class Main... | from tornado import ioloop, web, websocket
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message("You said: " + message)
def on_close(self):
print("WebSocket closed")
SCRIPT = '... | Load file or path now. | Load file or path now.
| Python | bsd-3-clause | GrAndSE/livehtml,GrAndSE/livehtml |
d00e84e1e41b43f5b680bb310b68444cd9bbcba5 | fireplace/cards/tgt/shaman.py | fireplace/cards/tgt/shaman.py | from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class... | from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class... | Implement more TGT Shaman cards | Implement more TGT Shaman cards
| Python | agpl-3.0 | oftc-ftw/fireplace,amw2104/fireplace,amw2104/fireplace,smallnamespace/fireplace,jleclanche/fireplace,liujimj/fireplace,Ragowit/fireplace,Meerkov/fireplace,liujimj/fireplace,smallnamespace/fireplace,Meerkov/fireplace,beheh/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,NightKev/fireplace |
4021d27a7bd15a396b637beb57c10fc95936cb3f | snippet_parser/fr.py | snippet_parser/fr.py | #-*- encoding: utf-8 -*-
import base
class SnippetParser(base.SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('unité'):
return ' '.join(map(unicode, template.params[:2]))
elif self.is_citation_needed(template):
repl = [b... | #-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(u... | Implement a couple of other French templates. | Implement a couple of other French templates.
Still need to add tests for these.
| Python | mit | Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,Stryn/citationhunt |
77c114925fb45fa56c1da358ed47d8222775f99f | tailor/listeners/mainlistener.py | tailor/listeners/mainlistener.py | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
className = ctx.getText()
if not isUpperCamelCase(className):
print('Line', str(ctx.start.line) + ':', 'Class name... | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
className = ctx.getText()
if not isUpperCamelCase(className):
print('Line', str(ctx.start.line) + ':', 'Class nam... | Add overrides for UpperCamelCase construct names | Add overrides for UpperCamelCase construct names
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
f5e6ba58fa29bd89722c1e4bf4ec743eb1125f75 | python/helpers/pycharm/django_manage_shell.py | python/helpers/pycharm/django_manage_shell.py | #!/usr/bin/env python
from fix_getpass import fixGetpass
import os
from django.core import management
import sys
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
def run(working_dir):
sys.path.insert(0, working_dir)
manage_file = os.getenv('PYCHARM_DJANGO_MANAGE_MODUL... | #!/usr/bin/env python
from fix_getpass import fixGetpass
import os
from django.core import management
import sys
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
def run(working_dir):
sys.path.insert(0, working_dir)
manage_file = os.getenv('PYCHARM_DJANGO_MANAGE_MODUL... | Fix circular import problem in Django console (PY-9030). | Fix circular import problem in Django console (PY-9030).
| Python | apache-2.0 | retomerz/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,caot/intellij-community,signed/intellij-community,hurr... |
0c0b163d6454134595fb8ba794281afe56bc0100 | gae-firebase-listener-python/main.py | gae-firebase-listener-python/main.py | import os
import webapp2
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
allowed_users = set()
if IS_DEV:
allowed_users.add("dev-instance")
class LoggingHandler(webapp2.RequestHandler):
def post(self):
user = self.request.headers.get('X-Appengine-Inbound-Appid', None)
if user and user in allo... | import os
import webapp2
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
allowed_users = set()
if IS_DEV:
allowed_users.add("dev-instance")
else:
# Add your Java App Engine proxy App Id here
allowed_users.add("your-java-appengine-proxy-app-id")
class LoggingHandler(webapp2.RequestHandler):
def po... | Add proxy app id to listener | Add proxy app id to listener
| Python | mit | misterwilliam/gae-firebase-event-proxy,misterwilliam/gae-firebase-event-proxy |
db4b8b2abbb1726a3d2db3496b82e0ad6c0572e9 | gateway_mac.py | gateway_mac.py | import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
... | import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3],... | Update to support multiple default gateways | Update to support multiple default gateways | Python | mit | nulledbyte/scripts |
4db52d5c8a10460fb9ea4a701e953f790a720f83 | admin/common_auth/forms.py | admin/common_auth/forms.py | from __future__ import absolute_import
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group
from osf.models.user import OSFUser
from admin.common_auth.models import AdminProfile
cl... | from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
... | Update UserRegistrationForm to be connected to an existing OSF user. | Update UserRegistrationForm to be connected to an existing OSF user.
| Python | apache-2.0 | aaxelb/osf.io,Nesiehr/osf.io,erinspace/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,adlius/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,binoculars/osf.io,adlius/osf.io,laurenrevere/osf.io,mfraezz/osf.io,cslzchen/osf.io,caneruguz/osf.io,chrisseto/osf.io,felliot... |
32c971233fa4c83a163036da0090d35463d43c75 | bananas/management/commands/syncpermissions.py | bananas/management/commands/syncpermissions.py | from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args, **options):
if args: # pragma: no cover
raise CommandError("Command doesn't accept an... | from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args, **options):
if args: # pragma: no cover
raise CommandError("Command doesn't accept an... | Update permission names when syncing | Update permission names when syncing
| Python | mit | 5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas |
66cfb6f42cf681d848f944af5bbb7d472280d895 | src/pyuniprot/cli.py | src/pyuniprot/cli.py | import click
from .manager import database
from .webserver.web import get_app
@click.group()
def main():
pass
@main.command()
def update():
"""Update PyUniProt data"""
database.update()
@main.command()
def web():
get_app().run()
| import click
from .manager import database
from .webserver.web import get_app
@click.group()
def main():
pass
@main.command()
def update():
"""Update PyUniProt data"""
database.update()
@main.command()
@click.option('--host', default='0.0.0.0', help='Flask host. Defaults to localhost')
@click.option('--... | Add host and port options to web runner | Add host and port options to web runner
| Python | apache-2.0 | cebel/pyuniprot,cebel/pyuniprot |
6556604fb98c2153412384d6f0f705db2da1aa60 | tinycss2/css-parsing-tests/make_color3_hsl.py | tinycss2/css-parsing-tests/make_color3_hsl.py | import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if a is not None else '', h,
trim(str(s / 10.)), trim(str(l / 10.)),
', %s' ... | import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if alpha is not None else '', hue,
trim(str(saturation / 10.)), trim(str(light / 10.)... | Fix failing tests with recent versions of pytest-flake8 | Fix failing tests with recent versions of pytest-flake8
| Python | bsd-3-clause | SimonSapin/tinycss2 |
13a39f4e025160f584beef8442e82ec3c3526a95 | raco/myrial/cli_test.py | raco/myrial/cli_test.py | """Basic test of the command-line interface to Myrial."""
import subprocess
import unittest
class CliTest(unittest.TestCase):
def test_cli(self):
out = subprocess.check_output(['python', 'scripts/myrial',
'examples/reachable.myl'])
self.assertIn('DO', out)
... | """Basic test of the command-line interface to Myrial."""
import subprocess
import unittest
class CliTest(unittest.TestCase):
def test_cli(self):
out = subprocess.check_output(['python', 'scripts/myrial',
'examples/reachable.myl'])
self.assertIn('DO', out)
... | Test of standalone myrial mode | Test of standalone myrial mode
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco |
a021b077834a932b5c8da6be49bb98e7862392d4 | setup.py | setup.py | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email=... | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email=... | Install templates when using pip to install package. | Install templates when using pip to install package.
| Python | apache-2.0 | emorozov/django-mingus,emorozov/django-mingus,emorozov/django-mingus,emorozov/django-mingus |
0f18b3ff63bf6183247e7bce25160547f8cfc21d | setup.py | setup.py | import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT ... | import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT ... | Change PyPI trove classifier for license terms. | Change PyPI trove classifier for license terms.
| Python | apache-2.0 | devinmcgloin/advent,devinmcgloin/advent |
024878fc913097364123d28a99ab7cb5501b0af5 | setup.py | setup.py | #!/usr/bin/env python
import subprocess
from distutils.core import setup
requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()]
description = 'Download videos from Udemy for personal offline use'
try:
subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o", "README... | #!/usr/bin/env python
import os
import subprocess
from distutils.core import setup
requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()]
description = 'Download videos from Udemy for personal offline use'
try:
subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o... | Set permission mask to allow read/exec for all users | Set permission mask to allow read/exec for all users
| Python | unlicense | rinodung/udemy-dl |
f27e08b0dcace5b9f49c5b2a211347a2f50f8254 | stats.py | stats.py | from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
stats = {}
content = soup.find_all('div', {'class':'content'})
stats['clan'] = content[0].get_text()
if stats['cl... | from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
if not tag.find('/') == -1:
tag = tag[::-1]
pos = tag.find('/')
tag = tag[:pos]
tag = tag[::-1]
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
descriptio... | Use tags or direct url | Use tags or direct url | Python | mit | atulya2109/Stats-Royale-Python |
c05b06577785bdf34f1fcd051ecf6d4398d2f77e | tasks.py | tasks.py | from os.path import join
from invoke import Collection, ctask as task
from invocations import docs as _docs
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
path = join(d, 'docs')
docs = Collection.from_module(_docs, name='docs', config={
'sphinx.source': path,
'sphinx.target': join(path, '... | from os.path import join
from shutil import rmtree, move
from invoke import Collection, ctask as task
from invocations import docs as _docs
from invocations.packaging import publish
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
docs_path = join(d, 'docs')
docs_build = join(docs_path, '_build')
d... | Add new release task w/ API doc prebuilding | Add new release task w/ API doc prebuilding
| Python | lgpl-2.1 | thusoy/paramiko,CptLemming/paramiko,rcorrieri/paramiko,redixin/paramiko,Automatic/paramiko,jaraco/paramiko,esc/paramiko,ameily/paramiko,zarr12steven/paramiko,dorianpula/paramiko,mirrorcoder/paramiko,jorik041/paramiko,thisch/paramiko,dlitz/paramiko,paramiko/paramiko,digitalquacks/paramiko,fvicente/paramiko,SebastianDeis... |
f4ba2cba93222b4dd494caf487cdd6be4309e41a | studygroups/forms.py | studygroups/forms.py | from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please t... | from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please t... | Update labels for application form | Update labels for application form
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles |
6755255332039ab3c0ea60346f61420b52e2f474 | tests/functional/test_l10n.py | tests/functional/test_l10n.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/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | # 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/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(b... | Fix intermittent failure in l10n language selector test | Fix intermittent failure in l10n language selector test
| Python | mpl-2.0 | sgarrity/bedrock,TheoChevalier/bedrock,craigcook/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,Sancus/bedrock,hoosteeno/bedrock,sylvestre/bedrock,schalkneethling/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,sylvestre/bedrock,glogiotatidis/bedrock,jgmize/bedrock,kyoshino/bedrock,mkmelin/bedrock,gerv/bedrock,dav... |
b37814280dc06dbf8aefec4490f6b73a47f05c1a | custom_fixers/fix_alt_unicode.py | custom_fixers/fix_alt_unicode.py | # Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name, BlankLine
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = """
func=funcdef< 'def' name='__unicode__'
... | # Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = "'__unicode__'"
def transform(self, node, results):
new = node.clone()
new.value = '__str__... | Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__. | Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
| Python | mit | live-clones/pybtex |
eb4cda636a0b0ceb5312b161e97ae5f8376c9f8e | indra/tests/test_biolookup_client.py | indra/tests/test_biolookup_client.py | from indra.databases import biolookup_client
def test_lookup_curie():
curie = 'pubchem.compound:40976'
res = biolookup_client.lookup_curie(curie)
assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \
'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \
'cyclopenta[a]phenanth... | from indra.databases import biolookup_client
def test_lookup_curie():
curie = 'pubchem.compound:40976'
res = biolookup_client.lookup_curie(curie)
assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \
'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \
'cyclopenta[a]phenanth... | Change biolookup test to work around service bug | Change biolookup test to work around service bug
| Python | bsd-2-clause | johnbachman/indra,bgyori/indra,johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/indra |
eac2f296e855f92d040321edee943ad5f8a8fb39 | nodeconductor/events/views.py | nodeconductor/events/views.py | from rest_framework import generics, response
from nodeconductor.events import elasticsearch_client
class EventListView(generics.GenericAPIView):
def list(self, request, *args, **kwargs):
order_by = request.GET.get('o', '-@timestamp')
elasticsearch_list = elasticsearch_client.ElasticsearchResult... | from rest_framework import generics, response
from nodeconductor.events import elasticsearch_client
class EventListView(generics.GenericAPIView):
def list(self, request, *args, **kwargs):
order_by = request.GET.get('o', '-@timestamp')
event_types = request.GET.getlist('event_type')
searc... | Add filtering to view (nc-463) | Add filtering to view (nc-463)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
72e948719145579eb7dfb9385b921f8eb6ea1384 | tests/v4/conftest.py | tests/v4/conftest.py | from .context import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
__all__ = ['EXEMPLAR_GENERATORS', 'EXEMPLAR_PRIMITIVE_GENERATORS', 'EXEMPLAR_DERIVED_GENERATORS']
def add(x, y):
return x + y
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Integer(100, 200... | from .context import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
__all__ = ['EXEMPLAR_GENERATORS', 'EXEMPLAR_PRIMITIVE_GENERATORS', 'EXEMPLAR_DERIVED_GENERATORS']
def add(x, y):
return x + y
EXEMPLAR_PRIMITIVE_GENERATORS = [
Boolean(p=0.3),
Constant("quux"),
... | Add more exemplar primitive generators | Add more exemplar primitive generators
| Python | mit | maxalbert/tohu |
24b8e2f7440926d6d1c384a7289dfb5d1124e82f | opps/core/admin/__init__.py | opps/core/admin/__init__.py | # -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
from opps.core.admin.source import *
| # -*- coding: utf-8 -*-
from opps.core.admin.article import *
from opps.core.admin.channel import *
from opps.core.admin.profile import *
from opps.core.admin.source import *
| Add article on core admin | Add article on core admin
| Python | mit | YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps |
ea416504c287bc5a3716289b57ebfd15bb770b9d | sql/branch.py | sql/branch.py | from gratipay import wireup
env = wireup.env()
db = wireup.db(env)
participants = []
with open('./sql/emails.txt') as f:
emails = [line.rstrip() for line in f]
participants = db.all("""
SELECT p.*::participants
FROM participants p
WHERE email_address IN %s
""", (tuple(emails), ... | import sys
from gratipay import wireup
env = wireup.env()
db = wireup.db(env)
# Temporary, will fill with actual values when running script
email_txt = """
rohitpaulk@live.com
abcd@gmail.com
"""
emails = [email.strip() for email in email_txt.split()]
assert len(emails) == 176
participants = []
participan... | Use a string instead of a file | Use a string instead of a file
(so that I can redirect input to heroku from a local file)
| Python | mit | eXcomm/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,studio666... |
34035c4b272e9271834c531990c404940eee8633 | apps/votes/models.py | apps/votes/models.py | from django.db import models
from meps.models import MEP
class Proposal(models.Model):
id = models.CharField(max_length=63, primary_key=True)
title = models.CharField(max_length=255, unique=True)
class SubProposal(models.Model):
datetime = models.DateTimeField()
subject = models.CharField(max_length=2... | from django.db import models
from meps.models import MEP
class Proposal(models.Model):
id = models.CharField(max_length=63, primary_key=True)
title = models.CharField(max_length=255, unique=True)
class SubProposal(models.Model):
datetime = models.DateTimeField()
subject = models.CharField(max_length=2... | Add a link between vote and subproposal | [enh] Add a link between vote and subproposal
| Python | agpl-3.0 | yohanboniface/memopol-core,yohanboniface/memopol-core,yohanboniface/memopol-core |
496481e3bd6392a44788fadc7cf517fc36143e96 | contrib/plugins/w3cdate.py | contrib/plugins/w3cdate.py | """
Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format
WARNING: you must have PyXML installed as part of your python installation
in order for this plugin to work
Place this plugin early in your load_plugins list, so that the w3cdate will
be available to subsequent plugins
"""
__author__ ... | """
Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format
WARNING: you must have PyXML installed as part of your python installation
in order for this plugin to work
Place this plugin early in your load_plugins list, so that the w3cdate will
be available to subsequent plugins
"""
__author__ ... | Change to cb_story, clean up TZ handling some more | Change to cb_story, clean up TZ handling some more
| Python | mit | willkg/douglas,daitangio/pyblosxom,willkg/douglas,daitangio/pyblosxom |
9fa55bc43a3f83a57318799ba8b9f2769676bd44 | test/test_flvlib.py | test/test_flvlib.py | import unittest
import test_primitives, test_astypes, test_helpers
def get_suite():
modules = (test_primitives, test_astypes, test_helpers)
suites = [unittest.TestLoader().loadTestsFromModule(module) for
module in modules]
return unittest.TestSuite(suites)
def main():
unittest.TextTestRu... | import unittest
import test_primitives, test_astypes, test_helpers, test_tags
def get_suite():
modules = (test_primitives, test_astypes, test_helpers, test_tags)
suites = [unittest.TestLoader().loadTestsFromModule(module) for
module in modules]
return unittest.TestSuite(suites)
def main():
... | Include the tags module tests in the full library testsuite. | Include the tags module tests in the full library testsuite.
| Python | mit | wulczer/flvlib |
47c2936e65d00a08896b4e60060ff737b7a2f675 | app/tests/workstations_tests/test_migrations.py | app/tests/workstations_tests/test_migrations.py | import pytest
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
@pytest.mark.django_db(transaction=True)
def test_workstation_group_migration():
executor = MigrationExecutor(connection)
app = "workstations"
migrate_from = [(app, "0001_initial")]
migrate_to = ... | import pytest
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from guardian.shortcuts import get_perms
from grandchallenge.workstations.models import Workstation
from tests.factories import UserFactory
@pytest.mark.django_db(transaction=True)
def test_workstation_group_mi... | Check that the permission migrations work | Check that the permission migrations work
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
54296c607b735ce06b3420efecb312f52876e012 | django_react_templatetags/context_processors.py | django_react_templatetags/context_processors.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def react_context_processor(request):
"""Expose a global list of react components to be processed"""
print("react_context_processor is no longer required.")
return {
'REACT_COMPONENTS': [],
}
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
def react_context_processor(request):
"""Expose a global list of react components to be processed"""
warnings.warn(
"react_context_processor is no longer required.", DeprecationWarning
)
return {
'REACT_COMPONENTS': [],
... | Replace warning message with deprecation warning | Replace warning message with deprecation warning
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags |
1fed9f26010f24af14abff9444862ed0861adb63 | thinglang/runner.py | thinglang/runner.py | from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.parser import parse
def run(source):
if not source:
raise ValueError('Got empty source')
source = source.strip().replace(' ' * 4, '\t')
lexical_groups = list(lexer(source))
... | from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.parser import parse
from thinglang.parser.simplifier import simplify
def run(source):
if not source:
raise ValueError('Source cannot be empty')
source = source.strip().replace(' ' *... | Add simplification between parsing and execution | Add simplification between parsing and execution
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
6138f02896bc865a98480be36300bf670a6defa8 | plugin/complete_database.py | plugin/complete_database.py | import vim
import re
import json
from os import path
current = vim.eval("expand('%:p')")
ccd = vim.eval("l:ccd")
opts = []
with open(ccd) as database:
data = json.load(database)
for d in data:
# hax for headers
fmatch = re.search(r'(.*)\.(\w+)$', current)
dmatch = re.search(r'(.*)\.(\... | import vim
import re
import json
from os import path
curr_file = vim.eval("expand('%:p')")
curr_file_noext = path.splitext(curr_file)[0]
ccd = vim.eval("l:ccd")
opts = []
with open(ccd) as database:
# Search for the right entry in the database matching file names
for d in json.load(database):
# This ... | Replace re by os.path utils | compdb: Replace re by os.path utils
Instead of using regular expressions to drop file name ending use
os.path.splitext().
| Python | isc | justmao945/vim-clang,justmao945/vim-clang |
0fe7cd8cf316dc6d4ef547d733b634de64fc768c | dbaas/dbaas_services/analyzing/admin/analyze.py | dbaas/dbaas_services/analyzing/admin/analyze.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm
class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
form = ... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm
class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
form = ... | Add more options on filters | Add more options on filters
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
2d09314ab58bb766372dc6e263fb17428b1fd3cd | doc/pool_scripts/cats.py | doc/pool_scripts/cats.py | import os
import photomosaic.flickr
import photomosaic as pm
if not os.path.isfile('~/pools/cats/pool.json'):
FLICKR_API_KEY = os.environ['FLICKR_API_KEY']
pm.set_options(flickr_api_key=FLICKR_API_KEY)
photomosaic.flickr.from_search('cats', '~/pools/cats/')
pool = pm.make_pool('~/pools/cats/*.jpg')
... | import os
import photomosaic.flickr
import photomosaic as pm
if not os.path.isfile(os.path.expanduser('~/pools/cats/pool.json')):
FLICKR_API_KEY = os.environ['FLICKR_API_KEY']
pm.set_options(flickr_api_key=FLICKR_API_KEY)
photomosaic.flickr.from_search('cats', '~/pools/cats/')
pool = pm.make_pool('~/... | Fix check for existing pools. | BLD: Fix check for existing pools.
| Python | bsd-3-clause | danielballan/photomosaic |
7d69bcc6474d954b311251bf077750e0418170cb | button.py | button.py | import RPi.GPIO as GPIO
import time
import os
from optparse import OptionParser
# Parse input arguments
parser = OptionParser()
parser.add_option("-t", "--testGPIO", action="store_true", help="Test GPIO connection, does not call the JS script.")
# The option --pin sets the Input Pin for your Button
# It default to G... | import RPi.GPIO as GPIO
import time
import os
from optparse import OptionParser
# Parse input arguments
parser = OptionParser()
parser.add_option("-t", "--testGPIO", action="store_true", help="Test GPIO connection, does not call the JS script.")
# The option --pin sets the Input Pin for your Button
# It default to G... | Fix typo and execute JS script found in local folder. | Fix typo and execute JS script found in local folder.
| Python | mit | henne-/guest-password-printer,henne-/guest-password-printer |
6c095c0e14c084666b9417b4bd269f396804bfab | src/ensign/_interfaces.py | src/ensign/_interfaces.py | # pylint: skip-file
from zope.interface import Attribute, Interface
class IFlag(Interface):
"""
Flag Interface.
Any kind of flag must implement this interface.
"""
TYPE = Attribute("""Flag type""")
store = Attribute("""Flag storage backend""")
name = Attribute("""Flag name""")
value... | # pylint: skip-file
from zope.interface import Attribute, Interface
class IFlag(Interface):
"""
Flag Interface.
Any kind of flag must implement this interface.
"""
TYPE = Attribute("""Flag type""")
store = Attribute("""Flag storage backend""")
name = Attribute("""Flag name""")
value... | Update interface with the latest changes in functionality. | Update interface with the latest changes in functionality.
| Python | isc | bolsote/py-cd-talk,bolsote/py-cd-talk |
f535228e38f33263289f28d46e910ccb0a98a381 | tournamentcontrol/competition/constants.py | tournamentcontrol/competition/constants.py | import pytz
from dateutil.rrule import DAILY, WEEKLY
from django.utils.translation import ugettext_lazy as _
GENDER_CHOICES = (
('M', _('Male')),
('F', _('Female')),
('X', _('Unspecified')),
)
SEASON_MODE_CHOICES = (
(WEEKLY, _("Season")),
(DAILY, _("Tournament")),
)
WIN_LOSE = {
'W': _("Winn... | import pytz
from dateutil.rrule import DAILY, WEEKLY
from django.utils.translation import ugettext_lazy as _
GENDER_CHOICES = (
('M', _('Male')),
('F', _('Female')),
('X', _('Unspecified')),
)
SEASON_MODE_CHOICES = (
(WEEKLY, _("Season")),
(DAILY, _("Tournament")),
)
WIN_LOSE = {
'W': _("Winn... | Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES | Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES
During Python 3 conversion this must have been missed.
| Python | bsd-3-clause | goodtune/vitriolic,goodtune/vitriolic,goodtune/vitriolic,goodtune/vitriolic |
c0787c468e1b71d7e9db93b5f5990ae9bb506d82 | pystruct/datasets/dataset_loaders.py | pystruct/datasets/dataset_loaders.py | import cPickle
from os.path import dirname
from os.path import join
import numpy as np
def load_letters():
"""Load the OCR letters dataset.
This is a chain classification task.
Each example consists of a word, segmented into letters.
The first letter of each word is ommited from the data,
as it ... | import cPickle
from os.path import dirname
from os.path import join
import numpy as np
def load_letters():
"""Load the OCR letters dataset.
This is a chain classification task.
Each example consists of a word, segmented into letters.
The first letter of each word is ommited from the data,
as it ... | FIX other two sample data load for Windows | FIX other two sample data load for Windows
| Python | bsd-2-clause | massmutual/pystruct,pystruct/pystruct,amueller/pystruct,d-mittal/pystruct,wattlebird/pystruct,pystruct/pystruct,d-mittal/pystruct,wattlebird/pystruct,massmutual/pystruct,amueller/pystruct |
f0ef4f5e269d7f2d7fd347e8f458c1c9ce1ffb34 | mqueue/hooks/redis/__init__.py | mqueue/hooks/redis/__init__.py | import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
name = DOMAIN+"_event"+str(event_num... | import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
global event_num
global R
na... | Fix bug in redis hook | Fix bug in redis hook
| Python | mit | synw/django-mqueue,synw/django-mqueue,synw/django-mqueue |
7ee29cfee740d6096fca8379253073077890a54c | examples/util/wordcount_redis.py | examples/util/wordcount_redis.py | from disco.schemes.scheme_redis import redis_output_stream
from disco.worker.task_io import task_output_stream
from disco.core import Job, result_iterator
class WordCount(Job):
reduce_output_stream = (task_output_stream, redis_output_stream)
@staticmethod
def map(line, params):
k, v = line
... | """
Usage:
python wordcount_redis.py redis://redis_server:6379:0 redis://redis_server:6379:1
The input is read from db 0 and the output is written to db 1. The inputs
should be of the form (key, list_of_values) (they are read from the server with the
lrange command. See the redis documentation for more info).
The ou... | Add more info to the redis example. | examples: Add more info to the redis example.
| Python | bsd-3-clause | seabirdzh/disco,discoproject/disco,oldmantaiter/disco,pooya/disco,oldmantaiter/disco,simudream/disco,pombredanne/disco,seabirdzh/disco,discoproject/disco,simudream/disco,discoproject/disco,ErikDubbelboer/disco,mozilla/disco,mozilla/disco,pombredanne/disco,ErikDubbelboer/disco,mwilliams3/disco,pooya/disco,mwilliams3/dis... |
9c7660fd63bc1c48a0533e867c7d18faf9d90c03 | main.py | main.py | #!/usr/bin/env python
from morss import main
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from morss import main, cgi_wrapper as application
if __name__ == '__main__':
main()
| Make use thru uwsgi easier | Make use thru uwsgi easier
Import the main cgi_wrapper as "application" in main.py
| Python | agpl-3.0 | pictuga/morss,pictuga/morss,pictuga/morss |
3cff942af436f16aab2078e6aeedd3073f4a5522 | flask_roots/extension.py | flask_roots/extension.py | from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
# from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions... | from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions =... | Add Flask-Mail, and null user loader | Add Flask-Mail, and null user loader | Python | bsd-3-clause | mikeboers/Flask-Roots,mikeboers/Flask-Roots |
0c0a1d0ec480c7df9dd8821d40af7791e46db453 | tests/lib/test_finance.py | tests/lib/test_finance.py | # Copyright (c) 2013 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from tests import OldPythonTestCase
__author__ = 'felix_kluge'
from pycroft.lib.finance import create_semester... | # Copyright (c) 2013 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from tests import OldPythonTestCase
__author__ = 'felix_kluge'
from pycroft.lib.finance import create_semester... | Fix for wrong test: create_semester_accounts | Fix for wrong test: create_semester_accounts
refs #448
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft |
169a8612eb06410a5ae7e110227f7bea010d2ba9 | tests/test_ghostscript.py | tests/test_ghostscript.py | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.com... | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.com... | Make stdout and stderr into strings. | Make stdout and stderr into strings.
| Python | mit | YPlan/treepoem |
ba37080645153d66a8ae1c8df10312806999f8ec | tests/test_observation.py | tests/test_observation.py | import unittest
from datetime import datetime
from dateutil.tz import tzutc
from fmi import FMI
class TestObservations(unittest.TestCase):
def test_lappeenranta(self):
now = datetime.now(tz=tzutc())
f = FMI(place='Lappeenranta')
for point in f.observations():
assert point.time... | import unittest
from datetime import datetime
from dateutil.tz import tzutc
from fmi import FMI
class TestObservations(unittest.TestCase):
def test_lappeenranta(self):
now = datetime.now(tz=tzutc())
f = FMI(place='Lappeenranta')
for point in f.observations():
assert point.time... | Add use of fmisid to tests. | Add use of fmisid to tests.
| Python | mit | kipe/fmi |
9369f72c4fe9a544e24f10a1db976589dc013424 | plinth/modules/sso/__init__.py | plinth/modules/sso/__init__.py | #
# This file is part of Plinth.
#
# This program 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
# License, or (at your option) any later version.
#
# This program is distribute... | #
# This file is part of Plinth.
#
# This program 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
# License, or (at your option) any later version.
#
# This program is distribute... | Add dependency on apache module | sso: Add dependency on apache module
This ensures that Apache is fully setup before setting up mod-auth-pubtkt.
Signed-off-by: Sunil Mohan Adapa <3eaa7035e78e5eca849aa1e8ea4aaf97b4588601@medhas.org>
Reviewed-by: James Valleroy <46e3063862880873c8617774e45d63de6172aab0@mailbox.org>
| Python | agpl-3.0 | kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth,kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,harry-7/Plinth |
ee98b5a5c6b82671738bc60e68ea87d838c5400f | migrations/0020_change_ds_name_to_non_uniqe.py | migrations/0020_change_ds_name_to_non_uniqe.py | from redash.models import db
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
# Change the uniqueness constraint on data source name to be (org, name):
success = False
... | from redash.models import db
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
# Change the uniqueness constraint on data source name to be (org, name):
# In some cases i... | Improve the migration for unique data source name | Improve the migration for unique data source name
| Python | bsd-2-clause | ninneko/redash,EverlyWell/redash,hudl/redash,useabode/redash,pubnative/redash,chriszs/redash,akariv/redash,alexanderlz/redash,easytaxibr/redash,pubnative/redash,amino-data/redash,rockwotj/redash,ninneko/redash,guaguadev/redash,rockwotj/redash,denisov-vlad/redash,imsally/redash,ninneko/redash,useabode/redash,crowdworks/... |
ca15e6523bd34e551528dce6c6ee3dcb70cf7806 | pyinfra/modules/util/files.py | pyinfra/modules/util/files.py | # pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return in... | # pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return in... | Use sed inline (unsure why mv was used originally). | Use sed inline (unsure why mv was used originally).
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra |
5a4d9255c59be0d5dda8272e0e7ced71822f4d40 | prime-factors/prime_factors.py | prime-factors/prime_factors.py | import sieve
def prime_factors(n):
primes = sieve.sieve(n)
factors = []
for p in primes:
while n % p == 0:
factors += [p]
n //= p
return factors
| def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
| Fix memory issues by just trying every number | Fix memory issues by just trying every number
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
8ea3350c6944946b60732308c912dc240952237c | project/settings_production.py | project/settings_production.py | from .settings import *
# Update SITE infos to use the common port 80 to publish the webapp
SITE_FIXED = {
'name': "Recalbox Manager",
'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname
'port': None, # If 'None' no port is added to hostname, so the server have to ... | from .settings import *
# Update SITE infos to use the common port 80 to publish the webapp
SITE_FIXED = {
'name': "Recalbox Manager",
'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname
'port': None, # If 'None' no port is added to hostname, so the server have to ... | Revert "Set the right recalbox.log path" | Revert "Set the right recalbox.log path"
| Python | mit | recalbox/recalbox-manager,recalbox/recalbox-manager,recalbox/recalbox-manager,sveetch/recalbox-manager,sveetch/recalbox-manager,sveetch/recalbox-manager,sveetch/recalbox-manager,recalbox/recalbox-manager,sveetch/recalbox-manager,recalbox/recalbox-manager |
fd4688cc899b08253cc50b345bb7e836081783d8 | bayespy/inference/vmp/nodes/__init__.py | bayespy/inference/vmp/nodes/__init__.py | ######################################################################
# Copyright (C) 2011,2012 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
###############... | ######################################################################
# Copyright (C) 2011,2012 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
###############... | Add Beta and Binomial to automatically imported nodes | ENH: Add Beta and Binomial to automatically imported nodes
| Python | mit | jluttine/bayespy,SalemAmeen/bayespy,fivejjs/bayespy,bayespy/bayespy |
06d0287a8fef0679b281296e6ed76e0b6c803acb | sorl/thumbnail/management/commands/thumbnail.py | sorl/thumbnail/management/commands/thumbnail.py | from django.core.management.base import BaseCommand, CommandError
from sorl.thumbnail.conf import settings
from sorl.thumbnail import default
class Command(BaseCommand):
help = (
u'Handles thumbnails and key value store'
)
args = '[cleanup, clear]'
option_list = BaseCommand.option_list
de... | import sys
from django.core.management.base import BaseCommand, CommandError
from sorl.thumbnail import default
class Command(BaseCommand):
help = (
u'Handles thumbnails and key value store'
)
args = '[cleanup, clear]'
option_list = BaseCommand.option_list
def handle(self, *labels, **opti... | Improve management command to clear or clean kvstore | Improve management command to clear or clean kvstore
| Python | bsd-3-clause | mariocesar/sorl-thumbnail,perdona/sorl-thumbnail,fdgogogo/sorl-thumbnail,Knotis/sorl-thumbnail,jcupitt/sorl-thumbnail,einvalentin/sorl-thumbnail,fladi/sorl-thumbnail,lampslave/sorl-thumbnail,seedinvest/sorl-thumbnail,guilouro/sorl-thumbnail,TriplePoint-Software/sorl-thumbnail,jazzband/sorl-thumbnail,jcupitt/sorl-thumbn... |
5c97b9911a2dafde5fd1e4c40cda4e84974eb855 | assembla/lib.py | assembla/lib.py | from functools import wraps
class AssemblaObject(object):
"""
Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`.
"""
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def keys(self):
return se... | from functools import wraps
class AssemblaObject(object):
"""
Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`.
"""
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value)... | Allow keys to be set (in anticipation of write commands). Better object __repr__() for spaces and tickets. | Allow keys to be set (in anticipation of write commands). Better object __repr__() for spaces and tickets. | Python | mit | markfinger/assembla |
07f86c47c58d6266bd4b42c81521001aca072ff1 | jsonconfigparser/test/__init__.py | jsonconfigparser/test/__init__.py | import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'foo = "bar"\n'
cf = JSONConfigParser()
cf.read_string(s... | import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
... | Add some more rubbish to example string | Add some more rubbish to example string
| Python | bsd-3-clause | bwhmather/json-config-parser |
e0dac0a621cbeed615553e5c3544f9c49de96eb2 | metadata/FrostNumberModel/hooks/pre-stage.py | metadata/FrostNumberModel/hooks/pre-stage.py | """A hook for modifying parameter values read from the WMT client."""
import os
import shutil
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
-------... | """A hook for modifying parameter values read from the WMT client."""
import os
import shutil
from wmt.utils.hook import find_simulation_input_file, yaml_dump
from topoflow_utils.hook import assign_parameters
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
... | Subtract 1 from model end_year | Subtract 1 from model end_year
This matches the behavior of the FrostNumberModel BMI.
| Python | mit | csdms/wmt-metadata |
9d29061f8520506d798ad75aa296be8dc838aaf7 | resolwe/elastic/pagination.py | resolwe/elastic/pagination.py | """.. Ignore pydocstyle D400.
==================
Elastic Paginators
==================
Paginator classes used in Elastic app.
.. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from rest_framework.pagination im... | """.. Ignore pydocstyle D400.
==================
Elastic Paginators
==================
Paginator classes used in Elastic app.
.. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from rest_framework.pagination im... | Remove leftover print call in paginator | Remove leftover print call in paginator
| Python | apache-2.0 | genialis/resolwe,jberci/resolwe,genialis/resolwe,jberci/resolwe |
61e4693988c5b89b4a82457181813e7a6e73403b | utils/text.py | utils/text.py | import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def slugify(model, field, value, validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
try:
validator(slug)
... | import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def no_validator(arg):
pass
def slugify(model, field, value, validator=no_validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
... | Fix slugify for use without validator | Fix slugify for use without validator
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten |
7c74017bc0d76ecb34e3fab44767290f51d98a09 | humbug/test_settings.py | humbug/test_settings.py | from settings import *
DATABASES["default"] = {"NAME": "zephyr/tests/zephyrdb.test",
"ENGINE": "django.db.backends.sqlite3",
"OPTIONS": { "timeout": 20, },}
TORNADO_SERVER = 'http://localhost:9983'
| from settings import *
DATABASES["default"] = {"NAME": "zephyr/tests/zephyrdb.test",
"ENGINE": "django.db.backends.sqlite3",
"OPTIONS": { "timeout": 20, },}
TORNADO_SERVER = 'http://localhost:9983'
# Decrease the get_updates timeout to 1 second.
# This allows CasperJS ... | Decrease get_updates timeout for client test suite | Decrease get_updates timeout for client test suite
Fixes #475.
(imported from commit d8f908c55f2e519541e5383a742edbf23183539c)
| Python | apache-2.0 | ryanbackman/zulip,christi3k/zulip,dnmfarrell/zulip,littledogboy/zulip,LAndreas/zulip,timabbott/zulip,hayderimran7/zulip,xuxiao/zulip,deer-hope/zulip,zhaoweigg/zulip,m1ssou/zulip,wdaher/zulip,punchagan/zulip,lfranchi/zulip,kokoar/zulip,voidException/zulip,brainwane/zulip,blaze225/zulip,akuseru/zulip,JPJPJPOPOP/zulip,hay... |
6486a888cbcec7285df92020f76e3f1c5fbba0e2 | bluebottle/test/test_runner.py | bluebottle/test/test_runner.py | from django.test.runner import DiscoverRunner
from django.db import connection
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *args, **kwargs):
result = supe... | from django.test.runner import DiscoverRunner
from django.db import connection
from django.core import management
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *arg... | Load exchange rates in test setup. Make it posible to use --keepdb | Load exchange rates in test setup. Make it posible to use --keepdb
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
873c5e8bf85a8be5a08852134967d29353ed3009 | examples/simple.py | examples/simple.py | from lobster import cmssw
from lobster.core import *
storage = StorageConfiguration(
output=[
"hdfs:///store/user/matze/test_shuffle_take29",
"file:///hadoop/store/user/matze/test_shuffle_take29",
"root://ndcms.crc.nd.edu//store/user/matze/test_shuffle_take29",
"... | from lobster import cmssw
from lobster.core import *
storage = StorageConfiguration(
output=[
"hdfs:///store/user/matze/test_shuffle_take29",
"file:///hadoop/store/user/matze/test_shuffle_take29",
"root://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
"sr... | Swap ndcms for generic T3 string. | Swap ndcms for generic T3 string.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster |
587abec7ff5b90c03885e164d9b6b62a1fb41f76 | grip/github_renderer.py | grip/github_renderer.py | from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
... | from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
... | Fix the headers sent by the GitHub renderer. | Fix the headers sent by the GitHub renderer.
| Python | mit | ssundarraj/grip,mgoddard-pivotal/grip,mgoddard-pivotal/grip,joeyespo/grip,joeyespo/grip,jbarreras/grip,jbarreras/grip,ssundarraj/grip |
d7cfdbd2bde0cc876db8c1bce020d8a1cf0ea77b | mdot_rest/views.py | mdot_rest/views.py | from django.shortcuts import render
from .models import Resource
from .serializers import ResourceSerializer
from rest_framework import generics, permissions
class ResourceList(generics.ListCreateAPIView):
queryset = Resource.objects.all()
serializer_class = ResourceSerializer
permission_classes = (permis... | from django.shortcuts import render
from .models import Resource
from .serializers import ResourceSerializer
from rest_framework import generics, permissions
import django_filters
class ResourceFilter(django_filters.FilterSet):
class Meta:
model = Resource
fields = ('name', 'featured', 'accessible... | Add search filtering for name and booleans in resource API. | Add search filtering for name and booleans in resource API.
| Python | apache-2.0 | uw-it-aca/mdot-rest,uw-it-aca/mdot-rest |
3555b002aae386220bc02d662a9b188426afc08f | cmsplugin_facebook/cms_plugins.py | cmsplugin_facebook/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_facebook import models
class BasePlugin(CMSPluginBase):
name = None
def render(self, context, instance, placeholder):
context.update({'instance': instance,
'name': self.name,
... | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_facebook import models
class BasePlugin(CMSPluginBase):
name = None
def render(self, context, instance, placeholder):
context.update({'instance': instance,
'name': self.name,
... | Create a specific group for the Facebook plugins - makes it a bit neater in the list of plugins. | Create a specific group for the Facebook plugins - makes it a bit neater in the list of plugins.
| Python | bsd-3-clause | chrisglass/cmsplugin_facebook |
97a490db75f0a4976199365c3f654ba8cdb9a781 | 01_Built-in_Types/tuple.py | 01_Built-in_Types/tuple.py | #!/usr/bin/env python
import sys
import pickle
# Check argument
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
# Write tuples
file = open(sys.argv[1], "wb");
line = []
while True:
print("Enter name, age, score (ex: zzz, 16, 90) or quit");
line = sys.stdin.readline()
... | #!/usr/bin/env python
import sys
import pickle
# Test zip, and format in print
names = ["xxx", "yyy", "zzz"]
ages = [18, 19, 20]
persons = zip(names, ages)
for name, age in persons:
print "{0}'s age is {1}".format(name, age)
# Check argument
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
rai... | Test zip, and print format | Test zip, and print format
| Python | bsd-2-clause | zzz0072/Python_Exercises,zzz0072/Python_Exercises |
e5963987e678926ad8cdde93e2551d0516a7686b | slave/skia_slave_scripts/android_bench_pictures.py | slave/skia_slave_scripts/android_bench_pictures.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run the Skia bench_pictures executable. """
from android_render_pictures import AndroidRenderPictures
from android_run_bench i... | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run the Skia bench_pictures executable. """
from android_render_pictures import AndroidRenderPictures
from android_run_bench i... | Increase timeout for bench_pictures on Android | Increase timeout for bench_pictures on Android
Unreviewed.
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@6290 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... |
b219823af7188f968d7c52c5273148c510bd7454 | blaze/compute/air/frontend/ckernel_impls.py | blaze/compute/air/frontend/ckernel_impls.py | """
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#----------------------... | """
Convert 'kernel' Op to 'ckernel'.
"""
from __future__ import absolute_import, division, print_function
from pykit.ir import transform, Op
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
class CKernelImplementations(object):
"""
For kernels... | Simplify the ckernel pass a bit more | Simplify the ckernel pass a bit more
| Python | bsd-3-clause | ChinaQuants/blaze,jdmcbr/blaze,xlhtc007/blaze,aterrel/blaze,FrancescAlted/blaze,mrocklin/blaze,maxalbert/blaze,alexmojaki/blaze,dwillmer/blaze,cowlicks/blaze,LiaoPan/blaze,jcrist/blaze,maxalbert/blaze,mrocklin/blaze,cowlicks/blaze,ChinaQuants/blaze,aterrel/blaze,scls19fr/blaze,mwiebe/blaze,FrancescAlted/blaze,nkhuyu/bl... |
970978b5355259fe943d5efed1b8b4ce945fdfa7 | weather.py | weather.py | #! /usr/bin/python2
from os.path import expanduser,isfile
from sys import argv
from urllib import urlopen
location_path="~/.location"
def location_from_homedir():
if isfile(expanduser(location_path)):
with open(expanduser(location_path)) as f:
return "&".join(f.read().split("\n"))
else:
... | #! /usr/bin/python2
from os.path import expanduser,isfile
import sys
from urllib import urlopen
location_path="~/.location"
def location_from_homedir():
if isfile(expanduser(location_path)):
with open(expanduser(location_path)) as f:
return "&".join(f.read().split("\n"))
else:
pri... | Debug control flow and exit on errors | Debug control flow and exit on errors
| Python | mit | robbystk/weather |
1caace2631f8e9c38cf0adfb1179a5260dcd3c33 | tools/management/commands/output_all_uniprot.py | tools/management/commands/output_all_uniprot.py | from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.db.models import Q
from django.template.loader import render_to_string
from protein.models import Protein
from residue.models im... | from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.db.models import Q
from django.template.loader import render_to_string
from protein.models import Protein
from residue.models im... | Change output_all_unitprot to allow multi ids for some proteins. | Change output_all_unitprot to allow multi ids for some proteins.
| Python | apache-2.0 | cmunk/protwis,fosfataza/protwis,fosfataza/protwis,fosfataza/protwis,cmunk/protwis,protwis/protwis,cmunk/protwis,cmunk/protwis,fosfataza/protwis,protwis/protwis,protwis/protwis |
abd3daed5cd0c70d76bf8fa1cfdda93efcda3e70 | knights/compat/django.py | knights/compat/django.py |
from django.core.urlresolvers import reverse
from django.utils.encoding import iri_to_uri
import datetime
from knights.library import Library
register = Library()
@register.helper
def now(fmt):
return datetime.datetime.now().strftime(fmt)
@register.helper
def url(name, *args, **kwargs):
try:
ret... |
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.encoding import iri_to_uri
import datetime
from knights.library import Library
register = Library()
@register.helper
def now(fmt):
return timezone.now().strftime(fmt)
@register.helper
def url(name, *args, **kwar... | Make the `now` helper timezone aware | Make the `now` helper timezone aware
Thanks @tysonclugg | Python | mit | funkybob/knights-templater,funkybob/knights-templater |
52a6ea1e7dd4333b9db6a0bbd53b8ae0b39a1f6d | Designs/redundant.py | Designs/redundant.py | '''Due to the needs arising from completing the project on time, I have defined redundant.py
which will hold replacement modules as I migrate from file based application to lists only web application. This modules
so far will offer the capabilities of registration, creating a shopping list and adding items into
a shopp... | '''Due to the needs arising from completing the project on time, I have defined redundant.py
which will hold replacement modules as I migrate from file based application to lists only web application. This modules
so far will offer the capabilities of registration, creating a shopping list and adding items into
a shopp... | Add __doc__ to module functions | [Fix] Add __doc__ to module functions
| Python | mit | AndersonMasese/Myshop,AndersonMasese/Myshop,AndersonMasese/Myshop |
5fbb4ff5d3427c8f4050fc5b75d4a6a2c15351c6 | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Donne Martin'
SITENAME = 'Donne Martin'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM ... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Donne Martin'
SITENAME = 'Donne Martin'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM ... | Set pygments style to monokai. | Set pygments style to monokai.
| Python | mit | donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io |
fbdaeff6f01ffaf0ac4f9a0d0d962a19c2865b32 | jupyterlab/labhubapp.py | jupyterlab/labhubapp.py | import os
import warnings
from traitlets import default
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(SingleUser... | import os
from traitlets import default
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, Lab... | Add docstring documenting the intended use of LabHubApp. | Add docstring documenting the intended use of LabHubApp.
| Python | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab |
de9f9c07c6f1dde8d7ad314b6a6fb58a963e1558 | geodj/youtube.py | geodj/youtube.py | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... | from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderb... | Return as many results as possible | Return as many results as possible
| Python | mit | 6/GeoDJ,6/GeoDJ |
db1653c551f71092a7eca96e6a4d1c96ef17e06a | lib/rapidsms/message.py | lib/rapidsms/message.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import copy
class Message(object):
def __init__(self, backend, caller=None, text=None):
self._backend = backend
self.caller = caller
self.text = text
# initialize some empty attributes
self.received = None
... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import copy
class Message(object):
def __init__(self, backend, caller=None, text=None):
self._backend = backend
self.caller = caller
self.text = text
self.responses = []
def __unicode__(self):
return self.text
... | Remove unused attributes; also, empty responses after it's flushed. | Remove unused attributes; also, empty responses after it's flushed.
| Python | bsd-3-clause | rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy |
4b54d1472a57ad4d45293ec7bdce9a0ed9746bde | ideasbox/mixins.py | ideasbox/mixins.py | from django.views.generic import ListView
class ByTagListView(ListView):
def get_queryset(self):
qs = super(ByTagListView, self).get_queryset()
if 'tag' in self.kwargs:
qs = qs.filter(tags__slug__in=[self.kwargs['tag']])
return qs
def get_context_data(self, **kwargs):
... | from django.views.generic import ListView
from taggit.models import Tag
class ByTagListView(ListView):
def get_queryset(self):
qs = super(ByTagListView, self).get_queryset()
if 'tag' in self.kwargs:
qs = qs.filter(tags__slug__in=[self.kwargs['tag']])
return qs
def get_co... | Use tag name not slug in tag page title | Use tag name not slug in tag page title
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,ideascube/ideascube |
72539e1a83eba8db9adfdeef6099081475ef8d86 | objectset/forms.py | objectset/forms.py | from django import forms
from .models import ObjectSet
def objectset_form_factory(Model, queryset=None):
"""Takes an ObjectSet subclass and defines a base form class.
In addition, an optional queryset can be supplied to limit the choices
for the objects.
This uses the generic `objects` field rather ... | from django import forms
from .models import ObjectSet
def objectset_form_factory(Model, queryset=None):
"""Takes an ObjectSet subclass and defines a base form class.
In addition, an optional queryset can be supplied to limit the choices
for the objects.
This uses the generic `objects` field rather ... | Handle Django 1.4 nuance for the empty ModelMultipleChoiceField values | Handle Django 1.4 nuance for the empty ModelMultipleChoiceField values | Python | bsd-2-clause | chop-dbhi/django-objectset,chop-dbhi/django-objectset |
6694a9e8d554c9450cdf6cd076bb56a324048b44 | social/apps/django_app/urls.py | social/apps/django_app/urls.py | """URLs module"""
from django.conf import settings
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.4
from django.conf.urls.defaults import patterns, url
from social.utils import setting_name
extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''
... | """URLs module"""
from django import VERSION
from django.conf import settings
from django.conf.urls import url
from social.apps.django_app import views
from social.utils import setting_name
extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''
urlpatterns = (
# authentication / associati... | Update the url patterns to be compliant with Django 1.9 new formatting | Update the url patterns to be compliant with Django 1.9 new formatting
so need to support Django < 1.8 because it is now deprecated for
security reasons
| Python | bsd-3-clause | cmichal/python-social-auth,cmichal/python-social-auth,cmichal/python-social-auth |
5c0282810f298762bdd00c260f40e2ceb7914eb0 | tests/test_dna.py | tests/test_dna.py | #!/usr/bin/env python2
import pytest
from kbkdna.dna import *
def test_reverse_complement():
assert reverse_complement('ATGC') == 'GCAT'
def test_gc_content():
assert gc_content('ATGC') == 0.5
| #!/usr/bin/env python2
import pytest
import kbkdna
def test_reverse_complement():
assert kbkdna.reverse_complement('ATGC') == 'GCAT'
def test_gc_content():
assert kbkdna.gc_content('ATGC') == 0.5
| Simplify the imports in the tests. | Simplify the imports in the tests.
| Python | mit | kalekundert/kbkdna |
1e62c328bb42ec123e75b5c66fb29f002cd57db2 | tests/test_nap.py | tests/test_nap.py |
from nap.api import Api
from . import HttpServerTestBase
class TestNap(HttpServerTestBase):
def test_unallowed_method(self):
"""Tries to use non-existent HTTP method"""
api = Api('http://localhost:8888')
with self.assertRaises(AttributeError):
api.resource.nonexisting()
| """
Tests for nap module.
These tests only focus that requests is called properly.
Everything related to HTTP requests should be tested in requests' own tests.
"""
import unittest
import requests
from nap.api import Api
class TestNap(unittest.TestCase):
def test_unallowed_method(self):
"""Tries to use... | Document module and add couple of tests | Document module and add couple of tests
| Python | mit | kimmobrunfeldt/nap |
5f72b6edc28caa7bf03720ed27a9f3aa32c8323e | go/billing/management/commands/go_gen_statements.py | go/billing/management/commands/go_gen_statements.py | from datetime import datetime
from optparse import make_option
from go.billing.models import Account
from go.billing.tasks import month_range, generate_monthly_statement
from go.base.command_utils import BaseGoCommand, get_user_by_email
class Command(BaseGoCommand):
help = "Generate monthly billing statements fo... | from datetime import datetime
from optparse import make_option
from go.billing.models import Account
from go.billing.tasks import month_range, generate_monthly_statement
from go.base.command_utils import BaseGoCommand, get_user_by_email
class Command(BaseGoCommand):
help = "Generate monthly billing statements fo... | Fix broken billing statement command tests | Fix broken billing statement command tests
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
1e8f9a95badc1e2b558bae7570ef9bc23f26a0df | pyhaystack/info.py | pyhaystack/info.py | # -*- coding: utf-8 -*-
"""
File : pyhaystackTest.py (2.x)
This module allow a connection to a haystack server
Feautures provided allow user to fetch data from the server and eventually, to post to it.
See http://www.project-haystack.org for more details
Project Haystack is an open source initiative to streamline wor... | # -*- coding: utf-8 -*-
"""
File : pyhaystackTest.py (2.x)
This module allow a connection to a haystack server
Feautures provided allow user to fetch data from the server and eventually, to post to it.
See http://www.project-haystack.org for more details
Project Haystack is an open source initiative to streamline wor... | Modify version to 0.72 to mark change | Modify version to 0.72 to mark change
Signed-off-by: Christian Tremblay <31ac1ca2e4859489ad6997067c1b3a4264642859@servisys.com>
| Python | apache-2.0 | ChristianTremblay/pyhaystack,vrtsystems/pyhaystack,ChristianTremblay/pyhaystack |
36ea751618287a75fc82db500d953d4fa40b373b | tests/containers/entrypoint/renew-demo-token.py | tests/containers/entrypoint/renew-demo-token.py | #!/usr/bin/python3
import os
import json
import time
from urllib import request
# Create the requested json
demo_json = {
"payload": {
"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
}
# Co... | #!/usr/bin/python3
import os
import json
import time
from urllib import request
# Request payload
payload = {"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
# Convert the format from... | Update token renewal due to demo.scitokens.org API update | Update token renewal due to demo.scitokens.org API update
| Python | apache-2.0 | matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,brianhlin/htcondor-ce |
1eacbac722ca949518e1a8e9d6a0a957e193ba9e | tests/functional/staging_and_prod/test_admin.py | tests/functional/staging_and_prod/test_admin.py | from retry.api import retry_call
from config import config
from tests.pages import UploadCsvPage
from tests.postman import (
send_notification_via_csv,
get_notification_by_id_via_api,
)
from tests.test_utils import assert_notification_body, recordtime, NotificationStatuses
@recordtime
def test_admin(driver... | import pytest
from retry.api import retry_call
from config import config
from tests.pages import UploadCsvPage
from tests.postman import (
send_notification_via_csv,
get_notification_by_id_via_api,
)
from tests.test_utils import assert_notification_body, recordtime, NotificationStatuses
@pytest.mark.skip(... | Disable CSV upload tests temporarily | Disable CSV upload tests temporarily
When the database tasks queue builds up we get false pager duty alerts due to the time it takes for the test csv to get through to the front of the queue. | Python | mit | alphagov/notifications-functional-tests,alphagov/notifications-functional-tests |
428889029541bb5c8f8998eb1f4cbc057a80fb87 | s2v2.py | s2v2.py | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv)
print(number_of_ties, "ties in our data sample") | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
print(number_of_ties, "ties in our data sample") | Subtract header row for acurate counting | Subtract header row for acurate counting
| Python | mit | alexmilesyounger/ds_basics |
bd7ef1be82a6cd68060dee47046d90202b3a9e0c | tempest/api/volume/test_availability_zone.py | tempest/api/volume/test_availability_zone.py | # Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | # Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | Remove unnecessary client alias in AvailabilityZoneTestJson | Remove unnecessary client alias in AvailabilityZoneTestJson
The class AvailabilityZoneTestJson is inherited from base.BaseVolumeTest,
and the latter has already declared the availability_zone_client. This
patch removes the unnecessary client alias for availability_zone_client.
Change-Id: I287d742087a72928774325681bb7... | Python | apache-2.0 | masayukig/tempest,masayukig/tempest,Juniper/tempest,Juniper/tempest,openstack/tempest,cisco-openstack/tempest,cisco-openstack/tempest,openstack/tempest |
bbfb09205974efa969fc636b6e1079a84dad3619 | mcstatus/application.py | mcstatus/application.py | from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
try:
query = MinecraftQuery("mc.voltaire.sh", 25565, 10, 3)
basicQuery = query.get_status()
fullQuery = query.get_rules()
except socket.error as e... | from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
query = MinecraftQuery("142.54.162.42", 25565)
basic_status = query.get_status()
all_status = query.get_rules()
server_info = 'The server has %d / %d players.' % (basic_... | Revert "check for connection failure" | Revert "check for connection failure"
This reverts commit cf4bd49e150f5542a5a7abba908ca81ebe1b9e75.
| Python | bsd-3-clause | voltaire/minecraft-site-old,voltaire/minecraft-site-old |
906247c6431b85c90f8aec8a7f4f73f1064abeba | mezzanine/pages/urls.py | mezzanine/pages/urls.py |
from django.conf.urls.defaults import patterns, url
# Page patterns.
urlpatterns = patterns("mezzanine.pages.views",
url("^admin_page_ordering/$", "admin_page_ordering",
name="admin_page_ordering"),
url("^(?P<slug>.*)/$", "page", name="page"),
)
|
from django.conf.urls.defaults import patterns, url
from django.conf import settings
# Page patterns.
urlpatterns = patterns("mezzanine.pages.views",
url("^admin_page_ordering/$", "admin_page_ordering",
name="admin_page_ordering"),
url("^(?P<slug>.*)" + ("/" if settings.APPEND_SLASH else "") + "$", "... | Use Page URLs without trailing slash when settings.APPEND_SLASH is False | Use Page URLs without trailing slash when settings.APPEND_SLASH is False
| Python | bsd-2-clause | biomassives/mezzanine,AlexHill/mezzanine,spookylukey/mezzanine,frankchin/mezzanine,saintbird/mezzanine,adrian-the-git/mezzanine,jjz/mezzanine,agepoly/mezzanine,geodesign/mezzanine,jerivas/mezzanine,saintbird/mezzanine,wyzex/mezzanine,Skytorn86/mezzanine,industrydive/mezzanine,ryneeverett/mezzanine,eino-makitalo/mezzani... |
32d5f2bfcaad65230632f1854fabd2e9de1c151b | tests/query_test/test_chars.py | tests/query_test/test_chars.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'function... | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'function... | Fix char test to only run on test/none. | Fix char test to only run on test/none.
Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326
Tested-by: jenkins
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
| Python | apache-2.0 | ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC |
9909ce7e900097b74b701ad52c0aae5ba68b8823 | morenines/repository.py | morenines/repository.py | import os
from morenines import output
from morenines import util
from morenines.index import Index
from morenines.ignores import Ignores
NAMES = {
'repo_dir': '.morenines',
'index': 'index',
'ignore': 'ignore',
}
class Repository(object):
def __init__(self):
self.path = None
self.... | import os
from morenines import output
from morenines import util
from morenines.index import Index
from morenines.ignores import Ignores
NAMES = {
'mn_dir': '.morenines',
'index': 'index',
'ignore': 'ignore',
}
class Repository(object):
def __init__(self):
self.path = None
self.in... | Rework Repository to include paths | Rework Repository to include paths
| Python | mit | mcgid/morenines,mcgid/morenines |
dc071e4961c7db7e98e7dfdcd74cce368ce31039 | dataportal/tests/test_examples.py | dataportal/tests/test_examples.py | from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
def run_example(example):
events = example.run()
assert_true(isinstance(events, list))
assert_true(isinsta... | import subprocess
from nose.tools import assert_true, assert_equal
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
examples = [temperature_ramp, multisource_event, image_and_scalar]
def run_example_... | Test commandline execution of examples. | TST: Test commandline execution of examples.
| Python | bsd-3-clause | tacaswell/dataportal,NSLS-II/datamuxer,tacaswell/dataportal,danielballan/datamuxer,NSLS-II/dataportal,ericdill/datamuxer,NSLS-II/dataportal,ericdill/databroker,ericdill/datamuxer,ericdill/databroker,danielballan/dataportal,danielballan/datamuxer,danielballan/dataportal |
1915cde046c1817c45317ad8ce882e807671fca3 | oauth_api/permissions.py | oauth_api/permissions.py | from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_on... | from django.core.exceptions import ImproperlyConfigured
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, req... | Raise ImproperlyConfigured if resource has no scopes defined | Raise ImproperlyConfigured if resource has no scopes defined
| Python | bsd-2-clause | eofs/django-oauth-api,eofs/django-oauth-api |
846a005c20ddc2e7702be48f5b2839b1c9fd1576 | project/apps/api/management/commands/denormalize.py | project/apps/api/management/commands/denormalize.py | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v... | from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v... | Remove ranking from denormalization command | Remove ranking from denormalization command
| Python | bsd-2-clause | barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore |
b98ab1c800a13792bdca69c5788e91bc07f1e215 | rpp/encoder.py | rpp/encoder.py | from uuid import UUID
from scanner import Symbol
def tostr(value):
if isinstance(value, Symbol):
return str(value)
elif isinstance(value, str):
return '"%s"' % value
elif isinstance(value, float):
return '%.14f' % value
elif isinstance(value, UUID):
return '{%s}' % str(v... | from uuid import UUID
from scanner import Symbol
def tostr(value):
if isinstance(value, Symbol):
return str(value)
elif isinstance(value, str):
return '"%s"' % value
elif isinstance(value, float):
return '%.14f' % value
elif isinstance(value, UUID):
return '{%s}' % str(v... | Insert new line for each Symbol object | Insert new line for each Symbol object
| Python | bsd-3-clause | Perlence/rpp |
2b70879e2d73453d81ed738f34cf20d39afdc3ad | byceps/blueprints/authorization/decorators.py | byceps/blueprints/authorization/decorators.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.authorization.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from functools import wraps
from flask import abort, g
def permission_required(permission):
"""Ensur... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.authorization.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from functools import wraps
from flask import abort, g
def permission_required(permission):
"""Ensur... | Call `has_permission` method instead of accessing the collection directly | Call `has_permission` method instead of accessing the collection directly
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps |
c7d522393930dabc1bb6997bbc2b450d043817e8 | wagtail/utils/widgets.py | wagtail/utils/widgets.py | from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
class WidgetWithScript(Widget):
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, a... | from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
class WidgetWithScript(Widget):
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, a... | Fix WidgetWithScript to accept renderer kwarg | Fix WidgetWithScript to accept renderer kwarg
| Python | bsd-3-clause | FlipperPA/wagtail,nimasmi/wagtail,timorieber/wagtail,kaedroho/wagtail,wagtail/wagtail,takeflight/wagtail,zerolab/wagtail,kaedroho/wagtail,gasman/wagtail,timorieber/wagtail,zerolab/wagtail,wagtail/wagtail,mikedingjan/wagtail,jnns/wagtail,zerolab/wagtail,mixxorz/wagtail,nimasmi/wagtail,zerolab/wagtail,mixxorz/wagtail,wag... |
ea3576e16b0a8278cd9d35715c8881e9d136eec8 | paystackapi/tests/test_cpanel.py | paystackapi/tests/test_cpanel.py | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.registe... | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.registe... | Add control panel test for update | Add control panel test for update
| Python | mit | andela-sjames/paystack-python |
3d88e62cdd2521472d0475a5f4c8598d49f88571 | code/python/echomesh/sound/CPlayer.py | code/python/echomesh/sound/CPlayer.py | from __future__ import absolute_import, division, print_function, unicode_literals
import cechomesh
from echomesh.expression.Envelope import Envelope
from echomesh.sound import PlayerSetter
from echomesh.util import Log
from echomesh.util.thread.MasterRunnable import MasterRunnable
LOGGER = Log.logger(__name__)
de... | from __future__ import absolute_import, division, print_function, unicode_literals
import cechomesh
from echomesh.expression.Envelope import Envelope
from echomesh.sound import PlayerSetter
from echomesh.util import Log
from echomesh.util.thread.MasterRunnable import MasterRunnable
LOGGER = Log.logger(__name__)
cla... | Remove tiny amounts of cruft. | Remove tiny amounts of cruft.
| Python | mit | rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh |
8e0d61aa69a15a9efc967ec263bc73c3018f9b3d | process_to_only_word.py | process_to_only_word.py | # -*- coding: utf-8 -*-
import re
import sys
###########################################################################
# This code is developing yet!!
# Target file(Already morphological analysis file) to process to word only.
###########################################################################
argvs = sys.a... | # -*- coding: utf-8 -*-
import re
import sys
###########################################################################
# This code is developing yet!!
# Target file(Already morphological analysis file) to process to word only.
# <How to use>
# python process_to_only_word.py <Target file(Already morphological analysi... | Add a "How to use(comment)" | Add a "How to use(comment)"
| Python | mit | shinshin86/little-magnifying-py-glass,shinshin86/little-magnifying-py-glass |
c2a8e69a5deee8f72c561f50732570801d4fc9ae | tests/test_stack_operations.py | tests/test_stack_operations.py | import pytest
from thinglang.execution.errors import UnknownVariable
from thinglang.runner import run
def test_stack_resolution_in_block():
assert run("""
thing Program
does start
number i = 0
Output.write("outside before, i =", i)
if true
Output.write("inside before, i =... | import pytest
from thinglang.execution.errors import UnknownVariable
from thinglang.runner import run
def test_stack_resolution_in_block():
assert run("""
thing Program
does start
number i = 0
Output.write("outside before, i =", i)
if true
Output.write("inside before, i =... | Add test for variables declared inside a scope (and accessed outside) | Add test for variables declared inside a scope (and accessed outside)
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.