commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
2029256cda7e3bc752d30361357932053cb98744 | shell.py | shell.py | from person import Person
def go(db):
global status
while status == 1:
inputText = input("command>")
for i in commands:
if inputText == i:
commands[i](db)
def helpMe(db):
print("help:")
for i in commandsHelp:
print(i, ":", commandsHelp[i])
def add... | from person import Person
def go(db):
global status
while status == 1:
inputText = input("command> ")
for i in commands:
if inputText == i:
commands[i](db)
def helpMe(db):
print("help:")
for i in commandsHelp:
print("\t", i, ":", commandsHelp[i])
... | Add whitespaces to print it better. | Add whitespaces to print it better.
Signed-off-by: Matej Dujava <03ce64f61b3ea1fda633fb2a103b989e3272d16b@gmail.com>
| Python | mit | matejd11/birthdayNotify | ---
+++
@@ -4,7 +4,7 @@
def go(db):
global status
while status == 1:
- inputText = input("command>")
+ inputText = input("command> ")
for i in commands:
if inputText == i:
commands[i](db)
@@ -12,19 +12,19 @@
def helpMe(db):
print("help:")
for ... |
a612e39f2395aa04bb3fd063188c4a1038324b04 | stock.py | stock.py | class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price = None
def update(self, timestamp, price):
self.price = price
| class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price = None
def update(self, timestamp, price):
if price < 0:
raise ValueError("price should not be negative")
self.price = price
| Update update method for negative price exception. | Update update method for negative price exception.
| Python | mit | bsmukasa/stock_alerter | ---
+++
@@ -4,4 +4,6 @@
self.price = None
def update(self, timestamp, price):
+ if price < 0:
+ raise ValueError("price should not be negative")
self.price = price |
0b7c0c727b3b56cc20b90da90732fae28aaaf479 | iis/jobs/__init__.py | iis/jobs/__init__.py | from flask import Blueprint
jobs = Blueprint('jobs', __name__, template_folder='./templates')
from . import views, models # noqa: E402, F401
| from flask import Blueprint
jobs = Blueprint('jobs', __name__,
template_folder='./templates') # type: Blueprint
from . import views, models # noqa: E402, F401
| Fix mypy complaint about unknown type | Fix mypy complaint about unknown type
| Python | agpl-3.0 | interactomix/iis,interactomix/iis | ---
+++
@@ -1,6 +1,7 @@
from flask import Blueprint
-jobs = Blueprint('jobs', __name__, template_folder='./templates')
+jobs = Blueprint('jobs', __name__,
+ template_folder='./templates') # type: Blueprint
from . import views, models # noqa: E402, F401 |
bfdb2c41c06375d1fe8ff196486ffd71873e0264 | wush/utils.py | wush/utils.py | import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
def _... | import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
def _... | Fix a recursion error caused by wrong signature. | Fix a recursion error caused by wrong signature.
| Python | mit | theju/wush | ---
+++
@@ -18,4 +18,4 @@
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
kwargs["job_class"] = CustomJob
- super(CustomQueue, self).__init__(self, *args, **kwargs)
+ super(CustomQueue, self).__init__(*args, **kwargs) |
731935873ee4c342bfaa5825cdc9e39ce79d71a5 | invocations/_version.py | invocations/_version.py | __version_info__ = (0, 9, 2)
__version__ = '.'.join(map(str, __version_info__))
| __version_info__ = (0, 10, 0)
__version__ = '.'.join(map(str, __version_info__))
| Cut 0.10 for new feature in docs module | Cut 0.10 for new feature in docs module
| Python | bsd-2-clause | pyinvoke/invocations,mrjmad/invocations,singingwolfboy/invocations | ---
+++
@@ -1,2 +1,2 @@
-__version_info__ = (0, 9, 2)
+__version_info__ = (0, 10, 0)
__version__ = '.'.join(map(str, __version_info__)) |
a8ccc99aa0923be9a102bb6d42590d3214d4d229 | tests.py | tests.py | import json
import unittest
from pyunio import pyunio
pyunio.use('httpbin')
params = {
'body': {
'name': 'James Bond'
}
}
def test_get():
response = json.loads(pyunio.get('get', params).text)
assert(response['args']['name'] == 'James Bond')
... | import json
import unittest
from pyunio import pyunio
pyunio.use('httpbin')
params = {
'body': {
'name': 'James Bond'
}
}
class pyuniotTest(unittest.TestCase):
def test_get(self):
response = json.loads(pyunio.get('get', params).text)
... | Add pyuniotest class for unittest, but still lake mock server for test. | Add pyuniotest class for unittest, but still lake mock server for test.
| Python | mit | citruspi/PyUnio | ---
+++
@@ -10,30 +10,27 @@
}
}
+class pyuniotTest(unittest.TestCase):
-def test_get():
-
- response = json.loads(pyunio.get('get', params).text)
-
- assert(response['args']['name'] == 'James Bond')
+ def test_get(self):
+ response = json.loads(pyunio.get('get', par... |
1aaa261af71d8f8a57f360b9525a38fb537858d1 | sites/us/apps/shipping/repository.py | sites/us/apps/shipping/repository.py | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')... | from decimal import Decimal as D
from oscar.apps.shipping import repository, methods, models
class Standard(methods.FixedPrice):
code = "standard"
name = "Standard"
charge_excl_tax = D('10.00')
class Express(methods.FixedPrice):
code = "express"
name = "Express"
charge_excl_tax = D('20.00')... | Bring US site shipping repo up-to-date | Bring US site shipping repo up-to-date
The repo internals had changed since the US site was born.
| Python | bsd-3-clause | jinnykoo/wuyisj,john-parton/django-oscar,rocopartners/django-oscar,QLGu/django-oscar,michaelkuty/django-oscar,WillisXChen/django-oscar,eddiep1101/django-oscar,kapari/django-oscar,sonofatailor/django-oscar,jinnykoo/wuyisj,faratro/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,WillisXChen/django-oscar,jmt... | ---
+++
@@ -16,17 +16,13 @@
class Repository(repository.Repository):
- methods = [Standard, Express]
- def get_shipping_methods(self, basket, user=None, shipping_addr=None,
- request=None, **kwargs):
- methods = super(Repository, self).get_shipping_methods(
- ... |
c2c9efed928b1414cb906cb23356e4af2baaf6e4 | LanguageServerClient.py | LanguageServerClient.py | import neovim
import os, subprocess
import json
@neovim.plugin
class LanguageServerClient:
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
# ['langserver-go', '-trace', '-logfile', '/tmp/lan... | import neovim
import os, subprocess
import json
@neovim.plugin
class LanguageServerClient:
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
["/bin/bash", "/opt/rls/wrapper.sh"],
# ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
... | Use inout proxy script for log. | Use inout proxy script for log.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L... | ---
+++
@@ -8,7 +8,8 @@
def __init__(self, nvim):
self.nvim = nvim
self.server = subprocess.Popen(
- ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
+ ["/bin/bash", "/opt/rls/wrapper.sh"],
+ # ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"],
... |
4c0ad1cbf346c6d34a924c77081f2dd37e7f86ac | mochi/utils/pycloader.py | mochi/utils/pycloader.py | """Import a Python object made by compiling a Mochi file.
"""
import os
from mochi.core import pyc_compile_monkeypatch
def get_function(name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
imported function.
"""
return getattr(get_module(name... | """Import a Python object made by compiling a Mochi file.
"""
import os
from mochi.core import init, pyc_compile_monkeypatch
def get_function(name, file_path):
"""Python function from Mochi.
Compiles a Mochi file to Python bytecode and returns the
imported function.
"""
return getattr(get_modul... | Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch | Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch
| Python | mit | slideclick/mochi,i2y/mochi,pya/mochi,slideclick/mochi,i2y/mochi,pya/mochi | ---
+++
@@ -3,7 +3,7 @@
import os
-from mochi.core import pyc_compile_monkeypatch
+from mochi.core import init, pyc_compile_monkeypatch
def get_function(name, file_path):
@@ -26,3 +26,5 @@
py_name = os.path.join(base_path, name + '.pyc')
pyc_compile_monkeypatch(mochi_name, py_name)
return __i... |
33198314eb70b079b2fdb918abd66d7296f65219 | website/addons/forward/tests/test_models.py | website/addons/forward/tests/test_models.py | # -*- coding: utf-8 -*-
from nose.tools import * # PEP8 asserts
from modularodm.exceptions import ValidationError
from tests.base import OsfTestCase
from website.addons.forward.tests.factories import ForwardSettingsFactory
class TestSettingsValidation(OsfTestCase):
def setUp(self):
super(TestSettings... | # -*- coding: utf-8 -*-
from nose.tools import * # PEP8 asserts
from modularodm.exceptions import ValidationError
from tests.base import OsfTestCase
from tests.factories import ProjectFactory, RegistrationFactory
from website.addons.forward.tests.factories import ForwardSettingsFactory
class TestNodeSettings(OsfT... | Add test for forward registering | Add test for forward registering
| Python | apache-2.0 | alexschiller/osf.io,mluo613/osf.io,emetsger/osf.io,chrisseto/osf.io,cslzchen/osf.io,DanielSBrown/osf.io,TomBaxter/osf.io,monikagrabowska/osf.io,mluo613/osf.io,caneruguz/osf.io,laurenrevere/osf.io,adlius/osf.io,aaxelb/osf.io,SSJohns/osf.io,SSJohns/osf.io,felliott/osf.io,saradbowman/osf.io,laurenrevere/osf.io,monikagrabo... | ---
+++
@@ -5,8 +5,24 @@
from modularodm.exceptions import ValidationError
from tests.base import OsfTestCase
+from tests.factories import ProjectFactory, RegistrationFactory
from website.addons.forward.tests.factories import ForwardSettingsFactory
+
+class TestNodeSettings(OsfTestCase):
+
+ def setUp(self)... |
6413ce937fbdfdf1acc5cffab4f01f0b40fb2cfc | views.py | views.py | #!/usr/bin/python3.4
from flask import Flask, render_template, url_for, Markup
from flask.ext.libsass import *
import pkg_resources
import markdown
app=Flask(__name__)
Sass(
{'app': 'scss/app.scss'},
app,
url_path='/static/css',
include_paths=[pkg_resources.resource_filename('views', 'scss')],
output_style='comp... | #!/usr/bin/python3.4
from flask import Flask, render_template, url_for, Markup, abort
from flask.ext.libsass import *
import pkg_resources
import markdown
app=Flask(__name__)
Sass(
{'app': 'scss/app.scss'},
app,
url_path='/static/css',
include_paths=[pkg_resources.resource_filename('views', 'scss')],
output_styl... | Add basic page request exception handling | Add basic page request exception handling
| Python | mpl-2.0 | vishwin/vishwin.info-http,vishwin/vishwin.info-http,vishwin/vishwin.info-http | ---
+++
@@ -1,5 +1,5 @@
#!/usr/bin/python3.4
-from flask import Flask, render_template, url_for, Markup
+from flask import Flask, render_template, url_for, Markup, abort
from flask.ext.libsass import *
import pkg_resources
import markdown
@@ -16,12 +16,15 @@
@app.route('/<page>')
def get_page(page):
- md=open... |
066d2db105e4ac1cc5f52c0987c6c6832054bd78 | pygraphc/clustering/ConnectedComponents.py | pygraphc/clustering/ConnectedComponents.py | import networkx as nx
class ConnectedComponents:
def __init__(self, g):
self.g = g
def get_connected_components(self):
clusters = []
for components in nx.connected_components(self.g):
clusters.append(components)
cluster_id = 0
for cluster in clusters:
... | import networkx as nx
class ConnectedComponents:
def __init__(self, g):
self.g = g
def get_clusters(self):
clusters = []
for components in nx.connected_components(self.g):
clusters.append(components)
cluster_id = 0
for cluster in clusters:
for ... | Rename method get_cluster and revise self.g.node when accessing a node | Rename method get_cluster and revise self.g.node when accessing a node
| Python | mit | studiawan/pygraphc | ---
+++
@@ -5,7 +5,7 @@
def __init__(self, g):
self.g = g
- def get_connected_components(self):
+ def get_clusters(self):
clusters = []
for components in nx.connected_components(self.g):
clusters.append(components)
@@ -13,7 +13,7 @@
cluster_id = 0
... |
ef323ee8d607b8b9e6a2ee8107324e62297e14ea | nesCart.py | nesCart.py | # http://fms.komkon.org/EMUL8/NES.html#LABM
import struct
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
self.romData = open(romPath, 'rb').read()
if "NES" not in self.romData[0:3]:
print "Unrecognized format!"
return None
... | # http://fms.komkon.org/EMUL8/NES.html#LABM
import struct
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
romData = open(romPath, 'rb').read()
headerSize = 0x10
bankSize = 0x4000
vromBankSize = 0x2000
if "NES" not in romData[0:4]:
... | Add the rest of the basic parsing code | Add the rest of the basic parsing code
| Python | bsd-2-clause | pusscat/refNes | ---
+++
@@ -5,14 +5,53 @@
class Rom(object):
def __init__(self, romPath, cpu):
self.path = romPath
- self.romData = open(romPath, 'rb').read()
+ romData = open(romPath, 'rb').read()
- if "NES" not in self.romData[0:3]:
+ headerSize = 0x10
+ bankSize = 0x4000
+ ... |
781a0cdce589c0b0f4ecc6966cb3abb9e79e98eb | kolibri/__init__.py | kolibri/__init__.py | """
CAUTION! Keep everything here at at minimum. Do not import stuff.
This module is imported in setup.py, so you cannot for instance
import a dependency.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils import env
from .utils.version ... | """
CAUTION! Keep everything here at at minimum. Do not import stuff.
This module is imported in setup.py, so you cannot for instance
import a dependency.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils import env
from .utils.version ... | Revert "Updating VERSION for a new alpha" | Revert "Updating VERSION for a new alpha"
This reverts commit c0ea9cf95e38f84f9edb4576dd45290ecf42ca1f.
| Python | mit | mrpau/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri | ---
+++
@@ -15,7 +15,7 @@
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
-VERSION = (0, 10, 4, 'alpha', 0)
+VERSION = (0, 10, 3, 'final', 0)
__author__ = 'Learning Equality'
__email__ = 'info@learningequali... |
e40f44cf090428eea3cab01913bef614d5dae121 | pnrg/filters.py | pnrg/filters.py | from jinja2._compat import text_type
from datetime import datetime
import re
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return text_type(value).rjust(width)
_LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
... | from jinja2._compat import text_type
import datetime
import re
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return text_type(value).rjust(width)
_LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compil... | Make strftime filter safe for non-date types | Make strftime filter safe for non-date types
It should probably also support datetime.datetime, but since I only have
datetime.date right now, that's not a pressing concern.
| Python | mit | sjbarag/poorly-named-resume-generator,sjbarag/poorly-named-resume-generator | ---
+++
@@ -1,5 +1,5 @@
from jinja2._compat import text_type
-from datetime import datetime
+import datetime
import re
def do_right(value, width=80):
@@ -32,4 +32,7 @@
"""
Formats a datetime object into a string. Just a simple facade around datetime.strftime.
"""
- return value.strftime(_forma... |
5b712a639b2de9015e5d1a25b4edf8482254e064 | mangopay/tasks.py | mangopay/tasks.py | from celery.task import task
from .models import MangoPayNaturalUser, MangoPayBankAccount
@task
def create_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isnull=True).create()
@task
def update_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isn... | from celery.task import task
from .models import MangoPayNaturalUser, MangoPayBankAccount, MangoPayDocument
@task
def create_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id, mangopay_id__isnull=True).create()
@task
def update_mangopay_natural_user(id):
MangoPayNaturalUser.objects.get(id=id... | Add mangopay document creation task | Add mangopay document creation task
| Python | mit | FundedByMe/django-mangopay,webu/django-mangopay,DylannCordel/django-mangopay,charlietjhin/django-mangopay | ---
+++
@@ -1,6 +1,6 @@
from celery.task import task
-from .models import MangoPayNaturalUser, MangoPayBankAccount
+from .models import MangoPayNaturalUser, MangoPayBankAccount, MangoPayDocument
@task
@@ -16,3 +16,13 @@
@task
def create_mangopay_bank_account(id):
MangoPayBankAccount.objects.get(id=id, ... |
27fa3be6b7dd55637ad2b683f4027f32578ee04a | utils.py | utils.py | import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect... | import sqlite3
import shelve
def connect_db(name):
"""
Open a connection to the database used to store quotes.
:param name: (str) Name of database file
:return: (shelve.DbfilenameShelf)
"""
try:
return shelve.open(name)
except Exception:
raise Exception('Unable to connect... | Add id field to quotes table | Add id field to quotes table
Specify names for insert fields
| Python | mit | nickdibari/Get-Quote | ---
+++
@@ -30,6 +30,7 @@
with self.conn:
self.conn.execute('''
CREATE TABLE IF NOT EXISTS quotes (
+ id INTEGER PRIMARY KEY,
author TEXT,
quote TEXT,
created_at TEXT
@@ -52,5 +53,5 @@
"""... |
bc95ab06932378b3befe1c5628735f25a2807b14 | utils.py | utils.py | from google.appengine.api import users
from model import User
def create_user(google_user):
user = User(
google_user=google_user,
)
user.put()
return user
def get_current_user_model():
return get_user_model_for(users.get_current_user())
def get_user_model_for(google_user=None):
return... | from google.appengine.api import users
from model import User
def create_user(google_user):
user = User(
google_user=google_user
)
user.put()
return user
def get_current_user_model():
return get_user_model_for(users.get_current_user())
def get_user_model_for(google_user=None):
return ... | Fix potential issue when creating users | Fix potential issue when creating users | Python | mit | studyindenmark/newscontrol,youtify/newscontrol,studyindenmark/newscontrol,youtify/newscontrol | ---
+++
@@ -3,7 +3,7 @@
def create_user(google_user):
user = User(
- google_user=google_user,
+ google_user=google_user
)
user.put()
return user |
25fc6aa427769e0d75e90e1ae0fbe41e2ca24931 | manager/__init__.py | manager/__init__.py | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 's... | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 's... | Add Core Views import to the application | Add Core Views import to the application
| Python | mit | hreeder/ignition,hreeder/ignition,hreeder/ignition | ---
+++
@@ -33,3 +33,5 @@
output='css_all.css'
)
)
+
+from manager.views import core |
f84466d96bf1d9ce1525857bcbd821f7b6ee3486 | pycon/dev-settings.py | pycon/dev-settings.py | from pycon.settings import *
DEFAULT_URL_PREFIX='http://localhost:8000'
DEBUG=True
PAYPAL_TEST = True
TEMPLATES[0]['OPTIONS']['debug'] = True | from pycon.settings import *
DEFAULT_URL_PREFIX='http://localhost:8000'
DEBUG=True
PAYPAL_TEST = True
TEMPLATES[0]['OPTIONS']['debug'] = True
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) | Add django-extensions in the dev settings | Add django-extensions in the dev settings
| Python | bsd-2-clause | artcz/epcon,EuroPython/epcon,artcz/epcon,artcz/epcon,artcz/epcon,artcz/epcon,EuroPython/epcon,EuroPython/epcon,artcz/epcon,EuroPython/epcon | ---
+++
@@ -6,3 +6,5 @@
PAYPAL_TEST = True
TEMPLATES[0]['OPTIONS']['debug'] = True
+
+INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) |
d45e40e9093b88d204335e6e0bae5dac30595d66 | pyface/qt/__init__.py | pyface/qt/__init__.py | #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: Qt API selector. Can be used to switch between pyQt and ... | #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: Qt API selector. Can be used to switch between pyQt and ... | Set the sip QDate API for enaml interop. | Set the sip QDate API for enaml interop.
| Python | bsd-3-clause | geggo/pyface,geggo/pyface | ---
+++
@@ -16,6 +16,7 @@
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
+ sip.setapi('QDate', 2)
qt_api = os.environ.get('QT_API')
|
d833d3f1ae0305466b691d37f3a5560821b24490 | easy/beautiful_strings/beautiful_strings.py | easy/beautiful_strings/beautiful_strings.py | from collections import Counter
import string
import sys
def beautiful_strings(line):
line = line.rstrip()
if line:
beauty = 0
count = Counter(''.join(letter for letter in line.lower()
if letter in string.lowercase))
for value in xrange(26, 26 - len(coun... | from collections import Counter
import string
import sys
def beautiful_strings(line):
line = line.rstrip()
if line:
beauty = 0
count = Counter(''.join(letter for letter in line.lower()
if letter in string.lowercase))
for value in xrange(26, 26 - len(coun... | Update solution to handle numbers | Update solution to handle numbers
| Python | mit | MikeDelaney/CodeEval | ---
+++
@@ -18,7 +18,6 @@
if __name__ == '__main__':
- from pdb import set_trace; set_trace()
with open(sys.argv[1], 'rt') as f:
for line in f:
print beautiful_strings(line) |
13ba4fba90f6ff654c26daf4a44d77bda3992b1f | model/__init__.py | model/__init__.py | import model.wu.user
from model.wu.user import User
def init_context(app):
model.wu.user.init_context(app)
# todo evaluate a parameter and decide which package to use (wu, hss, test(?))
| import os
model_name = os.getenv('SIPA_MODEL', 'sample')
module = __import__('{}.{}.user'.format(__name__, model_name),
fromlist='{}.{}'.format(__name__, model_name))
init_context = module.init_context
User = module.User
query_gauge_data = module.query_gauge_data
| Load model dynamically via envvar 'SIPA_MODEL' | Load model dynamically via envvar 'SIPA_MODEL'
| Python | mit | lukasjuhrich/sipa,agdsn/sipa,agdsn/sipa,fgrsnau/sipa,agdsn/sipa,agdsn/sipa,MarauderXtreme/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,fgrsnau/sipa,fgrsnau/sipa,MarauderXtreme/sipa,MarauderXtreme/sipa | ---
+++
@@ -1,8 +1,10 @@
-import model.wu.user
-from model.wu.user import User
+import os
+model_name = os.getenv('SIPA_MODEL', 'sample')
-def init_context(app):
- model.wu.user.init_context(app)
+module = __import__('{}.{}.user'.format(__name__, model_name),
+ fromlist='{}.{}'.format(__name... |
39dd8bb26523106ed3d4ea26cd63b8732482b0cf | relationships/urls.py | relationships/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('relationships.views',
url(r'^$', 'relationship_redirect', name='relationship_list_base'),
url(r'^(?P<username>[\w-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
url(r'^add/(?P<username>[\w-]+)/(?P<status_s... | from django.conf.urls.defaults import *
urlpatterns = patterns('relationships.views',
url(r'^$', 'relationship_redirect', name='relationship_list_base'),
url(r'^(?P<username>[\w.@+-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
url(r'^add/(?P<username>[\w.@+-]+)/(?P<st... | Update url username matching to match regex allowed by Django. | Update url username matching to match regex allowed by Django. | Python | mit | coleifer/django-relationships,maroux/django-relationships,maroux/django-relationships,coleifer/django-relationships | ---
+++
@@ -2,7 +2,7 @@
urlpatterns = patterns('relationships.views',
url(r'^$', 'relationship_redirect', name='relationship_list_base'),
- url(r'^(?P<username>[\w-]+)/(?:(?P<status_slug>[\w-]+)/)?$', 'relationship_list', name='relationship_list'),
- url(r'^add/(?P<username>[\w-]+)/(?P<status_slug>[\w-]... |
5779380fd4ec28367c1f232710291b3f81e1791f | nested_comments/views.py | nested_comments/views.py | # Django
from django.shortcuts import get_object_or_404
from django.views.generic import *
# Third party apps
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.rever... | # Django
from django.shortcuts import get_object_or_404
from django.views.generic import *
# Third party apps
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.rever... | Add queryset attribute to NestedCommentDetail view | Add queryset attribute to NestedCommentDetail view
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -41,6 +41,7 @@
API endpoint that represents a single nested comment.
"""
model = NestedComment
+ queryset = NestedComment.objects.all()
serializer_class = NestedCommentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrRea... |
761c6538d33daf59135d519f1aeaaac9b920c5ff | nova/objects/__init__.py | nova/objects/__init__.py | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | Fix importing InstanceInfoCache during register_all() | Fix importing InstanceInfoCache during register_all()
Related to blueprint unified-object-model
Change-Id: Ib5edd0d0af46d9ba9d0fcaa14c9601ad75b8d50d
| Python | apache-2.0 | openstack/oslo.versionedobjects,citrix-openstack-build/oslo.versionedobjects | ---
+++
@@ -18,3 +18,4 @@
# function in order for it to be registered by services that may
# need to receive it via RPC.
__import__('nova.objects.instance')
+ __import__('nova.objects.instance_info_cache') |
638e531d2007e63b45e19521c0f9a05f339dc12e | numpy/numarray/setup.py | numpy/numarray/setup.py | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
config.add_data_files('numpy/')
config.add_extension('_capi',
sources=['_capi.c'],
... | from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
config.add_data_files('numpy/*')
config.add_extension('_capi',
sources=['_capi.c'],
... | Fix installation of numarray headers on Windows. | Fix installation of numarray headers on Windows.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7048 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | Ademan/NumPy-GSoC,illume/numpy3k,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,teoliphant/numpy-refactor,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,c... | ---
+++
@@ -4,7 +4,7 @@
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
- config.add_data_files('numpy/')
+ config.add_data_files('numpy/*')
config.add_extension('_capi',
sources=['_capi.c'], |
555637aa86bef0b3cf5d3fe67b0341bcee5e271a | findaconf/tests/test_autocomplete_routes.py | findaconf/tests/test_autocomplete_routes.py | # coding: utf-8
from findaconf import app, db
from unittest import TestCase
from findaconf.tests.config import set_app, unset_app
class TestAutoCompleteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/autocomp... | # coding: utf-8
from findaconf import app, db
from unittest import TestCase
from findaconf.tests.config import set_app, unset_app
class TestAutoCompleteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/autocomp... | Add tests for 404 on invalid routes | Add tests for 404 on invalid routes
| Python | mit | cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf | ---
+++
@@ -26,3 +26,16 @@
resp = self.app.get(url)
assert resp.status_code == 200
assert resp.mimetype == 'application/json'
+
+ def test_google_places_blank(self):
+ resp = self.app.get('/autocomplete/places?query=')
+ assert resp.status_code == 404
+ print resp.da... |
47fb142f285f989f7b911915b7b130bf4a72254b | opencraft/urls.py | opencraft/urls.py | """opencraft URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', name... | """opencraft URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', name... | Remove 1.8 warning about redirect | Remove 1.8 warning about redirect
| Python | agpl-3.0 | omarkhan/opencraft,open-craft/opencraft,open-craft/opencraft,brousch/opencraft,omarkhan/opencraft,omarkhan/opencraft,omarkhan/opencraft,open-craft/opencraft,brousch/opencraft,brousch/opencraft,open-craft/opencraft,open-craft/opencraft | ---
+++
@@ -10,6 +10,6 @@
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('api.urls', namespace="api")),
url(r'^task/', include('task.urls', namespace="task")),
- url(r'^favicon\.ico$', RedirectView.as_view(url='/static/img/favicon/favicon.ico')),
+ url(r'^favicon\.ico$', Redirec... |
8d392a0723205a8229512a47355452bb94b36cfb | examples/visualization/eeg_on_scalp.py | examples/visualization/eeg_on_scalp.py | """
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plo... | """
.. _ex-eeg-on-scalp:
=================================
Plotting EEG sensors on the scalp
=================================
In this example, digitized EEG sensor locations are shown on the scalp.
"""
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# %%
import mne
from mne.viz import plo... | Remove brain example [skip azp] [skip actions] | FIX: Remove brain example [skip azp] [skip actions]
| Python | bsd-3-clause | wmvanvliet/mne-python,Eric89GXL/mne-python,Teekuningas/mne-python,mne-tools/mne-python,pravsripad/mne-python,larsoner/mne-python,drammock/mne-python,mne-tools/mne-python,olafhauk/mne-python,Teekuningas/mne-python,bloyl/mne-python,larsoner/mne-python,drammock/mne-python,kingjr/mne-python,Eric89GXL/mne-python,larsoner/mn... | ---
+++
@@ -28,12 +28,3 @@
coord_frame='head', subjects_dir=subjects_dir)
# Set viewing angle
set_3d_view(figure=fig, azimuth=135, elevation=80)
-
-# %%
-# A similar effect can be achieved using :class:`mne.viz.Brain`:
-
-brain = mne.viz.Brain(
- 'sample', 'both', 'pial', 'frontal', backgro... |
6eec6ac19073e5bef6d8d4fc9451d173015407f7 | examples/plot_pmt_time_slewing.py | examples/plot_pmt_time_slewing.py | # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Variant 3 is currently (as of 2020-10-16) what's also used in Jpp.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import km3pipe as kp
import numpy as np
import m... | # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Time slewing corrects the hit time due to different rise times of the
PMT signals depending on the number of photo electrons.
The reference point is at 26.4ns and hits with a d... | Add some docs to PMT time slewing | Add some docs to PMT time slewing
| Python | mit | tamasgal/km3pipe,tamasgal/km3pipe | ---
+++
@@ -7,7 +7,14 @@
Show different variants of PMT time slewing calculations.
-Variant 3 is currently (as of 2020-10-16) what's also used in Jpp.
+Time slewing corrects the hit time due to different rise times of the
+PMT signals depending on the number of photo electrons.
+The reference point is at 26.4ns ... |
cc4211e2a3cdc58bf5ac3bf64711b881d1c046d0 | modules/currency.py | modules/currency.py | import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
else:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = self.msg[5]
to = ... | import urllib.parse
from bs4 import BeautifulSoup
import re
import syscmd
def currency( self ):
amount = 1
frm = "eur"
to = "usd"
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
if len(self.msg) == 7:
try:
amount = float(self.msg[4])
except ValueError:
pass
frm = se... | Check for valid currencies in a file | Check for valid currencies in a file
| Python | mit | jasuka/pyBot,jasuka/pyBot | ---
+++
@@ -11,18 +11,23 @@
if len(self.msg) < 7:
self.send_chan("Usage: !currency <amount> <from> <to>")
- else:
+ if len(self.msg) == 7:
try:
amount = float(self.msg[4])
except ValueError:
pass
- frm = self.msg[5]
- to = self.msg[6]
- if isinstance( amount, float ):
- frm = urllib.parse.quo... |
fa5f50a4a257477f7dc0cbacec6d1cd3d8f0d217 | hdc1008test.py | hdc1008test.py | """Tests for the hdc1008 module"""
import pyb
from hdc1008 import HDC1008
i2c = pyb.I2C(2)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
hdc.reset()
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
while True:
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
print("Rel... | """Tests for the hdc1008 module"""
from hdc1008 import HDC1008
import utime
i2c = pyb.I2C(1)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
hdc.reset()
hdc.heated(False)
print("Sensor ID: %s" % (hex(hdc.serial())))
def read_sensors():
print("Temperature (degree celsius): %.2f" % (hdc.temp()))
p... | Update to the new API and small cosmetic changes. | Update to the new API and small cosmetic changes. | Python | mit | kfricke/micropython-hdc1008 | ---
+++
@@ -1,9 +1,8 @@
"""Tests for the hdc1008 module"""
+from hdc1008 import HDC1008
+import utime
-import pyb
-from hdc1008 import HDC1008
-
-i2c = pyb.I2C(2)
+i2c = pyb.I2C(1)
i2c.init(pyb.I2C.MASTER, baudrate=400000)
hdc = HDC1008(i2c)
@@ -11,9 +10,21 @@
hdc.heated(False)
print("Sensor ID: %s" % (hex(h... |
fdb63cca26170d1348526ce8c357803ac6b37cf6 | hybrid_analysis/file_reader/hybrid_reader.py | hybrid_analysis/file_reader/hybrid_reader.py | #!/usr/bin/python
# Functions for reading hybrid model output(s)
import os
def read_afterburner_output(filename, read_initial=False):
id_event = 0
particlelist = []
if os.path.isfile(filename):
read_data = False
initial_list = False
for line in open(filename, "r"):
inp... | #!/usr/bin/python
# Functions for reading hybrid model output(s)
import os
import copy
from .. import dataobjects.particledata
def read_afterburner_output(filename, read_initial=False):
id_event = 0
if os.path.isfile(filename):
read_data = False
initial_list = False
eventlist = []
... | Use ParticleData class in file reader | Use ParticleData class in file reader
File reader now creates lists of ParticleData objects.
Signed-off-by: Jussi Auvinen <16b8c81f9479dec4f5eedf7ae5a2413c6a10bc13@phy.duke.edu>
| Python | mit | jauvinen/hybrid-model-analysis | ---
+++
@@ -3,18 +3,24 @@
# Functions for reading hybrid model output(s)
import os
+import copy
+from .. import dataobjects.particledata
def read_afterburner_output(filename, read_initial=False):
id_event = 0
- particlelist = []
if os.path.isfile(filename):
read_data = False
init... |
a23641edf1fd941768eebb1938340d2173ac2e11 | iputil/parser.py | iputil/parser.py | import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
match = IP_REGEX.findall(line)
... | import json
import os
import re
IP_REGEX = re.compile(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})')
def find_ips(filename):
"""Returns all the unique IPs found within a file."""
matches = []
with open(filename) as f:
for line in f:
matches += IP_REGEX.findall(line)
... | Remove unnecessary check, used to re functions returning different types | Remove unnecessary check, used to re functions returning different types
| Python | mit | kolanos/iputil | ---
+++
@@ -10,9 +10,7 @@
matches = []
with open(filename) as f:
for line in f:
- match = IP_REGEX.findall(line)
- if match:
- matches += match
+ matches += IP_REGEX.findall(line)
return set(sorted(matches)) if matches else set()
|
18d5b71dbbef2112d9fa8c48e2e894aa7321a4dc | tests/end2end/testapp/wsgi.py | tests/end2end/testapp/wsgi.py | """
WSGI config for testsite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... | """
WSGI config for testapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTI... | Rename references to "testsite" to "testapp". | Rename references to "testsite" to "testapp".
| Python | apache-2.0 | obytes/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,wangwanzhong/django-prometheus,DingaGa/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus | ---
+++
@@ -1,5 +1,5 @@
"""
-WSGI config for testsite project.
+WSGI config for testapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
@@ -11,6 +11,6 @@
from django.core.wsgi import get_wsgi_application
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsite.sett... |
2e1774aa0505873f7a3e8fe5a120e8931200fa35 | pokr/models/__init__.py | pokr/models/__init__.py | import assembly
import bill
import bill_feed
import bill_keyword
import bill_review
import bill_status
import bill_withdrawal
import candidacy
import cosponsorship
import election
import favorite_keyword
import favorite_person
import feed
import keyword
import meeting
import meeting_attendee
import party
import person
... | from assembly import *
from bill import *
from bill_feed import *
from bill_keyword import *
from bill_review import *
from bill_status import *
from bill_withdrawal import *
from candidacy import *
from cosponsorship import *
from election import *
from favorite_keyword import *
from favorite_person import *
from feed... | Make 'from pokr.models import ~' possible | Make 'from pokr.models import ~' possible
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | ---
+++
@@ -1,24 +1,24 @@
-import assembly
-import bill
-import bill_feed
-import bill_keyword
-import bill_review
-import bill_status
-import bill_withdrawal
-import candidacy
-import cosponsorship
-import election
-import favorite_keyword
-import favorite_person
-import feed
-import keyword
-import meeting
-import ... |
09225071761ae059c46393d41180b6c37d1b3edc | portal/models/locale.py | portal/models/locale.py | from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
... | from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
... | Correct coding error - need to return coding from property function or it'll cache None. | Correct coding error - need to return coding from property function or it'll cache None.
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal | ---
+++
@@ -10,7 +10,6 @@
within for easy access and testing
"""
-
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
@@ -19,12 +18,12 @@
@lazyprop
def AmericanEnglish(self):
- Coding(
+ return Coding(
system=IETF_LANGUAGE_... |
3664b2d9b7590b6750e35abba2c0fe77c7afd4cd | bin/license_finder_pip.py | bin/license_finder_pip.py | #!/usr/bin/env python
import json
import sys
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
from pip._internal.download import PipSession
except ImportError:
from pip.download import PipSession
from pip._vendor imp... | #!/usr/bin/env python
import json
import sys
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
try:
# since pip 19.3
from pip._internal.network.session import PipSession
except ImportError:
try:
# since pip 10
... | Support finding licenses with pip>=19.3 | Support finding licenses with pip>=19.3
| Python | mit | pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder | ---
+++
@@ -7,9 +7,15 @@
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
+
try:
+ # since pip 19.3
+ from pip._internal.network.session import PipSession
+except ImportError:
+ try:
+ # since pip 10
from pip._inte... |
f4209f7be27ef1ce0725f525a7029246c4c54631 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
yield i
not_prime.update(range(i*i, n, i))
| def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| Switch to more optimal non-generator solution | Switch to more optimal non-generator solution
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,13 +1,10 @@
def sieve(n):
- return list(primes(n))
-
-
-def primes(n):
if n < 2:
- raise StopIteration
- yield 2
+ return []
not_prime = set()
+ prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
- yield i
- not_prime.update(ra... |
fd78ef63d6f4f39886a16e495c79ca42109e7886 | ip/__init__.py | ip/__init__.py | # -*- coding: utf-8 -*-
from ip import Ip
from ipv4 import Ipv4
from ipv6 import Ipv6
__name__ = 'ip'
__version__ = '0.1'
__description__ = "Foxfluff's IPv4 and IPv6 datatype handling"
__author__ = 'foxfluff/luma'
__url__ = 'https://github.com/foxfluff'
__all__ = ['Ip', 'Ipv4', 'Ipv6'] | # -*- coding: utf-8 -*-
from ip import Ip
from ipv4 import Ipv4
from ipv6 import Ipv6
__name__ = 'ip'
__version__ = '0.2'
__description__ = "Foxfluff's IPv4 and IPv6 datatype handling"
__author__ = 'foxfluff/luma'
__url__ = 'https://github.com/foxfluff'
__all__ = ['Ip', 'Ipv4', 'Ipv6'] | Increase version number due to usable Ipv4 class | Increase version number due to usable Ipv4 class
| Python | mit | foxfluff/ip-py | ---
+++
@@ -5,7 +5,7 @@
from ipv6 import Ipv6
__name__ = 'ip'
-__version__ = '0.1'
+__version__ = '0.2'
__description__ = "Foxfluff's IPv4 and IPv6 datatype handling"
__author__ = 'foxfluff/luma'
__url__ = 'https://github.com/foxfluff' |
a633e7c1c5ca2fff4018ab7f51136ba9ad1b9cde | grammpy_transforms/contextfree.py | grammpy_transforms/contextfree.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
class ContextFree():
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, tra... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from grammpy import Grammar
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
class ContextFree:
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, trans... | Add additional parameters into CotextFree.is_grammar_generating method | Add additional parameters into CotextFree.is_grammar_generating method
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -11,12 +11,14 @@
from .NongeneratingSymbolsRemove import remove_nongenerating_symbols
-class ContextFree():
+class ContextFree:
@staticmethod
def remove_nongenerating_symbols(grammar: Grammar, transform_grammar=False):
return remove_nongenerating_symbols(grammar, transform_grammar)
... |
fafd048452ebfb3379ab428cc74e795d3406478f | apps/comments/models.py | apps/comments/models.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.Foreig... | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from notification import models as notification
from ..core.models import BaseModel
class Comment(BaseModel):
user = models.Foreig... | Make sure we have a recipient before sending notification | Make sure we have a recipient before sending notification | Python | mit | SoPR/horas,SoPR/horas,SoPR/horas,SoPR/horas | ---
+++
@@ -27,13 +27,13 @@
protege = instance.content_object.protege
meeting_url = instance.content_object.get_url_with_domain()
- if created:
- if instance.user == mentor:
- recipient = protege
+ if instance.user == mentor:
+ recipient = protege
- elif instance.us... |
db4611b6e3585321e84876332ac84a26ec623ae9 | valuenetwork/local_settings_development.py | valuenetwork/local_settings_development.py |
#for a development machine
DEBUG = True
TEMPLATE_DEBUG = DEBUG
#this is nice for development
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'valuenetwork.sqlite'
}
}
# valueaccounting settings can be overridden
USE_WORK_NOW = False
SUBSTITUTABLE_DEFAULT = False
... |
#for a development machine
DEBUG = True
TEMPLATE_DEBUG = DEBUG
#this is nice for development
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'valuenetwork.sqlite'
}
}
# valueaccounting settings can be overridden
USE_WORK_NOW = False
SUBSTITUTABLE_DEFAULT = False
... | Add static URL to development settings | Add static URL to development settings
| Python | agpl-3.0 | thierrymarianne/valuenetwork,FreedomCoop/valuenetwork,valnet/valuenetwork,thierrymarianne/valuenetwork,django-rea/nrp,FreedomCoop/valuenetwork,valnet/valuenetwork,FreedomCoop/valuenetwork,django-rea/nrp,simontegg/valuenetwork,simontegg/valuenetwork,thierrymarianne/valuenetwork,FreedomCoop/valuenetwork,django-rea/nrp,th... | ---
+++
@@ -17,6 +17,8 @@
USE_WORK_NOW = False
SUBSTITUTABLE_DEFAULT = False
+STATIC_URL = "/static/"
+
#example: Greece
MAP_LATITUDE = 38.2749497
MAP_LONGITUDE = 23.8102717 |
be746c870f2015507af5513a8636905cf9018001 | image_cropping/thumbnail_processors.py | image_cropping/thumbnail_processors.py | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if isinstance(box, basestring):
if box.startswith('-... | import logging
logger = logging.getLogger(__name__)
def crop_corners(image, box=None, **kwargs):
"""
Crop corners to the selection defined by image_cropping
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
if box and not box.startswith('-'):
# a leading - i... | Tweak thumbnail processor a little | Tweak thumbnail processor a little
| Python | bsd-3-clause | henriquechehad/django-image-cropping,henriquechehad/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,winzard/django-image-cropping,henriquechehad/django-image-cropping | ---
+++
@@ -2,6 +2,7 @@
logger = logging.getLogger(__name__)
+
def crop_corners(image, box=None, **kwargs):
"""
@@ -9,30 +10,23 @@
`box` is a string of the format 'x1,y1,x2,y1' or a four-tuple of integers.
"""
- if isinstance(box, basestring):
- if box.startswith('-'):
- ... |
f6d4f822d8f0f34316c5a2c92c8ceade7bc7fdbd | movieman/movieman.py | movieman/movieman.py | import requests
import os
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, d... | import requests
import os
import sys
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
... | Replace console output for raw txt | Replace console output for raw txt
| Python | mit | kshvmdn/movieman | ---
+++
@@ -1,5 +1,6 @@
import requests
import os
+import sys
from pprint import pprint
from tabulate import tabulate
@@ -22,22 +23,24 @@
return movies
-def main(dir_='/Users/kashavmadan/Downloads/movies'):
- table = list()
- table.append(['Title', 'Plot', 'Genre', 'Actors', 'Rating', 'Runtime', ... |
0c027086cf6491a301b08b8e0cb1565715e615fe | webapp/byceps/blueprints/ticket/service.py | webapp/byceps/blueprints/ticket/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.ticket.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from ...database import db
from ..party.models import Party
from ..seating.models import Category
from .models import Ticket
... | Use more succinct syntax to filter in database query. | Use more succinct syntax to filter in database query.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -24,7 +24,7 @@
return None
return Ticket.query \
- .filter(Ticket.used_by == user) \
+ .filter_by(used_by=user) \
.options(
db.joinedload('occupied_seat').joinedload('area'),
) \ |
481fe3e66b51e0bed3b62a6b46919b487ac67369 | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. 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 by applicable law or a... | # Copyright 2017 Google Inc. 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 by applicable law or a... | Update dsub version to 0.4.3.dev0 | Update dsub version to 0.4.3.dev0
PiperOrigin-RevId: 337359189
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.4.2'
+DSUB_VERSION = '0.4.3.dev0' |
996611b4ec0f0e13769d40122f21b6a6362783a5 | app.tmpl/models.py | app.tmpl/models.py | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
os.path.join(app.root_path, app... | # Application models
#
# Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os, os.path
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from {{PROJECTNAME}} import app
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(
o... | Use newer package import syntax for Flask | Use newer package import syntax for Flask
| Python | mit | 0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template | ---
+++
@@ -5,7 +5,8 @@
import os, os.path
from datetime import datetime
-from flask.ext.sqlalchemy import SQLAlchemy
+from flask_sqlalchemy import SQLAlchemy
+from flask_migrate import Migrate
from {{PROJECTNAME}} import app
@@ -13,6 +14,7 @@
os.path.join(app.root_path, app.name + '.db'))
db = SQLAl... |
9d7c55855b2226ff1aef36ed82d34d2f3626d376 | easyium/exceptions.py | easyium/exceptions.py | __author__ = 'karl.gong'
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
self.msg = msg
self.message = self.msg
self.context = context
def __str__(self):
exception_msg = ""
if self.msg is not None:
exception_msg = self.msg
... | import re
__author__ = 'karl.gong'
filter_msg_regex = re.compile(r"\n \(Session info:.*?\)\n \(Driver info:.*?\(.*?\).*?\)")
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
# Remove Session info and Driver info of the message.
self.msg = filter_msg_regex.sub("", ... | Remove session info and driver info of webdriverexception. | Remove session info and driver info of webdriverexception.
| Python | apache-2.0 | KarlGong/easyium-python,KarlGong/easyium | ---
+++
@@ -1,9 +1,14 @@
+import re
+
__author__ = 'karl.gong'
+
+filter_msg_regex = re.compile(r"\n \(Session info:.*?\)\n \(Driver info:.*?\(.*?\).*?\)")
class EasyiumException(Exception):
def __init__(self, msg=None, context=None):
- self.msg = msg
+ # Remove Session info and Driver info... |
efa20f9d88fab8b62a95d126500f220255ce6633 | src/yaml_server_test/YamlReader_test.py | src/yaml_server_test/YamlReader_test.py | import unittest
import logging
from yaml_server.YamlReader import YamlReader
from yaml_server.YamlServerException import YamlServerException
class Test(unittest.TestCase):
data1_data = {
'data1': 'test1',
'data2': [
{
... | import unittest
import logging
from yaml_server.YamlReader import YamlReader
from yaml_server.YamlServerException import YamlServerException
class Test(unittest.TestCase):
data1_data = {
'data1': 'test1',
'data2': [
{
... | Adjust log prefix in tests for Python 2.4 | Adjust log prefix in tests for Python 2.4 | Python | apache-2.0 | ImmobilienScout24/yamlreader,pombredanne/yamlreader | ---
+++
@@ -23,7 +23,7 @@
unittest.TestCase.setUp(self)
self.logger = logging.getLogger()
self.loghandler = logging.StreamHandler()
- self.loghandler.setFormatter(logging.Formatter('yaml_server[%(module)s %(funcName)s]: %(levelname)s: %(message)s'))
+ self.loghandler.setFormat... |
b2854df273d2fa84a3bb5f2e0f2574f4ea80fb04 | migrations/211-recategorize-canned-responses.py | migrations/211-recategorize-canned-responses.py | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wik... | """
All the forum canned responses are stored in KB articles. There is a
category for them now. Luckily they follow a simple pattern of slugs, so
they are easy to find.
This could have been an SQL migration, but I'm lazy and prefer Python.
"""
from django.conf import settings
from wiki.models import Document
from wik... | Fix migration 211 to handle lack of data. | Fix migration 211 to handle lack of data.
| Python | bsd-3-clause | Osmose/kitsune,feer56/Kitsune1,orvi2014/kitsune,Osmose/kitsune,iDTLabssl/kitsune,mythmon/kitsune,asdofindia/kitsune,chirilo/kitsune,rlr/kitsune,feer56/Kitsune2,silentbob73/kitsune,mozilla/kitsune,philipp-sumo/kitsune,asdofindia/kitsune,YOTOV-LIMITED/kitsune,anushbmx/kitsune,rlr/kitsune,dbbhattacharya/kitsune,safwanrahm... | ---
+++
@@ -12,8 +12,11 @@
to_move = list(Document.objects.filter(slug__startswith='forum-response-',
locale=settings.WIKI_DEFAULT_LANGUAGE))
-to_move.append(Document.objects.get(slug='common-forum-responses',
- locale=settings.WIKI_DEFAULT... |
633e73238a4a5380f81dd142024efab5ae691f92 | frigg/settings/rest_framework.py | frigg/settings/rest_framework.py | REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '50/day',
}
}
| REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '5000/day',
}
}
| Raise throttle limit for anon users | Raise throttle limit for anon users
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq | ---
+++
@@ -3,6 +3,6 @@
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
- 'anon': '50/day',
+ 'anon': '5000/day',
}
} |
ff3e0eb9d38d2cbed1fab7b67a374915bf65b8f5 | engine/logger.py | engine/logger.py | #
# dp for Tornado
# YoungYong Park (youngyongpark@gmail.com)
# 2014.10.23
#
from .singleton import Singleton
class Logger(object, metaclass=Singleton):
def exception(self, e=None):
pass | #
# dp for Tornado
# YoungYong Park (youngyongpark@gmail.com)
# 2014.10.23
#
import logging
from .singleton import Singleton
class Logger(object, metaclass=Singleton):
def exception(self, msg, *args, **kwargs):
logging.exception(msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
... | Add logging helper. (exception, error, warning, info, debug) | Add logging helper. (exception, error, warning, info, debug)
| Python | mit | why2pac/dp-tornado,why2pac/dp-tornado,why2pac/dp-tornado,why2pac/dp-tornado | ---
+++
@@ -4,9 +4,24 @@
# 2014.10.23
#
+
+import logging
+
from .singleton import Singleton
class Logger(object, metaclass=Singleton):
- def exception(self, e=None):
- pass
+ def exception(self, msg, *args, **kwargs):
+ logging.exception(msg, *args, **kwargs)
+
+ def error(self, m... |
a673bc6b3b9daf27404e4d330819bebc25a73608 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_service_elasticsearch_running(host):
assert host.service("elasticsearch").is_running is True
def test_service_mongodb_running(host):
... | import os
import testinfra.utils.ansible_runner
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRu... | Add Selenium test for basic logic. | Add Selenium test for basic logic.
| Python | apache-2.0 | Graylog2/graylog-ansible-role | ---
+++
@@ -1,8 +1,36 @@
import os
import testinfra.utils.ansible_runner
+from selenium import webdriver
+from selenium.webdriver.common.keys import Keys
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+import time
testinfra_hosts = tes... |
8b78f3e84c688b0e45ecfa0dda827870eced4c4e | sdi/corestick.py | sdi/corestick.py | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ign... | def read(filename):
"""
Reads in a corestick file and returns a dictionary keyed by core_id.
Layer interface depths are positive and are relative to the lake bottom.
depths are returned in meters. Northing and Easting are typically in the
coordinate system used in the rest of the lake survey. We ign... | Fix reading in for layer_colors. | Fix reading in for layer_colors.
| Python | bsd-3-clause | twdb/sdi | ---
+++
@@ -30,7 +30,8 @@
float(fields[i]) * conv_factor
for i in range(5, len(fields), 4)
]
- data['layer_colors'] = [i for i in range(6, len(fields), 4)]
+ data['layer_colors'] = [
+ int(fields[i]) for i in range(6, len(fields), 4)]... |
c82efa3d0db2f3f9887f4639552e761802829be6 | pgcli/pgstyle.py | pgcli/pgstyle.py | from pygments.token import Token
from pygments.style import Style
import pygments.styles
def style_factory(name):
class PGStyle(Style):
styles = {
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
... | from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PG... | Add safety check for non-existent style. | Add safety check for non-existent style.
| Python | bsd-3-clause | j-bennet/pgcli,suzukaze/pgcli,dbcli/pgcli,darikg/pgcli,johshoff/pgcli,thedrow/pgcli,thedrow/pgcli,janusnic/pgcli,darikg/pgcli,j-bennet/pgcli,yx91490/pgcli,koljonen/pgcli,yx91490/pgcli,lk1ngaa7/pgcli,d33tah/pgcli,lk1ngaa7/pgcli,bitemyapp/pgcli,bitemyapp/pgcli,joewalnes/pgcli,d33tah/pgcli,w4ngyi/pgcli,dbcli/vcli,koljonen... | ---
+++
@@ -1,9 +1,15 @@
from pygments.token import Token
from pygments.style import Style
+from pygments.util import ClassNotFound
import pygments.styles
def style_factory(name):
+ try:
+ style = pygments.styles.get_style_by_name(name)
+ except ClassNotFound:
+ style = pygments.styles.get... |
200027f73a99f18eeeae4395be9622c65590916f | fireplace/cards/gvg/neutral_epic.py | fireplace/cards/gvg/neutral_epic.py | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION... | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
events = [
OWN_MINION_PLAY.on(
lambda self, player, card, *args: card.atk == 1 and [Buff(card, "GVG_104a")] or []
)
]
# Piloted Sky Golem
class GVG_105:
def deathrattle(self):
return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION... | Exclude Enhance-o Mechano from its own buff targets | Exclude Enhance-o Mechano from its own buff targets
| Python | agpl-3.0 | oftc-ftw/fireplace,smallnamespace/fireplace,butozerca/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,Meerkov/fireplace,NightKev/fireplace,butozerca/fireplace,amw2104/fireplace,beheh/fireplace,smallnamespace/fireplace,amw2104/fi... | ---
+++
@@ -29,7 +29,7 @@
# Enhance-o Mechano
class GVG_107:
def action(self):
- for target in self.controller.field:
+ for target in self.controller.field.exclude(self):
tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD))
yield SetTag(target, {tag: True})
|
631a096eb8b369258c85b5c014460166787abf6c | owid_grapher/various_scripts/extract_short_units_from_existing_vars.py | owid_grapher/various_scripts/extract_short_units_from_existing_vars.py | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import owid_grapher.wsgi
from grapher_admin.models import Variable
# use this script to extract and write short forms of unit of measurement for all variables that already exit in the db
common_short_units = ['$', '£', '€', '%']
all_variable... | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import owid_grapher.wsgi
from grapher_admin.models import Variable
# use this script to extract and write short forms of unit of measurement for all variables that already exit in the db
common_short_units = ['$', '£', '€', '%']
all_variable... | Make short unit extraction script idempotent | Make short unit extraction script idempotent
| Python | mit | OurWorldInData/owid-grapher,owid/owid-grapher,aaldaber/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,aaldaber/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-graphe... | ---
+++
@@ -11,7 +11,7 @@
all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi')
for each in all_variables:
- if each.unit:
+ if each.unit and not each.short_unit:
if ' per ' in each.unit:
short_form = each.unit.split(' per ')[0]
if any(w in short_form for w i... |
4335d5430fbcae6035f90495f1ce43d351e3927a | djangopypi/urls.py | djangopypi/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("",
# Simple PyPI
url(r'^/?$', "djangopypi.views.simple",
name="djangopypi-simple"),
url(r'^(?P<dist_name>[\w\d_\-]+)/(?P<version>[\w\.\d\-_]+)/?',
"djangopypi.views.show_version",
... | # -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns("",
# Simple PyPI
url(r'^/?$', "djangopypi.views.simple",
name="djangopypi-simple"),
url(r'^(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/?',
"djangopypi.views.show_version",... | Allow "." in project names. | Allow "." in project names.
| Python | bsd-3-clause | hsmade/djangopypi2,pitrho/djangopypi2,pitrho/djangopypi2,popen2/djangopypi2,mattcaldwell/djangopypi,hsmade/djangopypi2,disqus/djangopypi,EightMedia/djangopypi,EightMedia/djangopypi,ask/chishop,popen2/djangopypi2,disqus/djangopypi,benliles/djangopypi | ---
+++
@@ -6,11 +6,11 @@
url(r'^/?$', "djangopypi.views.simple",
name="djangopypi-simple"),
- url(r'^(?P<dist_name>[\w\d_\-]+)/(?P<version>[\w\.\d\-_]+)/?',
+ url(r'^(?P<dist_name>[\w\d_\.\-]+)/(?P<version>[\w\.\d\-_]+)/?',
"djangopypi.views.show_version",
name="djangopypi-sho... |
d8347132e246caf4874384000014353ce200dff4 | launcher/launcher/ui/__init__.py | launcher/launcher/ui/__init__.py | CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
"host": "",
"catalog_id": 1
},
"viewer_mode": "2d",
"curator_mode": False,
"cache_dir": "~/synspy"
}
| CURATORS = "https://auth.globus.org/6265343a-52e3-11e7-acd7-22000b100078"
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
"host": "synapse.isrd.isi.edu",
"catalog_id": 1
},
"viewer_mode": "2d",
"curator_mode": False,
"cache_dir": "~/synspy"
}
| Set prod server as config default. | Set prod server as config default.
| Python | bsd-3-clause | informatics-isi-edu/synspy,informatics-isi-edu/synspy,informatics-isi-edu/synspy | ---
+++
@@ -3,7 +3,7 @@
DEFAULT_CONFIG = {
"server": {
"protocol": "https",
- "host": "",
+ "host": "synapse.isrd.isi.edu",
"catalog_id": 1
},
"viewer_mode": "2d", |
8b88ca952ff562eb692f25cba54263afcbbcfafd | auth/models.py | auth/models.py | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def set_p... | from google.appengine.ext import db
import bcrypt
class User(db.Model):
email = db.EmailProperty()
first_name = db.StringProperty()
last_name = db.StringProperty()
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def __ini... | Set password in user ini | Set password in user ini
| Python | mit | haldun/optimyser2,haldun/optimyser2,haldun/tornado-gae-auth | ---
+++
@@ -9,6 +9,12 @@
password_hash = db.StringProperty()
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
+
+ def __init__(self, *args, **kwds):
+ db.Model.__init__(self, *args, **kwds)
+ password = kwds.pop('password', None)
+ if password:
+ se... |
7a448c4df3feb717d0b1d8abbf9d32237751aab5 | nbgrader/tests/apps/test_nbgrader_extension.py | nbgrader/tests/apps/test_nbgrader_extension.py | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 3
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
paths = [ex... | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
assert nbex... | Fix tests for nbgrader extensions | Fix tests for nbgrader extensions
| Python | bsd-3-clause | jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader | ---
+++
@@ -6,10 +6,11 @@
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
- assert len(nbexts) == 3
+ assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['... |
e385a20fdb877f0c6308883709814920cf0378d7 | behave/__main__.py | behave/__main__.py | #!/usr/bin/env python
"""
Convenience module to use:
python -m behave args...
"""
from __future__ import absolute_import
import sys
if __name__ == "__main__":
from .main import main
sys.exit(main())
| #!/usr/bin/env python
"""
Convenience module to use:
python -m behave args...
"""
from __future__ import absolute_import
import sys
from .main import main
if __name__ == "__main__":
sys.exit(main())
| Tweak for better backward compatibility w/ master repository. | Tweak for better backward compatibility w/ master repository.
| Python | bsd-2-clause | jenisys/behave,jenisys/behave | ---
+++
@@ -8,7 +8,7 @@
from __future__ import absolute_import
import sys
+from .main import main
if __name__ == "__main__":
- from .main import main
sys.exit(main()) |
ababeb31c0673c44b0c0e6d0b30bf369d67b9e55 | src/scikit-cycling/skcycling/power_profile/tests/test_power_profile.py | src/scikit-cycling/skcycling/power_profile/tests/test_power_profile.py | import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_equal
from numpy.testing import assert_raises
from skcycling.power_profile import Rpp
def rpp_initialisation():
a = Rp... | import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_equal
from numpy.testing import assert_raises
from skcycling.power_profile import Rpp
pow_ride_1 = np.linspace(100, 200, 4... | Bring some test which need to be finished | Bring some test which need to be finished
| Python | mit | glemaitre/power-profile,clemaitre58/power-profile,glemaitre/power-profile,clemaitre58/power-profile | ---
+++
@@ -8,5 +8,34 @@
from skcycling.power_profile import Rpp
-def rpp_initialisation():
- a = Rpp(max_duration=100)
+pow_ride_1 = np.linspace(100, 200, 4000)
+pow_ride_2 = np.linspace(50, 400, 4000)
+
+def test_fitting_rpp():
+ """ Test the computation of the fitting """
+ my_rpp = Rpp(max_duration_... |
67b80161fd686ef0743470dd57e56b64fe9f9128 | rnn_padding.py | rnn_padding.py | import torch
'''Utility for Padding Sequences to feed to RNN/LSTM.'''
def pad_single_sequence(single_tensor, length):
padding_vec_dim = (length - single_tensor.size(0), *single_tensor.size()[1:])
return torch.cat([single_tensor, torch.zeros(*padding_vec_dim)])
def pad_list_sequences(sequence_list, length=N... | import torch
'''Utility for Padding Sequences to feed to RNN/LSTM.'''
def pad_single_sequence(single_tensor, length):
padding_vec_dim = (length - single_tensor.size(0), *single_tensor.size()[1:])
return torch.cat([single_tensor, torch.zeros(*padding_vec_dim)])
def pad_list_sequences(sequence_list, length=N... | Return Vector is in decreasing order of origal length. | Return Vector is in decreasing order of origal length.
| Python | mit | reachtarunhere/pytorch-snippets | ---
+++
@@ -13,5 +13,6 @@
not specified padding till sentence of max length."""
if length is None:
length = max(s.size(0) for s in sequence_list)
- padded_list = [pad_single_sequence(s, length) for s in sequence_list]
+ padded_list = [pad_single_sequence(s, length) for s in
+ ... |
8f2b9eecc5c62be356225250783731c21a22abea | django_pickling.py | django_pickling.py | VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
from django.db.models import Model
from django.db.models.base import ModelState
try:
from itertools import izip
except ImportError:
izip = zip
def attnames(cls, _cache={}):
try:
return _cache[cls]
except KeyError:
_cache[cls]... | VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
from django.db.models import Model
from django.db.models.base import ModelState
try:
from itertools import izip
except ImportError:
izip = zip
def attnames(cls, _cache={}):
try:
return _cache[cls]
except KeyError:
_cache[cls]... | Use tuples of attnames instead of lists | Use tuples of attnames instead of lists
| Python | bsd-3-clause | Suor/django-pickling | ---
+++
@@ -14,7 +14,7 @@
try:
return _cache[cls]
except KeyError:
- _cache[cls] = [f.attname for f in cls._meta.fields]
+ _cache[cls] = tuple(f.attname for f in cls._meta.fields)
return _cache[cls]
|
8acb681ff8963621452f0e018781c76d4935cb84 | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', ... | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/... | Add url for project_status_edit option | Add url for project_status_edit option
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -4,6 +4,7 @@
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
+ url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/(?P<project_id... |
ef974d5b01940efa3886a4074eda964bfc07b133 | bookie/__init__.py | bookie/__init__.py | from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from bookie.lib.access import RequestWithUserAttribute
from bookie.models import initialize_sql
from bookie.models.au... | from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from bookie.lib.access import RequestWithUserAttribute
from bookie.models import initialize_sql
from bookie.models.au... | Fix the rootfactory for no matchdict so we can get a 404 back out | Fix the rootfactory for no matchdict so we can get a 404 back out
| Python | agpl-3.0 | pombredanne/Bookie,skmezanul/Bookie,teodesson/Bookie,GreenLunar/Bookie,wangjun/Bookie,bookieio/Bookie,skmezanul/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,charany1/Bookie,bookieio/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,bookieio/Bookie,pombredanne/Bookie,adamlincoln/Bookie,charany1/Bookie,charany1/Bookie,teodesso... | ---
+++
@@ -17,7 +17,8 @@
__acl__ = [ (Allow, Everyone, ALL_PERMISSIONS)]
def __init__(self, request):
- self.__dict__.update(request.matchdict)
+ if request.matchdict:
+ self.__dict__.update(request.matchdict)
def main(global_config, **settings): |
ffbe699a8435dd0abfb43a37c8528257cdaf386d | pymogilefs/request.py | pymogilefs/request.py | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
class Request:
def __init__(self, config, **kwargs):
self.config = config
self._kwargs = kwargs or {}
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (s... | try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
class Request:
def __init__(self, config, **kwargs):
self.config = config
self._kwargs = kwargs or {}
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (s... | Add __str__/__bytes__ Python 2.7 compatibility | Add __str__/__bytes__ Python 2.7 compatibility
| Python | mit | bwind/pymogilefs,bwind/pymogilefs | ---
+++
@@ -12,3 +12,7 @@
def __bytes__(self):
kwargs = urlencode(self._kwargs)
return ('%s %s\r\n' % (self.config.COMMAND, kwargs)).encode('utf-8')
+
+ # Python 2.7 compatibility
+ def __str__(self):
+ return self.__bytes__().decode() |
8b3e40e70101433157709d9d774b199ce606196f | violations/tests/test_base.py | violations/tests/test_base.py | from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
class ViolationsLibraryCase(TestCase):
"""Violations library case"""
def setUp(self):
self.library = ViolationsLibrary()
def test_register(self):
"""Test register"""
... | import sure
from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
class ViolationsLibraryCase(TestCase):
"""Violations library case"""
def setUp(self):
self.library = ViolationsLibrary()
def test_register(self):
"""Test regi... | Use sure in violations bases tests | Use sure in violations bases tests
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | ---
+++
@@ -1,3 +1,4 @@
+import sure
from django.test import TestCase
from ..base import ViolationsLibrary
from ..exceptions import ViolationDoesNotExists
@@ -15,12 +16,12 @@
def violation():
pass
- self.assertEqual(self.library.get('dummy'), violation)
+ self.library.get('dum... |
516bebe37212e72362b416bd1d9c87a83726fa5f | changes/api/cluster_nodes.py | changes/api/cluster_nodes.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', typ... | from __future__ import absolute_import
from datetime import datetime, timedelta
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.models import Cluster, JobStep, Node
class ClusterNodesAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('since', typ... | Enforce ordering on cluster nodes endpoint | Enforce ordering on cluster nodes endpoint
| Python | apache-2.0 | bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes | ---
+++
@@ -18,7 +18,7 @@
queryset = Node.query.filter(
Node.clusters.contains(cluster),
- )
+ ).order_by(Node.label.asc())
args = self.parser.parse_args()
if args.since: |
fe8266beb5541f1ac5b08f365edb5f30b3e8eddd | snakeeyes/blueprints/contact/tasks.py | snakeeyes/blueprints/contact/tasks.py | from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail... | from flask import current_app
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id:... | Fix contact form recipient email address | Fix contact form recipient email address
Since Celery is configured differently now we can't reach in and
grab config values outside of Celery.
| Python | mit | nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask | ---
+++
@@ -1,3 +1,5 @@
+from flask import current_app
+
from lib.flask_mailplus import send_template_message
from snakeeyes.app import create_celery_app
@@ -19,7 +21,7 @@
send_template_message(subject='[Snake Eyes] Contact',
sender=email,
- recipients=[c... |
4b451721c9e3530d83cf4ada1c1a7c994c217f15 | cloudbio/edition/__init__.py | cloudbio/edition/__init__.py | """An Edition reflects a base install, the default being BioLinux.
Editions are shared between multiple projects. To specialize an edition, create
a Flavor instead.
Other editions can be found in this directory
"""
from cloudbio.edition.base import Edition
from cloudbio.edition.minimal import Minimal
from cloudbio.e... | """An Edition reflects a base install, the default being BioLinux.
Editions are shared between multiple projects. To specialize an edition, create
a Flavor instead.
Other editions can be found in this directory
"""
from cloudbio.edition.base import Edition, Minimal, BioNode
_edition_map = {None: Edition,
... | Correct imports for new directory structure | Correct imports for new directory structure
| Python | mit | elkingtonmcb/cloudbiolinux,averagehat/cloudbiolinux,rchekaluk/cloudbiolinux,rchekaluk/cloudbiolinux,heuermh/cloudbiolinux,lpantano/cloudbiolinux,chapmanb/cloudbiolinux,averagehat/cloudbiolinux,AICIDNN/cloudbiolinux,elkingtonmcb/cloudbiolinux,AICIDNN/cloudbiolinux,kdaily/cloudbiolinux,averagehat/cloudbiolinux,elkingtonm... | ---
+++
@@ -6,9 +6,7 @@
Other editions can be found in this directory
"""
-from cloudbio.edition.base import Edition
-from cloudbio.edition.minimal import Minimal
-from cloudbio.edition.bionode import BioNode
+from cloudbio.edition.base import Edition, Minimal, BioNode
_edition_map = {None: Edition,
... |
d3f181f3151e158c569cc53f4287d3c4d7ca426e | proppy/main.py | proppy/main.py | import sys
import pytoml as toml
from proppy.exceptions import InvalidCommand, InvalidConfiguration
from proppy.proposal import Proposal
from proppy.render import to_pdf
def main(filename):
if not filename.endswith('.toml'):
raise InvalidCommand("You must use a TOML file as input")
with open(filenam... | import sys
import pytoml as toml
from proppy.exceptions import InvalidCommand, InvalidConfiguration
from proppy.proposal import Proposal
from proppy.render import to_pdf
def main(filename):
if not filename.endswith('.toml'):
raise InvalidCommand("You must use a TOML file as input")
with open(filenam... | Fix exception string for missing project | Fix exception string for missing project
| Python | mit | WeAreWizards/proppy,WeAreWizards/proppy | ---
+++
@@ -21,7 +21,7 @@
raise InvalidConfiguration("Missing customer in TOML file")
if not config.get('project'):
- raise InvalidConfiguration("Missing customer in TOML file")
+ raise InvalidConfiguration("Missing project in TOML file")
proposal = Proposal(co... |
6e6f906b47c1750f14e02b65cd825fd246a84c63 | tests/__init__.py | tests/__init__.py | import locale
# The test fixtures can break if the locale is non-US.
locale.setlocale(locale.LC_ALL, 'en_US')
| import locale
# The test fixtures can break if the locale is non-US.
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
| Set the locale to en_US.UTF-8 | test: Set the locale to en_US.UTF-8
| Python | mit | onyxfish/journalism,onyxfish/agate,wireservice/agate | ---
+++
@@ -1,4 +1,4 @@
import locale
# The test fixtures can break if the locale is non-US.
-locale.setlocale(locale.LC_ALL, 'en_US')
+locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') |
002be05d8bb07e610613b1ba6f24c904691c9f03 | tests/conftest.py | tests/conftest.py | """
Configuration, plugins and fixtures for `pytest`.
"""
import os
import pytest
from tests.utils import VuforiaServerCredentials
@pytest.fixture()
def vuforia_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials from environment variables.
"""
credentials = VuforiaServerCr... | """
Configuration, plugins and fixtures for `pytest`.
"""
import os
import pytest
from tests.utils import VuforiaServerCredentials
@pytest.fixture()
def vuforia_server_credentials() -> VuforiaServerCredentials:
"""
Return VWS credentials from environment variables.
"""
credentials = VuforiaServerCr... | Create credentials fixture for inactive project | Create credentials fixture for inactive project
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python | ---
+++
@@ -20,3 +20,16 @@
secret_key=os.environ['VUFORIA_SERVER_SECRET_KEY'],
) # type: VuforiaServerCredentials
return credentials
+
+
+@pytest.fixture()
+def vuforia_inactive_server_credentials() -> VuforiaServerCredentials:
+ """
+ Return VWS credentials for an inactive project from envi... |
ca0d9b40442f3ca9499f4b1630650c61700668ec | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root ... | Add the action required to fix the issue to the warning | Add the action required to fix the issue to the warning
| Python | mit | renanivo/pytest-testdox | ---
+++
@@ -17,7 +17,8 @@
if current_path_root not in pytest_testdox.__file__:
warnings.warn(
'pytest-testdox was not imported from your repository. '
- 'You might be testing the wrong code '
+ 'You might be testing the wrong code. '
+ 'Uninstall pytest-test... |
1d7e20e1dfb113839b4b213e49308c4b3f8f6605 | csunplugged/general/views.py | csunplugged/general/views.py | """Views for the general application."""
from django.views.generic import TemplateView
from django.http import HttpResponse
class GeneralIndexView(TemplateView):
"""View for the homepage that renders from a template."""
template_name = 'general/index.html'
class GeneralAboutView(TemplateView):
"""View... | """Views for the general application."""
from django.views.generic import TemplateView
from django.http import HttpResponse
class GeneralIndexView(TemplateView):
"""View for the homepage that renders from a template."""
template_name = 'general/index.html'
class GeneralAboutView(TemplateView):
"""View... | Reset file to pass style checks | Reset file to pass style checks
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -17,7 +17,7 @@
class GeneralContactView(TemplateView):
- """View for the contact page that renders from a template"""
+ """View for the contact page that renders from a template."""
template_name = 'general/contact.html'
|
687c0f3c1b8d1b5cd0cee6403a9664bb2b8f63d1 | cleverbot/utils.py | cleverbot/utils.py | def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
... | def error_on_kwarg(func, kwargs):
if kwargs:
message = "{0}() got an unexpected keyword argument {1!r}"
raise TypeError(message.format(func.__name__, next(iter(kwargs))))
def convo_property(name):
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
... | Add deleter to Conversation properties | Add deleter to Conversation properties
| Python | mit | orlnub123/cleverbot.py | ---
+++
@@ -8,4 +8,5 @@
_name = '_' + name
getter = lambda self: getattr(self, _name, getattr(self.cleverbot, name))
setter = lambda self, value: setattr(self, _name, value)
- return property(getter, setter)
+ deleter = lambda self: delattr(self, _name)
+ return property(getter, setter, delete... |
d2c50272ec4509e40562f441e534ba7457a493f3 | tests/test_api.py | tests/test_api.py | """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file_invalid_syntax(tmpdir) -> None:
"""Test to ensure file encoding is respected"""
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.w... | """Tests the isort API module"""
import pytest
from isort import api, exceptions
def test_sort_file_invalid_syntax(tmpdir) -> None:
"""Test to ensure file encoding is respected"""
tmp_file = tmpdir.join(f"test_bad_syntax.py")
tmp_file.write_text("""print('mismathing quotes")""", "utf8")
with pytest.w... | Add test for imperfect imports as well | Add test for imperfect imports as well
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -16,3 +16,7 @@
perfect = tmpdir.join(f"test_no_changes.py")
perfect.write_text("import a\nimport b\n", "utf8")
assert api.check_file(perfect, show_diff=True)
+
+ imperfect = tmpdir.join(f"test_needs_changes.py")
+ imperfect.write_text("import b\nimport a\n", "utf8")
+ assert not... |
a8f125236308cbfc9bb2eb5b225a0ac92a3a95e4 | ANN.py | ANN.py | from random import random
class Neuron:
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def get_output(self):
return sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
output = property(get_o... | from random import random
class Neuron:
output = None
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
def calculate(self):
self.output = sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >= 1
c... | Store output instead of calculating it each time | Store output instead of calculating it each time
| Python | mit | tysonzero/py-ann | ---
+++
@@ -2,14 +2,14 @@
class Neuron:
+ output = None
+
def __init__(self, parents=[]):
self.parents = parents
self.weights = [random() for parent in parents]
- def get_output(self):
- return sum([parent.output * self.weights[i] for i, parent in enumerate(self.parents)]) >... |
884483d27f7c0fac3975da17a7ef5c470ef9e3b4 | fcm_django/apps.py | fcm_django/apps.py | from django.apps import AppConfig
from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
| from django.apps import AppConfig
from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
default_auto_field = "django.db.models.BigAutoField"
| Use BigAutoField as the default ID | Use BigAutoField as the default ID | Python | mit | xtrinch/fcm-django | ---
+++
@@ -6,3 +6,4 @@
class FcmDjangoConfig(AppConfig):
name = "fcm_django"
verbose_name = SETTINGS["APP_VERBOSE_NAME"]
+ default_auto_field = "django.db.models.BigAutoField" |
a43e1c76ba3bef9ab3cbe1353c3b7289031a3b64 | pydub/playback.py | pydub/playback.py | import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name
PLAYER = get_player_name()
def play(audio_segment):
with NamedTemporaryFile("w+b", suffix=".wav") as f:
audio_segment.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
| import subprocess
from tempfile import NamedTemporaryFile
from .utils import get_player_name
PLAYER = get_player_name()
def _play_with_ffplay(seg):
with NamedTemporaryFile("w+b", suffix=".wav") as f:
seg.export(f.name, "wav")
subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
def _play_with_pyaudio(se... | Use Pyaudio when available, ffplay as fallback | Use Pyaudio when available, ffplay as fallback
| Python | mit | cbelth/pyMusic,miguelgrinberg/pydub,jiaaro/pydub,Geoion/pydub,joshrobo/pydub,sgml/pydub | ---
+++
@@ -4,7 +4,34 @@
PLAYER = get_player_name()
+
+
+def _play_with_ffplay(seg):
+ with NamedTemporaryFile("w+b", suffix=".wav") as f:
+ seg.export(f.name, "wav")
+ subprocess.call([PLAYER, "-nodisp", "-autoexit", f.name])
+
+
+def _play_with_pyaudio(seg):
+ import pyaudio
+
+ p = pyaudio.PyAudio()
+ strea... |
414dd0b03b3e4eabc11f848f79d681f3a284380e | pygcvs/helpers.py | pygcvs/helpers.py | from .parser import GcvsParser
try:
import ephem
except ImportError:
ephem = None
def read_gcvs(filename):
"""
Reads variable star data in `GCVS format`_.
:param filename: path to GCVS data file (usually ``iii.dat``)
.. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii/html/
"""
w... | from .parser import GcvsParser
try:
import ephem
except ImportError: # pragma: no cover
ephem = None
def read_gcvs(filename):
"""
Reads variable star data in `GCVS format`_.
:param filename: path to GCVS data file (usually ``iii.dat``)
.. _`GCVS format`: http://www.sai.msu.su/gcvs/gcvs/iii... | Exclude missing ephem from coverage | Exclude missing ephem from coverage
| Python | mit | zsiciarz/pygcvs | ---
+++
@@ -2,7 +2,7 @@
try:
import ephem
-except ImportError:
+except ImportError: # pragma: no cover
ephem = None
@@ -26,7 +26,7 @@
Requires `PyEphem <http://rhodesmill.org/pyephem/>`_ to be installed.
"""
- if ephem is None:
+ if ephem is None: # pragma: no cover
raise... |
cba707395196e78a54a1ded52066746680c5b225 | email_log/migrations/__init__.py | email_log/migrations/__init__.py | """
Django migrations for email_log app
This package does not contain South migrations. South migrations can be found
in the ``south_migrations`` package.
"""
SOUTH_ERROR_MESSAGE = """\n
For South support, customize the SOUTH_MIGRATION_MODULES setting like so:
SOUTH_MIGRATION_MODULES = {
'email_log': 'e... | Add friendly error message targeted at South users | Add friendly error message targeted at South users
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log | ---
+++
@@ -0,0 +1,21 @@
+"""
+Django migrations for email_log app
+
+This package does not contain South migrations. South migrations can be found
+in the ``south_migrations`` package.
+"""
+
+SOUTH_ERROR_MESSAGE = """\n
+For South support, customize the SOUTH_MIGRATION_MODULES setting like so:
+
+ SOUTH_MIGRATI... | |
332fcb6566727a4736da42ccde449679136690a6 | dbaas/dbaas/settings_test.py | dbaas/dbaas/settings_test.py | from settings import * # noqa
# Comment this line for turn on debug on tests
LOGGING = {}
DEBUG = 0
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--verbosity=0',
'--no-byte-compile',
'--debug-log=error_test.log',
'-s',
'--nologcapture'
]
if CI:
NOSE_ARGS += [
'--with-... | from settings import * # noqa
# Comment this line for turn on debug on tests
LOGGING = {}
DEBUG = 0
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--verbosity=4',
'--no-byte-compile',
'--debug-log=error_test.log',
'-l',
'-s',
# '-x',
'--nologcapture',
#'--collect-only'
... | Change parameters of tests to remove big output | Change parameters of tests to remove big output
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -5,11 +5,14 @@
DEBUG = 0
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
- '--verbosity=0',
+ '--verbosity=4',
'--no-byte-compile',
'--debug-log=error_test.log',
+ '-l',
'-s',
- '--nologcapture'
+ # '-x',
+ '--nologcapture',
+ #'--collect-only'
]
if ... |
9f37a35434389ff48afe52159f15d64e7f600ec2 | app/soc/models/grading_project_survey.py | app/soc/models/grading_project_survey.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Set default taking access for GradingProjectSurvey to org. | Set default taking access for GradingProjectSurvey to org.
This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles.
| Python | apache-2.0 | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | ---
+++
@@ -32,4 +32,4 @@
def __init__(self, *args, **kwargs):
super(GradingProjectSurvey, self).__init__(*args, **kwargs)
- self.taking_access = 'mentor'
+ self.taking_access = 'org' |
c9a9bf594f9d91a0a2f4c297e6200ebfa047bae6 | examples/manage.py | examples/manage.py | #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.pardir))
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.pardir))
if __name__ == "__main__":
from django.core.management import execute_from_command_line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bs3demo.settings')
execute_from_command_line(sys.argv)
| Use env variable for settings.py | Use env variable for settings.py
| Python | mit | rfleschenberg/djangocms-cascade,jtiki/djangocms-cascade,haricot/djangocms-bs4forcascade,haricot/djangocms-bs4forcascade,jrief/djangocms-cascade,jrief/djangocms-cascade,jrief/djangocms-cascade,rfleschenberg/djangocms-cascade,rfleschenberg/djangocms-cascade,jtiki/djangocms-cascade,jtiki/djangocms-cascade | ---
+++
@@ -7,4 +7,5 @@
if __name__ == "__main__":
from django.core.management import execute_from_command_line
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bs3demo.settings')
execute_from_command_line(sys.argv) |
1704ec592f1232364162ebc56e799d875f61ddd2 | app.py | app.py | import os
from flask import Flask, render_template
from pymongo import MongoClient
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
client = MongoClient('localhost', 27017)
@app.route('/')
@app.route('/index')
def index():
#online_users = mongo.db.users.find({'on... | import os
from flask import Flask, render_template
from pymongo import MongoClient
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
#client = MongoClient('localhost', 27017)
@app.route('/')
@app.route('/index')
def index():
#online_users = mongo.db.users.find({'o... | Comment out database connection until database is set up | Comment out database connection until database is set up
| Python | unknown | alanplotko/CoREdash,alanplotko/CoRE-Manager,alanplotko/CoREdash,alanplotko/CoRE-Manager | ---
+++
@@ -4,7 +4,7 @@
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
-client = MongoClient('localhost', 27017)
+#client = MongoClient('localhost', 27017)
@app.route('/')
@app.route('/index') |
2a379bbef9549005b0c55f29a1bfb0f41811a4e0 | fabfile.py | fabfile.py | from __future__ import with_statement
from fabric.api import run, cd
from fabric.context_managers import prefix
BASE_DIR = "/srv/dochub/source"
ACTIVATE = 'source ../ve/bin/activate'
def deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo sys... | from __future__ import with_statement
from fabric.api import run, cd
from fabric.context_managers import prefix
BASE_DIR = "/srv/dochub/source"
ACTIVATE = 'source ../ve/bin/activate'
def deploy():
with cd(BASE_DIR), prefix(ACTIVATE):
run('sudo systemctl stop dochub-gunicorn.socket')
run('sudo sys... | Add npm install to the fabric script | Add npm install to the fabric script
| Python | agpl-3.0 | UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub | ---
+++
@@ -13,6 +13,7 @@
run("../backup_db.sh")
run("git pull")
run("pip install -r requirements.txt -q")
+ run("npm install --no-progress")
run("npm run build")
run("./manage.py collectstatic --noinput -v 0")
run("./manage.py migrate") |
bbda0891e2fc4d2dfec157e9249e02d114c7c45a | corehq/tests/test_toggles.py | corehq/tests/test_toggles.py | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing... | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing... | Add test to check Solutions sub-tags names | Add test to check Solutions sub-tags names
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -14,3 +14,12 @@
assert toggle.tag, 'Toggle "{}" tag missing'.format(toggle.slug)
assert toggle.tag in ALL_TAGS, 'Toggle "{}" tag "{}" unrecognized'.format(toggle.slug, toggle.tag)
assert toggle.namespaces, 'Toggle "{}" namespaces missing'.format(toggle.slug)
+
+
+def test_solutio... |
d8310b3d0a4664f90d89b59fd6d5660f6cc0ab2b | conference/gmap.py | conference/gmap.py | # -*- coding: UTF-8 -*-
import urllib
import httplib
import simplejson
G = 'maps.google.com'
def geocode(address, key, country):
"""
Get the coordinates from Google Maps for a specified address
"""
# see http://code.google.com/intl/it/apis/maps/documentation/geocoding/#GeocodingRequests
params = {... | # -*- coding: UTF-8 -*-
import urllib
import httplib
import simplejson
G = 'maps.google.com'
# FIXME: use this function or this one, but the code is in double assopy.utils.geocode
def geocode(address, key, country): # pragma: no cover
"""
Get the coordinates from Google Maps for a specified address
"""
... | Add a pragma and in the future we need to fix the function, because it's a duplicata | Add a pragma and in the future we need to fix the function, because it's a duplicata
| Python | bsd-2-clause | artcz/epcon,EuroPython/epcon,EuroPython/epcon,artcz/epcon,artcz/epcon,artcz/epcon,artcz/epcon,EuroPython/epcon,EuroPython/epcon,artcz/epcon | ---
+++
@@ -5,7 +5,8 @@
G = 'maps.google.com'
-def geocode(address, key, country):
+# FIXME: use this function or this one, but the code is in double assopy.utils.geocode
+def geocode(address, key, country): # pragma: no cover
"""
Get the coordinates from Google Maps for a specified address
""" |
c82eaa445ddbe39f4142de7f51f0d19437a1aef0 | validators/url.py | validators/url.py | import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""... | import re
from .utils import validator
regex = (
r'^[a-z]+://([^/:]+{tld}|([0-9]{{1,3}}\.)'
r'{{3}}[0-9]{{1,3}})(:[0-9]+)?(\/.*)?$'
)
pattern_with_tld = re.compile(regex.format(tld=r'\.[a-z]{2,10}'))
pattern_without_tld = re.compile(regex.format(tld=''))
@validator
def url(value, require_tld=True):
"""... | Remove unnecessary heading from docstring | Remove unnecessary heading from docstring
| Python | mit | kvesteri/validators | ---
+++
@@ -14,9 +14,6 @@
@validator
def url(value, require_tld=True):
"""
- url
- ---
-
Returns whether or not given value is a valid URL. If the value is
valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`. |
1d4d317c826cd8528dfafd4ae47d006c1e8bb673 | reports/admin.py | reports/admin.py | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
list_filter = ['created_at', 'content']
search_fields = ['addressed_to', 'reported_from__us... | # coding: utf-8
from django.contrib import admin
from .models import Report
class ReportAdmin(admin.ModelAdmin):
list_display = ('addressed_to', 'reported_from', 'signed_from', 'created_at')
list_filter = ['created_at']
search_fields = ['addressed_to', 'reported_from__username', 'content', 'signed_from']
... | Change search and list fields | Change search and list fields
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -3,8 +3,8 @@
from .models import Report
class ReportAdmin(admin.ModelAdmin):
- list_display = ('addressed_to', 'reported_from', 'content', 'signed_from', 'get_copies', 'created_at')
- list_filter = ['created_at', 'content']
+ list_display = ('addressed_to', 'reported_from', 'signed_from', 'cre... |
4a98d2ce95d6a082588e4ccc8e04454c26260ca0 | helpers.py | helpers.py | def get_readable_list(passed_list, sep=', ', end=''):
output = ""
if isinstance(passed_list, list):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:
output += str(item)
elif i... | def get_readable_list(passed_list, sep=', ', end=''):
output = ""
if isinstance(passed_list, list) or isinstance(passed_list, tuple):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
else:
if i is not (len(passed_list) - 1):
output += str(item) + sep
else:... | Make get_readable_list process tuples, too | Make get_readable_list process tuples, too
| Python | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | ---
+++
@@ -1,6 +1,6 @@
def get_readable_list(passed_list, sep=', ', end=''):
output = ""
- if isinstance(passed_list, list):
+ if isinstance(passed_list, list) or isinstance(passed_list, tuple):
for i, item in enumerate(passed_list):
if len(passed_list) is 1:
output += str(item)
@@ -10,6 +10,7 @@
... |
9bc7d09e9abf79f6af7f7fd3cdddbfacd91ba9d3 | run.py | run.py | #!/usr/bin/env python
import os
import argparse
def run():
""" Reuse the Procfile to start the dev server """
with open("Procfile", "r") as f:
command = f.read().strip()
command = command.replace("web: ", "")
command += " --reload"
os.system(command)
def deploy():
os.system("git push ... | #!/usr/bin/env python
import os
import argparse
def run():
""" Reuse the Procfile to start the dev server """
with open("Procfile", "r") as f:
command = f.read().strip()
command = command.replace("web: ", "")
command += " --reload"
os.system(command)
def deploy():
os.system("git push ... | Add command to update dependencies. | Add command to update dependencies.
| Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger | ---
+++
@@ -14,15 +14,24 @@
def deploy():
os.system("git push dokku master")
+def dependencies():
+ os.system("pip-compile --upgrade requirements.in")
+ os.system("pip-compile --upgrade requirements-dev.in")
+ os.system("pip-sync requirements-dev.txt")
+
def main():
parser = argparse.ArgumentPa... |
5b208baa581e16290aa8332df966ad1d61876107 | deployment/ansible/filter_plugins/custom_filters.py | deployment/ansible/filter_plugins/custom_filters.py | class FilterModule(object):
''' Additional filters for use within Ansible. '''
def filters(self):
return {
'is_not_in': self.is_not_in,
'is_in': self.is_in,
'some_are_in': self.some_are_in
}
def is_not_in(self, *t):
"""Determnies if there are no ... | class FilterModule(object):
''' Additional filters for use within Ansible. '''
def filters(self):
return {
'is_not_in': self.is_not_in,
'is_in': self.is_in,
'some_are_in': self.some_are_in
}
def is_not_in(self, x, y):
"""Determines if there are n... | Add explicit method signature to custom filters | Add explicit method signature to custom filters
This changeset adds an explicit method signature to the Ansible custom filters.
| Python | agpl-3.0 | maurizi/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,maurizi/ny... | ---
+++
@@ -8,38 +8,32 @@
'some_are_in': self.some_are_in
}
- def is_not_in(self, *t):
- """Determnies if there are no elements in common between x and y
+ def is_not_in(self, x, y):
+ """Determines if there are no elements in common between x and y
x | is_no... |
b2e0b2047fa686fd716ba22dcec536b79f6fea41 | cookielaw/templatetags/cookielaw_tags.py | cookielaw/templatetags/cookielaw_tags.py | from classytags.helpers import InclusionTag
from django import template
from django.template.loader import render_to_string
register = template.Library()
class CookielawBanner(InclusionTag):
"""
Displays cookie law banner only if user has not dismissed it yet.
"""
template = 'cookielaw/banner.html'... | # -*- coding: utf-8 -*-
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
return render_to_st... | Use Django simple_tag instead of classytags because there were no context in template rendering. | Use Django simple_tag instead of classytags because there were no context in template rendering. | Python | bsd-2-clause | juan-cb/django-cookie-law,juan-cb/django-cookie-law,juan-cb/django-cookie-law,APSL/django-cookie-law,APSL/django-cookie-law,APSL/django-cookie-law | ---
+++
@@ -1,4 +1,5 @@
-from classytags.helpers import InclusionTag
+# -*- coding: utf-8 -*-
+
from django import template
from django.template.loader import render_to_string
@@ -6,18 +7,9 @@
register = template.Library()
-class CookielawBanner(InclusionTag):
- """
- Displays cookie law banner only if... |
92e7164cf152700c4ae60013bfbb9536e425a64c | neo/rawio/tests/test_nixrawio.py | neo/rawio/tests/test_nixrawio.py | import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
testfname = "neoraw.nix"
class TestNixRawIO(BaseTestRawIO, unittest.TestCase, ):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname]
if __name__ == "__mai... | import unittest
from neo.rawio.nixrawio import NIXRawIO
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
testfname = "nixrawio-1.5.nix"
class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = NIXRawIO
entities_to_test = [testfname]
files_to_download = [testfname]
if __name__ == "... | Change filename for NIXRawIO tests | [nixio] Change filename for NIXRawIO tests
| Python | bsd-3-clause | NeuralEnsemble/python-neo,INM-6/python-neo,JuliaSprenger/python-neo,apdavison/python-neo,rgerkin/python-neo,samuelgarcia/python-neo | ---
+++
@@ -3,9 +3,10 @@
from neo.rawio.tests.common_rawio_test import BaseTestRawIO
-testfname = "neoraw.nix"
+testfname = "nixrawio-1.5.nix"
-class TestNixRawIO(BaseTestRawIO, unittest.TestCase, ):
+
+class TestNixRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = NIXRawIO
entities_to_test = [te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.