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 |
|---|---|---|---|---|---|---|---|---|---|---|
dc6d56b7997a9c15419fb66cd724ae3fc1a011a0 | rdrf/rdrf/initial_data/iprestrict_permissive.py | rdrf/rdrf/initial_data/iprestrict_permissive.py | """Disable iprestriction completely."""
from iprestrict.models import IPGroup, IPRange, Rule
def load_data(**kwargs):
allow_all()
def allow_all():
all_group = get_or_create_all_group()
Rule.objects.all().delete()
Rule.objects.create(
ip_group=all_group,
action='A',
url_patt... | """Disable iprestriction completely."""
from iprestrict.models import RangeBasedIPGroup, IPRange, Rule
def load_data(**kwargs):
allow_all()
def allow_all():
all_group = get_or_create_all_group()
Rule.objects.all().delete()
Rule.objects.create(
ip_group=all_group,
action='A',
... | Update iprestrict models in initial data | Update iprestrict models in initial data
| Python | agpl-3.0 | muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf | ---
+++
@@ -1,6 +1,6 @@
"""Disable iprestriction completely."""
-from iprestrict.models import IPGroup, IPRange, Rule
+from iprestrict.models import RangeBasedIPGroup, IPRange, Rule
def load_data(**kwargs):
@@ -19,7 +19,7 @@
def get_or_create_all_group():
- all_group, created = IPGroup.objects.get_or_... |
a20a63415bf1343ab826d1155c1004e84b14077e | massa/validation.py | massa/validation.py | # -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=e.messages)
def weight_validator(val... | # -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
from .errors import InvalidInputError
def validate(schema, data):
try:
schema.import_data(data)
schema.validate()
except (ConversionError, ValidationError) as e:
raise InvalidInputError(details=... | Fix bug, InvalidInputError not defined. | Fix bug, InvalidInputError not defined. | Python | mit | jaapverloop/massa | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from schematics.exceptions import ConversionError, ValidationError
+from .errors import InvalidInputError
def validate(schema, data): |
a2b418c89e6ad3f85c88b7dfcc2238d62cb2e36e | karanja_me/polls/tests.py | karanja_me/polls/tests.py | from django.test import TestCase
# Create your tests here.
| import datetime
from django.utils import timezone
from django.test import TestCase
from .models import Question
class QuestionMethodTest(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recenlty() should return False for questions that the
pub_date is in the fut... | Test case for Question method added | Test case for Question method added
A test case to avoid future published questions read as recently added
| Python | mit | yoda-yoda/django-dive-in,yoda-yoda/django-dive-in,denisKaranja/django-dive-in,denisKaranja/django-dive-in | ---
+++
@@ -1,3 +1,18 @@
+import datetime
+
+from django.utils import timezone
from django.test import TestCase
-# Create your tests here.
+from .models import Question
+
+class QuestionMethodTest(TestCase):
+
+ def test_was_published_recently_with_future_question(self):
+ """
+ was_published_recenlty() sho... |
1a1f0a9bca7458153ef84316fd84dfbe56be08ef | dolo/config.py | dolo/config.py | #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printing as printing
from numpy import ndarray
from dolo.symbolic... | #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printing as printing
from numpy import ndarray
from dolo.symbolic... | Remove print("failing back on pretty_print") when using dolo-recs | Remove print("failing back on pretty_print") when using dolo-recs
| Python | bsd-2-clause | EconForge/dolo | ---
+++
@@ -25,8 +25,10 @@
from IPython.core.display import display
except:
-
- print("failing back on pretty_print")
+ import re
+ import sys
+ if not re.search('dolo-recs',sys.argv[0]):
+ print("failing back on pretty_print")
from pprint import pprint
def display(txt): |
bf69962ab7cb730c270ba31508af8af270c912a6 | examples/generate-manager-file.py | examples/generate-manager-file.py | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name
object_path = "/org/freedesktop/Telepathy/ConnectionMana... | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \
CONN_MGR_PARAM_FLAG_REGISTER
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_na... | Handle register flag; use CONN_MGR_PARAM_FLAG_REQUIRED not 1L | Handle register flag; use CONN_MGR_PARAM_FLAG_REQUIRED not 1L
20070911135601-4210b-dec39420c4af7a81bd9b6060cb81d787ebb707fc.gz
| Python | lgpl-2.1 | detrout/telepathy-python,max-posedon/telepathy-python,PabloCastellano/telepathy-python,epage/telepathy-python,PabloCastellano/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,epage/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,max-posedon/telepathy-python,detrout/t... | ---
+++
@@ -2,6 +2,8 @@
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
+from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \
+ CONN_MGR_PARAM_FLAG_REGISTER
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
@@ -23,9 +25,12 @@
for pr... |
5af9796dc0fcc425efd6b0283f2e4a79dec31d5f | server/liveblog/blogs/blogs_test.py | server/liveblog/blogs/blogs_test.py | import unittest
from liveblog.blogs.blogs import BlogService
from superdesk.errors import SuperdeskApiError
class BlogsTestCase(unittest.TestCase):
def setUp(self):
pass
def test_if_check_max_active(self):
increment = 10
"""so if check "subscription in SUBSCRIPTION_MAX_ACTIVE_BLOGS" p... | from liveblog.blogs import init_app
from superdesk.tests import TestCase
from superdesk import get_resource_service
from superdesk.errors import SuperdeskApiError
class BlogsTestCase(TestCase):
def setUp(self):
# from nose.tools import set_trace; set_trace()
init_app(self.app)
def test_if_no... | Test case: _check_max_active method to check both scenarios | Test case: _check_max_active method to check both scenarios
| Python | agpl-3.0 | liveblog/liveblog,superdesk/liveblog,hlmnrmr/liveblog,superdesk/liveblog,superdesk/liveblog,liveblog/liveblog,hlmnrmr/liveblog,liveblog/liveblog,liveblog/liveblog,liveblog/liveblog,hlmnrmr/liveblog,hlmnrmr/liveblog,superdesk/liveblog | ---
+++
@@ -1,19 +1,20 @@
-import unittest
-from liveblog.blogs.blogs import BlogService
+from liveblog.blogs import init_app
+from superdesk.tests import TestCase
+from superdesk import get_resource_service
from superdesk.errors import SuperdeskApiError
-class BlogsTestCase(unittest.TestCase):
+
+class BlogsTestC... |
eee7ee47f0a6e2be31c74f9967fa1b2f1a8b3b01 | experiments/example-fsrcnn/run.py | experiments/example-fsrcnn/run.py | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=3))
model.summary()
# Data
train_set = '91-i... | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=scale))
model.summary()
# Data
train_set = '... | Set the stride to scale | Set the stride to scale
| Python | mit | qobilidop/srcnn,qobilidop/srcnn | ---
+++
@@ -9,7 +9,7 @@
# Model
scale = 3
-model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=3))
+model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=scale))
model.summary()
# Data |
fd7f413925491f305a30a73f0c6eb6306a9ebf19 | tests/test_member_access.py | tests/test_member_access.py | import pytest # type: ignore
from ppb_vector import Vector
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
def test_index_access(vector):
assert vector[0] == 10
assert vector[1] == 20
def test_key_acces... | from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vecto... | Make {index.key}_access into Hypothesis tests | tests/member_access: Make {index.key}_access into Hypothesis tests
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -1,6 +1,8 @@
+from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
+from utils import vectors
@pytest.fixture()
@@ -13,11 +15,13 @@
assert vector.y == 20
-def test_index_access(vector):
- assert vector[0] == 10
- assert vector[1] == 20
+@given(v=v... |
7f99ba5d06d646eef03bd3848fae579d0f51e2f6 | alembic/testing/__init__.py | alembic/testing/__init__.py | from sqlalchemy.testing import config
from sqlalchemy.testing import emits_warning
from sqlalchemy.testing import engines
from sqlalchemy.testing import exclusions
from sqlalchemy.testing import mock
from sqlalchemy.testing import provide_metadata
from sqlalchemy.testing import skip_if
from sqlalchemy.testing import us... | from sqlalchemy.testing import config
from sqlalchemy.testing import emits_warning
from sqlalchemy.testing import engines
from sqlalchemy.testing import exclusions
from sqlalchemy.testing import mock
from sqlalchemy.testing import provide_metadata
from sqlalchemy.testing import skip_if
from sqlalchemy.testing import us... | Remove code to force ENABLE_ASYNCIO to False | Remove code to force ENABLE_ASYNCIO to False
Forcing ENABLE_ASYNCIO to False was interfering
with testing under async drivers when the
(third-party dialect) test suite included both
SQLAlchemy and Alembic tests.
Change-Id: I2fe40049c24ba8eba0a10011849a912c03aa381e
| Python | mit | zzzeek/alembic,sqlalchemy/alembic | ---
+++
@@ -27,10 +27,3 @@
from .assertions import ne_
from .fixtures import TestBase
from .util import resolve_lambda
-
-try:
- from sqlalchemy.testing import asyncio
-except ImportError:
- pass
-else:
- asyncio.ENABLE_ASYNCIO = False |
9ed6833c88e2718e54cb25b6c1837ff4868c81c9 | emote/emote.py | emote/emote.py | """ A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
... | """ A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
... | Add logic for displaying help if no args are specified. | Add logic for displaying help if no args are specified.
| Python | mit | d6e/emotion | ---
+++
@@ -15,5 +15,9 @@
parser.add_argument('-p','--web_port')
args = parser.parse_args()
+ # Print help if no cli args are specified.
+ if len(sys.argv) < 2:
+ parser.print_help()
+
if __name__ == "__main__":
main() |
df045cb2e5e53c497aa101719c528b1f17c03a1f | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlchemy(app)
from app import views, models | from werkzeug.contrib.fixers import ProxyFix
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
app.wsgi_app = ProxyFix(app.wsgi_app)
login_manager = LoginManager()
login_manager.init_app(app)
db = SQLAlch... | Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17 | Add ProxyFix() middleware component to fix the HTTPS redirection issue. See !17
| Python | mit | ngoduykhanh/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,ivanfilippov/PowerDNS-Admin,0x97/PowerDNS-Admin,ngoduykhanh/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,0x97/PowerDNS-Admin,0x97/PowerDNS-Admin,CaptainQwark/PowerDNS-Admin,ivanfilipp... | ---
+++
@@ -1,9 +1,12 @@
+from werkzeug.contrib.fixers import ProxyFix
from flask import Flask
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
+app.wsgi_app = ProxyFix(app.wsgi_app)
+
login_manager = LoginManager()
lo... |
c6c4c2f9acc348053372506a6ab8fe8d3b6d9b02 | tempodb/__init__.py | tempodb/__init__.py |
#!/usr/bin/env python
# encoding: utf-8
"""
tempodb/setup.py
Copyright (c) 2012 TempoDB Inc. All rights reserved.
"""
import client
from client import *
VERSION = (0, 3, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
... |
#!/usr/bin/env python
# encoding: utf-8
"""
tempodb/setup.py
Copyright (c) 2012 TempoDB Inc. All rights reserved.
"""
import client
from client import *
VERSION = (0, 2, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
... | Revert "Roll to version 0.3.0" | Revert "Roll to version 0.3.0"
This reverts commit d98b62b366317a6188a743912ee6feea035e998b.
| Python | mit | mrgaaron/tempoiq-python,tempodb/tempodb-python,TempoIQ/tempoiq-python,tempodb/tempodb-python | ---
+++
@@ -10,7 +10,7 @@
import client
from client import *
-VERSION = (0, 3, 0)
+VERSION = (0, 2, 0)
def get_version(): |
54e83b1836afcd758b9ef140a6bbf5c395ac4a4a | indico/modules/bootstrap/forms.py | indico/modules/bootstrap/forms.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from wtforms import BooleanField, StringField
from wtforms.fields... | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from wtforms import BooleanField, StringField
from wtforms.fields... | Add missing email validation during initial setup | Add missing email validation during initial setup
| Python | mit | pferreir/indico,indico/indico,DirkHoffmann/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico,pferreir/indico,OmeGak/indico,OmeGak/indico,indico/indico,OmeGak/indico,ThiefMaster/indico,mic4ael/indico,OmeGak/indico,ThiefMaster/indico,pferreir/indico,mic4ael/indico,indico/indico,pferreir/indico,mic4ael/ind... | ---
+++
@@ -20,7 +20,7 @@
class BootstrapForm(LocalRegistrationForm):
first_name = StringField('First Name', [DataRequired()])
last_name = StringField('Last Name', [DataRequired()])
- email = EmailField(_('Email address'), [DataRequired()])
+ email = EmailField(_('Email address'), [DataRequired(), Em... |
19b15df8b2d92b3a00f94f53b684f9422d570c13 | vumi/middleware/__init__.py | vumi/middleware/__init__.py | """Middleware classes to process messages on their way in and out of workers.
"""
from vumi.middleware.base import (
TransportMiddleware, ApplicationMiddleware, MiddlewareStack,
create_middlewares_from_config, setup_middlewares_from_config)
__all__ = [
'TransportMiddleware', 'ApplicationMiddleware', 'Midd... | """Middleware classes to process messages on their way in and out of workers.
"""
from vumi.middleware.base import (
BaseMiddleware, TransportMiddleware, ApplicationMiddleware,
MiddlewareStack, create_middlewares_from_config,
setup_middlewares_from_config)
__all__ = [
'BaseMiddleware', 'TransportMiddl... | Add BaseMiddleware to vumi.middleware API for 3rd-party middleware that wants to support both transports and applications. | Add BaseMiddleware to vumi.middleware API for 3rd-party middleware that wants to support both transports and applications.
| Python | bsd-3-clause | harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi | ---
+++
@@ -2,9 +2,11 @@
"""
from vumi.middleware.base import (
- TransportMiddleware, ApplicationMiddleware, MiddlewareStack,
- create_middlewares_from_config, setup_middlewares_from_config)
+ BaseMiddleware, TransportMiddleware, ApplicationMiddleware,
+ MiddlewareStack, create_middlewares_from_confi... |
22772750d7bee9e9f1f8ac28068d1865e8f0ec32 | fuf/interop.py | fuf/interop.py | import sys # Used to get rid of py2/3 differences
# Blatantly stolen from the excellent `six` library
# Allows the same calls between python2 and python3
if sys.version_info[0] == 3:
exec_ = getattr(__builtins__, "exec")
raw_input = input
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execu... | import sys # Used to get rid of py2/3 differences
# Blatantly stolen from the excellent `six` library
# Allows the same calls between python2 and python3
if sys.version_info[0] == 3:
exec_ = __builtins__["exec"]
raw_input = input
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code i... | Fix python 3 support for exec | Fix python 3 support for exec
| Python | mit | msoucy/fuf | ---
+++
@@ -3,7 +3,7 @@
# Blatantly stolen from the excellent `six` library
# Allows the same calls between python2 and python3
if sys.version_info[0] == 3:
- exec_ = getattr(__builtins__, "exec")
+ exec_ = __builtins__["exec"]
raw_input = input
else:
def exec_(_code_, _globs_=None, _locs_=None): |
ca8aca917234bdc10a47091ee83be8eed4845b5f | applications/decorators.py | applications/decorators.py | from functools import wraps
from django.http import HttpResponseNotFound
from django.shortcuts import redirect
from core.utils import get_event_page
def organiser_only(function):
"""
Decorator for views that checks that the user is logged in and that
they are a team member for a particular page. Returns... | from functools import wraps
from django.http import HttpResponseNotFound
from django.shortcuts import redirect
from core.utils import get_event_page
def organiser_only(function):
"""
Decorator for views that checks that the user is logged in and that
they are a team member for a particular page. Returns... | Define 'city' at top decorator | Define 'city' at top decorator
| Python | bsd-3-clause | patjouk/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls,patjouk/djangogirls,patjouk/djangogirls,patjouk/djangogirls,DjangoGirls/djangogirls | ---
+++
@@ -14,14 +14,15 @@
@wraps(function)
def decorator(request, *args, **kwargs):
- if not kwargs.get('city'):
+ city = kwargs.get('city')
+
+ if not city:
raise ValueError(
'"City" slug must be present to user this decorator.')
if not requ... |
6761d8230d59031ad5183615f68a71e51f5f0309 | elasticmock/__init__.py | elasticmock/__init__.py | # -*- coding: utf-8 -*-
from functools import wraps
from mock import patch
from elasticmock.fake_elasticsearch import FakeElasticsearch
ELASTIC_INSTANCES = {}
def _get_elasticmock(hosts=None):
elastic_key = 'localhost:9200' if hosts is None else '{0}:{1}'.format(hosts[0].get('host'), hosts[0].get('port'))
... | # -*- coding: utf-8 -*-
from functools import wraps
from mock import patch
from elasticmock.fake_elasticsearch import FakeElasticsearch
ELASTIC_INSTANCES = {}
def _get_elasticmock(hosts=None, *args, **kwargs):
elastic_key = 'localhost:9200' if hosts is None else '{0}:{1}'.format(hosts[0].get('host'), hosts[0]... | Allow ignored params to Elasticsearch | Allow ignored params to Elasticsearch
| Python | mit | vrcmarcos/elasticmock | ---
+++
@@ -9,7 +9,7 @@
ELASTIC_INSTANCES = {}
-def _get_elasticmock(hosts=None):
+def _get_elasticmock(hosts=None, *args, **kwargs):
elastic_key = 'localhost:9200' if hosts is None else '{0}:{1}'.format(hosts[0].get('host'), hosts[0].get('port'))
if elastic_key in ELASTIC_INSTANCES:
connectio... |
b291a1594985a3c671b81fb05a8487a8d7a403ea | icekit/page_types/layout_page/models.py | icekit/page_types/layout_page/models.py | from . import abstract_models
class LayoutPage(abstract_models.AbstractLayoutPage):
class Meta:
verbose_name = "Layout page"
# Fluent prepends `pagetype_` to the db table. This seems to break
# Django's inference of m2m table names during migrations, when the
# m2m is defined on an... | from . import abstract_models
class LayoutPage(abstract_models.AbstractLayoutPage):
class Meta:
verbose_name = "Page"
# Fluent prepends `pagetype_` to the db table. This seems to break
# Django's inference of m2m table names during migrations, when the
# m2m is defined on an abstra... | Change verbose name of Layout Page to ‘Page’ for simplicity. | Change verbose name of Layout Page to ‘Page’ for simplicity.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -3,7 +3,7 @@
class LayoutPage(abstract_models.AbstractLayoutPage):
class Meta:
- verbose_name = "Layout page"
+ verbose_name = "Page"
# Fluent prepends `pagetype_` to the db table. This seems to break
# Django's inference of m2m table names during migrations, when th... |
c21c53a625b2ca1e2f704286bfa99e61bbed0619 | takeyourmeds/reminders/reminders_calls/tests.py | takeyourmeds/reminders/reminders_calls/tests.py | from takeyourmeds.utils.test import TestCase
from ..enums import TypeEnum, SourceEnum
from .enums import StateEnum
class TwimlCallbackTest(TestCase):
def setUp(self):
super(TwimlCallbackTest, self).setUp()
self.call = self.user.reminders.create(
type=TypeEnum.call,
).instance... | from django.conf import settings
from takeyourmeds.utils.test import TestCase
from ..enums import TypeEnum, SourceEnum
from .enums import StateEnum
class TwimlCallbackTest(TestCase):
def setUp(self):
super(TwimlCallbackTest, self).setUp()
self.reminder = self.user.reminders.create(
... | Check we get some sane XML back | Check we get some sane XML back
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web | ---
+++
@@ -1,3 +1,5 @@
+from django.conf import settings
+
from takeyourmeds.utils.test import TestCase
from ..enums import TypeEnum, SourceEnum
@@ -8,9 +10,12 @@
def setUp(self):
super(TwimlCallbackTest, self).setUp()
- self.call = self.user.reminders.create(
+ self.reminder = self... |
5f77be6bc80b9ed653f85f4b8c0c60ccb520f2f8 | saleor/payment/gateways/utils.py | saleor/payment/gateways/utils.py | import warnings
from typing import TYPE_CHECKING, List
from django.conf import settings
if TYPE_CHECKING:
from ..interface import GatewayConfig
def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List[str]:
supp_currencies = config.supported_currencies
if not supp_currencies:
... | import re
import warnings
from typing import TYPE_CHECKING, List
from django.conf import settings
if TYPE_CHECKING:
from ..interface import GatewayConfig
def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List[str]:
supp_currencies = config.supported_currencies
if not supp_curre... | Update supported currencies in gateways, set default currency for dummy gateway | Update supported currencies in gateways, set default currency for dummy gateway
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -1,3 +1,4 @@
+import re
import warnings
from typing import TYPE_CHECKING, List
|
ea5499d36ef84e879737fd8c6d6148dd8305c356 | bookshelf/search_indexes.py | bookshelf/search_indexes.py |
# Imports #####################################################################
from haystack import indexes
from .models import Book
# Classes #####################################################################
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True,... |
# Imports #####################################################################
from haystack import indexes
from .models import Book
# Classes #####################################################################
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True,... | Allow some blank fields in Booki model from search | Allow some blank fields in Booki model from search
| Python | agpl-3.0 | antoviaque/plin,antoviaque/plin,antoviaque/plin | ---
+++
@@ -11,13 +11,13 @@
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
- subtitle = indexes.CharField(model_attr='subtitle')
+ subtitle = indexes.CharField(model_attr='subtitle', bla... |
03d8b2ca0b070f9247376c40e1f3a4655e579dd0 | kibitzr/notifier/telegram-split.py | kibitzr/notifier/telegram-split.py | from __future__ import absolute_import
import logging
from .telegram import TelegramBot
logger = logging.getLogger(__name__)
class TelegramBotSplit(TelegramBot):
def __init__(self, chat_id=None, split_on="\n"):
self.split_on = split_on
super(TelegramBotSplit, self).__init__(chat_id=chat_id)
... | from __future__ import absolute_import
import logging
from .telegram import TelegramBot
logger = logging.getLogger(__name__)
class TelegramBotSplit(TelegramBot):
def __init__(self, chat_id=None, split_on="\n"):
self.split_on = split_on
super(TelegramBotSplit, self).__init__(chat_id=chat_id)
... | Use parent 'post' function to actually send message | Use parent 'post' function to actually send message
| Python | mit | kibitzr/kibitzr,kibitzr/kibitzr | ---
+++
@@ -15,11 +15,7 @@
def post(self, report, **kwargs):
"""Overwrite post to split message on token"""
for m in report.split(self.split_on):
- self.bot.send_message(
- self.chat_id,
- m,
- parse_mode='Markdown',
- )
+ ... |
0b7cdb4b5a6dab5f2983313d745bea84ff302e01 | Machines/wxMachines.py | Machines/wxMachines.py | # -*- coding: utf-8 -*-
# Import
# Import for changing the Python Path for importing Gestalt
import sys
import os
# Change the Python Path
base_dir = os.path.dirname(__file__) or '.'
appdir = os.path.abspath(os.path.join(base_dir, os.pardir))
sys.path.insert(0, appdir)
# Import Gestalt
from gestalt import nodes
fro... | # -*- coding: utf-8 -*-
# Import
# Import for changing the Python Path for importing Gestalt
import sys
import os
# Change the Python Path
base_dir = os.path.dirname(__file__) or '.'
appdir = os.path.abspath(os.path.join(base_dir, os.pardir))
sys.path.insert(0, appdir)
# Import Gestalt
from gestalt import nodes
fro... | Improve general classes with input from Ilan Ellison Moyer's thesis | Improve general classes with input from Ilan Ellison Moyer's thesis
| Python | mit | openp2pdesign/wxGestalt | ---
+++
@@ -25,18 +25,64 @@
# Classes
-class Axis():
+# A class for each Node / Axis
+class wxNode():
def __init__(self):
self.linear = True
self.rotary = False
-class Machine():
+
+# A basic class for each Machine
+class wxMachine():
def __init__(self):
self.axes = []
... |
610d9a3c58f70d8b2002403003b705dd57513d92 | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
from django.core.management import execute_from_command_line
from wger.main import get_user_config_path, setup_django_environment
if __name__ == "__main__":
setup_django_environment(
get_user_config_path('wger', 'settings.py'))
#os.environ.setdefaul... | #!/usr/bin/env python
import sys
from django.core.management import execute_from_command_line
from wger.utils.main import (
setup_django_environment,
get_user_config_path
)
if __name__ == "__main__":
setup_django_environment(
get_user_config_path('wger', 'settings.py'))
#os.environ.s... | Change imports of helper functions | Change imports of helper functions
These are now in the utils app
| Python | agpl-3.0 | rolandgeider/wger,kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,kjagoo/wger_stark,kjagoo/wger_stark,petervanderdoes/wger,petervanderdoes/wger,rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,wger-project/wger,wger-project/wger,rolandgeider/wger,DeveloperMal/wger,DeveloperMal/wger,wger-project/wger,peter... | ---
+++
@@ -1,10 +1,12 @@
#!/usr/bin/env python
-import os
import sys
from django.core.management import execute_from_command_line
-from wger.main import get_user_config_path, setup_django_environment
+from wger.utils.main import (
+ setup_django_environment,
+ get_user_config_path
+)
if __name__ == "... |
8ae1a0793e1938cf845b249d0133e7fc352cda5b | django/website/logframe/tests/test_period_utils.py | django/website/logframe/tests/test_period_utils.py | from datetime import date
from ..period_utils import get_month_shift, get_periods
def test_get_month_shift_handles_december():
new_month, _ = get_month_shift(12, 1)
assert 12 == new_month
def test_get_periods_when_end_date_before_period_end():
# This should produce eight periods, 2 for each of the year... | from datetime import date, timedelta
from ..period_utils import get_month_shift, get_periods, periods_intersect
def test_get_month_shift_handles_december():
new_month, _ = get_month_shift(12, 1)
assert 12 == new_month
def test_get_periods_when_end_date_before_period_end():
# This should produce eight p... | Add tests for period_intersect logic | Add tests for period_intersect logic | Python | agpl-3.0 | aptivate/alfie,daniell/kashana,aptivate/alfie,daniell/kashana,aptivate/kashana,aptivate/kashana,daniell/kashana,daniell/kashana,aptivate/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana | ---
+++
@@ -1,6 +1,6 @@
-from datetime import date
+from datetime import date, timedelta
-from ..period_utils import get_month_shift, get_periods
+from ..period_utils import get_month_shift, get_periods, periods_intersect
def test_get_month_shift_handles_december():
@@ -13,3 +13,43 @@
# 2015 to 2018 inclu... |
74ededafa70c7ec5548d86289c6dbfc5e4cff6f2 | tests/integration/ssh/test_deploy.py | tests/integration/ssh/test_deploy.py | # -*- coding: utf-8 -*-
'''
salt-ssh testing
'''
# Import Python libs
from __future__ import absolute_import
# Import salt testing libs
from tests.support.case import SSHCase
class SSHTest(SSHCase):
'''
Test general salt-ssh functionality
'''
def test_ping(self):
'''
Test a simple pin... | # -*- coding: utf-8 -*-
'''
salt-ssh testing
'''
# Import Python libs
from __future__ import absolute_import
import os
import shutil
# Import salt testing libs
from tests.support.case import SSHCase
class SSHTest(SSHCase):
'''
Test general salt-ssh functionality
'''
def test_ping(self):
'''
... | Add ssh thin_dir integration test | Add ssh thin_dir integration test
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -4,6 +4,8 @@
'''
# Import Python libs
from __future__ import absolute_import
+import os
+import shutil
# Import salt testing libs
from tests.support.case import SSHCase
@@ -19,3 +21,21 @@
'''
ret = self.run_function('test.ping')
self.assertTrue(ret, 'Ping did not return tr... |
1ef311a2bef956acf09c8aae21f2e1e27c02e511 | 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.1.3.dev0 | Update dsub version to 0.1.3.dev0
PiperOrigin-RevId: 173965107
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | ---
+++
@@ -18,6 +18,12 @@
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
+
+The version should follow formatting requirements specified in PEP-440.
+ - https://www.python.org/dev/peps/pep-044... |
7a732c70fb5e07181aeb8f2386230fbecf0667e9 | test/test_historynode.py | test/test_historynode.py | """ Tests for the HistoryNode module """
pass
| """ Tests for the HistoryNode module """
from contextlib import contextmanager
from io import StringIO
import sys
import unittest
from src import historynode
@contextmanager
def captured_output():
""" Redirects stdout to StringIO so we can inspect Print statements """
new_out = StringIO()
old_out = sys.s... | Add unit test for print_board() | Add unit test for print_board()
| Python | mit | blairck/jaeger | ---
+++
@@ -1,3 +1,44 @@
""" Tests for the HistoryNode module """
-pass
+from contextlib import contextmanager
+from io import StringIO
+import sys
+import unittest
+
+from src import historynode
+
+@contextmanager
+def captured_output():
+ """ Redirects stdout to StringIO so we can inspect Print statements """... |
b5ca3dd7b5c743987223b42e302a4044367d4dc9 | opps/core/admin/article.py | opps/core/admin/article.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from opps.core.models import Post, PostImage
from redactor.widgets import RedactorEditor
class PostImageInline(admin.TabularInline):
model = PostImage
fk_name = 'post'
raw_id_fields = ['image']
actions = None
extr... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from opps.core.models import Post, PostImage, PostSource
from redactor.widgets import RedactorEditor
class PostImageInline(admin.TabularInline):
model = PostImage
fk_name = 'post'
raw_id_fields = ['image']
actions = N... | Create post source inline (admin Tabular Inline) on core post | Create post source inline (admin Tabular Inline) on core post
| Python | mit | YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,opps/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps | ---
+++
@@ -2,7 +2,7 @@
from django.contrib import admin
from django import forms
-from opps.core.models import Post, PostImage
+from opps.core.models import Post, PostImage, PostSource
from redactor.widgets import RedactorEditor
@@ -16,6 +16,16 @@
extra = 1
fieldsets = [(None, {'fields': ('image',... |
f627a76e8dac96282b0a9f76eeda8c7db70cc030 | telemetry/telemetry/internal/actions/javascript_click.py | telemetry/telemetry/internal/actions/javascript_click.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.actions import page_action
class ClickElementAction(page_action.ElementPageAction):
def RunAction(self, tab):
code = '''
... | Fix a regression where the user_gesture bit isn't set for ClickElement. | Fix a regression where the user_gesture bit isn't set for ClickElement.
The regrssion was introduced in
https://chromium-review.googlesource.com/c/catapult/+/1335627
Once this rolls into Chromium, I'll add a chromium side test to prevent
it from regress again in the future.
Bug: chromium:885912
TEST=manual
R=58bdb62... | Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult | ---
+++
@@ -17,4 +17,4 @@
}'''
# Click handler that plays media or requests fullscreen may not take
# effects without user_gesture set to True.
- self.EvaluateCallback(tab, code)
+ self.EvaluateCallback(tab, code, user_gesture=True) |
9e7dc537d09555d9c77ff5e1f16f5577721910f9 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... | #!/usr/bin/env python
import sys
from django.conf import settings
from django.core.management import execute_from_command_line
if not settings.configured:
params = dict(
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'consol... | Fix issue with old wagtail core paths | Fix issue with old wagtail core paths
| Python | mit | Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget | ---
+++
@@ -33,10 +33,10 @@
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sites',
- 'wagtail.wagtailcore',
- 'wagtail.wagtailsites',
- 'wagtail.wagtailusers',
- 'wagtail.wagtailimages',
+ 'wagtail.cor... |
6f5784e516f2f523ce83ab3fe4e7dda9d7f6b602 | examples/demo/demo.py | examples/demo/demo.py | # coding=utf8
"""
A mini-demo of what wsme can do.
To run it::
python setup.py develop
Then::
paster serve demo.cfg
"""
from wsme import *
from wsme.wsgi import adapt
import logging
class Person(object):
id = int
firstname = unicode
lastname = unicode
class DemoRoot(WSRoot):
@expose(in... | # coding=utf8
"""
A mini-demo of what wsme can do.
To run it::
python setup.py develop
Then::
paster serve demo.cfg
"""
from wsme import WSRoot, expose, validate
from wsme.wsgi import adapt
import logging
class Person(object):
id = int
firstname = unicode
lastname = unicode
class DemoRoot(... | Add a setperson function to test complex function arguments | Add a setperson function to test complex function arguments
| Python | mit | stackforge/wsme | ---
+++
@@ -11,7 +11,7 @@
paster serve demo.cfg
"""
-from wsme import *
+from wsme import WSRoot, expose, validate
from wsme.wsgi import adapt
import logging
@@ -33,7 +33,6 @@
def helloworld(self):
return u"こんにちは世界 (<- Hello World in Japanese !)"
-
@expose(Person)
def getperson(s... |
145158b5a1693a831d2d198473d24b9d4ef6e24e | sherlock.py | sherlock.py | # -*- coding: utf-8 -*-
import sys, datetime, getopt
from reddit_user import RedditUser
longopts, shortopts = getopt.getopt(sys.argv[2:], shortopts="", longopts=["file="])
args = dict(longopts)
file_mode = ""
if len(sys.argv) < 2:
sys.exit("Usage: python sherlock.py <username> --file=(read|write)")
if args.has_ke... | # -*- coding: utf-8 -*-
import sys, datetime, getopt
from reddit_user import RedditUser
longopts, shortopts = getopt.getopt(sys.argv[2:], shortopts="", longopts=["file="])
args = dict(longopts)
file_mode = ""
if len(sys.argv) < 2:
sys.exit("Usage: python sherlock.py <username> --file=(read|write)")
if args.has_ke... | Write output to text file | Write output to text file
| Python | mit | orionmelt/sherlock | ---
+++
@@ -19,6 +19,7 @@
start = datetime.datetime.now()
u = RedditUser(sys.argv[1])
+print "Processing user %s" % u.username
if file_mode == "write":
u.save_comments_to_file()
@@ -26,7 +27,10 @@
elif file_mode == "read":
u.process_comments_from_file()
else:
+ u.process_all_submissions()
u.process_all... |
4c6784bd17113261b95178deadd037ef3c8ea830 | normandy/recipes/tests/__init__.py | normandy/recipes/tests/__init__.py | import factory
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
class ActionFactory(factory.DjangoModelFactory):
cla... | import factory
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Locale, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
@factory.post_generation
def locale(self,... | Fix tests to handle Locale as a foreign key. | Fix tests to handle Locale as a foreign key.
| Python | mpl-2.0 | mozilla/normandy,Osmose/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy | ---
+++
@@ -1,7 +1,7 @@
import factory
from normandy.base.tests import FuzzyUnicode
-from normandy.recipes.models import Action, Recipe, RecipeAction
+from normandy.recipes.models import Action, Locale, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
@@ -10,6 +10,14 @@
name = Fuz... |
618dcb272a2b19e0cd3b973e65d74085775cf4dd | api/base/exceptions.py | api/base/exceptions.py |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_fr... |
from rest_framework import status
from rest_framework.exceptions import APIException, ParseError
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_fr... | Change key and value to more descriptive names | Change key and value to more descriptive names
| Python | apache-2.0 | billyhunt/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,RomanZWang/osf.io,zachjanicki/osf.io,jnayak1/osf.io,alexschiller/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,Ghalko/osf.io,doublebits/osf.io,leb2dg/osf.io,TomHeatwole/osf.io,laurenrevere/osf.io,adlius/osf.io,cosenal/osf.io,samanehs... | ---
+++
@@ -18,13 +18,14 @@
message = response.data
if isinstance(message, dict):
- for key, value in message.iteritems():
- if key in top_level_error_keys:
- errors.append({key: value})
+ for error_key, error_description in message.iteritems... |
a1e1f0661331f5bf8faa81210eae2cad0c2ad7b3 | calico_containers/tests/st/__init__.py | calico_containers/tests/st/__init__.py | import os
import sh
from sh import docker
def setup_package():
"""
Sets up docker images and host containers for running the STs.
"""
# Pull and save each image, so we can use them inside the host containers.
print sh.bash("./build_node.sh").stdout
docker.save("--output", "calico_containers/ca... | import os
import sh
from sh import docker
def setup_package():
"""
Sets up docker images and host containers for running the STs.
"""
# Pull and save each image, so we can use them inside the host containers.
print sh.bash("./build_node.sh").stdout
docker.save("--output", "calico_containers/ca... | Fix bug in file path. | Fix bug in file path.
| Python | apache-2.0 | dalanlan/calico-docker,projectcalico/calico-docker,L-MA/calico-docker,robbrockbank/calicoctl,insequent/calico-docker,TeaBough/calico-docker,Metaswitch/calico-docker,CiscoCloud/calico-docker,frostynova/calico-docker,L-MA/calico-docker,insequent/calico-docker,webwurst/calico-docker,Symmetric/calico-docker,TrimBiggs/calic... | ---
+++
@@ -10,7 +10,7 @@
# Pull and save each image, so we can use them inside the host containers.
print sh.bash("./build_node.sh").stdout
docker.save("--output", "calico_containers/calico-node.tar", "calico/node")
- if not os.path.isfile("busybox.tar"):
+ if not os.path.isfile("calico_containe... |
934a2f1da43cd0fbcc6a074c70c73406dfc2ad14 | gsensors/databases.py | gsensors/databases.py | #-*- coding:utf-8 -*-
import sys
import logging
from influxdb import InfluxDBClient
class InfluxDBPublish(object):
def __init__(self, influxdb, measurement, tags):
assert(isinstance(influxdb, InfluxDBClient))
self.influxdb = influxdb
self.tags = tags
self.measurement = measurement... | #-*- coding:utf-8 -*-
import sys
import logging
from influxdb import InfluxDBClient as OriginalInfluxDBClient
class InfluxDBClient(OriginalInfluxDBClient):
def Publish(self, measurement, tags):
return InfluxDBPublish(self, measurement, tags)
class InfluxDBPublish(object):
def __init__(self, influxd... | Add pubish action helper for influxdb | Add pubish action helper for influxdb
| Python | agpl-3.0 | enavarro222/gsensors | ---
+++
@@ -2,7 +2,12 @@
import sys
import logging
-from influxdb import InfluxDBClient
+from influxdb import InfluxDBClient as OriginalInfluxDBClient
+
+class InfluxDBClient(OriginalInfluxDBClient):
+ def Publish(self, measurement, tags):
+ return InfluxDBPublish(self, measurement, tags)
+
class Inf... |
4aeb2496eb02e130b7dbc37baef787669f8dd1e7 | typesetter/typesetter.py | typesetter/typesetter.py | from flask import Flask, render_template, jsonify
app = Flask(__name__)
app.config.update(
JSONIFY_PRETTYPRINT_REGULAR=False,
)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/search/<fragment>')
def search(fragment):
results = []
with open('typesetter/data/words... | from flask import Flask, render_template, jsonify
app = Flask(__name__)
app.config.update(
JSONIFY_PRETTYPRINT_REGULAR=False,
)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typesetter/data/words.txt') as f:
WORDS = f.read().spli... | Reduce search response time by keeping wordlist in memory | Reduce search response time by keeping wordlist in memory
| Python | mit | rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter | ---
+++
@@ -5,6 +5,11 @@
app.config.update(
JSONIFY_PRETTYPRINT_REGULAR=False,
)
+
+# Read in the entire wordlist at startup and keep it in memory.
+# Optimization for improving search response time.
+with open('typesetter/data/words.txt') as f:
+ WORDS = f.read().split('\n')
@app.route('/')
@@ -15,14 ... |
dac4ef0e30fb5dd26ef41eb74854919cf5295450 | subprocrunner/error.py | subprocrunner/error.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
class CommandError(Exception):
@property
def errno(self):
return self.__errno
def __init__(self, *args, **kwargs):
self.__errno = kwargs.pop... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
class CommandError(Exception):
@property
def cmd(self):
return self.__cmd
@property
def errno(self):
return self.__errno
def __init... | Add a property to an exception class | Add a property to an exception class
| Python | mit | thombashi/subprocrunner,thombashi/subprocrunner | ---
+++
@@ -9,10 +9,15 @@
class CommandError(Exception):
@property
+ def cmd(self):
+ return self.__cmd
+
+ @property
def errno(self):
return self.__errno
def __init__(self, *args, **kwargs):
+ self.__cmd = kwargs.pop("cmd", None)
self.__errno = kwargs.pop("er... |
c17b8e6141d2832b9920eb143de2937993fb8865 | linguist/models/base.py | linguist/models/base.py | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.C... | Rename locale field to language. | Rename locale field to language.
| Python | mit | ulule/django-linguist | ---
+++
@@ -20,12 +20,12 @@
verbose_name=_('The object ID'),
help_text=_('The object ID of this translation'))
- locale = models.CharField(
+ language = models.CharField(
max_length=10,
verbose_name=_('locale'),
- choices=settings.SUPPORTED_LOCALES,
- default=... |
caf90dce76e361531077840f570602a625c22ccb | argus/backends/base.py | argus/backends/base.py | import abc
import six
@six.add_metaclass(abc.ABCMeta)
class BaseBackend(object):
@abc.abstractmethod
def setup_instance(self):
"""Called by setUpClass to setup an instance"""
@abc.abstractmethod
def cleanup(self):
"""Needs to cleanup the resources created in ``setup_instance``"""
| # Copyright 2015 Cloudbase Solutions Srl
# 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 r... | Add the license header where it's missing. | Add the license header where it's missing.
| Python | apache-2.0 | PCManticore/argus-ci,cmin764/argus-ci,AlexandruTudose/cloudbase-init-ci,micumatei/cloudbase-init-ci,stefan-caraiman/cloudbase-init-ci,cloudbase/cloudbase-init-ci | ---
+++
@@ -1,3 +1,18 @@
+# Copyright 2015 Cloudbase Solutions Srl
+# 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/l... |
73d7377d0ba6c5ac768d547aaa957b48a6b1d46a | menu_generator/utils.py | menu_generator/utils.py | from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '... | from importlib import import_module
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
def get_callable(func_or_path):
"""
Receives a dotted path or a callable, Returns a callable or None
"""
if callable(func_or_path):
return func_or_path
module_name = '... | Fix exception message if app path is invalid | Fix exception message if app path is invalid | Python | mit | yamijuan/django-menu-generator | ---
+++
@@ -32,6 +32,6 @@
return new_app
else: # pragma: no cover
raise ImproperlyConfigured(
- "The application {0} is not in the configured apps or does" +
- "not have the pattern app.apps.AppConfig".format(app_path)
+ "The application... |
05f65ad42967f1499fb1ec37d37c76674e4d413a | biosys/apps/main/api/urls.py | biosys/apps/main/api/urls.py | from __future__ import absolute_import, unicode_literals, print_function, division
from django.conf.urls import url
from rest_framework import routers
from main.api import views as main_views
router = routers.DefaultRouter()
router.register(r'projects?', main_views.ProjectViewSet, 'project')
router.register(r'sites... | from __future__ import absolute_import, unicode_literals, print_function, division
from django.conf.urls import url
from rest_framework import routers
from main.api import views as main_views
router = routers.DefaultRouter()
router.register(r'projects?', main_views.ProjectViewSet, 'project')
router.register(r'sites... | Use snake case for API's URL: generic_records instead of genericRecord and species_observation instead of speciesObservation. | Use snake case for API's URL: generic_records instead of genericRecord and species_observation instead of speciesObservation.
| Python | apache-2.0 | gaiaresources/biosys,parksandwildlife/biosys,serge-gaia/biosys,ropable/biosys,parksandwildlife/biosys,parksandwildlife/biosys,serge-gaia/biosys,serge-gaia/biosys,gaiaresources/biosys,ropable/biosys,ropable/biosys,gaiaresources/biosys | ---
+++
@@ -10,9 +10,9 @@
router.register(r'projects?', main_views.ProjectViewSet, 'project')
router.register(r'sites?', main_views.SiteViewSet, 'site')
router.register(r'datasets?', main_views.DatasetViewSet, 'dataset')
-router.register(r'genericRecords?', main_views.GenericRecordViewSet, 'genericRecord')
+router... |
e73bb8cecf516f4379dd7d90282ef2412d348ac8 | autotranslate/utils.py | autotranslate/utils.py | import six
from autotranslate.compat import importlib
from django.conf import settings
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
Credits: https://github.com/tomchristie/django-rest-framework/blob/master/r... | import six
from autotranslate.compat import importlib
from django.conf import settings
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
Credits: https://github.com/tomchristie/django-rest-framework/blob/master/r... | Make sure we don't expose translator as global | Make sure we don't expose translator as global | Python | mit | ankitpopli1891/django-autotranslate | ---
+++
@@ -32,10 +32,11 @@
raise ImportError('Could not import {} for API setting {}. {}: {}.'
.format(val, setting_name, e.__class__.__name__, e))
-
-TranslatorService = getattr(settings, 'AUTOTRANSLATE_TRANSLATOR_SERVICE',
- 'autotranslate.services.G... |
79edc5861e37de0970d2af46ba45e07b47d30837 | test/test_retriever.py | test/test_retriever.py | """Tests for the EcoData Retriever"""
from StringIO import StringIO
from engine import Engine
def test_escape_single_quotes():
"""Test escaping of single quotes"""
test_engine = Engine()
assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'"
def test_escape_double_quotes():
"""Test e... | """Tests for the EcoData Retriever"""
from StringIO import StringIO
from engine import Engine
from table import Table
def test_escape_single_quotes():
"""Test escaping of single quotes"""
test_engine = Engine()
assert test_engine.escape_single_quotes("1,2,3,'a'") == "1,2,3,\\'a\\'"
def test_escape_double... | Add tests of automated identification of the delimiter | Add tests of automated identification of the delimiter
| Python | mit | bendmorris/retriever,embaldridge/retriever,davharris/retriever,goelakash/retriever,embaldridge/retriever,henrykironde/deletedret,davharris/retriever,bendmorris/retriever,davharris/retriever,bendmorris/retriever,embaldridge/retriever,goelakash/retriever,henrykironde/deletedret | ---
+++
@@ -2,6 +2,7 @@
from StringIO import StringIO
from engine import Engine
+from table import Table
def test_escape_single_quotes():
"""Test escaping of single quotes"""
@@ -17,3 +18,24 @@
"Test the creation of drop statements"
test_engine = Engine()
assert test_engine.drop_statement('... |
719777a0b2e3eed4f14355974c6673d20904ac83 | models/shopping_item.py | models/shopping_item.py | """
This is the sqlalchemy class for communicating with the shopping item table
"""
from sqlalchemy import Column, Integer, Unicode, ForeignKey
import base
class ShoppingItem(base.Base):
"""Sqlalchemy deals model"""
__tablename__ = "shopping_item"
catId = 'shopping_category.id'
visitId = 'visits.id... | """
This is the sqlalchemy class for communicating with the shopping item table
"""
from sqlalchemy import Column, Integer, Unicode, ForeignKey
import base
class ShoppingItem(base.Base):
"""Sqlalchemy deals model"""
__tablename__ = "shopping_item"
catId = 'shopping_category.id'
visitId = 'visits.id... | Add quantity to shopping item model | Add quantity to shopping item model
| Python | mit | jlutz777/FreeStore,jlutz777/FreeStore,jlutz777/FreeStore | ---
+++
@@ -16,5 +16,6 @@
id = Column(Integer, primary_key=True)
name = Column('name', Unicode)
+ quantity = Column('name', Integer)
category_id = Column('category', Integer, ForeignKey(catId))
visit_id = Column('visit', Integer, ForeignKey(visitId)) |
a52fe667125d9fd126b050cd32f694b9c3a97cdf | nlppln/save_ner_data.py | nlppln/save_ner_data.py | #!/usr/bin/env python
import click
import os
import codecs
import json
import pandas as pd
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_file', nargs=1, type=click.Path())
def nerstats(input_files, output_file):
output_dir = os.path.dirname(output_... | #!/usr/bin/env python
import click
import os
import codecs
import json
import pandas as pd
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_file', nargs=1, type=click.Path())
def nerstats(input_files, output_file):
output_dir = os.path.dirname(output_... | Update script to store the basename instead of the complete path | Update script to store the basename instead of the complete path
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln | ---
+++
@@ -23,7 +23,8 @@
data['word'] = [t['word'] for t in saf['tokens'] if 'ne' in t.keys()]
data['ner'] = [t['ne'] for t in saf['tokens'] if 'ne' in t.keys()]
data['w_id'] = [t['id'] for t in saf['tokens'] if 'ne' in t.keys()]
- data['text'] = [fi for t in saf['tokens'] if 'ne' i... |
00fd5643e94cbe5543a22e804c050e979776ac6b | opps/flatpages/views.py | opps/flatpages/views.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.contrib.sites.models import get_current_site
from django import template
from django.utils import timezone
from .models import FlatPage
class PageDetail(DetailView):
model = FlatPage
context_object_n... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from .models import FlatPage
class PageDetail(DetailView):
model = FlatPage
context_object_name = "context"
type = '... | Fix template load on PageDetail flatpages app | Fix template load on PageDetail flatpages app
| Python | mit | opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,williamroot/opps | ---
+++
@@ -2,7 +2,6 @@
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView
from django.contrib.sites.models import get_current_site
-from django import template
from django.utils import timezone
from .models import FlatPage
@@ -12,7 +11,7 @@
model = FlatPage
context_object_n... |
61e4af18ddef3723b49bc4e6e7a8ff00e8a755af | organise/views/todos.py | organise/views/todos.py | from flask import Blueprint, render_template
from organise.models import Todo
from organise import db
from flask import render_template, request, redirect, url_for, flash
todos = Blueprint('todos', __name__, template_folder='/../templates')
@todos.route('/')
def index():
all_todos = Todo.query.order_by(Todo.id.de... | from flask import Blueprint, render_template
from organise.models import Todo
from organise import db
from flask import render_template, request, redirect, url_for, flash
todos = Blueprint('todos', __name__, template_folder='/../templates')
@todos.route('/')
def index():
all_todos = Todo.query.order_by(Todo.id.de... | Add functionality for edit and delete functions | Add functionality for edit and delete functions
| Python | mit | msanatan/organise,msanatan/organise | ---
+++
@@ -16,7 +16,7 @@
todo = Todo(request.form['title'], request.form['description'])
db.session.add(todo)
db.session.commit()
- flash('New todo was added!')
+ flash('New todo was added')
return redirect(url_for('todos.index'))
@@ -26,11 +26,21 @@
return render_template('todo.ht... |
9bd09a225a1899d8cd4f8565986f23a8c3b44131 | api/migrations/0001_create_application.py | api/migrations/0001_create_application.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 20:29
from __future__ import unicode_literals
from django.db import migrations
from oauth2_provider.models import Application
class Migration(migrations.Migration):
def add_default_application(apps, schema_editor):
Application.objects.cre... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-26 20:29
from __future__ import unicode_literals
from django.db import migrations
from oauth2_provider.models import Application
class Migration(migrations.Migration):
def add_default_application(apps, schema_editor):
Application.objects.cre... | Include webpack-dev-server URL as a valid redirect | Include webpack-dev-server URL as a valid redirect
| Python | bsd-3-clause | hotosm/osm-export-tool2,hotosm/osm-export-tool2,hotosm/osm-export-tool2,hotosm/osm-export-tool2 | ---
+++
@@ -10,7 +10,8 @@
def add_default_application(apps, schema_editor):
Application.objects.create(
name="OSM Export Tool UI",
- redirect_uris="http://localhost/authorized",
+ redirect_uris=
+ "http://localhost/authorized http://localhost:8080/authorized... |
a6a646dec44b2eb613cac9c143cf6c7770f738e8 | tests/test_metadata.py | tests/test_metadata.py | """
Tests for BSE metadata
"""
import os
import hashlib
import bse
from bse import curate
data_dir = bse.default_data_dir
def test_get_metadata():
bse.get_metadata()
def test_metadata_uptodate():
old_metadata = os.path.join(data_dir, 'METADATA.json')
new_metadata = os.path.join(data_dir, 'METADATA.json... | """
Tests for BSE metadata
"""
import os
import bse
import json
from bse import curate
data_dir = bse.default_data_dir
def test_get_metadata():
bse.get_metadata()
def test_metadata_uptodate():
old_metadata = os.path.join(data_dir, 'METADATA.json')
new_metadata = os.path.join(data_dir, 'METADATA.json.ne... | Fix testing of metadata - hashing is too strict | Fix testing of metadata - hashing is too strict
| Python | bsd-3-clause | MOLSSI-BSE/basis_set_exchange | ---
+++
@@ -3,8 +3,8 @@
"""
import os
-import hashlib
import bse
+import json
from bse import curate
data_dir = bse.default_data_dir
@@ -18,14 +18,12 @@
new_metadata = os.path.join(data_dir, 'METADATA.json.new')
curate.create_metadata_file(new_metadata, data_dir)
- with open(old_metadata, 'rb'... |
9aa48fa2a3a693c7cd5a74712b9a63ac15f32a94 | tests/test_settings.py | tests/test_settings.py | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMi... | import django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middl... | Fix tests on Django 1.8. | Fix tests on Django 1.8.
| Python | bsd-3-clause | benkonrath/django-csv-export-view | ---
+++
@@ -1,3 +1,5 @@
+import django
+
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
@@ -19,6 +21,9 @@
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
+if django.VERSION < (1, 10):
+ MIDDLEWARE_CLASSES = MIDDLEWARE
+
USE_TZ = True
ROOT_URLCONF = 'tests... |
b0c3ef9a162109aa654de28d15f47d103ddbbf58 | fireplace/cards/brawl/gift_exchange.py | fireplace/cards/brawl/gift_exchange.py | """
Gift Exchange
"""
from ..utils import *
# Hardpacked Snowballs
class TB_GiftExchange_Snowball:
play = Bounce(RANDOM_ENEMY_MINION) * 3
# Winter's Veil Gift
class TB_GiftExchange_Treasure:
deathrattle = Give(CURRENT_PLAYER, "TB_GiftExchange_Treasure_Spell")
# Stolen Winter's Veil Gift
class TB_GiftExchange_T... | """
Gift Exchange
"""
from ..utils import *
# Hardpacked Snowballs
class TB_GiftExchange_Snowball:
play = Bounce(RANDOM_ENEMY_MINION) * 3
# Winter's Veil Gift
class TB_GiftExchange_Treasure:
deathrattle = Give(CURRENT_PLAYER, "TB_GiftExchange_Treasure_Spell")
# Stolen Winter's Veil Gift
class TB_GiftExchange_T... | Drop cost filtering from TB_GiftExchange_Treasure_Spell | Drop cost filtering from TB_GiftExchange_Treasure_Spell
It doesn't work, and makes things harder than they need to be.
| Python | agpl-3.0 | Ragowit/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,smallnamespace/fireplace,Ragowit/fireplace,jleclanche/fireplace | ---
+++
@@ -19,8 +19,8 @@
class TB_GiftExchange_Treasure_Spell:
# Surely none of this even sort of works.
RandomGift = RandomCollectible(
- COST >= 5,
- CLASS_CARD=Attr(Controller(OWNER), GameTag.CLASS)
+ # COST >= 5,
+ card_class=Attr(Controller(OWNER), GameTag.CLASS)
)
play = Discover(RandomGift).then(... |
b75e19bcc20f4b35a1712633fe941fdab1fd1029 | test_classy/test_route_base.py | test_classy/test_route_base.py | from flask import Flask
from .view_classes import BasicView, RouteBaseView
from nose.tools import *
app = Flask('route_base')
BasicView.register(app, route_base="/rb_test/")
BasicView.register(app)
RouteBaseView.register(app, route_base="/rb_test2/")
RouteBaseView.register(app)
def test_registered_route_base():
... | from flask import Flask
from .view_classes import BasicView, RouteBaseView
from nose.tools import *
app = Flask('route_base')
RouteBaseView.register(app, route_base="/rb_test2/")
def test_route_base_override():
client = app.test_client()
resp = client.get('/rb_test2/')
eq_(b"Index", resp.data)
| Remove some route_base tests that are no longer valid with Flask 0.10 | Remove some route_base tests that are no longer valid with Flask 0.10
| Python | bsd-3-clause | ei-grad/muffin-classy,apiguy/flask-classy,mapleoin/flask-classy,apiguy/flask-classy,apiguy/flask-classy,ei-grad/muffin-classy,teracyhq/flask-classy,hoatle/flask-classy,stas/flask-classy,teracyhq/flask-classy | ---
+++
@@ -3,31 +3,10 @@
from nose.tools import *
app = Flask('route_base')
-BasicView.register(app, route_base="/rb_test/")
-BasicView.register(app)
RouteBaseView.register(app, route_base="/rb_test2/")
-RouteBaseView.register(app)
-
-
-def test_registered_route_base():
- client = app.test_client()
- resp... |
81a0239812d01e9e876989d2334afe746e09f5da | chartflo/tests.py | chartflo/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from .views import ChartsView
# Create your tests here.
class TestVegaLiteChartsView(TestCase):
def setUpTestCase(self):
self.chart_view = ChartsView()
# Set Vega Lite as template engine
self.chart_view.engine = "vegalite"
def test_vega_lite_template(s... | Add Vega Lite template test | Add Vega Lite template test
| Python | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo | ---
+++
@@ -1,3 +1,20 @@
from django.test import TestCase
+from .views import ChartsView
# Create your tests here.
+class TestVegaLiteChartsView(TestCase):
+ def setUpTestCase(self):
+ self.chart_view = ChartsView()
+
+ # Set Vega Lite as template engine
+ self.chart_view.engine = "vegalit... |
c8418c27d1a0b7f204af6981948654ba5c17d050 | parsl/tests/test_staging/test_implicit_staging_ftp.py | parsl/tests/test_staging/test_implicit_staging_ftp.py | import pytest
import parsl
from parsl.app.app import App
from parsl.data_provider.files import File
from parsl.tests.configs.local_threads import config
parsl.clear()
parsl.load(config)
@App('python')
def sort_strings(inputs=[], outputs=[]):
with open(inputs[0].filepath, 'r') as u:
strs = u.readlines()
... | import pytest
import parsl
from parsl.app.app import App
from parsl.data_provider.files import File
from parsl.tests.configs.local_threads import config
parsl.clear()
parsl.load(config)
@App('python')
def sort_strings(inputs=[], outputs=[]):
with open(inputs[0].filepath, 'r') as u:
strs = u.readlines()
... | Change a URL to a ftp file in the ftp staging test. | Change a URL to a ftp file in the ftp staging test.
| Python | apache-2.0 | Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab | ---
+++
@@ -26,7 +26,7 @@
Create a remote input file (ftp) that points to file_test_cpt.txt.
"""
- unsorted_file = File('ftp://ftp.uconn.edu/48_hour/file_test_cpt.txt')
+ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README')
# Create a local file for output data
sorted_file = Fi... |
68b5484cfb0910b3ed68e99520decc6aca08bb2d | flask_webapi/__init__.py | flask_webapi/__init__.py | # Make marshmallow's functions and classes importable from flask-io
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
from .decorators import authenticator, permissions, content_negotiator, renderer,... | # Make marshmallow's functions and classes importable from flask-io
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema
from marshmallow.utils import missing
from .api import WebAPI
from .errors import APIError
from .decorators import authenticator, permissions, ... | Add import for APIError to make it easy to import by users | Add import for APIError to make it easy to import by users
| Python | mit | viniciuschiele/flask-webapi | ---
+++
@@ -3,6 +3,7 @@
from marshmallow.utils import missing
from .api import WebAPI
+from .errors import APIError
from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route
from .views import ViewBase
|
4c6f40f3d1394fff9ed9a4c6fe3ffd0ae5cb6230 | jsondb/file_writer.py | jsondb/file_writer.py | from .compat import decode, encode
def read_data(path):
"""
Reads a file and returns a json encoded representation of the file.
"""
db = open(path, "r+")
content = db.read()
obj = decode(content)
db.close()
return obj
def write_data(path, obj):
"""
Writes to a file and retu... | from .compat import decode, encode
def read_data(file_path):
"""
Reads a file and returns a json encoded representation of the file.
"""
if not is_valid(file_path):
write_data(file_path, {})
db = open(file_path, "r+")
content = db.read()
obj = decode(content)
db.close()
... | Create a new file if the path is invalid. | Create a new file if the path is invalid.
| Python | bsd-3-clause | gunthercox/jsondb | ---
+++
@@ -1,11 +1,15 @@
from .compat import decode, encode
-def read_data(path):
+def read_data(file_path):
"""
Reads a file and returns a json encoded representation of the file.
"""
- db = open(path, "r+")
+
+ if not is_valid(file_path):
+ write_data(file_path, {})
+
+ db = ope... |
45078e9b7bfff43d80e223b73dd6bf039c54de0e | flask_application/config.py | flask_application/config.py | #!/usr/bin/env python
# http://flask.pocoo.org/docs/config/#development-production
class Config(object):
SITE_TITLE = "Westminster Standards"
SITE_TAGLINE = "Read the Westminster Standards in a year."
TZ = 'US/Eastern'
SECRET_KEY = ''
SITE_NAME = 'reformedconfessions.com'
MEMCACHED_SERVERS = ... | #!/usr/bin/env python
# http://flask.pocoo.org/docs/config/#development-production
class Config(object):
SITE_TITLE = "Westminster Daily"
SITE_TAGLINE = "Read the Westminster Standards in a year."
TZ = 'US/Eastern'
SECRET_KEY = ''
SITE_NAME = 'reformedconfessions.com'
MEMCACHED_SERVERS = ['lo... | Change site name to Westminster DAily | Change site name to Westminster DAily
| Python | bsd-3-clause | olneyhymn/westminster-daily,olneyhymn/westminster-daily,olneyhymn/westminster-daily,tdhopper/westminster-daily,olneyhymn/westminster-daily,tdhopper/westminster-daily,tdhopper/westminster-daily | ---
+++
@@ -4,7 +4,7 @@
class Config(object):
- SITE_TITLE = "Westminster Standards"
+ SITE_TITLE = "Westminster Daily"
SITE_TAGLINE = "Read the Westminster Standards in a year."
TZ = 'US/Eastern'
SECRET_KEY = '' |
0a4aceb87eae57188c5f61bb93d78d5cc9f1779f | lava_scheduler_app/templatetags/utils.py | lava_scheduler_app/templatetags/utils.py | from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if pri... | from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if pri... | Use inline radio buttons for priority changes. | Use inline radio buttons for priority changes.
Change-Id: Ifb9a685bca654c5139aef3ca78e800b66ce77eb9
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server | ---
+++
@@ -12,6 +12,8 @@
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
+ select += '<label class="checkbox-inline">'
select += '<input type="radio" name="priority" style="..." id=... |
c9e90de4730050e4ab41fc6b42a4a51018262db7 | sergey/management/commands/fix_speaker_slugs.py | sergey/management/commands/fix_speaker_slugs.py | # coding: utf-8
from django.core.management import BaseCommand
from django.template.defaultfilters import slugify
from unidecode import unidecode
from richard.videos.models import Speaker
class Command(BaseCommand):
help = 'Fixes speaker slugs'
def handle(self, *args, **options):
for speaker in Spe... | # coding: utf-8
from django.core.management import BaseCommand
from django.template.defaultfilters import slugify
from unidecode import unidecode
from richard.videos.models import Speaker
class Command(BaseCommand):
help = 'Fixes speaker slugs'
def handle(self, *args, **options):
for speaker in Spe... | Fix management command for fixing slugs | Fix management command for fixing slugs
| Python | bsd-3-clause | WarmongeR1/pyvideo.ru,coagulant/pyvideo.ru,coagulant/pyvideo.ru,WarmongeR1/pyvideo.ru,WarmongeR1/pyvideo.ru,coagulant/pyvideo.ru | ---
+++
@@ -13,6 +13,9 @@
for speaker in Speaker.objects.all():
old_slug = speaker.slug
- fixed_slug = slugify(unidecode(speaker.name))
- speaker.save()
- self.stdout.write(u'Changed slug for %s "%s" => %s\n' % (speaker.name, old_slug, fixed_slug))
+ ... |
45b99469f13379acbc92e7be20968f5973882726 | prestoadmin/_version.py | prestoadmin/_version.py | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | Prepare for the next development iteration | Prepare for the next development iteration
| Python | apache-2.0 | prestodb/presto-admin,prestodb/presto-admin | ---
+++
@@ -15,4 +15,4 @@
# This must be the last line in the file and the format must be maintained
# even when the version is changed
-__version__ = '2.2'
+__version__ = '2.2-SNAPSHOT' |
9e73de0014b3f88b9e94ead11a878c6bc3819782 | selenium_testcase/tests/test_navigation.py | selenium_testcase/tests/test_navigation.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..testcases import SeleniumLiveTestCase
class NavigationTestCase(SeleniumLiveTestCase):
test_templates = [
(r'^nav_1/$', 'nav_1.html'),
(r'^nav_1/nav_2/$', 'nav_2.html')
]
def test_get_page(self):
""" Test tha... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..testcases import SeleniumLiveTestCase
class NavigationTestCase(SeleniumLiveTestCase):
test_templates = [
(r'^nav_1/$', 'nav_1.html'),
(r'^nav_1/nav_2/$', 'nav_2.html')
]
def test_get_page(self):
""" Test tha... | Test missing content and failed navigation tests. | Test missing content and failed navigation tests.
This commit adds unit tests outside of the happy path where
a url does not exist or the test is looking for conten that
doesn't exist on the page. Since testing for missing informaion
requires timeouts to be sure, some of these tests take several
seconds to execute.
| Python | bsd-3-clause | nimbis/django-selenium-testcase,nimbis/django-selenium-testcase | ---
+++
@@ -16,6 +16,26 @@
def test_get_page(self):
""" Test that you can traverse the page tree. """
self.get_page("/nav_1/")
+ self.has_title("Navigation 1")
+ self.title_contains("1")
self.should_see("This is nav 1.")
self.get_page("/nav_1/nav_2/")
se... |
1b27133a182204a44a8ee3cd73c832777fa3723b | tests/unit/test_metric_timer.py | tests/unit/test_metric_timer.py | """
Contains tests for the timer metric.
"""
from statsite.metrics import Timer
class TestTimerMetric(object):
def test_fold_sum(self):
"""
Tests that folding generates a sum of the timers.
"""
now = 10
metrics = [Timer("k", 10),
Timer("k", 15),
... | """
Contains tests for the timer metric.
"""
from statsite.metrics import Timer
class TestTimerMetric(object):
def test_fold_sum(self):
"""
Tests that folding generates a sum of the timers.
"""
now = 10
metrics = [Timer("k", 10),
Timer("k", 15),
... | Fix typo with expected metric | Fix typo with expected metric
| Python | bsd-3-clause | kiip/statsite | ---
+++
@@ -16,8 +16,8 @@
Timer("j", 8)]
result = Timer.fold(metrics, now)
- assert ("k", 25, now) == self._get_metric("timers.k.sum", result)
- assert ("j", 15, now) == self._get_metric("timers.j.sum", result)
+ assert ("timers.k.sum", 25, now) == self._get_metric(... |
21799c73bdc6f0dc7410edc61db5de5694ab911a | django/hello/world/models.py | django/hello/world/models.py | from django.db import models
# Create your models here.
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
db_table = 'world'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
db_table = 'fortune'
| from django.db import models
# Create your models here.
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
db_table = 'World'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
db_table = 'Fortune'
| Fix table name for MySQL | Fix table name for MySQL
| Python | bsd-3-clause | dmacd/FB-try1,julienschmidt/FrameworkBenchmarks,zapov/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,methane/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks... | ---
+++
@@ -5,9 +5,9 @@
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
- db_table = 'world'
+ db_table = 'World'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
- db_table = 'fortune'
+ db_table = 'Fortune' |
5a1ad6a2fdd0586517899b3f2ec3d27a00a5d2b1 | databroker/intake_xarray_core/__init__.py | databroker/intake_xarray_core/__init__.py | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
import intake # Import this first to avoid circular imports during discovery.
from .netcdf import NetCDFSource
from .opendap import OpenDapSource
from .raster import RasterIOSource
from .xzarr import ZarrSource
from .xarray_co... | import intake # Import this first to avoid circular imports during discovery.
from .xarray_container import RemoteXarray
import intake.container
intake.registry['remote-xarray'] = RemoteXarray
intake.container.container_map['xarray'] = RemoteXarray
| Remove imports of omitted modules. | Remove imports of omitted modules.
| Python | bsd-3-clause | ericdill/databroker,ericdill/databroker | ---
+++
@@ -1,14 +1,5 @@
-from ._version import get_versions
-__version__ = get_versions()['version']
-del get_versions
-
import intake # Import this first to avoid circular imports during discovery.
-from .netcdf import NetCDFSource
-from .opendap import OpenDapSource
-from .raster import RasterIOSource
-from .xza... |
68c256ef51f0e622dcfc92cb63bf4b0503fb61a8 | common/templatetags/lutris.py | common/templatetags/lutris.py | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system ... | import copy
from django import template
from django.conf import settings
from games import models
register = template.Library()
def get_links(user_agent):
systems = ['ubuntu', 'fedora', 'linux']
downloads = copy.copy(settings.DOWNLOADS)
main_download = None
for system in systems:
if system ... | Make code compatible with no user agent | Make code compatible with no user agent
| Python | agpl-3.0 | lutris/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website | ---
+++
@@ -24,7 +24,7 @@
@register.inclusion_tag('includes/download_links.html', takes_context=True)
def download_links(context):
request = context['request']
- user_agent = request.META['HTTP_USER_AGENT'].lower()
+ user_agent = request.META.get('HTTP_USER_AGENT', '').lower()
context['main_download... |
ed542ea8979882e7cc245aee7e3c4a6cb6235a5f | HARK/tests/test_validators.py | HARK/tests/test_validators.py | import unittest, sys
from HARK.validators import non_empty
class ValidatorsTests(unittest.TestCase):
'''
Tests for validator decorators which validate function arguments
'''
def test_non_empty(self):
@non_empty('list_a')
def foo(list_a, list_b):
pass
try:
... | import unittest, sys
from HARK.validators import non_empty
class ValidatorsTests(unittest.TestCase):
'''
Tests for validator decorators which validate function arguments
'''
def test_non_empty(self):
@non_empty('list_a')
def foo(list_a, list_b):
pass
try:
... | Fix other tests with same regexp issue | Fix other tests with same regexp issue | Python | apache-2.0 | econ-ark/HARK,econ-ark/HARK | ---
+++
@@ -34,13 +34,25 @@
def foo(list_a, list_b):
pass
- with self.assertRaisesRegex(
- TypeError,
- 'Expected non-empty argument for parameter list_b',
- ):
- foo([1], [])
- with self.assertRaisesRegex(
- TypeError,
- ... |
7623966ac3962dfe871638b6804e056fa794ea60 | api/webscripts/show_summary.py | api/webscripts/show_summary.py | from django import forms
from webscript import WebScript
from django.template.loader import render_to_string
import amcat.scripts.forms
import amcat.forms
from amcat.tools import keywordsearch
from amcat.scripts import script
#from amcat.scripts.searchscripts.articlelist import ArticleListScript, ArticleListSpecific... | from webscript import WebScript
from amcat.tools import keywordsearch
from amcat.scripts.searchscripts.articlelist import ArticleListScript
from amcat.scripts.forms import SelectionForm
class ShowSummary(WebScript):
name = "Summary"
form_template = None
form = None
def run(self):
se... | Clean user data before passing it to keywordsearch.get_total_n() | Clean user data before passing it to keywordsearch.get_total_n()
| Python | agpl-3.0 | amcat/amcat,tschmorleiz/amcat,tschmorleiz/amcat,tschmorleiz/amcat,amcat/amcat,amcat/amcat,tschmorleiz/amcat,amcat/amcat,tschmorleiz/amcat,amcat/amcat,amcat/amcat | ---
+++
@@ -1,16 +1,9 @@
-from django import forms
from webscript import WebScript
-from django.template.loader import render_to_string
-import amcat.scripts.forms
-import amcat.forms
from amcat.tools import keywordsearch
-from amcat.scripts import script
-
-#from amcat.scripts.searchscripts.articlelist import ... |
b7fd2af25423847236b5d382aeb829b00c556485 | alertaclient/auth/oidc.py | alertaclient/auth/oidc.py |
import webbrowser
from uuid import uuid4
from alertaclient.auth.token import TokenHandler
def login(client, oidc_auth_url, client_id):
xsrf_token = str(uuid4())
redirect_uri = 'http://127.0.0.1:9004'
url = (
'{oidc_auth_url}?'
'response_type=code'
'&client_id={client_id}'
... |
import webbrowser
from uuid import uuid4
from alertaclient.auth.token import TokenHandler
def login(client, oidc_auth_url, client_id):
xsrf_token = str(uuid4())
redirect_uri = 'http://localhost:9004' # azure only supports 'localhost'
url = (
'{oidc_auth_url}?'
'response_type=code'
... | Use localhost instead of 127.0.0.1 | Use localhost instead of 127.0.0.1
| Python | apache-2.0 | alerta/python-alerta,alerta/python-alerta-client,alerta/python-alerta-client | ---
+++
@@ -7,7 +7,7 @@
def login(client, oidc_auth_url, client_id):
xsrf_token = str(uuid4())
- redirect_uri = 'http://127.0.0.1:9004'
+ redirect_uri = 'http://localhost:9004' # azure only supports 'localhost'
url = (
'{oidc_auth_url}?' |
09cd2fb49950d654b6c30cb250f1f8acac39fc23 | accelerator/migrations/0074_update_url_to_community.py | accelerator/migrations/0074_update_url_to_community.py | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = ["/people", "/people/"]
mentor_url = "/directory"
community_url = "/community"
mentor_refinement_url = ("/directo... | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = ["/people", "/people/"]
mentor_url = "/directory"
community_url = "/community"
mentor_refinement_url = ("/directo... | Remove unused import and fix linting issues | [AC-9046] Remove unused import and fix linting issues
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -9,9 +9,9 @@
mentor_url = "/directory"
community_url = "/community"
mentor_refinement_url = ("/directory/?refinementList%5B"
- "home_program_family%5D%5B0%5D=Israel")
+ "home_program_family%5D%5B0%5D=Israel")
community_refinement_url = ("/community/?refinementList%5B"
- "prog... |
b3011d19e937694bca44a5677a12811188577084 | docker_xylem/compat.py | docker_xylem/compat.py | """
Very limited reimplementation of some of `twisted.logger.Logger`'s public
API so we can use older Twisted versions that don't have the new logging
features.
"""
try:
from twisted.logger import Logger
except ImportError:
import logging
from twisted.python import log
class Logger(object):
de... | """
Very limited reimplementation of some of `twisted.logger.Logger`'s public
API so we can use older Twisted versions that don't have the new logging
features.
"""
try:
from twisted.logger import Logger
except ImportError:
import logging
from twisted.python import log
class Logger(object):
de... | Add some more logging methods. (@JayH5) | Add some more logging methods. (@JayH5)
| Python | mit | praekeltfoundation/docker-xylem,praekeltfoundation/docker-xylem | ---
+++
@@ -11,8 +11,17 @@
from twisted.python import log
class Logger(object):
+ def debug(self, format, **kw):
+ log.msg(format.format(**kw), logLevel=logging.DEBUG)
+
def info(self, format, **kw):
log.msg(format.format(**kw), logLevel=logging.INFO)
def... |
77beb7f5a1503481e28179f1ea84531e1ece99ed | test/test_urlification.py | test/test_urlification.py | from tiddlywebplugins.markdown import render
from tiddlyweb.model.tiddler import Tiddler
def test_urlification():
tiddler = Tiddler('blah')
tiddler.text = """
lorem ipsum http://example.org dolor sit amet
... http://www.example.com/foo/bar ...
"""
environ = {'tiddlyweb.config... | from tiddlywebplugins.markdown import render
from tiddlyweb.model.tiddler import Tiddler
def test_urlification():
tiddler = Tiddler('blah')
tiddler.text = """
lorem ipsum http://example.org dolor sit amet
... http://www.example.com/foo/bar ...
"""
environ = {'tiddlyweb.config': {'markdown.wiki_link_... | Make work with modern markdown2 | Make work with modern markdown2
Within a pre block, links don't link, which is good.
| Python | bsd-2-clause | tiddlyweb/tiddlywebplugins.markdown | ---
+++
@@ -5,8 +5,8 @@
def test_urlification():
tiddler = Tiddler('blah')
tiddler.text = """
- lorem ipsum http://example.org dolor sit amet
- ... http://www.example.com/foo/bar ...
+lorem ipsum http://example.org dolor sit amet
+... http://www.example.com/foo/bar ...
"""
... |
2a6f0f7fbb655c568a42493e1181aeef9fa1ead1 | test_setup.py | test_setup.py | """Test setup.py."""
import os
import subprocess
import sys
def test_setup():
"""Run setup.py check."""
command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict']
assert subprocess.run(command).returncode == 0
def test_console_scripts():
"""Ensure console scripts were installed corr... | """Test setup.py."""
import os
import subprocess
import sys
def test_setup():
"""Run setup.py check."""
command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict']
assert subprocess.run(command).returncode == 0
def test_console_scripts():
"""Ensure console scripts were installed corr... | Use $PATH instead of sys.path | Use $PATH instead of sys.path
| Python | lgpl-2.1 | dmtucker/backlog | ---
+++
@@ -16,5 +16,5 @@
"""Ensure console scripts were installed correctly."""
assert any(
os.path.isfile(os.path.join(directory, 'backlog'))
- for directory in sys.path
+ for directory in os.environ['PATH'].split(':')
) |
a4507b7dcd5d2dfc1e56497040cfca6607b6de71 | edpwd/random_string.py | edpwd/random_string.py | # -*- coding: utf-8
from random import choice
import string
def random_string(length,
letters=True,
digits=True,
punctuation=False,
whitespace=False):
""" Returns a random string """
chars = ''
if letters:
chars += string.ascii_letters
if digits:
chars +... | # -*- coding: utf-8
import random, string
def random_string(length,
letters=True,
digits=True,
punctuation=False,
whitespace=False):
""" Returns a random string """
chars = ''
if letters:
chars += string.ascii_letters
if digits:
chars += string.digits
... | Use random.sample() rather than reinventing it. | Use random.sample() rather than reinventing it.
| Python | bsd-2-clause | tampakrap/edpwd | ---
+++
@@ -1,7 +1,6 @@
# -*- coding: utf-8
-from random import choice
-import string
+import random, string
def random_string(length,
letters=True,
@@ -18,4 +17,4 @@
chars += string.punctuation
if whitespace:
chars += string.whitespace
- return ''.join([choice(chars) for i in... |
166a78061059ad57189365d1cf56c81b513b7d9e | tests/test_ultrametric.py | tests/test_ultrametric.py | from viridis import tree
from six.moves import range
import pytest
@pytest.fixture
def base_tree():
t = tree.Ultrametric(list(range(6)))
t.merge(0, 1, 0.1) # 6
t.merge(6, 2, 0.2) # 7
t.merge(3, 4, 0.3) # 8
t.merge(8, 5, 0.4) # 9
t.merge(7, 9, 0.5) # 10
return t
def test_split(base_t... | from viridis import tree
from six.moves import range
import pytest
@pytest.fixture
def base_tree():
t = tree.Ultrametric(list(range(6)))
t.merge(0, 1, 0.1) # 6
t.merge(6, 2, 0.2) # 7
t.merge(3, 4, 0.3) # 8
t.merge(8, 5, 0.4) # 9
t.merge(7, 9, 0.5) # 10
return t
def test_split(base_t... | Add test for highest_ancestor function | Add test for highest_ancestor function
| Python | mit | jni/viridis | ---
+++
@@ -32,3 +32,12 @@
assert set(t.leaves(10)) == set(range(6))
assert set(t.leaves(6)) == set([0, 1])
assert set(t.leaves(9)) == set(range(3, 6))
+
+
+def test_highest(base_tree):
+ t = base_tree
+ for i in range(t.number_of_nodes()):
+ assert t.highest_ancestor(i) == 10
+ t.remov... |
3c95ba7e4eda0762d735503b718119e361eb7295 | tests/basics/try-finally-return.py | tests/basics/try-finally-return.py | def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
| def func1():
try:
return "it worked"
finally:
print("finally 1")
print(func1())
def func2():
try:
return "it worked"
finally:
print("finally 2")
def func3():
try:
s = func2()
return s + ", did this work?"
finally:
print("finally 3")
pr... | Add additional testcase for finally/return. | Add additional testcase for finally/return.
| Python | mit | heisewangluo/micropython,noahchense/micropython,henriknelson/micropython,alex-robbins/micropython,aethaniel/micropython,pramasoul/micropython,jlillest/micropython,noahwilliamsson/micropython,henriknelson/micropython,warner83/micropython,ruffy91/micropython,adafruit/circuitpython,mianos/micropython,dhylands/micropython,... | ---
+++
@@ -5,3 +5,19 @@
print("finally 1")
print(func1())
+
+
+def func2():
+ try:
+ return "it worked"
+ finally:
+ print("finally 2")
+
+def func3():
+ try:
+ s = func2()
+ return s + ", did this work?"
+ finally:
+ print("finally 3")
+
+print(func3()) |
cf6034fc62cc97a5655b371fdef4a4728707fdea | changes/utils/locking.py | changes/utils/locking.py | from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}'.format(
func.__name__,
md5(
'&'.... | from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}:{2}'.format(
func.__module__,
func.__name__,
... | Use __module__ to make @lock unique | Use __module__ to make @lock unique
Summary: Fixes T49428.
Test Plan:
Hard to test on changes_dev because it can't run both handlers (no
place to send notifications to), but this seems simple enough...
Reviewers: armooo, kylec
Reviewed By: kylec
Subscribers: changesbot, mkedia, jukka, vishal
Maniphest Tasks: T494... | Python | apache-2.0 | bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes | ---
+++
@@ -9,7 +9,8 @@
def lock(func):
@wraps(func)
def wrapped(**kwargs):
- key = '{0}:{1}'.format(
+ key = '{0}:{1}:{2}'.format(
+ func.__module__,
func.__name__,
md5(
'&'.join('{0}={1}'.format(k, repr(v)) |
f3c78eff85efda94915fd3c432d5c0485b5e302c | benchexec/tools/korn.py | benchexec/tools/korn.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import re
import benchexec.util as util
import benchexec.result as result
import benchexe... | Add tool info for Korn | Add tool info for Korn
For more information, see https://github.com/gernst/korn
| Python | apache-2.0 | sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec | ---
+++
@@ -0,0 +1,52 @@
+# This file is part of BenchExec, a framework for reliable benchmarking:
+# https://github.com/sosy-lab/benchexec
+#
+# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
+#
+# SPDX-License-Identifier: Apache-2.0
+
+
+import re
+import benchexec.util as util
+import benc... | |
06b547057e5822bfdff1272c1f8209f12c66bf2a | openedx/core/djangoapps/site_configuration/migrations/0005_populate_siteconfig_history_site_values.py | openedx/core/djangoapps/site_configuration/migrations/0005_populate_siteconfig_history_site_values.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
forward_sql = """
UPDATE
site_configuration_siteconfigurationhistory
SET
site_values = '{}';
"""
reverse_sql = """
UPDATE
site_configuration_siteconfigurationhistory
SET
site_values = '';
"""
class Migr... | Add migration to populate site_values in SiteConfigurationHistory | Add migration to populate site_values in SiteConfigurationHistory
Right now the ORM is very unhappy about the JSONField `site_values`
in SiteConfigurationHistory containing non-JSON (empty strings). We
cannot even write a data migration using the ORM to populate the field
because that causes a JSONDeserializationErro... | Python | agpl-3.0 | angelapper/edx-platform,edx-solutions/edx-platform,appsembler/edx-platform,angelapper/edx-platform,msegado/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,appsembler/edx-platform,cpennington/edx-platform,EDUlib/edx-platform,mitocw/edx-platform,stvstnfrd/edx-platform,eduNEXT/edunext-platform,s... | ---
+++
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+forward_sql = """
+UPDATE
+ site_configuration_siteconfigurationhistory
+SET
+ site_values = '{}';
+"""
+
+reverse_sql = """
+UPDATE
+ site_configuration_siteconfigurationhistory
... | |
2963909063e434936ba095ba9532782e7e3fd518 | tests/QtDeclarative/qdeclarativeview_test.py | tests/QtDeclarative/qdeclarativeview_test.py | '''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl, QStringList, QVariant
from PySide.QtGui import QPushButton
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDecla... | '''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
... | Remove use of deprecated types. | Remove use of deprecated types.
Reviewer: Hugo Parente Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org>,
Luciano Wolf <luciano.wolf@openbossa.org>
| Python | lgpl-2.1 | RobinD42/pyside,pankajp/pyside,RobinD42/pyside,BadSingleton/pyside2,IronManMark20/pyside2,M4rtinK/pyside-android,enthought/pyside,PySide/PySide,PySide/PySide,PySide/PySide,pankajp/pyside,PySide/PySide,M4rtinK/pyside-bb10,M4rtinK/pyside-android,M4rtinK/pyside-bb10,M4rtinK/pyside-bb10,RobinD42/pyside,IronManMark20/pyside... | ---
+++
@@ -2,8 +2,7 @@
import unittest
-from PySide.QtCore import QUrl, QStringList, QVariant
-from PySide.QtGui import QPushButton
+from PySide.QtCore import QUrl
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
@@ -14,7 +13,7 @@
def testQDeclarat... |
de00ac22c8becefa8b2538416e4e5cc8b36ecc40 | utils/exceptions.py | utils/exceptions.py | import json
from werkzeug.exceptions import HTTPException
from werkzeug.utils import escape
from utils.views import serialize_response, get_request_type
class BaseHttpException(HTTPException):
_template = {
'json': {
'description': lambda description: description,
'headers': ('Content-Type', 'app... | Raise exception depending request type | Raise exception depending request type
| Python | apache-2.0 | vtemian/kruncher | ---
+++
@@ -0,0 +1,83 @@
+import json
+
+from werkzeug.exceptions import HTTPException
+from werkzeug.utils import escape
+
+from utils.views import serialize_response, get_request_type
+
+
+class BaseHttpException(HTTPException):
+
+ _template = {
+ 'json': {
+ 'description': lambda description: description... | |
ab5fd972b0fcd6d1e418ab00058b6fd31014d38f | migrations/versions/0256_set_postage_tmplt_hstr.py | migrations/versions/0256_set_postage_tmplt_hstr.py | """
Revision ID: 0256_set_postage_tmplt_hstr
Revises: 0255_another_letter_org
Create Date: 2019-02-05 14:51:30.808067
"""
from alembic import op
import sqlalchemy as sa
revision = '0256_set_postage_tmplt_hstr'
down_revision = '0255_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - ... | Migrate postage into templates_history table | Migrate postage into templates_history table
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -0,0 +1,28 @@
+"""
+
+Revision ID: 0256_set_postage_tmplt_hstr
+Revises: 0255_another_letter_org
+Create Date: 2019-02-05 14:51:30.808067
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+revision = '0256_set_postage_tmplt_hstr'
+down_revision = '0255_another_letter_org'
+
+
+def upgrade():
+ ... | |
8113eefe3e80e472ee706c17306bf692c40115df | tests/dftModel_test.py | tests/dftModel_test.py | import numpy as np
from scipy.signal import get_window
import smst.models.dftModel as DFT
def test_simple_sinusoid():
window_size = 1024
t = np.linspace(0, 1, window_size)
x = np.cos(4 * 2 * np.pi * t)
window = get_window('hamming', window_size)
mag_spectrum, phase_spectrum = DFT.dftAnal(x, window,... | Add a very simple test for dftModel analysis + synthesis. | Add a very simple test for dftModel analysis + synthesis.
| Python | agpl-3.0 | bzamecnik/sms-tools,bzamecnik/sms-tools,bzamecnik/sms-tools | ---
+++
@@ -0,0 +1,17 @@
+import numpy as np
+from scipy.signal import get_window
+import smst.models.dftModel as DFT
+
+def test_simple_sinusoid():
+ window_size = 1024
+ t = np.linspace(0, 1, window_size)
+ x = np.cos(4 * 2 * np.pi * t)
+ window = get_window('hamming', window_size)
+ mag_spectrum, ph... | |
295fd3cf2c8e7a37b300798ee96462ab9d3e7cd9 | flstats/flstats_tests.py | flstats/flstats_tests.py | # -*- coding: utf-8 -*-
"""
flstats test script
~~~~~~~~~~~~~~~~~~~
This script is intended to test the flstats module.
"""
import json
import random
import unittest
from flstats import statistics, webstatistics
from flask import Flask
class FlstatsTestCase(unittest.TestCase):
def setUp(self):
"""Crea... | Add a test script for the flstats module | Add a test script for the flstats module
| Python | bsd-3-clause | yannlambret/flstats | ---
+++
@@ -0,0 +1,85 @@
+# -*- coding: utf-8 -*-
+
+"""
+flstats test script
+~~~~~~~~~~~~~~~~~~~
+
+This script is intended to test the flstats module.
+"""
+
+import json
+import random
+import unittest
+
+from flstats import statistics, webstatistics
+from flask import Flask
+
+class FlstatsTestCase(unittest.Test... | |
1655a878393dcd1424927f5c3b27e5963769956e | motion_tracker/data_setup/move_bad_images.py | motion_tracker/data_setup/move_bad_images.py | import cv2
import numpy as np
import os
import shutil
import sys
from os.path import join
from tqdm import tqdm
if __name__ == "__main__":
source_dir = sys.argv[1]
dest_dir = sys.argv[2]
os.makedirs(dest_dir, exist_ok=True)
fnames = os.listdir(source_dir)
for fname in tqdm(fnames):
img_pat... | Move bad images to new dir. | Move bad images to new dir.
| Python | mit | dansbecker/motion-tracking | ---
+++
@@ -0,0 +1,25 @@
+import cv2
+import numpy as np
+import os
+import shutil
+import sys
+from os.path import join
+from tqdm import tqdm
+
+if __name__ == "__main__":
+ source_dir = sys.argv[1]
+ dest_dir = sys.argv[2]
+ os.makedirs(dest_dir, exist_ok=True)
+
+ fnames = os.listdir(source_dir)
+ ... | |
42ea5a982216285d9844c1405a37eb8c14b18c12 | mrequests/examples/parse_response_headers.py | mrequests/examples/parse_response_headers.py | import mrequests
class MyResponse(mrequests.Response):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.headers = {}
def add_header(self, data):
# let base class handle headers, which influence response parsing
self._parse_header(data)
name, value = ... | Add example for custom response header parsing | Add example for custom response header parsing
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de>
| Python | mit | SpotlightKid/micropython-stm-lib | ---
+++
@@ -0,0 +1,37 @@
+import mrequests
+
+
+class MyResponse(mrequests.Response):
+ def __init__(self, *args, **kw):
+ super().__init__(*args, **kw)
+ self.headers = {}
+
+ def add_header(self, data):
+ # let base class handle headers, which influence response parsing
+ self._par... | |
5913a413cf5f39001a82389337c4c9b8bea2c2b7 | scripts/append_classified_to_lower_ranks.py | scripts/append_classified_to_lower_ranks.py | #!/usr/bin/env python
import pandas as pd, sys
def append_classified(df):
## Append classified name to each Unclassified rank in turn
p_unc = df[df.phylum=="Unclassified"]
df.loc[p_unc.index,"phylum"] += "."+df.loc[p_unc.index,"superkingdom"]
c_unc = df[df["class"]=="Unclassified"]
df.loc[c_unc.i... | Append classified tax name to lower ranking unclassified names | Append classified tax name to lower ranking unclassified names
| Python | mit | EnvGen/toolbox,EnvGen/toolbox | ---
+++
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+
+import pandas as pd, sys
+
+
+def append_classified(df):
+ ## Append classified name to each Unclassified rank in turn
+ p_unc = df[df.phylum=="Unclassified"]
+ df.loc[p_unc.index,"phylum"] += "."+df.loc[p_unc.index,"superkingdom"]
+ c_unc = df[df["class"... | |
3295b30ba3e243801a520adff332663dbe490cf9 | tools/mini_spectrum.py | tools/mini_spectrum.py | # -*- encoding: utf-8 -*-
# JN 2016-02-16
"""
Plot a spectrum from the first 1000 records of data
"""
import sys
import scipy.signal as sig
import matplotlib.pyplot as mpl
from combinato import NcsFile, DefaultFilter
def plot_spectrum(fname):
fid = NcsFile(fname)
rawdata = fid.read(0, 1000)
data = rawda... | Add small plot of power spectral density | Add small plot of power spectral density
| Python | mit | jniediek/combinato | ---
+++
@@ -0,0 +1,41 @@
+# -*- encoding: utf-8 -*-
+# JN 2016-02-16
+
+"""
+Plot a spectrum from the first 1000 records of data
+"""
+import sys
+import scipy.signal as sig
+import matplotlib.pyplot as mpl
+
+from combinato import NcsFile, DefaultFilter
+
+
+def plot_spectrum(fname):
+ fid = NcsFile(fname)
+ r... | |
753803c79b1bc8b5457909a1d2f6779eb72fb36a | bindings/python/examples/coverart_fetch.py | bindings/python/examples/coverart_fetch.py | #!/usr/bin/python
## Copyright (C) 2005 Nick Piper <nick-gtkpod at nickpiper co uk>
## Part of the gtkpod project.
## URL: http://www.gtkpod.org/
## URL: http://gtkpod.sourceforge.net/
## The code contained in this file is free software; you can redistribute
## it and/or modify it under the terms of the GNU L... | Add a toy script to fetch images from Amazon | Add a toy script to fetch images from Amazon
git-svn-id: 76cb8c96a56e2e269d2baf461dc2f0a164399ff5@1178 f01d2545-417e-4e96-918e-98f8d0dbbcb6
| Python | lgpl-2.1 | hyperair/libgpod,hyperair/libgpod,hyperair/libgpod,neuschaefer/libgpod,neuschaefer/libgpod,neuschaefer/libgpod,hyperair/libgpod,neuschaefer/libgpod,hyperair/libgpod,neuschaefer/libgpod | ---
+++
@@ -0,0 +1,72 @@
+#!/usr/bin/python
+
+## Copyright (C) 2005 Nick Piper <nick-gtkpod at nickpiper co uk>
+## Part of the gtkpod project.
+
+## URL: http://www.gtkpod.org/
+## URL: http://gtkpod.sourceforge.net/
+
+## The code contained in this file is free software; you can redistribute
+## it and/or m... | |
c078cc3fc0cf86b01fcec6c5ea6de9c4d3ee4ef5 | CSVTODSS.py | CSVTODSS.py | from hec.script import MessageBox
from hec.heclib.dss import HecDss
from hec.heclib.util import HecTime
from hec.io import TimeSeriesContainer
import java
import csv
try :
try :
#print 'Jython version: ', sys.version
NUM_METADATA_LINES = 3;
DSS_FILE_PATH = './2008_2_Events/2008_2_Events_for... | Store .csv daily precipitation in hec .dss database | Store .csv daily precipitation in hec .dss database
- Store precipitation data in .dss before running HEC-HMS model
- Also updated the Jython version of Hec-dssuve into 2.5
More details - http://resourceoptimism.blogspot.com/2017/03/store-csv-data-on-hec-dssuve-dss-for.html
| Python | apache-2.0 | gihankarunarathne/udp,gihankarunarathne/udp | ---
+++
@@ -0,0 +1,58 @@
+from hec.script import MessageBox
+from hec.heclib.dss import HecDss
+from hec.heclib.util import HecTime
+from hec.io import TimeSeriesContainer
+import java
+import csv
+
+try :
+ try :
+ #print 'Jython version: ', sys.version
+ NUM_METADATA_LINES = 3;
+ DSS_FILE_PA... | |
eb0dacc8af287c35e851c88792e795a79afda238 | tests/unit/states/test_loop.py | tests/unit/states/test_loop.py | # -*- coding: utf-8 -*-
'''
Tests for loop state(s)
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
p... | Add unit tests for loop.until state | Add unit tests for loop.until state
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,83 @@
+# -*- coding: utf-8 -*-
+'''
+Tests for loop state(s)
+'''
+
+# Import Python Libs
+from __future__ import absolute_import, print_function, unicode_literals
+
+# Import Salt Testing Libs
+from tests.support.mixins import LoaderModuleMockMixin
+from tests.support.unit import TestCase, skipIf
... | |
1f7b33d90844019b4ef23c9a871408e02f7a96eb | tools/verify_tempest_config.py | tools/verify_tempest_config.py | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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/licens... | Add config feature verification script | Add config feature verification script
This commit adds a new tool to tempest that will verify that API
queryable config options are set correctly. Right now the list of
options that are verified is very short. Later on additional checks
will be added to verify other services features when the tempest
clients for the ... | Python | apache-2.0 | redhat-cip/tempest,tudorvio/tempest,LIS/lis-tempest,cloudbase/lis-tempest,vedujoshi/os_tempest,danielmellado/tempest,xbezdick/tempest,adkerr/tempest,openstack/tempest,rzarzynski/tempest,vedujoshi/os_tempest,BeenzSyed/tempest,LIS/lis-tempest,bigswitch/tempest,tudorvio/tempest,nunogt/tempest,rakeshmi/tempest,Tesora/tesor... | ---
+++
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# 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
+#
+#... | |
ffd57de470f488793e0beda9ead552d43663f6b9 | designate/tests/test_backend/test_bind9.py | designate/tests/test_backend/test_bind9.py | # Copyright 2015 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Add test of BIND9 backend | Add test of BIND9 backend
Add test of the following source code.
designate/designate/backend/impl_bind9.py
Change-Id: If2c3292de483881d732d88397574de8e5a12f78a
| Python | apache-2.0 | grahamhayes/designate,grahamhayes/designate,openstack/designate,grahamhayes/designate,openstack/designate,openstack/designate | ---
+++
@@ -0,0 +1,55 @@
+# Copyright 2015 FUJITSU LIMITED
+#
+# 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... | |
d8e78b058239e7b23a1b69ffb25dc520b7487e1d | rayleigh-ritz-truss.py | rayleigh-ritz-truss.py | import string
import numpy as np
from scipy.optimize import fsolve
from scipy.optimize import minimize
letter_list=list(string.ascii_uppercase)
poly_size=input('Polynomial Size: ')
poly_helper=[]
helper_string=''
for x in range(0,int(poly_size)):
helper_string+=str(letter_list[x])+'*x^'+str(int(poly_size)-x-1)+' ... | Add framework for Rayleigh-Ritz polynomial approximations for a single truss | Add framework for Rayleigh-Ritz polynomial approximations for a single truss
| Python | mit | ndebuhr/openfea,ndebuhr/openfea | ---
+++
@@ -0,0 +1,22 @@
+import string
+import numpy as np
+from scipy.optimize import fsolve
+from scipy.optimize import minimize
+
+letter_list=list(string.ascii_uppercase)
+
+poly_size=input('Polynomial Size: ')
+poly_helper=[]
+helper_string=''
+for x in range(0,int(poly_size)):
+ helper_string+=str(letter_li... | |
1b49bc51c60a2c257ff842fefda17c9a6e2ef2a8 | fabfile/testbeds/testbed_nsheth_a27_a28.py | fabfile/testbeds/testbed_nsheth_a27_a28.py | from fabric.api import env
os_username = 'admin'
os_password = 'contrail123'
os_tenant_name = 'demo'
host1 = 'root@10.84.5.27'
host2 = 'root@10.84.5.28'
ext_routers = []
router_asn = 64512
public_vn_rtgt = 10000
host_build = 'nsheth@10.84.5.31'
env.roledefs = {
'all': [host1, host2],
'cfgm': [ho... | Save testbed for a27 + a28. | Save testbed for a27 + a28.
| Python | apache-2.0 | Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils | ---
+++
@@ -0,0 +1,41 @@
+from fabric.api import env
+
+os_username = 'admin'
+os_password = 'contrail123'
+os_tenant_name = 'demo'
+
+host1 = 'root@10.84.5.27'
+host2 = 'root@10.84.5.28'
+
+ext_routers = []
+router_asn = 64512
+public_vn_rtgt = 10000
+
+host_build = 'nsheth@10.84.5.31'
+
+env.roledefs = {
+ 'all'... | |
1b036dc1de34e11122723caa464ea9a3748288fa | tests/test_bulk.py | tests/test_bulk.py | import json
from django.db import models
from django.conf import settings
from django.test import TestCase
from localized_fields.fields import LocalizedField
from .data import get_init_values
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data struct... | Add simple test to verify LocalizedField can be used in bulk_create | Add simple test to verify LocalizedField can be used in bulk_create
| Python | mit | SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields | ---
+++
@@ -0,0 +1,33 @@
+import json
+
+from django.db import models
+from django.conf import settings
+from django.test import TestCase
+
+from localized_fields.fields import LocalizedField
+
+from .data import get_init_values
+from .fake_model import get_fake_model
+
+
+class LocalizedBulkTestCase(TestCase):
+ ... | |
5cd5a8453cc866cba9441700144b4fd36f017b1d | turbustat/simulator/tests/test_extended_fields.py | turbustat/simulator/tests/test_extended_fields.py |
from ..gen_field import make_3dfield, make_extended
import pytest
import numpy as np
import numpy.testing as npt
@pytest.mark.parametrize(('shape', 'slope'), [(shape, slope) for shape in
[32, 33] for slope in
np.arange(0.0, ... | Add tests for power-law functions | Add tests for power-law functions
| Python | mit | e-koch/TurbuStat,Astroua/TurbuStat | ---
+++
@@ -0,0 +1,54 @@
+
+from ..gen_field import make_3dfield, make_extended
+
+import pytest
+import numpy as np
+import numpy.testing as npt
+
+
+@pytest.mark.parametrize(('shape', 'slope'), [(shape, slope) for shape in
+ [32, 33] for slope in
+ ... | |
e20ba0715def82abddfdc964b9adc13fad308a95 | tools/mknbindex.py | tools/mknbindex.py | #!/usr/bin/env python
"""Simple script to auto-generate the index of notebooks in a given directory.
"""
import glob
import urllib
notebooks = sorted(glob.glob('*.ipynb'))
tpl = ( '* [{0}](http://nbviewer.ipython.org/url/github.com/ipython/ipython/'
'raw/master/examples/notebooks/{1})' )
idx = [
"""# A col... | Add script to auto-generate our index of example notebooks. | Add script to auto-generate our index of example notebooks.
It's highly hard-coded for now, but will do in the meantime. We can
generalize it later, but we're really hurting by not having this index
anywhere.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+"""Simple script to auto-generate the index of notebooks in a given directory.
+"""
+
+import glob
+import urllib
+
+notebooks = sorted(glob.glob('*.ipynb'))
+
+tpl = ( '* [{0}](http://nbviewer.ipython.org/url/github.com/ipython/ipython/'
+ 'raw/master/examples/... | |
a16aa19208ba9dc23708ade128383f06a3df3f77 | tests/test_managed.py | tests/test_managed.py | import glob
from jgo.jgo import InvalidEndpoint
import jgo
import os
import pathlib
import unittest
import shutil
import tempfile
import logging
_logger = logging.getLogger(__name__)
_logger.level = logging.INFO
SJC_VERSION = "2.87.0"
SJC_OPTIONAL_VERSION = "1.0.0"
MANAGED_ENDPOINT = (
"org.scijava:scijava-commo... | Add managed Endpoint unit tests | Add managed Endpoint unit tests
| Python | unlicense | ctrueden/jrun,ctrueden/jrun | ---
+++
@@ -0,0 +1,83 @@
+import glob
+from jgo.jgo import InvalidEndpoint
+import jgo
+import os
+import pathlib
+import unittest
+import shutil
+import tempfile
+
+import logging
+
+_logger = logging.getLogger(__name__)
+_logger.level = logging.INFO
+
+SJC_VERSION = "2.87.0"
+SJC_OPTIONAL_VERSION = "1.0.0"
+MANAGED... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.